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