xref: /XiangShan/src/main/scala/xiangshan/frontend/BPU.scala (revision 3fce4f48e1f4c43253ff1758dbd05b8b71627990)
1package xiangshan.frontend
2
3import chisel3._
4import chisel3.util._
5import utils._
6import xiangshan._
7import xiangshan.backend.ALUOpType
8import xiangshan.backend.JumpOpType
9
10trait HasBPUParameter extends HasXSParameter {
11  val BPUDebug = false
12  val EnableCFICommitLog = true
13  val EnbaleCFIPredLog = true
14  val EnableBPUTimeRecord = true
15}
16
17class TableAddr(val idxBits: Int, val banks: Int) extends XSBundle {
18  def tagBits = VAddrBits - idxBits - 1
19
20  val tag = UInt(tagBits.W)
21  val idx = UInt(idxBits.W)
22  val offset = UInt(1.W)
23
24  def fromUInt(x: UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this)
25  def getTag(x: UInt) = fromUInt(x).tag
26  def getIdx(x: UInt) = fromUInt(x).idx
27  def getBank(x: UInt) = getIdx(x)(log2Up(banks) - 1, 0)
28  def getBankIdx(x: UInt) = getIdx(x)(idxBits - 1, log2Up(banks))
29}
30
31class PredictorResponse extends XSBundle {
32  class UbtbResp extends XSBundle {
33  // the valid bits indicates whether a target is hit
34    val targets = Vec(PredictWidth, UInt(VAddrBits.W))
35    val hits = Vec(PredictWidth, Bool())
36    val takens = Vec(PredictWidth, Bool())
37    val brMask = Vec(PredictWidth, Bool())
38    val is_RVC = Vec(PredictWidth, Bool())
39  }
40  class BtbResp extends XSBundle {
41  // the valid bits indicates whether a target is hit
42    val targets = Vec(PredictWidth, UInt(VAddrBits.W))
43    val hits = Vec(PredictWidth, Bool())
44    val types = Vec(PredictWidth, UInt(2.W))
45    val isRVC = Vec(PredictWidth, Bool())
46  }
47  class BimResp extends XSBundle {
48    val ctrs = Vec(PredictWidth, UInt(2.W))
49  }
50  class TageResp extends XSBundle {
51  // the valid bits indicates whether a prediction is hit
52    val takens = Vec(PredictWidth, Bool())
53    val hits = Vec(PredictWidth, Bool())
54  }
55  class LoopResp extends XSBundle {
56    val exit = Vec(PredictWidth, Bool())
57  }
58
59  val ubtb = new UbtbResp
60  val btb = new BtbResp
61  val bim = new BimResp
62  val tage = new TageResp
63  val loop = new LoopResp
64}
65
66trait PredictorUtils {
67  // circular shifting
68  def circularShiftLeft(source: UInt, len: Int, shamt: UInt): UInt = {
69    val res = Wire(UInt(len.W))
70    val higher = source << shamt
71    val lower = source >> (len.U - shamt)
72    res := higher | lower
73    res
74  }
75
76  def circularShiftRight(source: UInt, len: Int, shamt: UInt): UInt = {
77    val res = Wire(UInt(len.W))
78    val higher = source << (len.U - shamt)
79    val lower = source >> shamt
80    res := higher | lower
81    res
82  }
83
84  // To be verified
85  def satUpdate(old: UInt, len: Int, taken: Bool): UInt = {
86    val oldSatTaken = old === ((1 << len)-1).U
87    val oldSatNotTaken = old === 0.U
88    Mux(oldSatTaken && taken, ((1 << len)-1).U,
89      Mux(oldSatNotTaken && !taken, 0.U,
90        Mux(taken, old + 1.U, old - 1.U)))
91  }
92
93  def signedSatUpdate(old: SInt, len: Int, taken: Bool): SInt = {
94    val oldSatTaken = old === ((1 << (len-1))-1).S
95    val oldSatNotTaken = old === (-(1 << (len-1))).S
96    Mux(oldSatTaken && taken, ((1 << (len-1))-1).S,
97      Mux(oldSatNotTaken && !taken, (-(1 << (len-1))).S,
98        Mux(taken, old + 1.S, old - 1.S)))
99  }
100}
101abstract class BasePredictor extends XSModule with HasBPUParameter with PredictorUtils {
102  val metaLen = 0
103
104  // An implementation MUST extend the IO bundle with a response
105  // and the special input from other predictors, as well as
106  // the metas to store in BRQ
107  abstract class Resp extends XSBundle {}
108  abstract class FromOthers extends XSBundle {}
109  abstract class Meta extends XSBundle {}
110
111  class DefaultBasePredictorIO extends XSBundle {
112    val flush = Input(Bool())
113    val pc = Flipped(ValidIO(UInt(VAddrBits.W)))
114    val hist = Input(UInt(HistoryLength.W))
115    val inMask = Input(UInt(PredictWidth.W))
116    val update = Flipped(ValidIO(new BranchUpdateInfoWithHist))
117  }
118
119  val io = new DefaultBasePredictorIO
120
121  val debug = false
122}
123
124class BPUStageIO extends XSBundle {
125  val pc = UInt(VAddrBits.W)
126  val mask = UInt(PredictWidth.W)
127  val resp = new PredictorResponse
128  val target = UInt(VAddrBits.W)
129  val brInfo = Vec(PredictWidth, new BranchInfo)
130  val saveHalfRVI = Bool()
131}
132
133
134abstract class BPUStage extends XSModule with HasBPUParameter{
135  class DefaultIO extends XSBundle {
136    val flush = Input(Bool())
137    val in = Flipped(Decoupled(new BPUStageIO))
138    val pred = Decoupled(new BranchPrediction)
139    val out = Decoupled(new BPUStageIO)
140    val predecode = Flipped(ValidIO(new Predecode))
141    val recover =  Flipped(ValidIO(new BranchUpdateInfo))
142    val cacheValid = Input(Bool())
143    val debug_hist = Input(UInt(HistoryLength.W))
144    val debug_histPtr = Input(UInt(log2Up(ExtHistoryLength).W))
145  }
146  val io = IO(new DefaultIO)
147
148  val predValid = RegInit(false.B)
149
150  io.in.ready := !predValid || io.out.fire() && io.pred.fire() || io.flush
151
152  def npc(pc: UInt, instCount: UInt) = pc + (instCount << 1.U)
153
154  val inFire = io.in.fire()
155  val inLatch = RegEnable(io.in.bits, inFire)
156
157  val outFire = io.out.fire()
158
159  // Each stage has its own logic to decide
160  // takens, notTakens and target
161
162  val takens = Wire(Vec(PredictWidth, Bool()))
163  val notTakens = Wire(Vec(PredictWidth, Bool()))
164  val brMask = Wire(Vec(PredictWidth, Bool()))
165  val jmpIdx = PriorityEncoder(takens)
166  val hasNTBr = (0 until PredictWidth).map(i => i.U <= jmpIdx && notTakens(i) && brMask(i)).reduce(_||_)
167  val taken = takens.reduce(_||_)
168  // get the last valid inst
169  val lastValidPos = WireInit(PriorityMux(Reverse(inLatch.mask), (PredictWidth-1 to 0 by -1).map(i => i.U)))
170  val lastHit   = Wire(Bool())
171  val lastIsRVC = Wire(Bool())
172  val saveHalfRVI = ((lastValidPos === jmpIdx && taken) || !taken ) && !lastIsRVC && lastHit
173
174  val targetSrc = Wire(Vec(PredictWidth, UInt(VAddrBits.W)))
175  val target = Mux(taken, targetSrc(jmpIdx), npc(inLatch.pc, PopCount(inLatch.mask)))
176
177  io.pred.bits <> DontCare
178  io.pred.bits.redirect := target =/= inLatch.target || inLatch.saveHalfRVI && !saveHalfRVI
179  io.pred.bits.taken := taken
180  io.pred.bits.jmpIdx := jmpIdx
181  io.pred.bits.hasNotTakenBrs := hasNTBr
182  io.pred.bits.target := target
183  io.pred.bits.saveHalfRVI := saveHalfRVI
184  io.pred.bits.takenOnBr := taken && brMask(jmpIdx)
185
186  io.out.bits <> DontCare
187  io.out.bits.pc := inLatch.pc
188  io.out.bits.mask := inLatch.mask
189  io.out.bits.target := target
190  io.out.bits.resp <> inLatch.resp
191  io.out.bits.brInfo := inLatch.brInfo
192  io.out.bits.saveHalfRVI := saveHalfRVI
193  (0 until PredictWidth).map(i =>
194    io.out.bits.brInfo(i).sawNotTakenBranch := (if (i == 0) false.B else (brMask.asUInt & notTakens.asUInt)(i-1,0).orR))
195
196  // Default logic
197  //  pred.ready not taken into consideration
198  //  could be broken
199  when (io.flush)     { predValid := false.B }
200  .elsewhen (inFire)  { predValid := true.B }
201  .elsewhen (outFire) { predValid := false.B }
202  .otherwise          { predValid := predValid }
203
204  io.out.valid  := predValid && !io.flush
205  io.pred.valid := predValid && !io.flush
206
207  if (BPUDebug) {
208    XSDebug(io.in.fire(), "in:(%d %d) pc=%x, mask=%b, target=%x\n",
209      io.in.valid, io.in.ready, io.in.bits.pc, io.in.bits.mask, io.in.bits.target)
210    XSDebug(io.out.fire(), "out:(%d %d) pc=%x, mask=%b, target=%x\n",
211      io.out.valid, io.out.ready, io.out.bits.pc, io.out.bits.mask, io.out.bits.target)
212    XSDebug("flush=%d\n", io.flush)
213    XSDebug("taken=%d, takens=%b, notTakens=%b, jmpIdx=%d, hasNTBr=%d, lastValidPos=%d, target=%x\n",
214      taken, takens.asUInt, notTakens.asUInt, jmpIdx, hasNTBr, lastValidPos, target)
215    val p = io.pred.bits
216    XSDebug(io.pred.fire(), "outPred: redirect=%d, taken=%d, jmpIdx=%d, hasNTBrs=%d, target=%x, saveHalfRVI=%d\n",
217      p.redirect, p.taken, p.jmpIdx, p.hasNotTakenBrs, p.target, p.saveHalfRVI)
218    XSDebug(io.pred.fire() && p.taken, "outPredTaken: fetchPC:%x, jmpPC:%x\n",
219      inLatch.pc, inLatch.pc + (jmpIdx << 1.U))
220    XSDebug(io.pred.fire() && p.redirect, "outPred: previous target:%x redirected to %x \n",
221      inLatch.target, p.target)
222    XSDebug(io.pred.fire(), "outPred targetSrc: ")
223    for (i <- 0 until PredictWidth) {
224      XSDebug(false, io.pred.fire(), "(%d):%x ", i.U, targetSrc(i))
225    }
226    XSDebug(false, io.pred.fire(), "\n")
227  }
228}
229
230class BPUStage1 extends BPUStage {
231
232  // 'overrides' default logic
233  // when flush, the prediction should also starts
234  when (inFire)        { predValid := true.B }
235  .elsewhen (io.flush) { predValid := false.B }
236  .elsewhen (outFire)  { predValid := false.B }
237  .otherwise           { predValid := predValid }
238  // io.out.valid := predValid
239
240  // ubtb is accessed with inLatch pc in s1,
241  // so we use io.in instead of inLatch
242  val ubtbResp = io.in.bits.resp.ubtb
243  // the read operation is already masked, so we do not need to mask here
244  takens    := VecInit((0 until PredictWidth).map(i => ubtbResp.hits(i) && ubtbResp.takens(i)))
245  notTakens := VecInit((0 until PredictWidth).map(i => ubtbResp.hits(i) && !ubtbResp.takens(i) && ubtbResp.brMask(i)))
246  targetSrc := ubtbResp.targets
247  brMask := ubtbResp.brMask
248
249  lastIsRVC := ubtbResp.is_RVC(lastValidPos)
250  lastHit   := ubtbResp.hits(lastValidPos)
251
252  // resp and brInfo are from the components,
253  // so it does not need to be latched
254  io.out.bits.resp <> io.in.bits.resp
255  io.out.bits.brInfo := io.in.bits.brInfo
256
257  // we do not need to compare target in stage1
258  io.pred.bits.redirect := taken
259
260  if (BPUDebug) {
261    XSDebug(io.pred.fire(), "outPred using ubtb resp: hits:%b, takens:%b, notTakens:%b, isRVC:%b\n",
262      ubtbResp.hits.asUInt, ubtbResp.takens.asUInt, ~ubtbResp.takens.asUInt & brMask.asUInt, ubtbResp.is_RVC.asUInt)
263  }
264  if (EnableBPUTimeRecord) {
265    io.out.bits.brInfo.map(_.debug_ubtb_cycle := GTimer())
266  }
267}
268
269class BPUStage2 extends BPUStage {
270
271  io.out.valid := predValid && !io.flush && io.cacheValid
272  // Use latched response from s1
273  val btbResp = inLatch.resp.btb
274  val bimResp = inLatch.resp.bim
275  takens    := VecInit((0 until PredictWidth).map(i => btbResp.hits(i) && (btbResp.types(i) === BTBtype.B && bimResp.ctrs(i)(1) || btbResp.types(i) =/= BTBtype.B)))
276  notTakens := VecInit((0 until PredictWidth).map(i => btbResp.hits(i) && btbResp.types(i) === BTBtype.B && !bimResp.ctrs(i)(1)))
277  targetSrc := btbResp.targets
278  brMask := VecInit(btbResp.types.map(_ === BTBtype.B))
279
280  lastIsRVC := btbResp.isRVC(lastValidPos)
281  lastHit   := btbResp.hits(lastValidPos)
282
283
284  if (BPUDebug) {
285    XSDebug(io.pred.fire(), "outPred using btb&bim resp: hits:%b, ctrTakens:%b\n",
286      btbResp.hits.asUInt, VecInit(bimResp.ctrs.map(_(1))).asUInt)
287  }
288  if (EnableBPUTimeRecord) {
289    io.out.bits.brInfo.map(_.debug_btb_cycle := GTimer())
290  }
291}
292
293class BPUStage3 extends BPUStage {
294
295
296  io.out.valid := predValid && io.predecode.valid && !io.flush
297  // TAGE has its own pipelines and the
298  // response comes directly from s3,
299  // so we do not use those from inLatch
300  val tageResp = io.in.bits.resp.tage
301  val tageTakens = tageResp.takens
302  val tageHits   = tageResp.hits
303  val tageValidTakens = VecInit((tageTakens zip tageHits).map{case (t, h) => t && h})
304
305  val loopResp = io.in.bits.resp.loop.exit
306
307  val pdMask = io.predecode.bits.mask
308  val pds    = io.predecode.bits.pd
309
310  val btbHits   = inLatch.resp.btb.hits.asUInt
311  val bimTakens = VecInit(inLatch.resp.bim.ctrs.map(_(1)))
312
313  val brs   = pdMask & Reverse(Cat(pds.map(_.isBr)))
314  val jals  = pdMask & Reverse(Cat(pds.map(_.isJal)))
315  val jalrs = pdMask & Reverse(Cat(pds.map(_.isJalr)))
316  val calls = pdMask & Reverse(Cat(pds.map(_.isCall)))
317  val rets  = pdMask & Reverse(Cat(pds.map(_.isRet)))
318  val RVCs = pdMask & Reverse(Cat(pds.map(_.isRVC)))
319
320   val callIdx = PriorityEncoder(calls)
321   val retIdx  = PriorityEncoder(rets)
322
323  // Use bim results for those who tage does not have an entry for
324  val brTakens = brs &
325    (if (EnableBPD) Reverse(Cat((0 until PredictWidth).map(i => tageValidTakens(i) || !tageHits(i) && bimTakens(i)))) else Reverse(Cat((0 until PredictWidth).map(i => bimTakens(i))))) &
326    (if (EnableLoop) ~loopResp.asUInt else Fill(PredictWidth, 1.U(1.W)))
327    // if (EnableBPD) {
328    //   brs & Reverse(Cat((0 until PredictWidth).map(i => tageValidTakens(i))))
329    // } else {
330    //   brs & Reverse(Cat((0 until PredictWidth).map(i => bimTakens(i))))
331    // }
332
333  // predict taken only if btb has a target, jal targets will be provided by IFU
334  takens := VecInit((0 until PredictWidth).map(i => (brTakens(i) || jalrs(i)) && btbHits(i) || jals(i)))
335  // Whether should we count in branches that are not recorded in btb?
336  // PS: Currently counted in. Whenever tage does not provide a valid
337  //     taken prediction, the branch is counted as a not taken branch
338  notTakens := ((VecInit((0 until PredictWidth).map(i => brs(i) && !takens(i)))).asUInt |
339               (if (EnableLoop) { VecInit((0 until PredictWidth).map(i => brs(i) && loopResp(i)))}
340                else { WireInit(0.U.asTypeOf(UInt(PredictWidth.W))) }).asUInt).asTypeOf(Vec(PredictWidth, Bool()))
341  targetSrc := inLatch.resp.btb.targets
342  brMask := WireInit(brs.asTypeOf(Vec(PredictWidth, Bool())))
343
344  //RAS
345  if(EnableRAS){
346    val ras = Module(new RAS)
347    ras.io <> DontCare
348    ras.io.pc.bits := inLatch.pc
349    ras.io.pc.valid := io.out.fire()//predValid
350    ras.io.is_ret := rets.orR  && (retIdx === jmpIdx) && io.predecode.valid
351    ras.io.callIdx.valid := calls.orR && (callIdx === jmpIdx) && io.predecode.valid
352    ras.io.callIdx.bits := callIdx
353    ras.io.isRVC := (calls & RVCs).orR   //TODO: this is ugly
354    ras.io.isLastHalfRVI := !io.predecode.bits.isFetchpcEqualFirstpc
355    ras.io.recover := io.recover
356
357    for(i <- 0 until PredictWidth){
358      io.out.bits.brInfo(i).rasSp :=  ras.io.branchInfo.rasSp
359      io.out.bits.brInfo(i).rasTopCtr := ras.io.branchInfo.rasTopCtr
360      io.out.bits.brInfo(i).rasToqAddr := ras.io.branchInfo.rasToqAddr
361    }
362    takens := VecInit((0 until PredictWidth).map(i => {
363      ((brTakens(i) || jalrs(i)) && btbHits(i)) ||
364          jals(i) ||
365          (!ras.io.out.bits.specEmpty && rets(i)) ||
366          (ras.io.out.bits.specEmpty && btbHits(i))
367      }
368    ))
369    when(ras.io.is_ret && ras.io.out.valid){
370      targetSrc(retIdx) :=  ras.io.out.bits.target
371    }
372  }
373
374
375  // when (!io.predecode.bits.isFetchpcEqualFirstpc) {
376  //   lastValidPos := PriorityMux(Reverse(inLatch.mask), (PredictWidth-1 to 0 by -1).map(i => i.U)) + 1.U
377  // }
378
379  lastIsRVC := pds(lastValidPos).isRVC
380  when (lastValidPos === 1.U) {
381    lastHit := pdMask(1) |
382      !pdMask(0) & !pdMask(1) |
383      pdMask(0) & !pdMask(1) & (pds(0).isRVC | !io.predecode.bits.isFetchpcEqualFirstpc)
384  }.elsewhen (lastValidPos > 0.U) {
385    lastHit := pdMask(lastValidPos) |
386      !pdMask(lastValidPos - 1.U) & !pdMask(lastValidPos) |
387      pdMask(lastValidPos - 1.U) & !pdMask(lastValidPos) & pds(lastValidPos - 1.U).isRVC
388  }.otherwise {
389    lastHit := pdMask(0) | !pdMask(0) & !pds(0).isRVC
390  }
391
392
393  io.pred.bits.saveHalfRVI := ((lastValidPos === jmpIdx && taken && !(jmpIdx === 0.U && !io.predecode.bits.isFetchpcEqualFirstpc)) || !taken ) && !lastIsRVC && lastHit
394
395  // Wrap tage resp and tage meta in
396  // This is ugly
397  io.out.bits.resp.tage <> io.in.bits.resp.tage
398  io.out.bits.resp.loop <> io.in.bits.resp.loop
399  for (i <- 0 until PredictWidth) {
400    io.out.bits.brInfo(i).tageMeta := io.in.bits.brInfo(i).tageMeta
401    io.out.bits.brInfo(i).specCnt := io.in.bits.brInfo(i).specCnt
402  }
403
404  if (BPUDebug) {
405    XSDebug(io.predecode.valid, "predecode: pc:%x, mask:%b\n", inLatch.pc, io.predecode.bits.mask)
406    for (i <- 0 until PredictWidth) {
407      val p = io.predecode.bits.pd(i)
408      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",
409        i.U, p.brType, p.isBr, p.isJal, p.isJalr, p.isCall, p.isRet, p.isRVC, p.excType)
410    }
411  }
412
413  if (EnbaleCFIPredLog) {
414    val out = io.out
415    XSDebug(out.fire(), p"cfi_pred: fetchpc(${Hexadecimal(out.bits.pc)}) mask(${out.bits.mask}) brmask(${brMask.asUInt}) hist(${Hexadecimal(io.debug_hist)}) histPtr(${io.debug_histPtr})\n")
416  }
417
418  if (EnableBPUTimeRecord) {
419    io.out.bits.brInfo.map(_.debug_tage_cycle := GTimer())
420  }
421}
422
423trait BranchPredictorComponents extends HasXSParameter {
424  val ubtb = Module(new MicroBTB)
425  val btb = Module(new BTB)
426  val bim = Module(new BIM)
427  val tage = (if(EnableBPD) { Module(new Tage) }
428              else          { Module(new FakeTage) })
429  val loop = Module(new LoopPredictor)
430  val preds = Seq(ubtb, btb, bim, tage, loop)
431  preds.map(_.io := DontCare)
432}
433
434class BPUReq extends XSBundle {
435  val pc = UInt(VAddrBits.W)
436  val hist = UInt(HistoryLength.W)
437  val inMask = UInt(PredictWidth.W)
438  val histPtr = UInt(log2Up(ExtHistoryLength).W) // only for debug
439}
440
441class BranchUpdateInfoWithHist extends XSBundle {
442  val ui = new BranchUpdateInfo
443  val hist = UInt(HistoryLength.W)
444}
445
446object BranchUpdateInfoWithHist {
447  def apply (brInfo: BranchUpdateInfo, hist: UInt) = {
448    val b = Wire(new BranchUpdateInfoWithHist)
449    b.ui <> brInfo
450    b.hist := hist
451    b
452  }
453}
454
455abstract class BaseBPU extends XSModule with BranchPredictorComponents with HasBPUParameter{
456  val io = IO(new Bundle() {
457    // from backend
458    val inOrderBrInfo    = Flipped(ValidIO(new BranchUpdateInfoWithHist))
459    val outOfOrderBrInfo = Flipped(ValidIO(new BranchUpdateInfoWithHist))
460    // from ifu, frontend redirect
461    val flush = Input(Vec(3, Bool()))
462    val cacheValid = Input(Bool())
463    // from if1
464    val in = Flipped(ValidIO(new BPUReq))
465    // to if2/if3/if4
466    val out = Vec(3, Decoupled(new BranchPrediction))
467    // from if4
468    val predecode = Flipped(ValidIO(new Predecode))
469    // to if4, some bpu info used for updating
470    val branchInfo = Decoupled(Vec(PredictWidth, new BranchInfo))
471  })
472
473  def npc(pc: UInt, instCount: UInt) = pc + (instCount << 1.U)
474
475  preds.map(_.io.update <> io.outOfOrderBrInfo)
476  tage.io.update <> io.inOrderBrInfo
477
478  val s1 = Module(new BPUStage1)
479  val s2 = Module(new BPUStage2)
480  val s3 = Module(new BPUStage3)
481
482  s1.io.flush := io.flush(0)
483  s2.io.flush := io.flush(1)
484  s3.io.flush := io.flush(2)
485
486  s1.io.in <> DontCare
487  s2.io.in <> s1.io.out
488  s3.io.in <> s2.io.out
489
490  io.out(0) <> s1.io.pred
491  io.out(1) <> s2.io.pred
492  io.out(2) <> s3.io.pred
493
494  s1.io.predecode <> DontCare
495  s2.io.predecode <> DontCare
496  s3.io.predecode <> io.predecode
497
498  io.branchInfo.valid := s3.io.out.valid
499  io.branchInfo.bits := s3.io.out.bits.brInfo
500  s3.io.out.ready := io.branchInfo.ready
501
502  s1.io.recover <> DontCare
503  s2.io.recover <> DontCare
504  s3.io.recover.valid <> io.inOrderBrInfo.valid
505  s3.io.recover.bits <> io.inOrderBrInfo.bits.ui
506
507  s1.io.cacheValid := DontCare
508  s2.io.cacheValid := io.cacheValid
509  s3.io.cacheValid := io.cacheValid
510
511
512  if (BPUDebug) {
513    XSDebug(io.branchInfo.fire(), "branchInfo sent!\n")
514    for (i <- 0 until PredictWidth) {
515      val b = io.branchInfo.bits(i)
516      XSDebug(io.branchInfo.fire(), "brInfo(%d): ubtbWrWay:%d, ubtbHit:%d, btbWrWay:%d, btbHitJal:%d, bimCtr:%d, fetchIdx:%d\n",
517        i.U, b.ubtbWriteWay, b.ubtbHits, b.btbWriteWay, b.btbHitJal, b.bimCtr, b.fetchIdx)
518      val t = b.tageMeta
519      XSDebug(io.branchInfo.fire(), "  tageMeta: pvder(%d):%d, altDiffers:%d, pvderU:%d, pvderCtr:%d, allocate(%d):%d\n",
520        t.provider.valid, t.provider.bits, t.altDiffers, t.providerU, t.providerCtr, t.allocate.valid, t.allocate.bits)
521    }
522  }
523  val debug_verbose = false
524}
525
526
527class FakeBPU extends BaseBPU {
528  io.out.foreach(i => {
529    // Provide not takens
530    i.valid := true.B
531    i.bits <> DontCare
532    i.bits.redirect := false.B
533  })
534  io.branchInfo <> DontCare
535}
536
537class BPU extends BaseBPU {
538
539  //**********************Stage 1****************************//
540  val s1_fire = s1.io.in.fire()
541  val s1_resp_in = Wire(new PredictorResponse)
542  val s1_brInfo_in = Wire(Vec(PredictWidth, new BranchInfo))
543
544  s1_resp_in.tage := DontCare
545  s1_resp_in.loop := DontCare
546  s1_brInfo_in    := DontCare
547  (0 until PredictWidth).foreach(i => s1_brInfo_in(i).fetchIdx := i.U)
548
549  val s1_inLatch = RegEnable(io.in, s1_fire)
550  ubtb.io.flush := io.flush(0) // TODO: fix this
551  ubtb.io.pc.valid := s1_inLatch.valid
552  ubtb.io.pc.bits := s1_inLatch.bits.pc
553  ubtb.io.inMask := s1_inLatch.bits.inMask
554
555
556
557  // Wrap ubtb response into resp_in and brInfo_in
558  s1_resp_in.ubtb <> ubtb.io.out
559  for (i <- 0 until PredictWidth) {
560    s1_brInfo_in(i).ubtbWriteWay := ubtb.io.uBTBBranchInfo.writeWay(i)
561    s1_brInfo_in(i).ubtbHits := ubtb.io.uBTBBranchInfo.hits(i)
562  }
563
564  btb.io.flush := io.flush(0) // TODO: fix this
565  btb.io.pc.valid := io.in.valid
566  btb.io.pc.bits := io.in.bits.pc
567  btb.io.inMask := io.in.bits.inMask
568
569
570
571  // Wrap btb response into resp_in and brInfo_in
572  s1_resp_in.btb <> btb.io.resp
573  for (i <- 0 until PredictWidth) {
574    s1_brInfo_in(i).btbWriteWay := btb.io.meta.writeWay(i)
575    s1_brInfo_in(i).btbHitJal   := btb.io.meta.hitJal(i)
576  }
577
578  bim.io.flush := io.flush(0) // TODO: fix this
579  bim.io.pc.valid := io.in.valid
580  bim.io.pc.bits := io.in.bits.pc
581  bim.io.inMask := io.in.bits.inMask
582
583
584  // Wrap bim response into resp_in and brInfo_in
585  s1_resp_in.bim <> bim.io.resp
586  for (i <- 0 until PredictWidth) {
587    s1_brInfo_in(i).bimCtr := bim.io.meta.ctrs(i)
588  }
589
590
591  s1.io.in.valid := io.in.valid
592  s1.io.in.bits.pc := io.in.bits.pc
593  s1.io.in.bits.mask := io.in.bits.inMask
594  s1.io.in.bits.target := DontCare
595  s1.io.in.bits.resp <> s1_resp_in
596  s1.io.in.bits.brInfo <> s1_brInfo_in
597  s1.io.in.bits.saveHalfRVI := false.B
598
599  val s1_hist = RegEnable(io.in.bits.hist, enable=s1_fire)
600  val s2_hist = RegEnable(s1_hist, enable=s2.io.in.fire())
601  val s3_hist = RegEnable(s2_hist, enable=s3.io.in.fire())
602
603  s1.io.debug_hist := s1_hist
604  s2.io.debug_hist := s2_hist
605  s3.io.debug_hist := s3_hist
606
607  val s1_histPtr = RegEnable(io.in.bits.histPtr, enable=s1_fire)
608  val s2_histPtr = RegEnable(s1_histPtr, enable=s2.io.in.fire())
609  val s3_histPtr = RegEnable(s2_histPtr, enable=s3.io.in.fire())
610
611  s1.io.debug_histPtr := s1_histPtr
612  s2.io.debug_histPtr := s2_histPtr
613  s3.io.debug_histPtr := s3_histPtr
614
615  //**********************Stage 2****************************//
616  tage.io.flush := io.flush(1) // TODO: fix this
617  tage.io.pc.valid := s1.io.out.fire()
618  tage.io.pc.bits := s1.io.out.bits.pc // PC from s1
619  tage.io.hist := s1_hist // The inst is from s1
620  tage.io.inMask := s1.io.out.bits.mask
621  tage.io.s3Fire := s3.io.in.fire() // Tell tage to march 1 stage
622  tage.io.bim <> s1.io.out.bits.resp.bim // Use bim results from s1
623
624  //**********************Stage 3****************************//
625  // Wrap tage response and meta into s3.io.in.bits
626  // This is ugly
627
628  loop.io.flush := io.flush(2)
629  loop.io.pc.valid := s2.io.out.fire()
630  loop.io.pc.bits := s2.io.out.bits.pc
631  loop.io.inMask := s2.io.out.bits.mask
632
633  s3.io.in.bits.resp.tage <> tage.io.resp
634  s3.io.in.bits.resp.loop <> loop.io.resp
635  for (i <- 0 until PredictWidth) {
636    s3.io.in.bits.brInfo(i).tageMeta := tage.io.meta(i)
637    s3.io.in.bits.brInfo(i).specCnt := loop.io.meta.specCnts(i)
638  }
639
640  if (BPUDebug) {
641    if (debug_verbose) {
642      val uo = ubtb.io.out
643      XSDebug("debug: ubtb hits:%b, takens:%b, notTakens:%b\n", uo.hits.asUInt, uo.takens.asUInt, ~uo.takens.asUInt & uo.brMask.asUInt)
644      val bio = bim.io.resp
645      XSDebug("debug: bim takens:%b\n", VecInit(bio.ctrs.map(_(1))).asUInt)
646      val bo = btb.io.resp
647      XSDebug("debug: btb hits:%b\n", bo.hits.asUInt)
648    }
649  }
650
651
652
653  if (EnableCFICommitLog) {
654    val buValid = io.inOrderBrInfo.valid
655    val buinfo  = io.inOrderBrInfo.bits.ui
656    val pd = buinfo.pd
657    val tage_cycle = buinfo.brInfo.debug_tage_cycle
658    XSDebug(buValid, p"cfi_update: isBr(${pd.isBr}) pc(${Hexadecimal(buinfo.pc)}) taken(${buinfo.taken}) mispred(${buinfo.isMisPred}) cycle($tage_cycle) hist(${Hexadecimal(io.inOrderBrInfo.bits.hist)})\n")
659  }
660
661}
662
663object BPU{
664  def apply(enableBPU: Boolean = true) = {
665      if(enableBPU) {
666        val BPU = Module(new BPU)
667        BPU
668      }
669      else {
670        val FakeBPU = Module(new FakeBPU)
671        FakeBPU
672      }
673  }
674}
675