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