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