xref: /XiangShan/src/main/scala/xiangshan/frontend/BPU.scala (revision 2fbdb79b0dac3bb7914f7bed10f912a36e5741cb)
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 = false
13  val EnbaleCFIPredLog = false
14  val EnableBPUTimeRecord = false
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  if (BPUDebug) {
258    XSDebug(io.pred.fire(), "outPred using ubtb resp: hits:%b, takens:%b, notTakens:%b, isRVC:%b\n",
259      ubtbResp.hits.asUInt, ubtbResp.takens.asUInt, ~ubtbResp.takens.asUInt & brMask.asUInt, ubtbResp.is_RVC.asUInt)
260  }
261  if (EnableBPUTimeRecord) {
262    io.out.bits.brInfo.map(_.debug_ubtb_cycle := GTimer())
263  }
264}
265
266class BPUStage2 extends BPUStage {
267
268  io.out.valid := predValid && !io.flush && io.cacheValid
269  // Use latched response from s1
270  val btbResp = inLatch.resp.btb
271  val bimResp = inLatch.resp.bim
272  takens    := VecInit((0 until PredictWidth).map(i => btbResp.hits(i) && (btbResp.types(i) === BTBtype.B && bimResp.ctrs(i)(1) || btbResp.types(i) =/= BTBtype.B)))
273  notTakens := VecInit((0 until PredictWidth).map(i => btbResp.hits(i) && btbResp.types(i) === BTBtype.B && !bimResp.ctrs(i)(1)))
274  targetSrc := btbResp.targets
275  brMask := VecInit(btbResp.types.map(_ === BTBtype.B))
276
277  lastIsRVC := btbResp.isRVC(lastValidPos)
278  lastHit   := btbResp.hits(lastValidPos)
279
280
281  if (BPUDebug) {
282    XSDebug(io.pred.fire(), "outPred using btb&bim resp: hits:%b, ctrTakens:%b\n",
283      btbResp.hits.asUInt, VecInit(bimResp.ctrs.map(_(1))).asUInt)
284  }
285  if (EnableBPUTimeRecord) {
286    io.out.bits.brInfo.map(_.debug_btb_cycle := GTimer())
287  }
288}
289
290class BPUStage3 extends BPUStage {
291
292
293  io.out.valid := predValid && io.predecode.valid && !io.flush
294  // TAGE has its own pipelines and the
295  // response comes directly from s3,
296  // so we do not use those from inLatch
297  val tageResp = io.in.bits.resp.tage
298  val tageTakens = tageResp.takens
299  val tageHits   = tageResp.hits
300  val tageValidTakens = VecInit((tageTakens zip tageHits).map{case (t, h) => t && h})
301
302  val loopResp = io.in.bits.resp.loop.exit
303
304  val pdMask = io.predecode.bits.mask
305  val pds    = io.predecode.bits.pd
306
307  val btbHits   = inLatch.resp.btb.hits.asUInt
308  val bimTakens = VecInit(inLatch.resp.bim.ctrs.map(_(1)))
309
310  val brs   = pdMask & Reverse(Cat(pds.map(_.isBr)))
311  val jals  = pdMask & Reverse(Cat(pds.map(_.isJal)))
312  val jalrs = pdMask & Reverse(Cat(pds.map(_.isJalr)))
313  val calls = pdMask & Reverse(Cat(pds.map(_.isCall)))
314  val rets  = pdMask & Reverse(Cat(pds.map(_.isRet)))
315  val RVCs = pdMask & Reverse(Cat(pds.map(_.isRVC)))
316
317   val callIdx = PriorityEncoder(calls)
318   val retIdx  = PriorityEncoder(rets)
319
320  // Use bim results for those who tage does not have an entry for
321  val brTakens = brs &
322    (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))))) &
323    (if (EnableLoop) ~loopResp.asUInt else Fill(PredictWidth, 1.U(1.W)))
324    // if (EnableBPD) {
325    //   brs & Reverse(Cat((0 until PredictWidth).map(i => tageValidTakens(i))))
326    // } else {
327    //   brs & Reverse(Cat((0 until PredictWidth).map(i => bimTakens(i))))
328    // }
329
330  // predict taken only if btb has a target, jal targets will be provided by IFU
331  takens := VecInit((0 until PredictWidth).map(i => (brTakens(i) || jalrs(i)) && btbHits(i) || jals(i)))
332  // Whether should we count in branches that are not recorded in btb?
333  // PS: Currently counted in. Whenever tage does not provide a valid
334  //     taken prediction, the branch is counted as a not taken branch
335  notTakens := ((VecInit((0 until PredictWidth).map(i => brs(i) && !takens(i)))).asUInt |
336               (if (EnableLoop) { VecInit((0 until PredictWidth).map(i => brs(i) && loopResp(i)))}
337                else { WireInit(0.U.asTypeOf(UInt(PredictWidth.W))) }).asUInt).asTypeOf(Vec(PredictWidth, Bool()))
338  targetSrc := inLatch.resp.btb.targets
339  brMask := WireInit(brs.asTypeOf(Vec(PredictWidth, Bool())))
340
341  //RAS
342  if(EnableRAS){
343    val ras = Module(new RAS)
344    ras.io <> DontCare
345    ras.io.pc.bits := inLatch.pc
346    ras.io.pc.valid := io.out.fire()//predValid
347    ras.io.is_ret := rets.orR  && (retIdx === jmpIdx) && io.predecode.valid
348    ras.io.callIdx.valid := calls.orR && (callIdx === jmpIdx) && io.predecode.valid
349    ras.io.callIdx.bits := callIdx
350    ras.io.isRVC := (calls & RVCs).orR   //TODO: this is ugly
351    ras.io.recover := io.recover
352
353    for(i <- 0 until PredictWidth){
354      io.out.bits.brInfo(i).rasSp :=  ras.io.branchInfo.rasSp
355      io.out.bits.brInfo(i).rasTopCtr := ras.io.branchInfo.rasTopCtr
356      io.out.bits.brInfo(i).rasToqAddr := ras.io.branchInfo.rasToqAddr
357    }
358    takens := VecInit((0 until PredictWidth).map(i => (brTakens(i) || jalrs(i)) && btbHits(i) || jals(i)|| rets(i)))
359    when(ras.io.is_ret && ras.io.out.valid){targetSrc(retIdx) :=  ras.io.out.bits.target}
360  }
361
362
363  // when (!io.predecode.bits.isFetchpcEqualFirstpc) {
364  //   lastValidPos := PriorityMux(Reverse(inLatch.mask), (PredictWidth-1 to 0 by -1).map(i => i.U)) + 1.U
365  // }
366
367  lastIsRVC := pds(lastValidPos).isRVC
368  when (lastValidPos === 1.U) {
369    lastHit := pdMask(1) |
370      !pdMask(0) & !pdMask(1) |
371      pdMask(0) & !pdMask(1) & (pds(0).isRVC | !io.predecode.bits.isFetchpcEqualFirstpc)
372  }.elsewhen (lastValidPos > 0.U) {
373    lastHit := pdMask(lastValidPos) |
374      !pdMask(lastValidPos - 1.U) & !pdMask(lastValidPos) |
375      pdMask(lastValidPos - 1.U) & !pdMask(lastValidPos) & pds(lastValidPos - 1.U).isRVC
376  }.otherwise {
377    lastHit := pdMask(0) | !pdMask(0) & !pds(0).isRVC
378  }
379
380
381  io.pred.bits.saveHalfRVI := ((lastValidPos === jmpIdx && taken && !(jmpIdx === 0.U && !io.predecode.bits.isFetchpcEqualFirstpc)) || !taken ) && !lastIsRVC && lastHit
382
383  // Wrap tage resp and tage meta in
384  // This is ugly
385  io.out.bits.resp.tage <> io.in.bits.resp.tage
386  io.out.bits.resp.loop <> io.in.bits.resp.loop
387  for (i <- 0 until PredictWidth) {
388    io.out.bits.brInfo(i).tageMeta := io.in.bits.brInfo(i).tageMeta
389    io.out.bits.brInfo(i).specCnt := io.in.bits.brInfo(i).specCnt
390  }
391
392  if (BPUDebug) {
393    XSDebug(io.predecode.valid, "predecode: pc:%x, mask:%b\n", inLatch.pc, io.predecode.bits.mask)
394    for (i <- 0 until PredictWidth) {
395      val p = io.predecode.bits.pd(i)
396      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",
397        i.U, p.brType, p.isBr, p.isJal, p.isJalr, p.isCall, p.isRet, p.isRVC, p.excType)
398    }
399  }
400
401  if (EnbaleCFIPredLog) {
402    val out = io.out
403    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")
404  }
405
406  if (EnableBPUTimeRecord) {
407    io.out.bits.brInfo.map(_.debug_tage_cycle := GTimer())
408  }
409}
410
411trait BranchPredictorComponents extends HasXSParameter {
412  val ubtb = Module(new MicroBTB)
413  val btb = Module(new BTB)
414  val bim = Module(new BIM)
415  val tage = (if(EnableBPD) { Module(new Tage) }
416              else          { Module(new FakeTage) })
417  val loop = Module(new LoopPredictor)
418  val preds = Seq(ubtb, btb, bim, tage, loop)
419  preds.map(_.io := DontCare)
420}
421
422class BPUReq extends XSBundle {
423  val pc = UInt(VAddrBits.W)
424  val hist = UInt(HistoryLength.W)
425  val inMask = UInt(PredictWidth.W)
426  val histPtr = UInt(log2Up(ExtHistoryLength).W) // only for debug
427}
428
429class BranchUpdateInfoWithHist extends XSBundle {
430  val ui = new BranchUpdateInfo
431  val hist = UInt(HistoryLength.W)
432}
433
434object BranchUpdateInfoWithHist {
435  def apply (brInfo: BranchUpdateInfo, hist: UInt) = {
436    val b = Wire(new BranchUpdateInfoWithHist)
437    b.ui <> brInfo
438    b.hist := hist
439    b
440  }
441}
442
443abstract class BaseBPU extends XSModule with BranchPredictorComponents with HasBPUParameter{
444  val io = IO(new Bundle() {
445    // from backend
446    val inOrderBrInfo    = Flipped(ValidIO(new BranchUpdateInfoWithHist))
447    val outOfOrderBrInfo = Flipped(ValidIO(new BranchUpdateInfoWithHist))
448    // from ifu, frontend redirect
449    val flush = Input(Vec(3, Bool()))
450    val cacheValid = Input(Bool())
451    // from if1
452    val in = Flipped(ValidIO(new BPUReq))
453    // to if2/if3/if4
454    val out = Vec(3, Decoupled(new BranchPrediction))
455    // from if4
456    val predecode = Flipped(ValidIO(new Predecode))
457    // to if4, some bpu info used for updating
458    val branchInfo = Decoupled(Vec(PredictWidth, new BranchInfo))
459  })
460
461  def npc(pc: UInt, instCount: UInt) = pc + (instCount << 1.U)
462
463  preds.map(_.io.update <> io.outOfOrderBrInfo)
464  tage.io.update <> io.inOrderBrInfo
465
466  val s1 = Module(new BPUStage1)
467  val s2 = Module(new BPUStage2)
468  val s3 = Module(new BPUStage3)
469
470  s1.io.flush := io.flush(0)
471  s2.io.flush := io.flush(1)
472  s3.io.flush := io.flush(2)
473
474  s1.io.in <> DontCare
475  s2.io.in <> s1.io.out
476  s3.io.in <> s2.io.out
477
478  io.out(0) <> s1.io.pred
479  io.out(1) <> s2.io.pred
480  io.out(2) <> s3.io.pred
481
482  s1.io.predecode <> DontCare
483  s2.io.predecode <> DontCare
484  s3.io.predecode <> io.predecode
485
486  io.branchInfo.valid := s3.io.out.valid
487  io.branchInfo.bits := s3.io.out.bits.brInfo
488  s3.io.out.ready := io.branchInfo.ready
489
490  s1.io.recover <> DontCare
491  s2.io.recover <> DontCare
492  s3.io.recover.valid <> io.inOrderBrInfo.valid
493  s3.io.recover.bits <> io.inOrderBrInfo.bits.ui
494
495  s1.io.cacheValid := DontCare
496  s2.io.cacheValid := io.cacheValid
497  s3.io.cacheValid := io.cacheValid
498
499
500  if (BPUDebug) {
501    XSDebug(io.branchInfo.fire(), "branchInfo sent!\n")
502    for (i <- 0 until PredictWidth) {
503      val b = io.branchInfo.bits(i)
504      XSDebug(io.branchInfo.fire(), "brInfo(%d): ubtbWrWay:%d, ubtbHit:%d, btbWrWay:%d, btbHitJal:%d, bimCtr:%d, fetchIdx:%d\n",
505        i.U, b.ubtbWriteWay, b.ubtbHits, b.btbWriteWay, b.btbHitJal, b.bimCtr, b.fetchIdx)
506      val t = b.tageMeta
507      XSDebug(io.branchInfo.fire(), "  tageMeta: pvder(%d):%d, altDiffers:%d, pvderU:%d, pvderCtr:%d, allocate(%d):%d\n",
508        t.provider.valid, t.provider.bits, t.altDiffers, t.providerU, t.providerCtr, t.allocate.valid, t.allocate.bits)
509    }
510  }
511  val debug_verbose = false
512}
513
514
515class FakeBPU extends BaseBPU {
516  io.out.foreach(i => {
517    // Provide not takens
518    i.valid := true.B
519    i.bits <> DontCare
520    i.bits.redirect := false.B
521  })
522  io.branchInfo <> DontCare
523}
524
525class BPU extends BaseBPU {
526
527  //**********************Stage 1****************************//
528  val s1_fire = s1.io.in.fire()
529  val s1_resp_in = Wire(new PredictorResponse)
530  val s1_brInfo_in = Wire(Vec(PredictWidth, new BranchInfo))
531
532  s1_resp_in.tage := DontCare
533  s1_resp_in.loop := DontCare
534  s1_brInfo_in    := DontCare
535  (0 until PredictWidth).foreach(i => s1_brInfo_in(i).fetchIdx := i.U)
536
537  val s1_inLatch = RegEnable(io.in, s1_fire)
538  ubtb.io.flush := io.flush(0) // TODO: fix this
539  ubtb.io.pc.valid := s1_inLatch.valid
540  ubtb.io.pc.bits := s1_inLatch.bits.pc
541  ubtb.io.inMask := s1_inLatch.bits.inMask
542
543
544
545  // Wrap ubtb response into resp_in and brInfo_in
546  s1_resp_in.ubtb <> ubtb.io.out
547  for (i <- 0 until PredictWidth) {
548    s1_brInfo_in(i).ubtbWriteWay := ubtb.io.uBTBBranchInfo.writeWay(i)
549    s1_brInfo_in(i).ubtbHits := ubtb.io.uBTBBranchInfo.hits(i)
550  }
551
552  btb.io.flush := io.flush(0) // TODO: fix this
553  btb.io.pc.valid := io.in.valid
554  btb.io.pc.bits := io.in.bits.pc
555  btb.io.inMask := io.in.bits.inMask
556
557
558
559  // Wrap btb response into resp_in and brInfo_in
560  s1_resp_in.btb <> btb.io.resp
561  for (i <- 0 until PredictWidth) {
562    s1_brInfo_in(i).btbWriteWay := btb.io.meta.writeWay(i)
563    s1_brInfo_in(i).btbHitJal   := btb.io.meta.hitJal(i)
564  }
565
566  bim.io.flush := io.flush(0) // TODO: fix this
567  bim.io.pc.valid := io.in.valid
568  bim.io.pc.bits := io.in.bits.pc
569  bim.io.inMask := io.in.bits.inMask
570
571
572  // Wrap bim response into resp_in and brInfo_in
573  s1_resp_in.bim <> bim.io.resp
574  for (i <- 0 until PredictWidth) {
575    s1_brInfo_in(i).bimCtr := bim.io.meta.ctrs(i)
576  }
577
578
579  s1.io.in.valid := io.in.valid
580  s1.io.in.bits.pc := io.in.bits.pc
581  s1.io.in.bits.mask := io.in.bits.inMask
582  s1.io.in.bits.target := npc(io.in.bits.pc, PopCount(io.in.bits.inMask)) // Deault target npc
583  s1.io.in.bits.resp <> s1_resp_in
584  s1.io.in.bits.brInfo <> s1_brInfo_in
585  s1.io.in.bits.saveHalfRVI := false.B
586
587  val s1_hist = RegEnable(io.in.bits.hist, enable=s1_fire)
588  val s2_hist = RegEnable(s1_hist, enable=s2.io.in.fire())
589  val s3_hist = RegEnable(s2_hist, enable=s3.io.in.fire())
590
591  s1.io.debug_hist := s1_hist
592  s2.io.debug_hist := s2_hist
593  s3.io.debug_hist := s3_hist
594
595  val s1_histPtr = RegEnable(io.in.bits.histPtr, enable=s1_fire)
596  val s2_histPtr = RegEnable(s1_histPtr, enable=s2.io.in.fire())
597  val s3_histPtr = RegEnable(s2_histPtr, enable=s3.io.in.fire())
598
599  s1.io.debug_histPtr := s1_histPtr
600  s2.io.debug_histPtr := s2_histPtr
601  s3.io.debug_histPtr := s3_histPtr
602
603  //**********************Stage 2****************************//
604  tage.io.flush := io.flush(1) // TODO: fix this
605  tage.io.pc.valid := s1.io.out.fire()
606  tage.io.pc.bits := s1.io.out.bits.pc // PC from s1
607  tage.io.hist := s1_hist // The inst is from s1
608  tage.io.inMask := s1.io.out.bits.mask
609  tage.io.s3Fire := s3.io.in.fire() // Tell tage to march 1 stage
610  tage.io.bim <> s1.io.out.bits.resp.bim // Use bim results from s1
611
612  //**********************Stage 3****************************//
613  // Wrap tage response and meta into s3.io.in.bits
614  // This is ugly
615
616  loop.io.flush := io.flush(2)
617  loop.io.pc.valid := s2.io.out.fire()
618  loop.io.pc.bits := s2.io.out.bits.pc
619  loop.io.inMask := s2.io.out.bits.mask
620
621  s3.io.in.bits.resp.tage <> tage.io.resp
622  s3.io.in.bits.resp.loop <> loop.io.resp
623  for (i <- 0 until PredictWidth) {
624    s3.io.in.bits.brInfo(i).tageMeta := tage.io.meta(i)
625    s3.io.in.bits.brInfo(i).specCnt := loop.io.meta.specCnts(i)
626  }
627
628  if (BPUDebug) {
629    if (debug_verbose) {
630      val uo = ubtb.io.out
631      XSDebug("debug: ubtb hits:%b, takens:%b, notTakens:%b\n", uo.hits.asUInt, uo.takens.asUInt, ~uo.takens.asUInt & uo.brMask.asUInt)
632      val bio = bim.io.resp
633      XSDebug("debug: bim takens:%b\n", VecInit(bio.ctrs.map(_(1))).asUInt)
634      val bo = btb.io.resp
635      XSDebug("debug: btb hits:%b\n", bo.hits.asUInt)
636    }
637  }
638
639
640
641  if (EnableCFICommitLog) {
642    val buValid = io.inOrderBrInfo.valid
643    val buinfo  = io.inOrderBrInfo.bits.ui
644    val pd = buinfo.pd
645    val tage_cycle = buinfo.brInfo.debug_tage_cycle
646    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")
647  }
648
649}
650
651object BPU{
652  def apply(enableBPU: Boolean = true) = {
653      if(enableBPU) {
654        val BPU = Module(new BPU)
655        BPU
656      }
657      else {
658        val FakeBPU = Module(new FakeBPU)
659        FakeBPU
660      }
661  }
662}
663