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