xref: /XiangShan/src/main/scala/xiangshan/frontend/BPU.scala (revision f95e78ec87f53e4dd7d903ef0fca75af3838cb5e)
1package xiangshan.frontend
2
3import chisel3._
4import chisel3.util._
5import xiangshan._
6import xiangshan.utils._
7import xiangshan.backend.ALUOpType
8import utils._
9
10class TableAddr(val idxBits: Int, val banks: Int) extends XSBundle {
11  def tagBits = VAddrBits - idxBits - 2
12
13  val tag = UInt(tagBits.W)
14  val idx = UInt(idxBits.W)
15  val offset = UInt(2.W)
16
17  def fromUInt(x: UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this)
18  def getTag(x: UInt) = fromUInt(x).tag
19  def getIdx(x: UInt) = fromUInt(x).idx
20  def getBank(x: UInt) = getIdx(x)(log2Up(banks) - 1, 0)
21  def getBankIdx(x: UInt) = getIdx(x)(idxBits - 1, log2Up(banks))
22}
23
24class Stage1To2IO extends XSBundle {
25  val pc = Output(UInt(VAddrBits.W))
26  val btb = new Bundle {
27    val hits = Output(UInt(FetchWidth.W))
28    val targets = Output(Vec(FetchWidth, UInt(VAddrBits.W)))
29  }
30  val jbtac = new Bundle {
31    val hitIdx = Output(UInt(FetchWidth.W))
32    val target = Output(UInt(VAddrBits.W))
33  }
34  val tage = new Bundle {
35    val hits = Output(UInt(FetchWidth.W))
36    val takens = Output(Vec(FetchWidth, Bool()))
37  }
38  val hist = Output(Vec(FetchWidth, UInt(HistoryLength.W)))
39  val btbPred = ValidIO(new BranchPrediction)
40}
41
42class BPUStage1 extends XSModule {
43  val io = IO(new Bundle() {
44    val in = new Bundle { val pc = Flipped(Decoupled(UInt(VAddrBits.W))) }
45    // from backend
46    val redirectInfo = Flipped(new RedirectInfo)
47    // from Stage3
48    val flush = Input(Bool())
49    val s3RollBackHist = Input(UInt(HistoryLength.W))
50    val s3Taken = Input(Bool())
51    // to ifu, quick prediction result
52    val s1OutPred = ValidIO(new BranchPrediction)
53    // to Stage2
54    val out = Decoupled(new Stage1To2IO)
55  })
56
57  // flush Stage1 when io.flush
58  val flushS1 = BoolStopWatch(io.flush, io.in.pc.fire(), startHighPriority = true)
59
60  // global history register
61  val ghr = RegInit(0.U(HistoryLength.W))
62  // modify updateGhr and newGhr when updating ghr
63  val updateGhr = WireInit(false.B)
64  val newGhr = WireInit(0.U(HistoryLength.W))
65  when (updateGhr) { ghr := newGhr }
66  // use hist as global history!!!
67  val hist = Mux(updateGhr, newGhr, ghr)
68
69  // Tage predictor
70  val tage = Module(new Tage)
71  tage.io.req.valid := io.in.pc.fire()
72  tage.io.req.bits.pc := io.in.pc.bits
73  tage.io.req.bits.hist := hist
74  tage.io.redirectInfo <> io.redirectInfo
75  io.out.bits.tage <> tage.io.out
76  io.s1OutPred.bits.tageMeta := tage.io.meta
77
78  // BTB
79  val btbAddr = new TableAddr(log2Up(BtbSets), BtbBanks)
80  val predictWidth = FetchWidth
81  def btbDataEntry() = new Bundle {
82    val valid = Bool()
83    val target = UInt(VAddrBits.W)
84    val pred = UInt(2.W) // 2-bit saturated counter as a quick predictor
85    val _type = UInt(2.W)
86    val offset = UInt(offsetBits().W) // Could be zero
87
88    def offsetBits() = log2Up(FetchWidth / predictWidth)
89  }
90  def btbMetaEntry() = new Bundle {
91    val valid = Bool()
92    // TODO: don't need full length of tag
93    val tag = UInt(btbAddr.tagBits.W)
94  }
95
96  val btbMeta = List.fill(BtbWays)(List.fill(BtbBanks)(
97    Module(new SRAMTemplate(btbMetaEntry(), set = BtbSets / BtbBanks, way = 1, shouldReset = true, holdRead = true))
98  ))
99  val btbData = List.fill(BtbWays)(List.fill(BtbBanks)(
100    Module(new SRAMTemplate(btbDataEntry(), set = BtbSets / BtbBanks, way = predictWidth, shouldReset = true, holdRead = true))
101  ))
102
103  // BTB read requests
104  // read addr comes from pc[6:2]
105  // read 4 ways in parallel
106  (0 until BtbWays).map(
107    w => (0 until BtbBanks).map(
108      b => {
109        btbMeta(w)(b).reset := reset.asBool
110        btbMeta(w)(b).io.r.req.valid := io.in.pc.fire() && b.U === btbAddr.getBank(io.in.pc.bits)
111        btbMeta(w)(b).io.r.req.bits.setIdx := btbAddr.getBankIdx(io.in.pc.bits)
112        btbData(w)(b).reset := reset.asBool
113        btbData(w)(b).io.r.req.valid := io.in.pc.fire() && b.U === btbAddr.getBank(io.in.pc.bits)
114        btbData(w)(b).io.r.req.bits.setIdx := btbAddr.getBankIdx(io.in.pc.bits)
115      }
116    )
117  )
118
119  // latch pc for 1 cycle latency when reading SRAM
120  val pcLatch = RegEnable(io.in.pc.bits, io.in.pc.fire())
121  // Entries read from SRAM
122  val btbMetaRead = Wire(Vec(BtbWays, btbMetaEntry()))
123  val btbDataRead = Wire(Vec(BtbWays, Vec(predictWidth, btbDataEntry())))
124  val btbReadFire = Wire(Vec(BtbWays, Vec(BtbBanks, Bool())))
125  // 1/4 hit
126  val btbWayHits = Wire(Vec(BtbWays, Bool()))
127
128  // #(predictWidth) results
129  val btbTargets = Wire(Vec(predictWidth, UInt(VAddrBits.W)))
130  val btbTypes = Wire(Vec(predictWidth, UInt(2.W)))
131  // val btbPreds = Wire(Vec(FetchWidth, UInt(2.W)))
132  val btbCtrs = Wire(Vec(predictWidth, UInt(2.W)))
133  val btbTakens = Wire(Vec(predictWidth, Bool()))
134  val btbValids = Wire(Vec(predictWidth, Bool()))
135
136  val btbHitWay = Wire(UInt(log2Up(BtbWays).W))
137  val btbHitBank = btbAddr.getBank(pcLatch)
138
139  (0 until BtbWays).map(
140    w => {
141      btbMetaRead(w) := btbMeta(w)(btbHitBank).io.r.resp.data(0)
142      (0 until predictWidth).map(i => btbDataRead(w)(i) := btbData(w)(btbHitBank).io.r.resp.data(i))
143    }
144  )
145
146  btbWayHits := 0.U.asTypeOf(Vec(BtbWays, Bool()))
147  btbValids := 0.U.asTypeOf(Vec(predictWidth, Bool()))
148  btbTargets := DontCare
149  btbCtrs := DontCare
150  btbTakens := DontCare
151  btbTypes := DontCare
152  for (w <- 0 until BtbWays) {
153    for (b <- 0 until BtbBanks) { btbReadFire(w)(b) := btbMeta(w)(b).io.r.req.fire() && btbData(w)(b).io.r.req.fire() }
154    when (btbMetaRead(w).valid && btbMetaRead(w).tag === btbAddr.getTag(pcLatch)) {
155      btbWayHits(w) := !flushS1 && RegNext(btbReadFire(w)(btbHitBank), init = false.B)
156      for (i <- until predictWidth) {
157        btbValids(i) := btbDataRead(w)(i).valid
158        btbTargets(i) := btbDataRead(w)(i).target
159        btbCtrs(i) := btbDataRead(w)(i).pred
160        btbTakens(i) := (btbDataRead(w)(i).pred)(1).asBool
161        btbTypes(i) := btbDataRead(w)(i)._type
162      }
163    }
164  }
165
166  val btbHit = btbWayHits.reduce(_|_)
167  btbHitWay := OHToUInt(HighestBit(btbWayHits.asUInt, BtbWays))
168
169  // Priority mux which corresponds with inst orders
170  // BTB only produce one single prediction
171  val btbJumps = Wire(Vec(predictWidth, Bool()))
172  (0 until predictWidth).map(i => btbJumps(i) := btbValids(i) && (btbTypes(i) === BTBtype.J || btbTypes(i) === BTBtype.B && btbTakens(i)))
173  val btbTakenTarget = MuxCase(0.U, btbJumps zip btbTargets)
174  val btbTakenType   = MuxCase(0.U, btbJumps zip btbTypes)
175  val btbTaken       = btbJumps.reduce(_|_)
176  // Record which inst is predicted taken
177  val btbTakenIdx = MuxCase(0.U, btbJumps zip (0 until predictWidth).map(_.U))
178
179  // JBTAC, divided into 8 banks, makes prediction for indirect jump except ret.
180  val jbtacAddr = new TableAddr(log2Up(JbtacSize), JbtacBanks)
181  def jbtacEntry() = new Bundle {
182    val valid = Bool()
183    // TODO: don't need full length of tag and target
184    val tag = UInt(jbtacAddr.tagBits.W)
185    val target = UInt(VAddrBits.W)
186    val offset = UInt(log2Up(FetchWidth).W)
187  }
188
189  val jbtac = List.fill(JbtacBanks)(Module(new SRAMTemplate(jbtacEntry(), set = JbtacSize / JbtacBanks, shouldReset = true, holdRead = true, singlePort = false)))
190
191  val jbtacRead = Wire(Vec(JbtacBanks, jbtacEntry()))
192
193  val jbtacFire = Reg(Vec(JbtacBanks, Bool()))
194  // Only read one bank
195  val histXORAddr = io.in.pc.bits ^ Cat(hist, 0.U(2.W))(VAddrBits - 1, 0)
196  val histXORAddrLatch = RegEnable(histXORAddr, io.in.pc.valid)
197  jbtacFire := 0.U.asTypeOf(Vec(JbtacBanks, Bool()))
198  (0 until JbtacBanks).map(
199    b => {
200      jbtac(b).reset := reset.asBool
201      jbtac(b).io.r.req.valid := io.in.pc.fire() && b.U === jbtacAddr.getBank(histXORAddr)
202      jbtac(b).io.r.req.bits.setIdx := jbtacAddr.getBankIdx(histXORAddr)
203      jbtacFire(b) := jbtac(b).io.r.req.fire()
204      jbtacRead(b) := jbtac(b).io.r.resp.data(0)
205    }
206  )
207
208  val jbtacBank = jbtacAddr.getBank(histXORAddrLatch)
209  val jbtacHit = jbtacRead(jbtacBank).valid && jbtacRead(jbtacBank).tag === jbtacAddr.getTag(pcLatch) && !flushS1 && jbtacFire(jbtacBank)
210  val jbtacHitIdx = jbtacRead(jbtacBank).offset
211  val jbtacTarget = jbtacRead(jbtacBank).target
212
213  // choose one way as victim way
214  val btbWayInvalids = Cat(btbMetaRead.map(e => !e.valid)).asUInt
215  val victim = Mux(btbHit, btbHitWay, Mux(btbWayInvalids.orR, OHToUInt(LowestBit(btbWayInvalids)), LFSR64()(log2Up(BtbWays) - 1, 0)))
216
217  // calculate global history of each instr
218  val firstHist = RegNext(hist)
219  val histShift = Wire(Vec(FetchWidth, UInt(log2Up(FetchWidth).W)))
220  val btbNotTakens = Wire(Vec(FetchWidth, Bool()))
221  (0 until FetchWidth).map(i => btbNotTakens(i) := btbValids(i) && btbTypes(i) === BTBtype.B && !btbCtrs(1))
222  val shift = Wire(Vec(FetchWidth, Vec(FetchWidth, UInt(1.W))))
223  (0 until FetchWidth).map(i => shift(i) := Mux(!btbNotTakens(i), 0.U, ~LowerMask(UIntToOH(i.U), FetchWidth)).asTypeOf(Vec(FetchWidth, UInt(1.W))))
224  for (j <- 0 until FetchWidth) {
225    var tmp = 0.U
226    for (i <- 0 until FetchWidth) {
227      tmp = tmp + shift(i)(j)
228    }
229    histShift(j) := tmp
230  }
231  (0 until FetchWidth).map(i => io.s1OutPred.bits.hist(i) := firstHist << histShift(i))
232
233  // update btb, jbtac, ghr
234  val r = io.RedirectInfo.redirect
235  val updateFetchpc = r.pc - r.fetchIdx << 2.U
236  val updateMisPred = io.RedirectInfo.misPred
237  val updateFetchIdx = r.fetchIdx
238  val updateVictimWay = r.btbVictimWay
239  val updateOldCtr = r.btbPredCtr
240  // 1. update btb
241  // 1.1 calculate new 2-bit saturated counter value
242  val newPredCtr = Mux(!r.btbHitWay, "b01".U, Mux(r.taken, Mux(updateOldCtr === "b11".U, "b11".U, updateOldCtr + 1.U),
243                                                           Mux(updateOldCtr === "b00".U, "b00".U, updateOldCtr - 1.U)))
244  // 1.2 write btb
245  val updateBank = btbAddr.getBank(updateFetchpc)
246  val updateBankIdx = btbAddr.getBankIdx(updateFetchpc)
247  val updateWaymask = UIntToOH(updateFetchIdx)
248  val btbMetaWrite = Wire(btbMetaEntry())
249  btbMetaWrite.valid := true.B
250  btbMetaWrite.tag := btbAddr.getTag(updateFetchpc)
251  val btbDataWrite = Wire(btbDataEntry())
252  btbDataWrite.valid := true.B
253  btbDataWrite.target := r.brTarget
254  btbDataWrite.pred := newPredCtr
255  btbDataWrite._type := r._type
256  btbDataWrite.offset := DontCare
257  val btbWriteValid = io.redirectInfo.valid && (r._type === BTBtype.B || r._type === BTBtype.J)
258
259  for (w <- 0 until BtbWays) {
260    for (b <- 0 until BtbBanks) {
261      when (b.U === updateBank && w.U === updateVictimWay) {
262        btbMeta(w)(b).io.w.req.valid := btbWriteValid
263        btbMeta(w)(b).io.w.req.bits.setIdx := updateBankIdx
264        btbMeta(w)(b).io.w.req.bits.data := btbMetaWrite
265        btbData(w)(b).io.w.req.valid := btbWriteValid
266        btbData(w)(b).io.w.req.bits.setIdx := updateBankIdx
267        btbData(w)(b).io.w.req.bits.waymask := updateWaymask
268        btbData(w)(b).io.w.req.bits.data := btbDataWrite
269      }.otherwise {
270        btbMeta(w)(b).io.w.req.valid := false.B
271        btbData(w)(b).io.w.req.valid := false.B
272      }
273    }
274  }
275
276  // 2. update jbtac
277  val jbtacWrite = Wire(jbtacEntry())
278  val updateHistXORAddr = updateFetchpc ^ Cat(r.hist, 0.U(2.W))(VAddrBits - 1, 0)
279  jbtacWrite.valid := true.B
280  jbtacWrite.tag := jbtacAddr.getTag(updateFetchpc)
281  jbtacWrite.target := r.target
282  jbtacWrite.offset := updateFetchIdx
283  for (b <- 0 until JbtacBanks) {
284    when (b.U === jbtacAddr.getBank(updateHistXORAddr)) {
285      jbtac(b).io.w.req.valid := io.redirectInfo.valid && updateMisPred && r._type === BTBtype.I
286      jbtac(b).io.w.req.bits.setIdx := jbtacAddr.getBankIdx(updateHistXORAddr)
287      jbtac(b).io.w.req.bits.data := jbtacWrite
288    }
289  }
290
291  // 3. update ghr
292  updateGhr := io.s1OutPred.bits.redirect || io.flush
293  val brJumpIdx = Mux(!(btbHit && btbTaken), 0.U, UIntToOH(btbTakenIdx))
294  val indirectIdx = Mux(!jbtacHit, 0.U, UIntToOH(jbtacHitIdx))
295  //val newTaken = Mux(io.redirectInfo.flush(), !(r._type === BTBtype.B && !r.taken), )
296  newGhr := Mux(io.redirectInfo.flush(),    (r.hist << 1.U) | !(r._type === BTBtype.B && !r.taken),
297            Mux(io.flush,                   Mux(io.s3Taken, io.s3RollBackHist << 1.U | 1.U, io.s3RollBackHist),
298            Mux(io.s1OutPred.bits.redirect, PriorityMux(brJumpIdx | indirectIdx, io.s1OutPred.bits.hist) << 1.U | 1.U,
299                                            io.s1OutPred.bits.hist(0) << PopCount(btbNotTakens))))
300
301  // redirect based on BTB and JBTAC
302  io.out.valid := RegNext(io.in.pc.fire()) && !flushS1
303
304  io.s1OutPred.valid := io.out.valid
305  io.s1OutPred.bits.redirect := btbHit && btbTaken || jbtacHit
306  // io.s1OutPred.bits.instrValid := LowerMask(UIntToOH(btbTakenIdx), FetchWidth) & LowerMask(UIntToOH(jbtacHitIdx), FetchWidth)
307  io.s1OutPred.bits.instrValid := Mux(io.s1OutPred.bits.redirect, LowerMask(LowestBit(brJumpIdx | indirectIdx)), Fill(FetchWidth, 1.U(1.W))).asTypeOf(Vec(FetchWidth, Bool()))
308  io.s1OutPred.bits.target := Mux(brJumpIdx === LowestBit(brJumpIdx | indirectIdx), btbTakenTarget, jbtacTarget)
309  io.s1OutPred.bits.btbVictimWay := victim
310  io.s1OutPred.bits.predCtr := btbCtrs
311  io.s1OutPred.bits.btbHitWay := btbHit
312  io.s1OutPred.bits.rasSp := DontCare
313  io.s1OutPred.bits.rasTopCtr := DontCare
314
315  io.out.bits.pc := pcLatch
316  io.out.bits.btb.hits := btbValids.asUInt
317  (0 until FetchWidth).map(i => io.out.bits.btb.targets(i) := btbTargets(i))
318  io.out.bits.jbtac.hitIdx := UIntToOH(jbtacHitIdx)
319  io.out.bits.jbtac.target := jbtacTarget
320  // TODO: we don't need this repeatedly!
321  io.out.bits.hist := io.s1OutPred.bits.hist
322  io.out.bits.btbPred := io.s1OutPred
323
324  io.in.pc.ready := true.B
325
326}
327
328class Stage2To3IO extends Stage1To2IO {
329}
330
331class BPUStage2 extends XSModule {
332  val io = IO(new Bundle() {
333    // flush from Stage3
334    val flush = Input(Bool())
335    val in = Flipped(Decoupled(new Stage1To2IO))
336    val out = Decoupled(new Stage2To3IO)
337  })
338
339  // flush Stage2 when Stage3 or banckend redirects
340  val flushS2 = BoolStopWatch(io.flush, io.in.fire(), startHighPriority = true)
341  io.out.valid := !flushS2 && RegNext(io.in.fire())
342  io.in.ready := !io.out.valid || io.out.fire()
343
344  // do nothing
345  io.out.bits := RegEnable(io.in.bits, io.in.fire())
346}
347
348class BPUStage3 extends XSModule {
349  val io = IO(new Bundle() {
350    val flush = Input(Bool())
351    val in = Flipped(Decoupled(new Stage2To3IO))
352    val out = ValidIO(new BranchPrediction)
353    // from icache
354    val predecode = Flipped(ValidIO(new Predecode))
355    // from backend
356    val redirectInfo = Flipped(new RedirectInfo)
357    // to Stage1 and Stage2
358    val flushBPU = Output(Bool())
359    // to Stage1, restore ghr in stage1 when flushBPU is valid
360    val s1RollBackHist = Output(UInt(HistoryLength.W))
361    val s3Taken = Output(Bool())
362  })
363
364  val flushS3 = BoolStopWatch(io.flush, io.in.fire(), startHighPriority = true)
365  val inLatch = RegInit(0.U.asTypeOf(io.in.bits))
366  val validLatch = RegInit(false.B)
367  when (io.in.fire()) { inLatch := io.in.bits }
368  when (io.in.fire()) {
369    validLatch := !io.flush
370  }.elsewhen (io.out.valid) {
371    validLatch := false.B
372  }
373  io.out.valid := validLatch && io.predecode.valid && !flushS3
374  io.in.ready := !validLatch || io.out.valid
375
376  // RAS
377  // TODO: split retAddr and ctr
378  def rasEntry() = new Bundle {
379    val retAddr = UInt(VAddrBits.W)
380    val ctr = UInt(8.W) // layer of nested call functions
381  }
382  val ras = RegInit(VecInit(Seq.fill(RasSize)(0.U.asTypeOf(rasEntry()))))
383  val sp = Counter(RasSize)
384  val rasTop = ras(sp.value)
385  val rasTopAddr = rasTop.retAddr
386
387  // get the first taken branch/jal/call/jalr/ret in a fetch line
388  // brTakenIdx/jalIdx/callIdx/jalrIdx/retIdx/jmpIdx is one-hot encoded.
389  // brNotTakenIdx indicates all the not-taken branches before the first jump instruction.
390  val brIdx = inLatch.btb.hits & Cat(io.predecode.bits.fuTypes.map { t => ALUOpType.isBranch(t) }).asUInt & io.predecode.bits.mask
391  val brTakenIdx = LowestBit(brIdx & inLatch.tage.takens.asUInt, FetchWidth)
392  val jalIdx = LowestBit(inLatch.btb.hits & Cat(io.predecode.bits.fuTypes.map { t => t === ALUOpType.jal }).asUInt & io.predecode.bits.mask, FetchWidth)
393  val callIdx = LowestBit(inLatch.btb.hits & io.predecode.bits.mask & Cat(io.predecode.bits.fuTypes.map { t => t === ALUOpType.call }).asUInt, FetchWidth)
394  val jalrIdx = LowestBit(inLatch.jbtac.hitIdx & io.predecode.bits.mask & Cat(io.predecode.bits.fuTypes.map { t => t === ALUOpType.jalr }).asUInt, FetchWidth)
395  val retIdx = LowestBit(io.predecode.bits.mask & Cat(io.predecode.bits.fuTypes.map { t => t === ALUOpType.ret }).asUInt, FetchWidth)
396
397  val jmpIdx = LowestBit(brTakenIdx | jalIdx | callIdx | jalrIdx | retIdx, FetchWidth)
398  val brNotTakenIdx = brIdx & ~inLatch.tage.takens.asUInt & LowerMask(jmpIdx, FetchWidth)
399
400  io.out.bits.redirect := jmpIdx.orR.asBool
401  io.out.bits.target := Mux(jmpIdx === retIdx, rasTopAddr,
402    Mux(jmpIdx === jalrIdx, inLatch.jbtac.target,
403    Mux(jmpIdx === 0.U, inLatch.pc + 32.U, // TODO: RVC
404    PriorityMux(jmpIdx, inLatch.btb.targets))))
405  io.out.bits.instrValid := Mux(jmpIdx.orR, LowerMask(jmpIdx, FetchWidth).asTypeOf(Vec(FetchWidth, Bool())), Fill(FetchWidth, 1.U(1.W))).asTypeOf(Vec(FetchWidth, Bool()))
406  io.out.bits.btbVictimWay := inLatch.btbPred.bits.btbVictimWay
407  io.out.bits.predCtr := inLatch.btbPred.bits.predCtr
408  io.out.bits.btbHitWay := inLatch.btbPred.bits.btbHitWay
409  io.out.bits.tageMeta := inLatch.btbPred.bits.tageMeta
410  //io.out.bits._type := Mux(jmpIdx === retIdx, BTBtype.R,
411  //  Mux(jmpIdx === jalrIdx, BTBtype.I,
412  //  Mux(jmpIdx === brTakenIdx, BTBtype.B, BTBtype.J)))
413  val firstHist = inLatch.btbPred.bits.hist(0)
414  // there may be several notTaken branches before the first jump instruction,
415  // so we need to calculate how many zeroes should each instruction shift in its global history.
416  // each history is exclusive of instruction's own jump direction.
417  val histShift = Wire(Vec(FetchWidth, UInt(log2Up(FetchWidth).W)))
418  val shift = Wire(Vec(FetchWidth, Vec(FetchWidth, UInt(1.W))))
419  (0 until FetchWidth).map(i => shift(i) := Mux(!brNotTakenIdx(i), 0.U, ~LowerMask(UIntToOH(i.U), FetchWidth)).asTypeOf(Vec(FetchWidth, UInt(1.W))))
420  for (j <- 0 until FetchWidth) {
421    var tmp = 0.U
422    for (i <- 0 until FetchWidth) {
423      tmp = tmp + shift(i)(j)
424    }
425    histShift(j) := tmp
426  }
427  (0 until FetchWidth).map(i => io.out.bits.hist(i) := firstHist << histShift(i))
428  // save ras checkpoint info
429  io.out.bits.rasSp := sp.value
430  io.out.bits.rasTopCtr := rasTop.ctr
431
432  // flush BPU and redirect when target differs from the target predicted in Stage1
433  io.out.bits.redirect := !inLatch.btbPred.bits.redirect ^ jmpIdx.orR.asBool ||
434    inLatch.btbPred.bits.redirect && jmpIdx.orR.asBool && io.out.bits.target =/= inLatch.btbPred.bits.target
435  io.flushBPU := io.out.bits.redirect && io.out.valid
436
437  // speculative update RAS
438  val rasWrite = WireInit(0.U.asTypeOf(rasEntry()))
439  rasWrite.retAddr := inLatch.pc + OHToUInt(callIdx) << 2.U + 4.U
440  val allocNewEntry = rasWrite.retAddr =/= rasTopAddr
441  rasWrite.ctr := Mux(allocNewEntry, 1.U, rasTop.ctr + 1.U)
442  when (io.out.valid) {
443    when (jmpIdx === callIdx) {
444      ras(Mux(allocNewEntry, sp.value + 1.U, sp.value)) := rasWrite
445      when (allocNewEntry) { sp.value := sp.value + 1.U }
446    }.elsewhen (jmpIdx === retIdx) {
447      when (rasTop.ctr === 1.U) {
448        sp.value := Mux(sp.value === 0.U, 0.U, sp.value - 1.U)
449      }.otherwise {
450        ras(sp.value) := Cat(rasTop.ctr - 1.U, rasTopAddr).asTypeOf(rasEntry())
451      }
452    }
453  }
454  // use checkpoint to recover RAS
455  val recoverSp = io.redirectInfo.redirect.rasSp
456  val recoverCtr = io.redirectInfo.redirect.rasTopCtr
457  when (io.redirectInfo.valid && io.redirectInfo.misPred) {
458    sp.value := recoverSp
459    ras(recoverSp) := Cat(recoverCtr, ras(recoverSp).retAddr).asTypeOf(rasEntry())
460  }
461
462  // roll back global history in S1 if S3 redirects
463  io.s1RollBackHist := Mux(io.s3Taken, PriorityMux(jmpIdx, io.out.bits.hist), io.out.bits.hist(0) << PopCount(brIdx & ~inLatch.tage.takens.asUInt))
464  // whether Stage3 has a taken jump
465  io.s3Taken := jmpIdx.orR.asBool
466}
467
468class BPU extends XSModule {
469  val io = IO(new Bundle() {
470    // from backend
471    // flush pipeline if misPred and update bpu based on redirect signals from brq
472    val redirectInfo = Flipped(new RedirectInfo)
473
474    val in = new Bundle { val pc = Flipped(Valid(UInt(VAddrBits.W))) }
475
476    val btbOut = ValidIO(new BranchPrediction)
477    val tageOut = ValidIO(new BranchPrediction)
478
479    // predecode info from icache
480    // TODO: simplify this after implement predecode unit
481    val predecode = Flipped(ValidIO(new Predecode))
482  })
483
484  val s1 = Module(new BPUStage1)
485  val s2 = Module(new BPUStage2)
486  val s3 = Module(new BPUStage3)
487
488  s1.io.redirectInfo <> io.redirectInfo
489  s1.io.flush := s3.io.flushBPU || io.redirectInfo.flush()
490  s1.io.in.pc.valid := io.in.pc.valid
491  s1.io.in.pc.bits <> io.in.pc.bits
492  io.btbOut <> s1.io.s1OutPred
493  s1.io.s3RollBackHist := s3.io.s1RollBackHist
494  s1.io.s3Taken := s3.io.s3Taken
495
496  s1.io.out <> s2.io.in
497  s2.io.flush := s3.io.flushBPU || io.redirectInfo.flush()
498
499  s2.io.out <> s3.io.in
500  s3.io.flush := io.redirectInfo.flush()
501  s3.io.predecode <> io.predecode
502  io.tageOut <> s3.io.out
503  s3.io.redirectInfo <> io.redirectInfo
504}