xref: /XiangShan/src/main/scala/xiangshan/frontend/BPU.scala (revision a9ecfa67572f9dc8d32a66b8924cfc8e21bbda0c)
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
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.recover := io.recover
334
335    for(i <- 0 until PredictWidth){
336      io.out.bits.brInfo(i).rasSp :=  ras.io.branchInfo.rasSp
337      io.out.bits.brInfo(i).rasTopCtr := ras.io.branchInfo.rasTopCtr
338      io.out.bits.brInfo(i).rasToqAddr := ras.io.branchInfo.rasToqAddr
339    }
340    takens := VecInit((0 until PredictWidth).map(i => {
341      ((brTakens(i) || jalrs(i)) && btbHits(i)) ||
342          jals(i) ||
343          (!ras.io.out.bits.specEmpty && rets(i)) ||
344          (ras.io.out.bits.specEmpty && btbHits(i))
345      }
346    ))
347    when(ras.io.is_ret && ras.io.out.valid){
348      targetSrc(retIdx) :=  ras.io.out.bits.target
349    }
350  }
351
352
353  // when (!io.predecode.bits.isFetchpcEqualFirstpc) {
354  //   lastValidPos := PriorityMux(Reverse(inLatch.mask), (PredictWidth-1 to 0 by -1).map(i => i.U)) + 1.U
355  // }
356
357  lastIsRVC := pds(lastValidPos).isRVC
358  when (lastValidPos === 1.U) {
359    lastHit := pdMask(1) |
360      !pdMask(0) & !pdMask(1) |
361      pdMask(0) & !pdMask(1) & (pds(0).isRVC | !io.predecode.bits.isFetchpcEqualFirstpc)
362  }.elsewhen (lastValidPos > 0.U) {
363    lastHit := pdMask(lastValidPos) |
364      !pdMask(lastValidPos - 1.U) & !pdMask(lastValidPos) |
365      pdMask(lastValidPos - 1.U) & !pdMask(lastValidPos) & pds(lastValidPos - 1.U).isRVC
366  }.otherwise {
367    lastHit := pdMask(0) | !pdMask(0) & !pds(0).isRVC
368  }
369
370
371  io.pred.bits.saveHalfRVI := ((lastValidPos === jmpIdx && taken && !(jmpIdx === 0.U && !io.predecode.bits.isFetchpcEqualFirstpc)) || !taken ) && !lastIsRVC && lastHit
372
373  // Wrap tage resp and tage meta in
374  // This is ugly
375  io.out.bits.resp.tage <> io.in.bits.resp.tage
376  io.out.bits.resp.loop <> io.in.bits.resp.loop
377  for (i <- 0 until PredictWidth) {
378    io.out.bits.brInfo(i).tageMeta := io.in.bits.brInfo(i).tageMeta
379    io.out.bits.brInfo(i).specCnt := io.in.bits.brInfo(i).specCnt
380  }
381
382  if (BPUDebug) {
383    XSDebug(io.predecode.valid, "predecode: pc:%x, mask:%b\n", inLatch.pc, io.predecode.bits.mask)
384    for (i <- 0 until PredictWidth) {
385      val p = io.predecode.bits.pd(i)
386      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",
387        i.U, p.brType, p.isBr, p.isJal, p.isJalr, p.isCall, p.isRet, p.isRVC, p.excType)
388    }
389  }
390
391  if (EnbaleCFIPredLog) {
392    val out = io.out
393    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")
394  }
395
396  if (EnableBPUTimeRecord) {
397    io.out.bits.brInfo.map(_.debug_tage_cycle := GTimer())
398  }
399}
400
401trait BranchPredictorComponents extends HasXSParameter {
402  val ubtb = Module(new MicroBTB)
403  val btb = Module(new BTB)
404  val bim = Module(new BIM)
405  val tage = (if(EnableBPD) { Module(new Tage) }
406              else          { Module(new FakeTage) })
407  val loop = Module(new LoopPredictor)
408  val preds = Seq(ubtb, btb, bim, tage, loop)
409  preds.map(_.io := DontCare)
410}
411
412class BPUReq extends XSBundle {
413  val pc = UInt(VAddrBits.W)
414  val hist = UInt(HistoryLength.W)
415  val inMask = UInt(PredictWidth.W)
416  val histPtr = UInt(log2Up(ExtHistoryLength).W) // only for debug
417}
418
419class BranchUpdateInfoWithHist extends XSBundle {
420  val ui = new BranchUpdateInfo
421  val hist = UInt(HistoryLength.W)
422}
423
424object BranchUpdateInfoWithHist {
425  def apply (brInfo: BranchUpdateInfo, hist: UInt) = {
426    val b = Wire(new BranchUpdateInfoWithHist)
427    b.ui <> brInfo
428    b.hist := hist
429    b
430  }
431}
432
433abstract class BaseBPU extends XSModule with BranchPredictorComponents with HasBPUParameter{
434  val io = IO(new Bundle() {
435    // from backend
436    val inOrderBrInfo    = Flipped(ValidIO(new BranchUpdateInfoWithHist))
437    val outOfOrderBrInfo = Flipped(ValidIO(new BranchUpdateInfoWithHist))
438    // from ifu, frontend redirect
439    val flush = Input(Vec(3, Bool()))
440    val cacheValid = Input(Bool())
441    // from if1
442    val in = Flipped(ValidIO(new BPUReq))
443    // to if2/if3/if4
444    val out = Vec(3, Decoupled(new BranchPrediction))
445    // from if4
446    val predecode = Flipped(ValidIO(new Predecode))
447    // to if4, some bpu info used for updating
448    val branchInfo = Decoupled(Vec(PredictWidth, new BranchInfo))
449  })
450
451  def npc(pc: UInt, instCount: UInt) = pc + (instCount << 1.U)
452
453  preds.map(_.io.update <> io.outOfOrderBrInfo)
454  tage.io.update <> io.inOrderBrInfo
455
456  val s1 = Module(new BPUStage1)
457  val s2 = Module(new BPUStage2)
458  val s3 = Module(new BPUStage3)
459
460  s1.io.flush := io.flush(0)
461  s2.io.flush := io.flush(1)
462  s3.io.flush := io.flush(2)
463
464  s1.io.in <> DontCare
465  s2.io.in <> s1.io.out
466  s3.io.in <> s2.io.out
467
468  io.out(0) <> s1.io.pred
469  io.out(1) <> s2.io.pred
470  io.out(2) <> s3.io.pred
471
472  s1.io.predecode <> DontCare
473  s2.io.predecode <> DontCare
474  s3.io.predecode <> io.predecode
475
476  io.branchInfo.valid := s3.io.out.valid
477  io.branchInfo.bits := s3.io.out.bits.brInfo
478  s3.io.out.ready := io.branchInfo.ready
479
480  s1.io.recover <> DontCare
481  s2.io.recover <> DontCare
482  s3.io.recover.valid <> io.inOrderBrInfo.valid
483  s3.io.recover.bits <> io.inOrderBrInfo.bits.ui
484
485  s1.io.cacheValid := DontCare
486  s2.io.cacheValid := io.cacheValid
487  s3.io.cacheValid := io.cacheValid
488
489
490  if (BPUDebug) {
491    XSDebug(io.branchInfo.fire(), "branchInfo sent!\n")
492    for (i <- 0 until PredictWidth) {
493      val b = io.branchInfo.bits(i)
494      XSDebug(io.branchInfo.fire(), "brInfo(%d): ubtbWrWay:%d, ubtbHit:%d, btbWrWay:%d, btbHitJal:%d, bimCtr:%d, fetchIdx:%d\n",
495        i.U, b.ubtbWriteWay, b.ubtbHits, b.btbWriteWay, b.btbHitJal, b.bimCtr, b.fetchIdx)
496      val t = b.tageMeta
497      XSDebug(io.branchInfo.fire(), "  tageMeta: pvder(%d):%d, altDiffers:%d, pvderU:%d, pvderCtr:%d, allocate(%d):%d\n",
498        t.provider.valid, t.provider.bits, t.altDiffers, t.providerU, t.providerCtr, t.allocate.valid, t.allocate.bits)
499    }
500  }
501  val debug_verbose = false
502}
503
504
505class FakeBPU extends BaseBPU {
506  io.out.foreach(i => {
507    // Provide not takens
508    i.valid := true.B
509    i.bits <> DontCare
510    i.bits.redirect := false.B
511  })
512  io.branchInfo <> DontCare
513}
514
515class BPU extends BaseBPU {
516
517  //**********************Stage 1****************************//
518  val s1_fire = s1.io.in.fire()
519  val s1_resp_in = Wire(new PredictorResponse)
520  val s1_brInfo_in = Wire(Vec(PredictWidth, new BranchInfo))
521
522  s1_resp_in.tage := DontCare
523  s1_resp_in.loop := DontCare
524  s1_brInfo_in    := DontCare
525  (0 until PredictWidth).foreach(i => s1_brInfo_in(i).fetchIdx := i.U)
526
527  val s1_inLatch = RegEnable(io.in, s1_fire)
528  ubtb.io.flush := io.flush(0) // TODO: fix this
529  ubtb.io.pc.valid := s1_inLatch.valid
530  ubtb.io.pc.bits := s1_inLatch.bits.pc
531  ubtb.io.inMask := s1_inLatch.bits.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(i).ubtbWriteWay := ubtb.io.uBTBBranchInfo.writeWay(i)
539    s1_brInfo_in(i).ubtbHits := ubtb.io.uBTBBranchInfo.hits(i)
540  }
541
542  btb.io.flush := io.flush(0) // TODO: fix this
543  btb.io.pc.valid := io.in.valid
544  btb.io.pc.bits := io.in.bits.pc
545  btb.io.inMask := io.in.bits.inMask
546
547
548
549  // Wrap btb response into resp_in and brInfo_in
550  s1_resp_in.btb <> btb.io.resp
551  for (i <- 0 until PredictWidth) {
552    s1_brInfo_in(i).btbWriteWay := btb.io.meta.writeWay(i)
553    s1_brInfo_in(i).btbHitJal   := btb.io.meta.hitJal(i)
554  }
555
556  bim.io.flush := io.flush(0) // TODO: fix this
557  bim.io.pc.valid := io.in.valid
558  bim.io.pc.bits := io.in.bits.pc
559  bim.io.inMask := io.in.bits.inMask
560
561
562  // Wrap bim response into resp_in and brInfo_in
563  s1_resp_in.bim <> bim.io.resp
564  for (i <- 0 until PredictWidth) {
565    s1_brInfo_in(i).bimCtr := bim.io.meta.ctrs(i)
566  }
567
568
569  s1.io.in.valid := io.in.valid
570  s1.io.in.bits.pc := io.in.bits.pc
571  s1.io.in.bits.mask := io.in.bits.inMask
572  s1.io.in.bits.target := npc(io.in.bits.pc, PopCount(io.in.bits.inMask)) // Deault target npc
573  s1.io.in.bits.resp <> s1_resp_in
574  s1.io.in.bits.brInfo <> s1_brInfo_in
575  s1.io.in.bits.saveHalfRVI := false.B
576
577  val s1_hist = RegEnable(io.in.bits.hist, enable=s1_fire)
578  val s2_hist = RegEnable(s1_hist, enable=s2.io.in.fire())
579  val s3_hist = RegEnable(s2_hist, enable=s3.io.in.fire())
580
581  s1.io.debug_hist := s1_hist
582  s2.io.debug_hist := s2_hist
583  s3.io.debug_hist := s3_hist
584
585  val s1_histPtr = RegEnable(io.in.bits.histPtr, enable=s1_fire)
586  val s2_histPtr = RegEnable(s1_histPtr, enable=s2.io.in.fire())
587  val s3_histPtr = RegEnable(s2_histPtr, enable=s3.io.in.fire())
588
589  s1.io.debug_histPtr := s1_histPtr
590  s2.io.debug_histPtr := s2_histPtr
591  s3.io.debug_histPtr := s3_histPtr
592
593  //**********************Stage 2****************************//
594  tage.io.flush := io.flush(1) // TODO: fix this
595  tage.io.pc.valid := s1.io.out.fire()
596  tage.io.pc.bits := s1.io.out.bits.pc // PC from s1
597  tage.io.hist := s1_hist // The inst is from s1
598  tage.io.inMask := s1.io.out.bits.mask
599  tage.io.s3Fire := s3.io.in.fire() // Tell tage to march 1 stage
600  tage.io.bim <> s1.io.out.bits.resp.bim // Use bim results from s1
601
602  //**********************Stage 3****************************//
603  // Wrap tage response and meta into s3.io.in.bits
604  // This is ugly
605
606  loop.io.flush := io.flush(2)
607  loop.io.pc.valid := s2.io.out.fire()
608  loop.io.pc.bits := s2.io.out.bits.pc
609  loop.io.inMask := s2.io.out.bits.mask
610
611  s3.io.in.bits.resp.tage <> tage.io.resp
612  s3.io.in.bits.resp.loop <> loop.io.resp
613  for (i <- 0 until PredictWidth) {
614    s3.io.in.bits.brInfo(i).tageMeta := tage.io.meta(i)
615    s3.io.in.bits.brInfo(i).specCnt := loop.io.meta.specCnts(i)
616  }
617
618  if (BPUDebug) {
619    if (debug_verbose) {
620      val uo = ubtb.io.out
621      XSDebug("debug: ubtb hits:%b, takens:%b, notTakens:%b\n", uo.hits.asUInt, uo.takens.asUInt, ~uo.takens.asUInt & uo.brMask.asUInt)
622      val bio = bim.io.resp
623      XSDebug("debug: bim takens:%b\n", VecInit(bio.ctrs.map(_(1))).asUInt)
624      val bo = btb.io.resp
625      XSDebug("debug: btb hits:%b\n", bo.hits.asUInt)
626    }
627  }
628
629
630
631  if (EnableCFICommitLog) {
632    val buValid = io.inOrderBrInfo.valid
633    val buinfo  = io.inOrderBrInfo.bits.ui
634    val pd = buinfo.pd
635    val tage_cycle = buinfo.brInfo.debug_tage_cycle
636    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")
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