xref: /XiangShan/src/main/scala/xiangshan/frontend/FTB.scala (revision c3d62b63806081d89ce058890959e23bc09e4de1)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.frontend
18
19import chisel3._
20import chisel3.util._
21import org.chipsalliance.cde.config.Parameters
22import scala.{Tuple2 => &}
23import utility._
24import xiangshan._
25
26trait FTBParams extends HasXSParameter with HasBPUConst {
27  val numEntries = FtbSize
28  val numWays    = FtbWays
29  val numSets    = numEntries / numWays // 512
30  val tagSize    = 20
31
32  val TAR_STAT_SZ = 2
33  def TAR_FIT     = 0.U(TAR_STAT_SZ.W)
34  def TAR_OVF     = 1.U(TAR_STAT_SZ.W)
35  def TAR_UDF     = 2.U(TAR_STAT_SZ.W)
36
37  def BR_OFFSET_LEN  = 12
38  def JMP_OFFSET_LEN = 20
39
40  def FTBCLOSE_THRESHOLD_SZ = log2Ceil(500)
41  def FTBCLOSE_THRESHOLD    = 500.U(FTBCLOSE_THRESHOLD_SZ.W) // can be modified
42}
43
44class FtbSlot_FtqMem(implicit p: Parameters) extends XSBundle with FTBParams {
45  val offset  = UInt(log2Ceil(PredictWidth).W)
46  val sharing = Bool()
47  val valid   = Bool()
48}
49
50class FtbSlot(val offsetLen: Int, val subOffsetLen: Option[Int] = None)(implicit p: Parameters) extends FtbSlot_FtqMem
51    with FTBParams {
52  if (subOffsetLen.isDefined) {
53    require(subOffsetLen.get <= offsetLen)
54  }
55  val lower   = UInt(offsetLen.W)
56  val tarStat = UInt(TAR_STAT_SZ.W)
57
58  def setLowerStatByTarget(pc: UInt, target: UInt, isShare: Boolean) = {
59    def getTargetStatByHigher(pc_higher: UInt, target_higher: UInt) =
60      Mux(target_higher > pc_higher, TAR_OVF, Mux(target_higher < pc_higher, TAR_UDF, TAR_FIT))
61    def getLowerByTarget(target: UInt, offsetLen: Int) = target(offsetLen, 1)
62    val offLen        = if (isShare) this.subOffsetLen.get else this.offsetLen
63    val pc_higher     = pc(VAddrBits - 1, offLen + 1)
64    val target_higher = target(VAddrBits - 1, offLen + 1)
65    val stat          = getTargetStatByHigher(pc_higher, target_higher)
66    val lower         = ZeroExt(getLowerByTarget(target, offLen), this.offsetLen)
67    this.lower   := lower
68    this.tarStat := stat
69    this.sharing := isShare.B
70  }
71
72  def getTarget(pc: UInt, last_stage: Option[Tuple2[UInt, Bool]] = None) = {
73    def getTarget(offLen: Int)(pc: UInt, lower: UInt, stat: UInt, last_stage: Option[Tuple2[UInt, Bool]] = None) = {
74      val h                = pc(VAddrBits - 1, offLen + 1)
75      val higher           = Wire(UInt((VAddrBits - offLen - 1).W))
76      val higher_plus_one  = Wire(UInt((VAddrBits - offLen - 1).W))
77      val higher_minus_one = Wire(UInt((VAddrBits - offLen - 1).W))
78
79      // Switch between previous stage pc and current stage pc
80      // Give flexibility for timing
81      if (last_stage.isDefined) {
82        val last_stage_pc   = last_stage.get._1
83        val last_stage_pc_h = last_stage_pc(VAddrBits - 1, offLen + 1)
84        val stage_en        = last_stage.get._2
85        higher           := RegEnable(last_stage_pc_h, stage_en)
86        higher_plus_one  := RegEnable(last_stage_pc_h + 1.U, stage_en)
87        higher_minus_one := RegEnable(last_stage_pc_h - 1.U, stage_en)
88      } else {
89        higher           := h
90        higher_plus_one  := h + 1.U
91        higher_minus_one := h - 1.U
92      }
93      val target =
94        Cat(
95          Mux1H(Seq(
96            (stat === TAR_OVF, higher_plus_one),
97            (stat === TAR_UDF, higher_minus_one),
98            (stat === TAR_FIT, higher)
99          )),
100          lower(offLen - 1, 0),
101          0.U(1.W)
102        )
103      require(target.getWidth == VAddrBits)
104      require(offLen != 0)
105      target
106    }
107    if (subOffsetLen.isDefined)
108      Mux(
109        sharing,
110        getTarget(subOffsetLen.get)(pc, lower, tarStat, last_stage),
111        getTarget(offsetLen)(pc, lower, tarStat, last_stage)
112      )
113    else
114      getTarget(offsetLen)(pc, lower, tarStat, last_stage)
115  }
116  def fromAnotherSlot(that: FtbSlot) = {
117    require(
118      this.offsetLen > that.offsetLen && this.subOffsetLen.map(_ == that.offsetLen).getOrElse(true) ||
119        this.offsetLen == that.offsetLen
120    )
121    this.offset  := that.offset
122    this.tarStat := that.tarStat
123    this.sharing := (this.offsetLen > that.offsetLen && that.offsetLen == this.subOffsetLen.get).B
124    this.valid   := that.valid
125    this.lower   := ZeroExt(that.lower, this.offsetLen)
126  }
127
128  def slotConsistent(that: FtbSlot) =
129    VecInit(
130      this.offset === that.offset,
131      this.lower === that.lower,
132      this.tarStat === that.tarStat,
133      this.sharing === that.sharing,
134      this.valid === that.valid
135    ).reduce(_ && _)
136
137}
138
139class FTBEntry_part(implicit p: Parameters) extends XSBundle with FTBParams with BPUUtils {
140  val isCall = Bool()
141  val isRet  = Bool()
142  val isJalr = Bool()
143
144  def isJal = !isJalr
145}
146
147class FTBEntry_FtqMem(implicit p: Parameters) extends FTBEntry_part with FTBParams with BPUUtils {
148
149  val brSlots  = Vec(numBrSlot, new FtbSlot_FtqMem)
150  val tailSlot = new FtbSlot_FtqMem
151
152  def jmpValid =
153    tailSlot.valid && !tailSlot.sharing
154
155  def getBrRecordedVec(offset: UInt) =
156    VecInit(
157      brSlots.map(s => s.valid && s.offset === offset) :+
158        (tailSlot.valid && tailSlot.offset === offset && tailSlot.sharing)
159    )
160
161  def brIsSaved(offset: UInt) = getBrRecordedVec(offset).reduce(_ || _)
162
163  def getBrMaskByOffset(offset: UInt) =
164    brSlots.map { s =>
165      s.valid && s.offset <= offset
166    } :+
167      (tailSlot.valid && tailSlot.offset <= offset && tailSlot.sharing)
168
169  def newBrCanNotInsert(offset: UInt) = {
170    val lastSlotForBr = tailSlot
171    lastSlotForBr.valid && lastSlotForBr.offset < offset
172  }
173
174}
175
176class FTBEntry(implicit p: Parameters) extends FTBEntry_part with FTBParams with BPUUtils {
177
178  val valid = Bool()
179
180  val brSlots = Vec(numBrSlot, new FtbSlot(BR_OFFSET_LEN))
181
182  val tailSlot = new FtbSlot(JMP_OFFSET_LEN, Some(BR_OFFSET_LEN))
183
184  // Partial Fall-Through Address
185  val pftAddr = UInt(log2Up(PredictWidth).W)
186  val carry   = Bool()
187
188  val last_may_be_rvi_call = Bool()
189
190  val always_taken = Vec(numBr, Bool())
191
192  def getSlotForBr(idx: Int): FtbSlot = {
193    require(idx <= numBr - 1)
194    (idx, numBr) match {
195      case (i, n) if i == n - 1 => this.tailSlot
196      case _                    => this.brSlots(idx)
197    }
198  }
199  def allSlotsForBr =
200    (0 until numBr).map(getSlotForBr(_))
201  def setByBrTarget(brIdx: Int, pc: UInt, target: UInt) = {
202    val slot = getSlotForBr(brIdx)
203    slot.setLowerStatByTarget(pc, target, brIdx == numBr - 1)
204  }
205  def setByJmpTarget(pc: UInt, target: UInt) =
206    this.tailSlot.setLowerStatByTarget(pc, target, false)
207
208  def getTargetVec(pc: UInt, last_stage: Option[Tuple2[UInt, Bool]] = None) = {
209    /*
210    Previous design: Use the getTarget function of FTBSlot to calculate three sets of targets separately;
211    During this process, nine sets of registers will be generated to register the values of the higher plus one minus one
212    Current design: Reuse the duplicate parts of the original nine sets of registers,
213    calculate the common high bits last_stage_pc_higher of brtarget and jmptarget,
214    and the high bits last_stage_pc_middle that need to be added and subtracted from each other,
215    and then concatenate them according to the carry situation to obtain brtarget and jmptarget
216     */
217    val h_br                  = pc(VAddrBits - 1, BR_OFFSET_LEN + 1)
218    val higher_br             = Wire(UInt((VAddrBits - BR_OFFSET_LEN - 1).W))
219    val higher_plus_one_br    = Wire(UInt((VAddrBits - BR_OFFSET_LEN - 1).W))
220    val higher_minus_one_br   = Wire(UInt((VAddrBits - BR_OFFSET_LEN - 1).W))
221    val h_tail                = pc(VAddrBits - 1, JMP_OFFSET_LEN + 1)
222    val higher_tail           = Wire(UInt((VAddrBits - JMP_OFFSET_LEN - 1).W))
223    val higher_plus_one_tail  = Wire(UInt((VAddrBits - JMP_OFFSET_LEN - 1).W))
224    val higher_minus_one_tail = Wire(UInt((VAddrBits - JMP_OFFSET_LEN - 1).W))
225    if (last_stage.isDefined) {
226      val last_stage_pc                  = last_stage.get._1
227      val stage_en                       = last_stage.get._2
228      val last_stage_pc_higher           = RegEnable(last_stage_pc(VAddrBits - 1, JMP_OFFSET_LEN + 1), stage_en)
229      val last_stage_pc_middle           = RegEnable(last_stage_pc(JMP_OFFSET_LEN, BR_OFFSET_LEN + 1), stage_en)
230      val last_stage_pc_higher_plus_one  = RegEnable(last_stage_pc(VAddrBits - 1, JMP_OFFSET_LEN + 1) + 1.U, stage_en)
231      val last_stage_pc_higher_minus_one = RegEnable(last_stage_pc(VAddrBits - 1, JMP_OFFSET_LEN + 1) - 1.U, stage_en)
232      val last_stage_pc_middle_plus_one =
233        RegEnable(Cat(0.U(1.W), last_stage_pc(JMP_OFFSET_LEN, BR_OFFSET_LEN + 1)) + 1.U, stage_en)
234      val last_stage_pc_middle_minus_one =
235        RegEnable(Cat(0.U(1.W), last_stage_pc(JMP_OFFSET_LEN, BR_OFFSET_LEN + 1)) - 1.U, stage_en)
236
237      higher_br := Cat(last_stage_pc_higher, last_stage_pc_middle)
238      higher_plus_one_br := Mux(
239        last_stage_pc_middle_plus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN),
240        Cat(last_stage_pc_higher_plus_one, last_stage_pc_middle_plus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN - 1, 0)),
241        Cat(last_stage_pc_higher, last_stage_pc_middle_plus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN - 1, 0))
242      )
243      higher_minus_one_br := Mux(
244        last_stage_pc_middle_minus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN),
245        Cat(last_stage_pc_higher_minus_one, last_stage_pc_middle_minus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN - 1, 0)),
246        Cat(last_stage_pc_higher, last_stage_pc_middle_minus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN - 1, 0))
247      )
248
249      higher_tail           := last_stage_pc_higher
250      higher_plus_one_tail  := last_stage_pc_higher_plus_one
251      higher_minus_one_tail := last_stage_pc_higher_minus_one
252    } else {
253      higher_br             := h_br
254      higher_plus_one_br    := h_br + 1.U
255      higher_minus_one_br   := h_br - 1.U
256      higher_tail           := h_tail
257      higher_plus_one_tail  := h_tail + 1.U
258      higher_minus_one_tail := h_tail - 1.U
259    }
260    val br_slots_targets = VecInit(brSlots.map(s =>
261      Cat(
262        Mux1H(Seq(
263          (s.tarStat === TAR_OVF, higher_plus_one_br),
264          (s.tarStat === TAR_UDF, higher_minus_one_br),
265          (s.tarStat === TAR_FIT, higher_br)
266        )),
267        s.lower(s.offsetLen - 1, 0),
268        0.U(1.W)
269      )
270    ))
271    val tail_target = Wire(UInt(VAddrBits.W))
272    if (tailSlot.subOffsetLen.isDefined) {
273      tail_target := Mux(
274        tailSlot.sharing,
275        Cat(
276          Mux1H(Seq(
277            (tailSlot.tarStat === TAR_OVF, higher_plus_one_br),
278            (tailSlot.tarStat === TAR_UDF, higher_minus_one_br),
279            (tailSlot.tarStat === TAR_FIT, higher_br)
280          )),
281          tailSlot.lower(tailSlot.subOffsetLen.get - 1, 0),
282          0.U(1.W)
283        ),
284        Cat(
285          Mux1H(Seq(
286            (tailSlot.tarStat === TAR_OVF, higher_plus_one_tail),
287            (tailSlot.tarStat === TAR_UDF, higher_minus_one_tail),
288            (tailSlot.tarStat === TAR_FIT, higher_tail)
289          )),
290          tailSlot.lower(tailSlot.offsetLen - 1, 0),
291          0.U(1.W)
292        )
293      )
294    } else {
295      tail_target := Cat(
296        Mux1H(Seq(
297          (tailSlot.tarStat === TAR_OVF, higher_plus_one_tail),
298          (tailSlot.tarStat === TAR_UDF, higher_minus_one_tail),
299          (tailSlot.tarStat === TAR_FIT, higher_tail)
300        )),
301        tailSlot.lower(tailSlot.offsetLen - 1, 0),
302        0.U(1.W)
303      )
304    }
305
306    br_slots_targets.map(t => require(t.getWidth == VAddrBits))
307    require(tail_target.getWidth == VAddrBits)
308    val targets = VecInit(br_slots_targets :+ tail_target)
309    targets
310  }
311
312  def getOffsetVec = VecInit(brSlots.map(_.offset) :+ tailSlot.offset)
313  def getFallThrough(pc: UInt, last_stage_entry: Option[Tuple2[FTBEntry, Bool]] = None) =
314    if (last_stage_entry.isDefined) {
315      var stashed_carry = RegEnable(last_stage_entry.get._1.carry, last_stage_entry.get._2)
316      getFallThroughAddr(pc, stashed_carry, pftAddr)
317    } else {
318      getFallThroughAddr(pc, carry, pftAddr)
319    }
320
321  def hasBr(offset: UInt) =
322    brSlots.map(s => s.valid && s.offset <= offset).reduce(_ || _) ||
323      (tailSlot.valid && tailSlot.offset <= offset && tailSlot.sharing)
324
325  def getBrMaskByOffset(offset: UInt) =
326    brSlots.map { s =>
327      s.valid && s.offset <= offset
328    } :+
329      (tailSlot.valid && tailSlot.offset <= offset && tailSlot.sharing)
330
331  def getBrRecordedVec(offset: UInt) =
332    VecInit(
333      brSlots.map(s => s.valid && s.offset === offset) :+
334        (tailSlot.valid && tailSlot.offset === offset && tailSlot.sharing)
335    )
336
337  def brIsSaved(offset: UInt) = getBrRecordedVec(offset).reduce(_ || _)
338
339  def brValids =
340    VecInit(
341      brSlots.map(_.valid) :+ (tailSlot.valid && tailSlot.sharing)
342    )
343
344  def noEmptySlotForNewBr =
345    VecInit(brSlots.map(_.valid) :+ tailSlot.valid).reduce(_ && _)
346
347  def newBrCanNotInsert(offset: UInt) = {
348    val lastSlotForBr = tailSlot
349    lastSlotForBr.valid && lastSlotForBr.offset < offset
350  }
351
352  def jmpValid =
353    tailSlot.valid && !tailSlot.sharing
354
355  def brOffset =
356    VecInit(brSlots.map(_.offset) :+ tailSlot.offset)
357
358  def entryConsistent(that: FTBEntry) = {
359    val validDiff = this.valid === that.valid
360    val brSlotsDiffSeq: IndexedSeq[Bool] =
361      this.brSlots.zip(that.brSlots).map {
362        case (x, y) => x.slotConsistent(y)
363      }
364    val tailSlotDiff         = this.tailSlot.slotConsistent(that.tailSlot)
365    val pftAddrDiff          = this.pftAddr === that.pftAddr
366    val carryDiff            = this.carry === that.carry
367    val isCallDiff           = this.isCall === that.isCall
368    val isRetDiff            = this.isRet === that.isRet
369    val isJalrDiff           = this.isJalr === that.isJalr
370    val lastMayBeRviCallDiff = this.last_may_be_rvi_call === that.last_may_be_rvi_call
371    val alwaysTakenDiff: IndexedSeq[Bool] =
372      this.always_taken.zip(that.always_taken).map {
373        case (x, y) => x === y
374      }
375    VecInit(
376      validDiff,
377      brSlotsDiffSeq.reduce(_ && _),
378      tailSlotDiff,
379      pftAddrDiff,
380      carryDiff,
381      isCallDiff,
382      isRetDiff,
383      isJalrDiff,
384      lastMayBeRviCallDiff,
385      alwaysTakenDiff.reduce(_ && _)
386    ).reduce(_ && _)
387  }
388
389  def display(cond: Bool): Unit = {
390    XSDebug(cond, p"-----------FTB entry----------- \n")
391    XSDebug(cond, p"v=${valid}\n")
392    for (i <- 0 until numBr) {
393      XSDebug(
394        cond,
395        p"[br$i]: v=${allSlotsForBr(i).valid}, offset=${allSlotsForBr(i).offset}," +
396          p"lower=${Hexadecimal(allSlotsForBr(i).lower)}\n"
397      )
398    }
399    XSDebug(
400      cond,
401      p"[tailSlot]: v=${tailSlot.valid}, offset=${tailSlot.offset}," +
402        p"lower=${Hexadecimal(tailSlot.lower)}, sharing=${tailSlot.sharing}}\n"
403    )
404    XSDebug(cond, p"pftAddr=${Hexadecimal(pftAddr)}, carry=$carry\n")
405    XSDebug(cond, p"isCall=$isCall, isRet=$isRet, isjalr=$isJalr\n")
406    XSDebug(cond, p"last_may_be_rvi_call=$last_may_be_rvi_call\n")
407    XSDebug(cond, p"------------------------------- \n")
408  }
409
410}
411
412class FTBEntryWithTag(implicit p: Parameters) extends XSBundle with FTBParams with BPUUtils {
413  val entry = new FTBEntry
414  val tag   = UInt(tagSize.W)
415  def display(cond: Bool): Unit = {
416    entry.display(cond)
417    XSDebug(cond, p"tag is ${Hexadecimal(tag)}\n------------------------------- \n")
418  }
419}
420
421class FTBMeta(implicit p: Parameters) extends XSBundle with FTBParams {
422  val writeWay   = UInt(log2Ceil(numWays).W)
423  val hit        = Bool()
424  val pred_cycle = if (!env.FPGAPlatform) Some(UInt(64.W)) else None
425}
426
427object FTBMeta {
428  def apply(writeWay: UInt, hit: Bool, pred_cycle: UInt)(implicit p: Parameters): FTBMeta = {
429    val e = Wire(new FTBMeta)
430    e.writeWay := writeWay
431    e.hit      := hit
432    e.pred_cycle.map(_ := pred_cycle)
433    e
434  }
435}
436
437// class UpdateQueueEntry(implicit p: Parameters) extends XSBundle with FTBParams {
438//   val pc = UInt(VAddrBits.W)
439//   val ftb_entry = new FTBEntry
440//   val hit = Bool()
441//   val hit_way = UInt(log2Ceil(numWays).W)
442// }
443//
444// object UpdateQueueEntry {
445//   def apply(pc: UInt, fe: FTBEntry, hit: Bool, hit_way: UInt)(implicit p: Parameters): UpdateQueueEntry = {
446//     val e = Wire(new UpdateQueueEntry)
447//     e.pc := pc
448//     e.ftb_entry := fe
449//     e.hit := hit
450//     e.hit_way := hit_way
451//     e
452//   }
453// }
454
455class FTBTableAddr(val idxBits: Int, val banks: Int, val skewedBits: Int)(implicit p: Parameters) extends XSBundle {
456  val addr = new TableAddr(idxBits, banks)
457  def getIdx(x: UInt) = addr.getIdx(x) ^ Cat(addr.getTag(x), addr.getIdx(x))(idxBits + skewedBits - 1, skewedBits)
458  def getTag(x: UInt) = addr.getTag(x)
459}
460
461class FTB(implicit p: Parameters) extends BasePredictor with FTBParams with BPUUtils
462    with HasCircularQueuePtrHelper with HasPerfEvents {
463  override val meta_size = WireInit(0.U.asTypeOf(new FTBMeta)).getWidth
464
465  val ftbAddr = new FTBTableAddr(log2Up(numSets), 1, 3)
466
467  class FTBBank(val numSets: Int, val nWays: Int) extends XSModule with BPUUtils {
468    val io = IO(new Bundle {
469      val s1_fire = Input(Bool())
470
471      // when ftb hit, read_hits.valid is true, and read_hits.bits is OH of hit way
472      // when ftb not hit, read_hits.valid is false, and read_hits is OH of allocWay
473      // val read_hits = Valid(Vec(numWays, Bool()))
474      val req_pc    = Flipped(DecoupledIO(UInt(VAddrBits.W)))
475      val read_resp = Output(new FTBEntry)
476      val read_hits = Valid(UInt(log2Ceil(numWays).W))
477
478      val read_multi_entry = Output(new FTBEntry)
479      val read_multi_hits  = Valid(UInt(log2Ceil(numWays).W))
480
481      val u_req_pc      = Flipped(DecoupledIO(UInt(VAddrBits.W)))
482      val update_hits   = Valid(UInt(log2Ceil(numWays).W))
483      val update_access = Input(Bool())
484
485      val update_pc          = Input(UInt(VAddrBits.W))
486      val update_write_data  = Flipped(Valid(new FTBEntryWithTag))
487      val update_write_way   = Input(UInt(log2Ceil(numWays).W))
488      val update_write_alloc = Input(Bool())
489    })
490
491    // Extract holdRead logic to fix bug that update read override predict read result
492    val ftb = Module(new SRAMTemplate(
493      new FTBEntryWithTag,
494      set = numSets,
495      way = numWays,
496      shouldReset = true,
497      holdRead = false,
498      singlePort = true
499    ))
500    val ftb_r_entries = ftb.io.r.resp.data.map(_.entry)
501
502    val pred_rdata = HoldUnless(ftb.io.r.resp.data, RegNext(io.req_pc.valid && !io.update_access))
503    ftb.io.r.req.valid := io.req_pc.valid || io.u_req_pc.valid // io.s0_fire
504    ftb.io.r.req.bits.setIdx := Mux(
505      io.u_req_pc.valid,
506      ftbAddr.getIdx(io.u_req_pc.bits),
507      ftbAddr.getIdx(io.req_pc.bits)
508    ) // s0_idx
509
510    assert(!(io.req_pc.valid && io.u_req_pc.valid))
511
512    io.req_pc.ready   := ftb.io.r.req.ready
513    io.u_req_pc.ready := ftb.io.r.req.ready
514
515    val req_tag = RegEnable(ftbAddr.getTag(io.req_pc.bits)(tagSize - 1, 0), io.req_pc.valid)
516    val req_idx = RegEnable(ftbAddr.getIdx(io.req_pc.bits), io.req_pc.valid)
517
518    val u_req_tag = RegEnable(ftbAddr.getTag(io.u_req_pc.bits)(tagSize - 1, 0), io.u_req_pc.valid)
519
520    val read_entries = pred_rdata.map(_.entry)
521    val read_tags    = pred_rdata.map(_.tag)
522
523    val total_hits =
524      VecInit((0 until numWays).map(b => read_tags(b) === req_tag && read_entries(b).valid && io.s1_fire))
525    val hit = total_hits.reduce(_ || _)
526    // val hit_way_1h = VecInit(PriorityEncoderOH(total_hits))
527    val hit_way = OHToUInt(total_hits)
528
529    // There may be two hits in the four paths of the ftbBank, and the OHToUInt will fail.
530    // If there is a redirect in s2 at this time, the wrong FTBEntry will be used to calculate the target,
531    // resulting in an address error and affecting performance.
532    // The solution is to select a hit entry during multi hit as the entry for s2.
533    // Considering timing, use this entry in s3 and trigger s3-redirect.
534    val total_hits_reg   = RegEnable(total_hits, io.s1_fire)
535    val read_entries_reg = read_entries.map(w => RegEnable(w, io.s1_fire))
536
537    val multi_hit = VecInit((0 until numWays).map {
538      i =>
539        (0 until numWays).map { j =>
540          if (i < j) total_hits_reg(i) && total_hits_reg(j)
541          else false.B
542        }.reduce(_ || _)
543    }).reduce(_ || _)
544    val multi_way = PriorityMux(Seq.tabulate(numWays)(i => (total_hits_reg(i)) -> i.asUInt(log2Ceil(numWays).W)))
545    val multi_hit_selectEntry = PriorityMux(Seq.tabulate(numWays)(i => (total_hits_reg(i)) -> read_entries_reg(i)))
546
547    // Check if the entry read by ftbBank is legal.
548    for (n <- 0 to numWays - 1) {
549      val req_pc_reg       = RegEnable(io.req_pc.bits, 0.U.asTypeOf(io.req_pc.bits), io.req_pc.valid)
550      val req_pc_reg_lower = Cat(0.U(1.W), req_pc_reg(instOffsetBits + log2Ceil(PredictWidth) - 1, instOffsetBits))
551      val ftbEntryEndLowerwithCarry = Cat(read_entries(n).carry, read_entries(n).pftAddr)
552      val fallThroughErr            = req_pc_reg_lower + PredictWidth.U >= ftbEntryEndLowerwithCarry
553      when(read_entries(n).valid && total_hits(n) && io.s1_fire) {
554        assert(fallThroughErr, s"FTB read sram entry in way${n} fallThrough address error!")
555      }
556    }
557
558    val u_total_hits = VecInit((0 until numWays).map(b =>
559      ftb.io.r.resp.data(b).tag === u_req_tag && ftb.io.r.resp.data(b).entry.valid && RegNext(io.update_access)
560    ))
561    val u_hit = u_total_hits.reduce(_ || _)
562    // val hit_way_1h = VecInit(PriorityEncoderOH(total_hits))
563    val u_hit_way = OHToUInt(u_total_hits)
564
565    // assert(PopCount(total_hits) === 1.U || PopCount(total_hits) === 0.U)
566    // assert(PopCount(u_total_hits) === 1.U || PopCount(u_total_hits) === 0.U)
567    for (n <- 1 to numWays) {
568      XSPerfAccumulate(f"ftb_pred_${n}_way_hit", PopCount(total_hits) === n.U)
569      XSPerfAccumulate(f"ftb_update_${n}_way_hit", PopCount(u_total_hits) === n.U)
570    }
571
572    val replacer = ReplacementPolicy.fromString(Some("setplru"), numWays, numSets)
573    // val allocWriteWay = replacer.way(req_idx)
574
575    val touch_set = Seq.fill(1)(Wire(UInt(log2Ceil(numSets).W)))
576    val touch_way = Seq.fill(1)(Wire(Valid(UInt(log2Ceil(numWays).W))))
577
578    val write_set = Wire(UInt(log2Ceil(numSets).W))
579    val write_way = Wire(Valid(UInt(log2Ceil(numWays).W)))
580
581    val read_set = Wire(UInt(log2Ceil(numSets).W))
582    val read_way = Wire(Valid(UInt(log2Ceil(numWays).W)))
583
584    read_set       := req_idx
585    read_way.valid := hit
586    read_way.bits  := hit_way
587
588    // Read replacer access is postponed for 1 cycle
589    // this helps timing
590    touch_set(0)       := Mux(write_way.valid, write_set, RegNext(read_set))
591    touch_way(0).valid := write_way.valid || RegNext(read_way.valid)
592    touch_way(0).bits  := Mux(write_way.valid, write_way.bits, RegNext(read_way.bits))
593
594    replacer.access(touch_set, touch_way)
595
596    // Select the update allocate way
597    // Selection logic:
598    //    1. if any entries within the same index is not valid, select it
599    //    2. if all entries is valid, use replacer
600    def allocWay(valids: UInt, idx: UInt): UInt =
601      if (numWays > 1) {
602        val w     = Wire(UInt(log2Up(numWays).W))
603        val valid = WireInit(valids.andR)
604        w := Mux(valid, replacer.way(idx), PriorityEncoder(~valids))
605        w
606      } else {
607        val w = WireInit(0.U(log2Up(numWays).W))
608        w
609      }
610
611    io.read_resp       := Mux1H(total_hits, read_entries) // Mux1H
612    io.read_hits.valid := hit
613    io.read_hits.bits  := hit_way
614
615    io.read_multi_entry      := multi_hit_selectEntry
616    io.read_multi_hits.valid := multi_hit
617    io.read_multi_hits.bits  := multi_way
618
619    io.update_hits.valid := u_hit
620    io.update_hits.bits  := u_hit_way
621
622    // Update logic
623    val u_valid       = io.update_write_data.valid
624    val u_data        = io.update_write_data.bits
625    val u_idx         = ftbAddr.getIdx(io.update_pc)
626    val allocWriteWay = allocWay(RegNext(VecInit(ftb_r_entries.map(_.valid))).asUInt, u_idx)
627    val u_way         = Mux(io.update_write_alloc, allocWriteWay, io.update_write_way)
628    val u_mask        = UIntToOH(u_way)
629
630    for (i <- 0 until numWays) {
631      XSPerfAccumulate(f"ftb_replace_way$i", u_valid && io.update_write_alloc && u_way === i.U)
632      XSPerfAccumulate(
633        f"ftb_replace_way${i}_has_empty",
634        u_valid && io.update_write_alloc && !ftb_r_entries.map(_.valid).reduce(_ && _) && u_way === i.U
635      )
636      XSPerfAccumulate(f"ftb_hit_way$i", hit && !io.update_access && hit_way === i.U)
637    }
638
639    ftb.io.w.apply(u_valid, u_data, u_idx, u_mask)
640
641    // for replacer
642    write_set       := u_idx
643    write_way.valid := u_valid
644    write_way.bits  := Mux(io.update_write_alloc, allocWriteWay, io.update_write_way)
645
646    // print hit entry info
647    Mux1H(total_hits, ftb.io.r.resp.data).display(true.B)
648  } // FTBBank
649
650  // FTB switch register & temporary storage of fauftb prediction results
651  val s0_close_ftb_req            = RegInit(false.B)
652  val s1_close_ftb_req            = RegEnable(s0_close_ftb_req, false.B, io.s0_fire(0))
653  val s2_close_ftb_req            = RegEnable(s1_close_ftb_req, false.B, io.s1_fire(0))
654  val s2_fauftb_ftb_entry_dup     = io.s1_fire.map(f => RegEnable(io.fauftb_entry_in, f))
655  val s2_fauftb_ftb_entry_hit_dup = io.s1_fire.map(f => RegEnable(io.fauftb_entry_hit_in, f))
656
657  val ftbBank = Module(new FTBBank(numSets, numWays))
658
659  // for close ftb read_req
660  ftbBank.io.req_pc.valid := io.s0_fire(0) && !s0_close_ftb_req
661  ftbBank.io.req_pc.bits  := s0_pc_dup(0)
662
663  val s2_multi_hit        = ftbBank.io.read_multi_hits.valid && io.s2_fire(0)
664  val s2_multi_hit_way    = ftbBank.io.read_multi_hits.bits
665  val s2_multi_hit_entry  = ftbBank.io.read_multi_entry
666  val s2_multi_hit_enable = s2_multi_hit && !s2_close_ftb_req
667  XSPerfAccumulate("ftb_s2_multi_hit", s2_multi_hit)
668  XSPerfAccumulate("ftb_s2_multi_hit_enable", s2_multi_hit_enable)
669
670  // After closing ftb, the entry output from s2 is the entry of FauFTB cached in s1
671  val btb_enable_dup   = dup(RegNext(io.ctrl.btb_enable))
672  val s1_read_resp     = Mux(s1_close_ftb_req, io.fauftb_entry_in, ftbBank.io.read_resp)
673  val s2_ftbBank_dup   = io.s1_fire.map(f => RegEnable(ftbBank.io.read_resp, f))
674  val s2_ftb_entry_dup = dup(0.U.asTypeOf(new FTBEntry))
675  for (
676    ((s2_fauftb_entry, s2_ftbBank_entry), s2_ftb_entry) <-
677      s2_fauftb_ftb_entry_dup zip s2_ftbBank_dup zip s2_ftb_entry_dup
678  ) {
679    s2_ftb_entry := Mux(s2_close_ftb_req, s2_fauftb_entry, s2_ftbBank_entry)
680  }
681  val s3_ftb_entry_dup = io.s2_fire.zip(s2_ftb_entry_dup).map { case (f, e) =>
682    RegEnable(Mux(s2_multi_hit_enable, s2_multi_hit_entry, e), f)
683  }
684  val real_s2_ftb_entry         = Mux(s2_multi_hit_enable, s2_multi_hit_entry, s2_ftb_entry_dup(0))
685  val real_s2_pc                = s2_pc_dup(0).getAddr()
686  val real_s2_startLower        = Cat(0.U(1.W), real_s2_pc(instOffsetBits + log2Ceil(PredictWidth) - 1, instOffsetBits))
687  val real_s2_endLowerwithCarry = Cat(real_s2_ftb_entry.carry, real_s2_ftb_entry.pftAddr)
688  val real_s2_fallThroughErr =
689    real_s2_startLower >= real_s2_endLowerwithCarry || real_s2_endLowerwithCarry > (real_s2_startLower + PredictWidth.U)
690  val real_s3_fallThroughErr_dup = io.s2_fire.map(f => RegEnable(real_s2_fallThroughErr, f))
691
692  // After closing ftb, the hit output from s2 is the hit of FauFTB cached in s1.
693  // s1_hit is the ftbBank hit.
694  val s1_hit         = Mux(s1_close_ftb_req, false.B, ftbBank.io.read_hits.valid && io.ctrl.btb_enable)
695  val s2_ftb_hit_dup = io.s1_fire.map(f => RegEnable(s1_hit, 0.B, f))
696  val s2_hit_dup     = dup(0.U.asTypeOf(Bool()))
697  for (
698    ((s2_fauftb_hit, s2_ftb_hit), s2_hit) <-
699      s2_fauftb_ftb_entry_hit_dup zip s2_ftb_hit_dup zip s2_hit_dup
700  ) {
701    s2_hit := Mux(s2_close_ftb_req, s2_fauftb_hit, s2_ftb_hit)
702  }
703  val s3_hit_dup = io.s2_fire.zip(s2_hit_dup).map { case (f, h) =>
704    RegEnable(Mux(s2_multi_hit_enable, s2_multi_hit, h), 0.B, f)
705  }
706  val s3_multi_hit_dup  = io.s2_fire.map(f => RegEnable(s2_multi_hit_enable, f))
707  val writeWay          = Mux(s1_close_ftb_req, 0.U, ftbBank.io.read_hits.bits)
708  val s2_ftb_meta       = RegEnable(FTBMeta(writeWay.asUInt, s1_hit, GTimer()).asUInt, io.s1_fire(0))
709  val s2_multi_hit_meta = FTBMeta(s2_multi_hit_way.asUInt, s2_multi_hit, GTimer()).asUInt
710
711  // Consistent count of entries for fauftb and ftb
712  val fauftb_ftb_entry_consistent_counter = RegInit(0.U(FTBCLOSE_THRESHOLD_SZ.W))
713  val fauftb_ftb_entry_consistent         = s2_fauftb_ftb_entry_dup(0).entryConsistent(s2_ftbBank_dup(0))
714
715  // if close ftb_req, the counter need keep
716  when(io.s2_fire(0) && s2_fauftb_ftb_entry_hit_dup(0) && s2_ftb_hit_dup(0)) {
717    fauftb_ftb_entry_consistent_counter := Mux(
718      fauftb_ftb_entry_consistent,
719      fauftb_ftb_entry_consistent_counter + 1.U,
720      0.U
721    )
722  }.elsewhen(io.s2_fire(0) && !s2_fauftb_ftb_entry_hit_dup(0) && s2_ftb_hit_dup(0)) {
723    fauftb_ftb_entry_consistent_counter := 0.U
724  }
725
726  when((fauftb_ftb_entry_consistent_counter >= FTBCLOSE_THRESHOLD) && io.s0_fire(0)) {
727    s0_close_ftb_req := true.B
728  }
729
730  // Clear counter during false_hit or ifuRedirect
731  val ftb_false_hit = WireInit(false.B)
732  val needReopen    = s0_close_ftb_req && (ftb_false_hit || io.redirectFromIFU)
733  ftb_false_hit := io.update.valid && io.update.bits.false_hit
734  when(needReopen) {
735    fauftb_ftb_entry_consistent_counter := 0.U
736    s0_close_ftb_req                    := false.B
737  }
738
739  val s2_close_consistent     = s2_fauftb_ftb_entry_dup(0).entryConsistent(s2_ftb_entry_dup(0))
740  val s2_not_close_consistent = s2_ftbBank_dup(0).entryConsistent(s2_ftb_entry_dup(0))
741
742  when(s2_close_ftb_req && io.s2_fire(0)) {
743    assert(s2_close_consistent, s"Entry inconsistency after ftb req is closed!")
744  }.elsewhen(!s2_close_ftb_req && io.s2_fire(0)) {
745    assert(s2_not_close_consistent, s"Entry inconsistency after ftb req is not closed!")
746  }
747
748  val reopenCounter         = !s1_close_ftb_req && s2_close_ftb_req && io.s2_fire(0)
749  val falseHitReopenCounter = ftb_false_hit && s1_close_ftb_req
750  XSPerfAccumulate("ftb_req_reopen_counter", reopenCounter)
751  XSPerfAccumulate("false_hit_reopen_Counter", falseHitReopenCounter)
752  XSPerfAccumulate("ifuRedirec_needReopen", s1_close_ftb_req && io.redirectFromIFU)
753  XSPerfAccumulate("this_cycle_is_close", s2_close_ftb_req && io.s2_fire(0))
754  XSPerfAccumulate("this_cycle_is_open", !s2_close_ftb_req && io.s2_fire(0))
755
756  // io.out.bits.resp := RegEnable(io.in.bits.resp_in(0), 0.U.asTypeOf(new BranchPredictionResp), io.s1_fire)
757  io.out := io.in.bits.resp_in(0)
758
759  io.out.s2.full_pred.map { case fp => fp.multiHit := false.B }
760
761  io.out.s2.full_pred.zip(s2_hit_dup).map { case (fp, h) => fp.hit := h }
762  for (
763    full_pred & s2_ftb_entry & s2_pc & s1_pc & s1_fire <-
764      io.out.s2.full_pred zip s2_ftb_entry_dup zip s2_pc_dup zip s1_pc_dup zip io.s1_fire
765  ) {
766    full_pred.fromFtbEntry(
767      s2_ftb_entry,
768      s2_pc.getAddr(),
769      // Previous stage meta for better timing
770      Some(s1_pc, s1_fire),
771      Some(s1_read_resp, s1_fire)
772    )
773  }
774
775  io.out.s3.full_pred.zip(s3_hit_dup).map { case (fp, h) => fp.hit := h }
776  io.out.s3.full_pred.zip(s3_multi_hit_dup).map { case (fp, m) => fp.multiHit := m }
777  for (
778    full_pred & s3_ftb_entry & s3_pc & s2_pc & s2_fire <-
779      io.out.s3.full_pred zip s3_ftb_entry_dup zip s3_pc_dup zip s2_pc_dup zip io.s2_fire
780  )
781    full_pred.fromFtbEntry(s3_ftb_entry, s3_pc.getAddr(), Some((s2_pc.getAddr(), s2_fire)))
782
783  // Overwrite the fallThroughErr value
784  io.out.s3.full_pred.zipWithIndex.map { case (fp, i) => fp.fallThroughErr := real_s3_fallThroughErr_dup(i) }
785
786  io.out.last_stage_ftb_entry := s3_ftb_entry_dup(0)
787  io.out.last_stage_meta      := RegEnable(Mux(s2_multi_hit_enable, s2_multi_hit_meta, s2_ftb_meta), io.s2_fire(0))
788  io.out.s1_ftbCloseReq       := s1_close_ftb_req
789  io.out.s1_uftbHit           := io.fauftb_entry_hit_in
790  val s1_uftbHasIndirect = io.fauftb_entry_in.jmpValid &&
791    io.fauftb_entry_in.isJalr && !io.fauftb_entry_in.isRet // uFTB determines that it's real JALR, RET and JAL are excluded
792  io.out.s1_uftbHasIndirect := s1_uftbHasIndirect
793
794  // always taken logic
795  for (i <- 0 until numBr) {
796    for (
797      out_fp & in_fp & s2_hit & s2_ftb_entry <-
798        io.out.s2.full_pred zip io.in.bits.resp_in(0).s2.full_pred zip s2_hit_dup zip s2_ftb_entry_dup
799    )
800      out_fp.br_taken_mask(i) := in_fp.br_taken_mask(i) || s2_hit && s2_ftb_entry.always_taken(i)
801    for (
802      out_fp & in_fp & s3_hit & s3_ftb_entry <-
803        io.out.s3.full_pred zip io.in.bits.resp_in(0).s3.full_pred zip s3_hit_dup zip s3_ftb_entry_dup
804    )
805      out_fp.br_taken_mask(i) := in_fp.br_taken_mask(i) || s3_hit && s3_ftb_entry.always_taken(i)
806  }
807
808  // Update logic
809  val update = io.update.bits
810
811  val u_meta  = update.meta.asTypeOf(new FTBMeta)
812  val u_valid = io.update.valid && !io.update.bits.old_entry
813
814  val (_, delay2_pc)    = DelayNWithValid(update.pc, u_valid, 2)
815  val (_, delay2_entry) = DelayNWithValid(update.ftb_entry, u_valid, 2)
816
817  val update_now       = u_valid && u_meta.hit
818  val update_need_read = u_valid && !u_meta.hit
819  // stall one more cycle because we use a whole cycle to do update read tag hit
820  io.s1_ready := ftbBank.io.req_pc.ready && !update_need_read && !RegNext(update_need_read)
821
822  ftbBank.io.u_req_pc.valid := update_need_read
823  ftbBank.io.u_req_pc.bits  := update.pc
824
825  val ftb_write = Wire(new FTBEntryWithTag)
826  ftb_write.entry := Mux(update_now, update.ftb_entry, delay2_entry)
827  ftb_write.tag   := ftbAddr.getTag(Mux(update_now, update.pc, delay2_pc))(tagSize - 1, 0)
828
829  val write_valid = update_now || DelayN(u_valid && !u_meta.hit, 2)
830  val write_pc    = Mux(update_now, update.pc, delay2_pc)
831
832  ftbBank.io.update_write_data.valid := write_valid
833  ftbBank.io.update_write_data.bits  := ftb_write
834  ftbBank.io.update_pc               := write_pc
835  ftbBank.io.update_write_way := Mux(
836    update_now,
837    u_meta.writeWay,
838    RegNext(ftbBank.io.update_hits.bits)
839  ) // use it one cycle later
840  ftbBank.io.update_write_alloc := Mux(
841    update_now,
842    false.B,
843    RegNext(!ftbBank.io.update_hits.valid)
844  ) // use it one cycle later
845  ftbBank.io.update_access := u_valid && !u_meta.hit
846  ftbBank.io.s1_fire       := io.s1_fire(0)
847
848  val ftb_write_fallThrough = ftb_write.entry.getFallThrough(write_pc)
849  when(write_valid) {
850    assert(write_pc + (FetchWidth * 4).U >= ftb_write_fallThrough, s"FTB write_entry fallThrough address error!")
851  }
852
853  XSDebug("req_v=%b, req_pc=%x, ready=%b (resp at next cycle)\n", io.s0_fire(0), s0_pc_dup(0), ftbBank.io.req_pc.ready)
854  XSDebug("s2_hit=%b, hit_way=%b\n", s2_hit_dup(0), writeWay.asUInt)
855  XSDebug(
856    "s2_br_taken_mask=%b, s2_real_taken_mask=%b\n",
857    io.in.bits.resp_in(0).s2.full_pred(0).br_taken_mask.asUInt,
858    io.out.s2.full_pred(0).real_slot_taken_mask().asUInt
859  )
860  XSDebug("s2_target=%x\n", io.out.s2.getTarget(0))
861
862  s2_ftb_entry_dup(0).display(true.B)
863
864  XSPerfAccumulate("ftb_read_hits", RegNext(io.s0_fire(0)) && s1_hit)
865  XSPerfAccumulate("ftb_read_misses", RegNext(io.s0_fire(0)) && !s1_hit)
866
867  XSPerfAccumulate("ftb_commit_hits", io.update.valid && u_meta.hit)
868  XSPerfAccumulate("ftb_commit_misses", io.update.valid && !u_meta.hit)
869
870  XSPerfAccumulate("ftb_update_req", io.update.valid)
871  XSPerfAccumulate("ftb_update_ignored", io.update.valid && io.update.bits.old_entry)
872  XSPerfAccumulate("ftb_updated", u_valid)
873
874  override val perfEvents = Seq(
875    ("ftb_commit_hits            ", io.update.valid && u_meta.hit),
876    ("ftb_commit_misses          ", io.update.valid && !u_meta.hit)
877  )
878  generatePerfEvent()
879}
880