xref: /XiangShan/src/main/scala/xiangshan/frontend/BPU.scala (revision a996520a06b1fafcb50b31098442f625a33d052b)
1package xiangshan.frontend
2
3import chisel3._
4import chisel3.util._
5import utils._
6import xiangshan._
7import xiangshan.backend.ALUOpType
8import xiangshan.backend.JumpOpType
9
10class TableAddr(val idxBits: Int, val banks: Int) extends XSBundle {
11  def tagBits = VAddrBits - idxBits - 1
12
13  val tag = UInt(tagBits.W)
14  val idx = UInt(idxBits.W)
15  val offset = UInt(1.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(PredictWidth.W))
28    val targets = Output(Vec(PredictWidth, UInt(VAddrBits.W)))
29  }
30  val jbtac = new Bundle {
31    val hitIdx = Output(UInt(PredictWidth.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(PredictWidth, 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 = Input(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  io.in.pc.ready := true.B
58
59  // flush Stage1 when io.flush
60  val flushS1 = BoolStopWatch(io.flush, io.in.pc.fire(), startHighPriority = true)
61  val s1OutPredLatch = RegEnable(io.s1OutPred.bits, RegNext(io.in.pc.fire()))
62  val outLatch = RegEnable(io.out.bits, RegNext(io.in.pc.fire()))
63
64  val s1Valid = RegInit(false.B)
65  when (io.flush) {
66    s1Valid := false.B
67  }.elsewhen (io.in.pc.fire()) {
68    s1Valid := true.B
69  }.elsewhen (io.out.fire()) {
70    s1Valid := false.B
71  }
72  io.out.valid := s1Valid
73
74
75  // global history register
76  val ghr = RegInit(0.U(HistoryLength.W))
77  // modify updateGhr and newGhr when updating ghr
78  val updateGhr = WireInit(false.B)
79  val newGhr = WireInit(0.U(HistoryLength.W))
80  when (updateGhr) { ghr := newGhr }
81  // use hist as global history!!!
82  val hist = Mux(updateGhr, newGhr, ghr)
83
84  // Tage predictor
85  val tage = if(EnableBPD) Module(new Tage) else Module(new FakeTAGE)
86  tage.io.req.valid := io.in.pc.fire()
87  tage.io.req.bits.pc := io.in.pc.bits
88  tage.io.req.bits.hist := hist
89  tage.io.redirectInfo <> io.redirectInfo
90  // io.s1OutPred.bits.tageMeta := tage.io.meta
91
92  // latch pc for 1 cycle latency when reading SRAM
93  val pcLatch = RegEnable(io.in.pc.bits, io.in.pc.fire())
94  // TODO: pass real mask in
95  // val maskLatch = RegEnable(btb.io.in.mask, io.in.pc.fire())
96  val maskLatch = Fill(PredictWidth, 1.U(1.W))
97
98  val r = io.redirectInfo.redirect
99  val updateFetchpc = r.pc - (r.fetchIdx << 1.U)
100  // BTB
101  val btb = Module(new BTB)
102  btb.io.in.pc <> io.in.pc
103  btb.io.in.pcLatch := pcLatch
104  // TODO: pass real mask in
105  btb.io.in.mask := Fill(PredictWidth, 1.U(1.W))
106  btb.io.redirectValid := io.redirectInfo.valid
107  btb.io.flush := io.flush
108
109  // btb.io.update.fetchPC := updateFetchpc
110  // btb.io.update.fetchIdx := r.fetchIdx
111  btb.io.update.pc := r.pc
112  btb.io.update.hit := r.btbHit
113  btb.io.update.misPred := io.redirectInfo.misPred
114  // btb.io.update.writeWay := r.btbVictimWay
115  btb.io.update.oldCtr := r.btbPredCtr
116  btb.io.update.taken := r.taken
117  btb.io.update.target := r.brTarget
118  btb.io.update.btbType := r.btbType
119  // TODO: add RVC logic
120  btb.io.update.isRVC := r.isRVC
121
122  // val btbHit = btb.io.out.hit
123  val btbTaken = btb.io.out.taken
124  val btbTakenIdx = btb.io.out.takenIdx
125  val btbTakenTarget = btb.io.out.target
126  // val btbWriteWay = btb.io.out.writeWay
127  val btbNotTakens = btb.io.out.notTakens
128  val btbCtrs = VecInit(btb.io.out.dEntries.map(_.pred))
129  val btbValids = btb.io.out.hits
130  val btbTargets = VecInit(btb.io.out.dEntries.map(_.target))
131  val btbTypes = VecInit(btb.io.out.dEntries.map(_.btbType))
132  val btbIsRVCs = VecInit(btb.io.out.dEntries.map(_.isRVC))
133
134
135  val jbtac = Module(new JBTAC)
136  jbtac.io.in.pc <> io.in.pc
137  jbtac.io.in.pcLatch := pcLatch
138  // TODO: pass real mask in
139  jbtac.io.in.mask := Fill(PredictWidth, 1.U(1.W))
140  jbtac.io.in.hist := hist
141  jbtac.io.redirectValid := io.redirectInfo.valid
142  jbtac.io.flush := io.flush
143
144  jbtac.io.update.fetchPC := updateFetchpc
145  jbtac.io.update.fetchIdx := r.fetchIdx
146  jbtac.io.update.misPred := io.redirectInfo.misPred
147  jbtac.io.update.btbType := r.btbType
148  jbtac.io.update.target := r.target
149  jbtac.io.update.hist := r.hist
150  jbtac.io.update.isRVC := r.isRVC
151
152  val jbtacHit = jbtac.io.out.hit
153  val jbtacTarget = jbtac.io.out.target
154  val jbtacHitIdx = jbtac.io.out.hitIdx
155
156  // calculate global history of each instr
157  val firstHist = RegNext(hist)
158  val histShift = Wire(Vec(PredictWidth, UInt(log2Up(PredictWidth).W)))
159  val shift = Wire(Vec(PredictWidth, Vec(PredictWidth, UInt(1.W))))
160  (0 until PredictWidth).foreach(i => shift(i) := Mux(!btbNotTakens(i), 0.U, ~LowerMask(UIntToOH(i.U), PredictWidth)).asTypeOf(Vec(PredictWidth, UInt(1.W))))
161  for (j <- 0 until PredictWidth) {
162    var tmp = 0.U
163    for (i <- 0 until PredictWidth) {
164      tmp = tmp + shift(i)(j)
165    }
166    histShift(j) := tmp
167  }
168
169  // update ghr
170  updateGhr := io.s1OutPred.bits.redirect ||
171               RegNext(io.in.pc.fire) && ~io.s1OutPred.bits.redirect && (btbNotTakens.asUInt & maskLatch).reduce(_||_) ||
172               io.flush
173  val brJumpIdx = Mux(!(btbHit && btbTaken), 0.U, UIntToOH(btbTakenIdx))
174  val indirectIdx = Mux(!jbtacHit, 0.U, UIntToOH(jbtacHitIdx))
175  // if backend redirects, restore history from backend;
176  // if stage3 redirects, restore history from stage3;
177  // if stage1 redirects, speculatively update history;
178  // if none of above happens, check if stage1 has not-taken branches and shift zeroes accordingly
179  newGhr := Mux(io.redirectInfo.flush(),    (r.hist << 1.U) | !(r.btbType === BTBtype.B && !r.taken),
180            Mux(io.flush,                   Mux(io.s3Taken, (io.s3RollBackHist << 1.U) | 1.U, io.s3RollBackHist),
181            Mux(io.s1OutPred.bits.redirect, (PriorityMux(brJumpIdx | indirectIdx, io.s1OutPred.bits.hist) << 1.U | 1.U),
182                                            io.s1OutPred.bits.hist(0) << PopCount(btbNotTakens.asUInt & maskLatch))))
183
184  def getInstrValid(i: Int): UInt = {
185    val vec = Wire(Vec(PredictWidth, UInt(1.W)))
186    for (j <- 0 until PredictWidth) {
187      if (j <= i)
188        vec(j) := 1.U
189      else
190        vec(j) := 0.U
191    }
192    vec.asUInt
193  }
194
195  // redirect based on BTB and JBTAC
196  val takenIdx = LowestBit(brJumpIdx | indirectIdx, PredictWidth)
197
198  // io.out.valid := RegNext(io.in.pc.fire()) && !io.flush
199
200  // io.s1OutPred.valid := io.out.valid
201  io.s1OutPred.valid := io.out.fire()
202  when (RegNext(io.in.pc.fire())) {
203    io.s1OutPred.bits.redirect := btbTaken || jbtacHit
204    // io.s1OutPred.bits.instrValid := Mux(!io.s1OutPred.bits.redirect || io.s1OutPred.bits.lateJump, maskLatch,
205    //                                 Mux(!btbIsRVCs(OHToUInt(takenIdx)), LowerMask(takenIdx << 1.U, PredictWidth),
206    //                                 LowerMask(takenIdx, PredictWidth))).asTypeOf(Vec(PredictWidth, Bool()))
207    io.s1OutPred.bits.redirect := (maskLatch & Fill(PredictWidth, ~io.s1OutPred.bits.redirect || io.s1OutPred.bits.lateJump) |
208      PriorityMux(brJumpIdx | indirectIdx, (0 until PredictWidth).map(getInstrValid(_)))).asTypeOf(Vec(PredictWidth, Bool()))
209    io.s1OutPred.bits.target := Mux(takenIdx === 0.U, pcLatch + (PopCount(maskLatch) << 1.U), Mux(takenIdx === brJumpIdx, btbTakenTarget, jbtacTarget))
210    io.s1OutPred.bits.lateJump := btb.io.out.isRVILateJump || jbtac.io.out.isRVILateJump
211    (0 until PredictWidth).map(i => io.s1OutPred.bits.hist(i) := firstHist << histShift(i))
212    // io.s1OutPred.bits.btbVictimWay := btbWriteWay
213    io.s1OutPred.bits.predCtr := btbCtrs
214    io.s1OutPred.bits.btbHit := btbValids
215    io.s1OutPred.bits.tageMeta := DontCare // TODO: enableBPD
216    io.s1OutPred.bits.rasSp := DontCare
217    io.s1OutPred.bits.rasTopCtr := DontCare
218  }.otherwise {
219    io.s1OutPred.bits := s1OutPredLatch
220  }
221
222  when (RegNext(io.in.pc.fire())) {
223    io.out.bits.pc := pcLatch
224    io.out.bits.btb.hits := btbValids.asUInt
225    (0 until PredictWidth).map(i => io.out.bits.btb.targets(i) := btbTargets(i))
226    io.out.bits.jbtac.hitIdx := Mux(jbtacHit, UIntToOH(jbtacHitIdx), 0.U) // UIntToOH(jbtacHitIdx)
227    io.out.bits.jbtac.target := jbtacTarget
228    io.out.bits.tage <> tage.io.out
229    // TODO: we don't need this repeatedly!
230    io.out.bits.hist := io.s1OutPred.bits.hist
231    io.out.bits.btbPred := io.s1OutPred
232  }.otherwise {
233    io.out.bits := outLatch
234  }
235
236
237  // debug info
238  XSDebug("in:(%d %d)   pc=%x ghr=%b\n", io.in.pc.valid, io.in.pc.ready, io.in.pc.bits, hist)
239  XSDebug("outPred:(%d) pc=0x%x, redirect=%d instrValid=%b tgt=%x\n",
240    io.s1OutPred.valid, pcLatch, io.s1OutPred.bits.redirect, io.s1OutPred.bits.instrValid.asUInt, io.s1OutPred.bits.target)
241  XSDebug(io.flush && io.redirectInfo.flush(),
242    "flush from backend: pc=%x tgt=%x brTgt=%x btbType=%b taken=%d oldHist=%b fetchIdx=%d isExcpt=%d\n",
243    r.pc, r.target, r.brTarget, r.btbType, r.taken, r.hist, r.fetchIdx, r.isException)
244  XSDebug(io.flush && !io.redirectInfo.flush(),
245    "flush from Stage3:  s3Taken=%d s3RollBackHist=%b\n", io.s3Taken, io.s3RollBackHist)
246
247}
248
249class Stage2To3IO extends Stage1To2IO {
250}
251
252class BPUStage2 extends XSModule {
253  val io = IO(new Bundle() {
254    // flush from Stage3
255    val flush = Input(Bool())
256    val in = Flipped(Decoupled(new Stage1To2IO))
257    val out = Decoupled(new Stage2To3IO)
258  })
259
260  // flush Stage2 when Stage3 or banckend redirects
261  val flushS2 = BoolStopWatch(io.flush, io.in.fire(), startHighPriority = true)
262  val inLatch = RegInit(0.U.asTypeOf(io.in.bits))
263  when (io.in.fire()) { inLatch := io.in.bits }
264  val validLatch = RegInit(false.B)
265  when (io.flush) {
266    validLatch := false.B
267  }.elsewhen (io.in.fire()) {
268    validLatch := true.B
269  }.elsewhen (io.out.fire()) {
270    validLatch := false.B
271  }
272
273  io.out.valid := !io.flush && !flushS2 && validLatch
274  io.in.ready := !validLatch || io.out.fire()
275
276  // do nothing
277  io.out.bits := inLatch
278
279  // debug info
280  XSDebug("in:(%d %d) pc=%x out:(%d %d) pc=%x\n",
281    io.in.valid, io.in.ready, io.in.bits.pc, io.out.valid, io.out.ready, io.out.bits.pc)
282  XSDebug("validLatch=%d pc=%x\n", validLatch, inLatch.pc)
283  XSDebug(io.flush, "flush!!!\n")
284}
285
286class BPUStage3 extends XSModule {
287  val io = IO(new Bundle() {
288    val flush = Input(Bool())
289    val in = Flipped(Decoupled(new Stage2To3IO))
290    val out = Decoupled(new BranchPrediction)
291    // from icache
292    val predecode = Flipped(ValidIO(new Predecode))
293    // from backend
294    val redirectInfo = Input(new RedirectInfo)
295    // to Stage1 and Stage2
296    val flushBPU = Output(Bool())
297    // to Stage1, restore ghr in stage1 when flushBPU is valid
298    val s1RollBackHist = Output(UInt(HistoryLength.W))
299    val s3Taken = Output(Bool())
300  })
301
302  val flushS3 = BoolStopWatch(io.flush, io.in.fire(), startHighPriority = true)
303  val inLatch = RegInit(0.U.asTypeOf(io.in.bits))
304  val validLatch = RegInit(false.B)
305  val predecodeLatch = RegInit(0.U.asTypeOf(io.predecode.bits))
306  val predecodeValidLatch = RegInit(false.B)
307  when (io.in.fire()) { inLatch := io.in.bits }
308  when (io.flush) {
309    validLatch := false.B
310  }.elsewhen (io.in.fire()) {
311    validLatch := true.B
312  }.elsewhen (io.out.fire()) {
313    validLatch := false.B
314  }
315
316  when (io.predecode.valid) { predecodeLatch := io.predecode.bits }
317  when (io.flush || io.out.fire()) {
318    predecodeValidLatch := false.B
319  }.elsewhen (io.predecode.valid) {
320    predecodeValidLatch := true.B
321  }
322
323  val predecodeValid = io.predecode.valid || predecodeValidLatch
324  val predecode = Mux(io.predecode.valid, io.predecode.bits, predecodeLatch)
325  io.out.valid := validLatch && predecodeValid && !flushS3 && !io.flush
326  io.in.ready := !validLatch || io.out.fire()
327
328  // RAS
329  // TODO: split retAddr and ctr
330  def rasEntry() = new Bundle {
331    val retAddr = UInt(VAddrBits.W)
332    val ctr = UInt(8.W) // layer of nested call functions
333  }
334  val ras = RegInit(VecInit(Seq.fill(RasSize)(0.U.asTypeOf(rasEntry()))))
335  val sp = Counter(RasSize)
336  val rasTop = ras(sp.value)
337  val rasTopAddr = rasTop.retAddr
338
339  // get the first taken branch/jal/call/jalr/ret in a fetch line
340  // brNotTakenIdx indicates all the not-taken branches before the first jump instruction
341
342
343  val brs = inLatch.btb.hits & Reverse(Cat(predecode.fuOpTypes.map { t => ALUOpType.isBranch(t) }).asUInt) & predecode.mask
344  // val brTakens = brs & inLatch.tage.takens.asUInt
345  val brTakens = if (EnableBPD) {
346    brs & Reverse(Cat(inLatch.tage.takens.map {t => Fill(2, t.asUInt)}).asUInt)
347  } else {
348    brs & Reverse(Cat(inLatch.btbPred.bits.predCtr.map {c => c(1)}).asUInt)
349  }
350  val jals = inLatch.btb.hits & Reverse(Cat(predecode.fuOpTypes.map { t => t === JumpOpType.jal }).asUInt) & predecode.mask
351  val calls = inLatch.btb.hits & predecode.mask & Reverse(Cat(predecode.fuOpTypes.map { t => t === JumpOpType.call }).asUInt)
352  val jalrs = inLatch.jbtac.hitIdx & predecode.mask & Reverse(Cat(predecode.fuOpTypes.map { t => t === JumpOpType.jalr }).asUInt)
353  val rets = predecode.mask & Reverse(Cat(predecode.fuOpTypes.map { t => t === JumpOpType.ret }).asUInt)
354
355  val brTakenIdx = PriorityMux(brTakens, (0 until PredictWidth).map(_.U))
356  val jalIdx = PriorityMux(jals, (0 until PredictWidth).map(_.U))
357  val callIdx = PriorityMux(calls, (0 until PredictWidth).map(_.U))
358  val jalrIdx = PriorityMux(jalrs, (0 until PredictWidth).map(_.U))
359  val retIdx = PriorityMux(rets, (0 until PredictWidth).map(_.U))
360
361  val jmps = (if (EnableRAS) {brTakens | jals | calls | jalrs | rets} else {brTakens | jals | calls | jalrs})
362  val jmpIdx = MuxCase(0.U, (0 until PredictWidth).map(i => (jmps(i), i.U)))
363  io.s3Taken := MuxCase(false.B, (0 until PredictWidth).map(i => (jmps(i), true.B)))
364
365  // val brNotTakens = VecInit((0 until PredictWidth).map(i => brs(i) && ~inLatch.tage.takens(i) && i.U <= jmpIdx && io.predecode.bits.mask(i)))
366  val brNotTakens = if (EnableBPD) {
367    VecInit((0 until PredictWidth).map(i => brs(i) && i.U <= jmpIdx && ~inLatch.tage.takens(i>>1) && predecode.mask(i)))
368  } else {
369    VecInit((0 until PredictWidth).map(i => brs(i) && i.U <= jmpIdx && ~inLatch.btbPred.bits.predCtr(i)(1) && predecode.mask(i)))
370  }
371
372  // TODO: what if if4 and if2 late jump to the same target?
373  val lateJump = io.s3Taken && PriorityMux(Reverse(predecode.mask),((PredictWidth - 1) to 0).map(_.U)) === jmpIdx && !predecode.isRVC(jmpIdx)
374  io.out.bits.lateJump := lateJump
375
376  io.out.bits.predCtr := inLatch.btbPred.bits.predCtr
377  io.out.bits.btbHit := inLatch.btbPred.bits.btbHit
378  io.out.bits.tageMeta := inLatch.btbPred.bits.tageMeta
379  //io.out.bits.btbType := Mux(jmpIdx === retIdx, BTBtype.R,
380  //  Mux(jmpIdx === jalrIdx, BTBtype.I,
381  //  Mux(jmpIdx === brTakenIdx, BTBtype.B, BTBtype.J)))
382  val firstHist = inLatch.btbPred.bits.hist(0)
383  // there may be several notTaken branches before the first jump instruction,
384  // so we need to calculate how many zeroes should each instruction shift in its global history.
385  // each history is exclusive of instruction's own jump direction.
386  val histShift = Wire(Vec(PredictWidth, UInt(log2Up(PredictWidth).W)))
387  val shift = Wire(Vec(PredictWidth, Vec(PredictWidth, UInt(1.W))))
388  (0 until PredictWidth).foreach(i => shift(i) := Mux(!brNotTakens(i), 0.U, ~LowerMask(UIntToOH(i.U), PredictWidth)).asTypeOf(Vec(PredictWidth, UInt(1.W))))
389  for (j <- 0 until PredictWidth) {
390    var tmp = 0.U
391    for (i <- 0 until PredictWidth) {
392      tmp = tmp + shift(i)(j)
393    }
394    histShift(j) := tmp
395  }
396  (0 until PredictWidth).foreach(i => io.out.bits.hist(i) := firstHist << histShift(i))
397  // save ras checkpoint info
398  io.out.bits.rasSp := sp.value
399  io.out.bits.rasTopCtr := rasTop.ctr
400
401  // flush BPU and redirect when target differs from the target predicted in Stage1
402  val tToNt = inLatch.btbPred.bits.redirect && ~io.s3Taken
403  val ntToT = ~inLatch.btbPred.bits.redirect && io.s3Taken
404  val dirDiffers = tToNt || ntToT
405  val tgtDiffers = inLatch.btbPred.bits.redirect && io.s3Taken && io.out.bits.target =/= inLatch.btbPred.bits.target
406  // io.out.bits.redirect := (if (EnableBPD) {dirDiffers || tgtDiffers} else false.B)
407  io.out.bits.redirect := dirDiffers || tgtDiffers
408  io.out.bits.target := Mux(!io.s3Taken, inLatch.pc + (PopCount(predecode.mask) << 1.U), // TODO: RVC
409                        Mux(jmpIdx === retIdx, rasTopAddr,
410                        Mux(jmpIdx === jalrIdx, inLatch.jbtac.target,
411                        inLatch.btb.targets(jmpIdx))))
412  // for (i <- 0 until FetchWidth) {
413  //   io.out.bits.instrValid(i) := ((io.s3Taken && i.U <= jmpIdx) || ~io.s3Taken) && io.predecode.bits.mask(i)
414  // }
415  for (i <- PredictWidth - 1 to 0) {
416    io.out.bits.instrValid(i) := (io.s3Taken && i.U <= jmpIdx || !io.s3Taken) && predecode.mask(i)
417    if (i != (PredictWidth - 1)) {
418      when (!lateJump && !predecode.isRVC(i)) {
419        io.out.bits.instrValid(i+1) := predecode.mask(i+1)
420      }
421    }
422  }
423  io.flushBPU := io.out.bits.redirect && io.out.fire()
424
425  // speculative update RAS
426  val rasWrite = WireInit(0.U.asTypeOf(rasEntry()))
427  val retAddr = inLatch.pc + (callIdx << 1.U) + Mux(predecode.isRVC(callIdx), 2.U, 4.U)
428  rasWrite.retAddr := retAddr
429  val allocNewEntry = rasWrite.retAddr =/= rasTopAddr
430  rasWrite.ctr := Mux(allocNewEntry, 1.U, rasTop.ctr + 1.U)
431  val rasWritePosition = Mux(allocNewEntry, sp.value + 1.U, sp.value)
432  when (io.out.fire() && io.s3Taken) {
433    when (jmpIdx === callIdx) {
434      ras(rasWritePosition) := rasWrite
435      when (allocNewEntry) { sp.value := sp.value + 1.U }
436    }.elsewhen (jmpIdx === retIdx) {
437      when (rasTop.ctr === 1.U) {
438        sp.value := Mux(sp.value === 0.U, 0.U, sp.value - 1.U)
439      }.otherwise {
440        ras(sp.value) := Cat(rasTop.ctr - 1.U, rasTopAddr).asTypeOf(rasEntry())
441      }
442    }
443  }
444  // use checkpoint to recover RAS
445  val recoverSp = io.redirectInfo.redirect.rasSp
446  val recoverCtr = io.redirectInfo.redirect.rasTopCtr
447  when (io.redirectInfo.flush()) {
448    sp.value := recoverSp
449    ras(recoverSp) := Cat(recoverCtr, ras(recoverSp).retAddr).asTypeOf(rasEntry())
450  }
451
452  // roll back global history in S1 if S3 redirects
453  io.s1RollBackHist := Mux(io.s3Taken, io.out.bits.hist(jmpIdx),
454                       io.out.bits.hist(0) << PopCount(brs & predecode.mask & ~Reverse(Cat(inLatch.tage.takens.map {t => Fill(2, t.asUInt)}).asUInt)))
455
456  // debug info
457  XSDebug(io.in.fire(), "in:(%d %d) pc=%x\n", io.in.valid, io.in.ready, io.in.bits.pc)
458  XSDebug(io.out.fire(), "out:(%d %d) pc=%x redirect=%d predcdMask=%b instrValid=%b tgt=%x\n",
459    io.out.valid, io.out.ready, inLatch.pc, io.out.bits.redirect, predecode.mask, io.out.bits.instrValid.asUInt, io.out.bits.target)
460  XSDebug("flushS3=%d\n", flushS3)
461  XSDebug("validLatch=%d predecode.valid=%d\n", validLatch, predecodeValid)
462  XSDebug("brs=%b brTakens=%b brNTakens=%b jals=%b jalrs=%b calls=%b rets=%b\n",
463    brs, brTakens, brNotTakens.asUInt, jals, jalrs, calls, rets)
464  // ?????condition is wrong
465  // XSDebug(io.in.fire() && callIdx.orR, "[RAS]:pc=0x%x, rasWritePosition=%d, rasWriteAddr=0x%x\n",
466  //           io.in.bits.pc, rasWritePosition, retAddr)
467}
468
469class BPU extends XSModule {
470  val io = IO(new Bundle() {
471    // from backend
472    // flush pipeline if misPred and update bpu based on redirect signals from brq
473    val redirectInfo = Input(new RedirectInfo)
474
475    val in = new Bundle { val pc = Flipped(Valid(UInt(VAddrBits.W))) }
476
477    val btbOut = ValidIO(new BranchPrediction)
478    val tageOut = Decoupled(new BranchPrediction)
479
480    // predecode info from icache
481    // TODO: simplify this after implement predecode unit
482    val predecode = Flipped(ValidIO(new Predecode))
483  })
484
485  val s1 = Module(new BPUStage1)
486  val s2 = Module(new BPUStage2)
487  val s3 = Module(new BPUStage3)
488
489  s1.io.redirectInfo <> io.redirectInfo
490  s1.io.flush := s3.io.flushBPU || io.redirectInfo.flush()
491  s1.io.in.pc.valid := io.in.pc.valid
492  s1.io.in.pc.bits <> io.in.pc.bits
493  io.btbOut <> s1.io.s1OutPred
494  s1.io.s3RollBackHist := s3.io.s1RollBackHist
495  s1.io.s3Taken := s3.io.s3Taken
496
497  s1.io.out <> s2.io.in
498  s2.io.flush := s3.io.flushBPU || io.redirectInfo.flush()
499
500  s2.io.out <> s3.io.in
501  s3.io.flush := io.redirectInfo.flush()
502  s3.io.predecode <> io.predecode
503  io.tageOut <> s3.io.out
504  s3.io.redirectInfo <> io.redirectInfo
505}