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