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