xref: /XiangShan/src/main/scala/xiangshan/frontend/BPU.scala (revision c105c2d33d0759193133e2489a231bad9d99a0a8)
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
102abstract class 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 = Wire(Vec(PredictWidth, Bool()))
127  val notTakens = Wire(Vec(PredictWidth, Bool()))
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   = Wire(Bool())
135  val lastIsRVC = Wire(Bool())
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 = Wire(Vec(PredictWidth, UInt(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  XSDebug(io.pred.fire() && p.taken, "outPredTaken: fetchPC:%x, jmpPC:%x\n",
180    inLatch.pc, inLatch.pc + (jmpIdx << 1.U))
181  XSDebug(io.pred.fire() && p.redirect, "outPred: previous target:%x redirected to %x \n",
182    inLatch.target, p.target)
183  XSDebug(io.pred.fire(), "outPred targetSrc: ")
184  for (i <- 0 until PredictWidth) {
185    XSDebug(false, io.pred.fire(), "(%d):%x ", i.U, targetSrc(i))
186  }
187  XSDebug(false, io.pred.fire(), "\n")
188}
189
190class BPUStage1 extends BPUStage {
191
192  // 'overrides' default logic
193  // when flush, the prediction should also starts
194  when (io.flush || inFire) { predValid := true.B }
195  .elsewhen(outFire)        { predValid := false.B }
196  .otherwise                { predValid := predValid }
197  io.in.ready := !predValid || io.out.fire() && io.pred.fire() || io.flush
198  // io.out.valid := predValid
199
200  // ubtb is accessed with inLatch pc in s1,
201  // so we use io.in instead of inLatch
202  val ubtbResp = io.in.bits.resp.ubtb
203  // the read operation is already masked, so we do not need to mask here
204  takens    := VecInit((0 until PredictWidth).map(i => ubtbResp.hits(i) && ubtbResp.takens(i)))
205  notTakens := VecInit((0 until PredictWidth).map(i => ubtbResp.hits(i) && ubtbResp.notTakens(i)))
206  targetSrc := ubtbResp.targets
207
208  lastIsRVC := ubtbResp.is_RVC(lastValidPos)
209  lastHit   := ubtbResp.hits(lastValidPos)
210
211  // resp and brInfo are from the components,
212  // so it does not need to be latched
213  io.out.bits.resp <> io.in.bits.resp
214  io.out.bits.brInfo := io.in.bits.brInfo
215
216  XSDebug(io.pred.fire(), "outPred using ubtb resp: hits:%b, takens:%b, notTakens:%b, isRVC:%b\n",
217    ubtbResp.hits.asUInt, ubtbResp.takens.asUInt, ubtbResp.notTakens.asUInt, ubtbResp.is_RVC.asUInt)
218}
219
220class BPUStage2 extends BPUStage {
221
222  // Use latched response from s1
223  val btbResp = inLatch.resp.btb
224  val bimResp = inLatch.resp.bim
225  takens    := VecInit((0 until PredictWidth).map(i => btbResp.hits(i) && (btbResp.types(i) === BTBtype.B && bimResp.ctrs(i)(1) || btbResp.types(i) === BTBtype.J)))
226  notTakens := VecInit((0 until PredictWidth).map(i => btbResp.hits(i) && btbResp.types(i) === BTBtype.B && !bimResp.ctrs(i)(1)))
227  targetSrc := btbResp.targets
228
229  lastIsRVC := btbResp.isRVC(lastValidPos)
230  lastHit   := btbResp.hits(lastValidPos)
231
232  XSDebug(io.pred.fire(), "outPred using btb&bim resp: hits:%b, ctrTakens:%b\n",
233    btbResp.hits.asUInt, VecInit(bimResp.ctrs.map(_(1))).asUInt)
234}
235
236class BPUStage3 extends BPUStage {
237
238  io.out.valid := predValid && io.predecode.valid && !io.flush
239
240  // TAGE has its own pipelines and the
241  // response comes directly from s3,
242  // so we do not use those from inLatch
243  val tageResp = io.in.bits.resp.tage
244  val tageValidTakens = VecInit((0 until PredictWidth).map( i => tageResp.takens(i) && tageResp.hits(i)))
245
246  val pdMask = io.predecode.bits.mask
247  val pds    = io.predecode.bits.pd
248
249  val btbHits   = inLatch.resp.btb.hits.asUInt
250  val bimTakens = VecInit(inLatch.resp.bim.ctrs.map(_(1)))
251
252  val brs   = pdMask & Reverse(Cat(pds.map(_.isBr)))
253  val jals  = pdMask & Reverse(Cat(pds.map(_.isJal)))
254  val jalrs = pdMask & Reverse(Cat(pds.map(_.isJalr)))
255  // val calls = pdMask & Reverse(Cat(pds.map(_.isCall)))
256  // val rets  = pdMask & Reverse(Cat(pds.map(_.isRet)))
257
258  // val callIdx = PriorityEncoder(calls)
259  // val retIdx  = PriorityEncoder(rets)
260
261  val brTakens =
262    if (EnableBPD) {
263      brs & Reverse(Cat((0 until PredictWidth).map(i => tageValidTakens(i))))
264    } else {
265      brs & Reverse(Cat((0 until PredictWidth).map(i => bimTakens(i))))
266    }
267
268  // predict taken only if btb has a target
269  takens := VecInit((0 until PredictWidth).map(i => (brTakens(i) || jalrs(i)) && btbHits(i) || jals(i)))
270  // Whether should we count in branches that are not recorded in btb?
271  // PS: Currently counted in. Whenever tage does not provide a valid
272  //     taken prediction, the branch is counted as a not taken branch
273  notTakens := (if (EnableBPD) { VecInit((0 until PredictWidth).map(i => brs(i) && !tageValidTakens(i)))}
274                else           { VecInit((0 until PredictWidth).map(i => brs(i) && !bimTakens(i)))})
275  targetSrc := inLatch.resp.btb.targets
276
277  lastIsRVC := pds(lastValidPos).isRVC
278  lastHit   := pdMask(lastValidPos)
279
280  // Wrap tage resp and tage meta in
281  // This is ugly
282  io.out.bits.resp.tage <> io.in.bits.resp.tage
283  for (i <- 0 until PredictWidth) {
284    io.out.bits.brInfo(i).tageMeta := io.in.bits.brInfo(i).tageMeta
285  }
286
287  XSDebug(io.predecode.valid, "predecode: pc:%x, mask:%b\n", inLatch.pc, io.predecode.bits.mask)
288  for (i <- 0 until PredictWidth) {
289    val p = io.predecode.bits.pd(i)
290    XSDebug(io.predecode.valid && io.predecode.bits.mask(i), "predecode(%d): brType:%d, br:%d, jal:%d, jalr:%d, call:%d, ret:%d, RVC:%d, excType:%d\n",
291      i.U, p.brType, p.isBr, p.isJal, p.isJalr, p.isCall, p.isRet, p.isRVC, p.excType)
292  }
293}
294
295trait BranchPredictorComponents extends HasXSParameter {
296  val ubtb = Module(new MicroBTB)
297  val btb = Module(new BTB)
298  val bim = Module(new BIM)
299  val tage = (if(EnableBPD) { Module(new Tage) }
300              else          { Module(new FakeTage) })
301  val preds = Seq(ubtb, btb, bim, tage)
302  // preds.map(_.io := DontCare)
303}
304
305class BPUReq extends XSBundle {
306  val pc = UInt(VAddrBits.W)
307  val hist = UInt(HistoryLength.W)
308  val inMask = UInt(PredictWidth.W)
309}
310
311class BranchUpdateInfoWithHist extends XSBundle {
312  val ui = new BranchUpdateInfo
313  val hist = UInt(HistoryLength.W)
314}
315
316object BranchUpdateInfoWithHist {
317  def apply (brInfo: BranchUpdateInfo, hist: UInt) = {
318    val b = Wire(new BranchUpdateInfoWithHist)
319    b.ui <> brInfo
320    b.hist := hist
321    b
322  }
323}
324
325abstract class BaseBPU extends XSModule with BranchPredictorComponents{
326  val io = IO(new Bundle() {
327    // from backend
328    val inOrderBrInfo = Flipped(ValidIO(new BranchUpdateInfoWithHist))
329    // from ifu, frontend redirect
330    val flush = Input(Vec(3, Bool()))
331    // from if1
332    val in = Flipped(ValidIO(new BPUReq))
333    // to if2/if3/if4
334    val out = Vec(3, Decoupled(new BranchPrediction))
335    // from if4
336    val predecode = Flipped(ValidIO(new Predecode))
337    // to if4, some bpu info used for updating
338    val branchInfo = Decoupled(Vec(PredictWidth, new BranchInfo))
339  })
340
341  def npc(pc: UInt, instCount: UInt) = pc + (instCount << 1.U)
342
343  preds.map(_.io.update <> io.inOrderBrInfo)
344
345  val s1 = Module(new BPUStage1)
346  val s2 = Module(new BPUStage2)
347  val s3 = Module(new BPUStage3)
348
349  s1.io.flush := io.flush(0)
350  s2.io.flush := io.flush(1)
351  s3.io.flush := io.flush(2)
352
353  s1.io.in <> DontCare
354  s2.io.in <> s1.io.out
355  s3.io.in <> s2.io.out
356
357  io.out(0) <> s1.io.pred
358  io.out(1) <> s2.io.pred
359  io.out(2) <> s3.io.pred
360
361  s1.io.predecode <> DontCare
362  s2.io.predecode <> DontCare
363  s3.io.predecode <> io.predecode
364
365  io.branchInfo.valid := s3.io.out.valid
366  io.branchInfo.bits := s3.io.out.bits.brInfo
367  s3.io.out.ready := io.branchInfo.ready
368
369  XSDebug(io.branchInfo.fire(), "branchInfo sent!\n")
370  for (i <- 0 until PredictWidth) {
371    val b = io.branchInfo.bits(i)
372    XSDebug(io.branchInfo.fire(), "brInfo(%d): ubtbWrWay:%d, ubtbHit:%d, btbWrWay:%d, bimCtr:%d\n",
373      i.U, b.ubtbWriteWay, b.ubtbHits, b.btbWriteWay, b.bimCtr)
374    val t = b.tageMeta
375    XSDebug(io.branchInfo.fire(), "  tageMeta: pvder(%d):%d, altDiffers:%d, pvderU:%d, pvderCtr:%d, allocate(%d):%d\n",
376      t.provider.valid, t.provider.bits, t.altDiffers, t.providerU, t.providerCtr, t.allocate.valid, t.allocate.bits)
377  }
378}
379
380
381class FakeBPU extends BaseBPU {
382  io.out.foreach(i => {
383    // Provide not takens
384    i.valid := true.B
385    i.bits <> DontCare
386    i.bits.redirect := false.B
387  })
388  io.branchInfo <> DontCare
389}
390
391class BPU extends BaseBPU {
392
393  //**********************Stage 1****************************//
394  val s1_fire = s1.io.in.fire()
395  val s1_resp_in = Wire(new PredictorResponse)
396  val s1_brInfo_in = Wire(Vec(PredictWidth, new BranchInfo))
397
398  s1_resp_in.tage := DontCare
399  s1_brInfo_in.map(i => {
400    i.histPtr   := DontCare
401    i.tageMeta  := DontCare
402    i.rasSp     := DontCare
403    i.rasTopCtr := DontCare
404  })
405
406  val s1_inLatch = RegEnable(io.in, s1_fire)
407  ubtb.io.flush := io.flush(0) // TODO: fix this
408  ubtb.io.pc.valid := s1_inLatch.valid
409  ubtb.io.pc.bits := s1_inLatch.bits.pc
410  ubtb.io.inMask := s1_inLatch.bits.inMask
411  ubtb.io.hist := DontCare
412
413  val uo = ubtb.io.out
414  XSDebug("debug: ubtb hits:%b, takens:%b, notTakens:%b\n",
415    uo.hits.asUInt, uo.takens.asUInt, uo.notTakens.asUInt)
416
417  // Wrap ubtb response into resp_in and brInfo_in
418  s1_resp_in.ubtb <> ubtb.io.out
419  for (i <- 0 until PredictWidth) {
420    s1_brInfo_in(i).ubtbWriteWay := ubtb.io.uBTBBranchInfo.writeWay(i)
421    s1_brInfo_in(i).ubtbHits := ubtb.io.uBTBBranchInfo.hits(i)
422  }
423
424  btb.io.flush := io.flush(0) // TODO: fix this
425  btb.io.pc.valid := io.in.valid
426  btb.io.pc.bits := io.in.bits.pc
427  btb.io.inMask := io.in.bits.inMask
428  btb.io.hist := DontCare
429
430  val bo = btb.io.resp
431  XSDebug("debug: btb hits:%b\n", bo.hits.asUInt)
432
433  // Wrap btb response into resp_in and brInfo_in
434  s1_resp_in.btb <> btb.io.resp
435  for (i <- 0 until PredictWidth) {
436    s1_brInfo_in(i).btbWriteWay := btb.io.meta.writeWay(i)
437  }
438
439  bim.io.flush := io.flush(0) // TODO: fix this
440  bim.io.pc.valid := io.in.valid
441  bim.io.pc.bits := io.in.bits.pc
442  bim.io.inMask := io.in.bits.inMask
443  bim.io.hist := DontCare
444
445  val bio = bim.io.resp
446  XSDebug("debug: bim takens:%b\n", VecInit(bio.ctrs.map(_(1))).asUInt)
447
448
449  // Wrap bim response into resp_in and brInfo_in
450  s1_resp_in.bim <> bim.io.resp
451  for (i <- 0 until PredictWidth) {
452    s1_brInfo_in(i).bimCtr := bim.io.meta.ctrs(i)
453  }
454
455
456  s1.io.in.valid := io.in.valid
457  s1.io.in.bits.pc := io.in.bits.pc
458  s1.io.in.bits.mask := io.in.bits.inMask
459  s1.io.in.bits.target := npc(io.in.bits.pc, PopCount(io.in.bits.inMask)) // Deault target npc
460  s1.io.in.bits.resp <> s1_resp_in
461  s1.io.in.bits.brInfo <> s1_brInfo_in
462
463  //**********************Stage 2****************************//
464  tage.io.flush := io.flush(1) // TODO: fix this
465  tage.io.pc.valid := s1.io.out.fire()
466  tage.io.pc.bits := s1.io.out.bits.pc // PC from s1
467  tage.io.hist := io.in.bits.hist // The inst is from s1
468  tage.io.inMask := s1.io.out.bits.mask
469  tage.io.s3Fire := s3.io.in.fire() // Tell tage to march 1 stage
470  tage.io.bim <> s1.io.out.bits.resp.bim // Use bim results from s1
471
472  //**********************Stage 3****************************//
473  // Wrap tage response and meta into s3.io.in.bits
474  // This is ugly
475
476  s3.io.in.bits.resp.tage <> tage.io.resp
477  for (i <- 0 until PredictWidth) {
478    s3.io.in.bits.brInfo(i).tageMeta := tage.io.meta(i)
479  }
480
481}
482