xref: /XiangShan/src/main/scala/xiangshan/frontend/FTB.scala (revision 211d620b07edb797ba35b635d24fef4e7294bae2)
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  // Mark the conditional branch for the first jump and the jalr instruction that appears for the first time,
191  // and train the tag/ittage without using its results when strong_bias is true.
192  val strong_bias = Vec(numBr, Bool())
193
194  def getSlotForBr(idx: Int): FtbSlot = {
195    require(idx <= numBr - 1)
196    (idx, numBr) match {
197      case (i, n) if i == n - 1 => this.tailSlot
198      case _                    => this.brSlots(idx)
199    }
200  }
201  def allSlotsForBr =
202    (0 until numBr).map(getSlotForBr(_))
203  def setByBrTarget(brIdx: Int, pc: UInt, target: UInt) = {
204    val slot = getSlotForBr(brIdx)
205    slot.setLowerStatByTarget(pc, target, brIdx == numBr - 1)
206  }
207  def setByJmpTarget(pc: UInt, target: UInt) =
208    this.tailSlot.setLowerStatByTarget(pc, target, false)
209
210  def getTargetVec(pc: UInt, last_stage: Option[Tuple2[UInt, Bool]] = None) = {
211    /*
212    Previous design: Use the getTarget function of FTBSlot to calculate three sets of targets separately;
213    During this process, nine sets of registers will be generated to register the values of the higher plus one minus one
214    Current design: Reuse the duplicate parts of the original nine sets of registers,
215    calculate the common high bits last_stage_pc_higher of brtarget and jmptarget,
216    and the high bits last_stage_pc_middle that need to be added and subtracted from each other,
217    and then concatenate them according to the carry situation to obtain brtarget and jmptarget
218     */
219    val h_br                  = pc(VAddrBits - 1, BR_OFFSET_LEN + 1)
220    val higher_br             = Wire(UInt((VAddrBits - BR_OFFSET_LEN - 1).W))
221    val higher_plus_one_br    = Wire(UInt((VAddrBits - BR_OFFSET_LEN - 1).W))
222    val higher_minus_one_br   = Wire(UInt((VAddrBits - BR_OFFSET_LEN - 1).W))
223    val h_tail                = pc(VAddrBits - 1, JMP_OFFSET_LEN + 1)
224    val higher_tail           = Wire(UInt((VAddrBits - JMP_OFFSET_LEN - 1).W))
225    val higher_plus_one_tail  = Wire(UInt((VAddrBits - JMP_OFFSET_LEN - 1).W))
226    val higher_minus_one_tail = Wire(UInt((VAddrBits - JMP_OFFSET_LEN - 1).W))
227    if (last_stage.isDefined) {
228      val last_stage_pc                  = last_stage.get._1
229      val stage_en                       = last_stage.get._2
230      val last_stage_pc_higher           = RegEnable(last_stage_pc(VAddrBits - 1, JMP_OFFSET_LEN + 1), stage_en)
231      val last_stage_pc_middle           = RegEnable(last_stage_pc(JMP_OFFSET_LEN, BR_OFFSET_LEN + 1), stage_en)
232      val last_stage_pc_higher_plus_one  = RegEnable(last_stage_pc(VAddrBits - 1, JMP_OFFSET_LEN + 1) + 1.U, stage_en)
233      val last_stage_pc_higher_minus_one = RegEnable(last_stage_pc(VAddrBits - 1, JMP_OFFSET_LEN + 1) - 1.U, stage_en)
234      val last_stage_pc_middle_plus_one =
235        RegEnable(Cat(0.U(1.W), last_stage_pc(JMP_OFFSET_LEN, BR_OFFSET_LEN + 1)) + 1.U, stage_en)
236      val last_stage_pc_middle_minus_one =
237        RegEnable(Cat(0.U(1.W), last_stage_pc(JMP_OFFSET_LEN, BR_OFFSET_LEN + 1)) - 1.U, stage_en)
238
239      higher_br := Cat(last_stage_pc_higher, last_stage_pc_middle)
240      higher_plus_one_br := Mux(
241        last_stage_pc_middle_plus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN),
242        Cat(last_stage_pc_higher_plus_one, last_stage_pc_middle_plus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN - 1, 0)),
243        Cat(last_stage_pc_higher, last_stage_pc_middle_plus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN - 1, 0))
244      )
245      higher_minus_one_br := Mux(
246        last_stage_pc_middle_minus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN),
247        Cat(last_stage_pc_higher_minus_one, last_stage_pc_middle_minus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN - 1, 0)),
248        Cat(last_stage_pc_higher, last_stage_pc_middle_minus_one(JMP_OFFSET_LEN - BR_OFFSET_LEN - 1, 0))
249      )
250
251      higher_tail           := last_stage_pc_higher
252      higher_plus_one_tail  := last_stage_pc_higher_plus_one
253      higher_minus_one_tail := last_stage_pc_higher_minus_one
254    } else {
255      higher_br             := h_br
256      higher_plus_one_br    := h_br + 1.U
257      higher_minus_one_br   := h_br - 1.U
258      higher_tail           := h_tail
259      higher_plus_one_tail  := h_tail + 1.U
260      higher_minus_one_tail := h_tail - 1.U
261    }
262    val br_slots_targets = VecInit(brSlots.map(s =>
263      Cat(
264        Mux1H(Seq(
265          (s.tarStat === TAR_OVF, higher_plus_one_br),
266          (s.tarStat === TAR_UDF, higher_minus_one_br),
267          (s.tarStat === TAR_FIT, higher_br)
268        )),
269        s.lower(s.offsetLen - 1, 0),
270        0.U(1.W)
271      )
272    ))
273    val tail_target = Wire(UInt(VAddrBits.W))
274    if (tailSlot.subOffsetLen.isDefined) {
275      tail_target := Mux(
276        tailSlot.sharing,
277        Cat(
278          Mux1H(Seq(
279            (tailSlot.tarStat === TAR_OVF, higher_plus_one_br),
280            (tailSlot.tarStat === TAR_UDF, higher_minus_one_br),
281            (tailSlot.tarStat === TAR_FIT, higher_br)
282          )),
283          tailSlot.lower(tailSlot.subOffsetLen.get - 1, 0),
284          0.U(1.W)
285        ),
286        Cat(
287          Mux1H(Seq(
288            (tailSlot.tarStat === TAR_OVF, higher_plus_one_tail),
289            (tailSlot.tarStat === TAR_UDF, higher_minus_one_tail),
290            (tailSlot.tarStat === TAR_FIT, higher_tail)
291          )),
292          tailSlot.lower(tailSlot.offsetLen - 1, 0),
293          0.U(1.W)
294        )
295      )
296    } else {
297      tail_target := Cat(
298        Mux1H(Seq(
299          (tailSlot.tarStat === TAR_OVF, higher_plus_one_tail),
300          (tailSlot.tarStat === TAR_UDF, higher_minus_one_tail),
301          (tailSlot.tarStat === TAR_FIT, higher_tail)
302        )),
303        tailSlot.lower(tailSlot.offsetLen - 1, 0),
304        0.U(1.W)
305      )
306    }
307
308    br_slots_targets.map(t => require(t.getWidth == VAddrBits))
309    require(tail_target.getWidth == VAddrBits)
310    val targets = VecInit(br_slots_targets :+ tail_target)
311    targets
312  }
313
314  def getOffsetVec = VecInit(brSlots.map(_.offset) :+ tailSlot.offset)
315  def getFallThrough(pc: UInt, last_stage_entry: Option[Tuple2[FTBEntry, Bool]] = None) =
316    if (last_stage_entry.isDefined) {
317      var stashed_carry = RegEnable(last_stage_entry.get._1.carry, last_stage_entry.get._2)
318      getFallThroughAddr(pc, stashed_carry, pftAddr)
319    } else {
320      getFallThroughAddr(pc, carry, pftAddr)
321    }
322
323  def hasBr(offset: UInt) =
324    brSlots.map(s => s.valid && s.offset <= offset).reduce(_ || _) ||
325      (tailSlot.valid && tailSlot.offset <= offset && tailSlot.sharing)
326
327  def getBrMaskByOffset(offset: UInt) =
328    brSlots.map { s =>
329      s.valid && s.offset <= offset
330    } :+
331      (tailSlot.valid && tailSlot.offset <= offset && tailSlot.sharing)
332
333  def getBrRecordedVec(offset: UInt) =
334    VecInit(
335      brSlots.map(s => s.valid && s.offset === offset) :+
336        (tailSlot.valid && tailSlot.offset === offset && tailSlot.sharing)
337    )
338
339  def brIsSaved(offset: UInt) = getBrRecordedVec(offset).reduce(_ || _)
340
341  def brValids =
342    VecInit(
343      brSlots.map(_.valid) :+ (tailSlot.valid && tailSlot.sharing)
344    )
345
346  def noEmptySlotForNewBr =
347    VecInit(brSlots.map(_.valid) :+ tailSlot.valid).reduce(_ && _)
348
349  def newBrCanNotInsert(offset: UInt) = {
350    val lastSlotForBr = tailSlot
351    lastSlotForBr.valid && lastSlotForBr.offset < offset
352  }
353
354  def jmpValid =
355    tailSlot.valid && !tailSlot.sharing
356
357  def brOffset =
358    VecInit(brSlots.map(_.offset) :+ tailSlot.offset)
359
360  def entryConsistent(that: FTBEntry) = {
361    val validDiff = this.valid === that.valid
362    val brSlotsDiffSeq: IndexedSeq[Bool] =
363      this.brSlots.zip(that.brSlots).map {
364        case (x, y) => x.slotConsistent(y)
365      }
366    val tailSlotDiff         = this.tailSlot.slotConsistent(that.tailSlot)
367    val pftAddrDiff          = this.pftAddr === that.pftAddr
368    val carryDiff            = this.carry === that.carry
369    val isCallDiff           = this.isCall === that.isCall
370    val isRetDiff            = this.isRet === that.isRet
371    val isJalrDiff           = this.isJalr === that.isJalr
372    val lastMayBeRviCallDiff = this.last_may_be_rvi_call === that.last_may_be_rvi_call
373    val alwaysTakenDiff: IndexedSeq[Bool] =
374      this.strong_bias.zip(that.strong_bias).map {
375        case (x, y) => x === y
376      }
377    VecInit(
378      validDiff,
379      brSlotsDiffSeq.reduce(_ && _),
380      tailSlotDiff,
381      pftAddrDiff,
382      carryDiff,
383      isCallDiff,
384      isRetDiff,
385      isJalrDiff,
386      lastMayBeRviCallDiff,
387      alwaysTakenDiff.reduce(_ && _)
388    ).reduce(_ && _)
389  }
390
391  def display(cond: Bool): Unit = {
392    XSDebug(cond, p"-----------FTB entry----------- \n")
393    XSDebug(cond, p"v=${valid}\n")
394    for (i <- 0 until numBr) {
395      XSDebug(
396        cond,
397        p"[br$i]: v=${allSlotsForBr(i).valid}, offset=${allSlotsForBr(i).offset}," +
398          p"lower=${Hexadecimal(allSlotsForBr(i).lower)}\n"
399      )
400    }
401    XSDebug(
402      cond,
403      p"[tailSlot]: v=${tailSlot.valid}, offset=${tailSlot.offset}," +
404        p"lower=${Hexadecimal(tailSlot.lower)}, sharing=${tailSlot.sharing}}\n"
405    )
406    XSDebug(cond, p"pftAddr=${Hexadecimal(pftAddr)}, carry=$carry\n")
407    XSDebug(cond, p"isCall=$isCall, isRet=$isRet, isjalr=$isJalr\n")
408    XSDebug(cond, p"last_may_be_rvi_call=$last_may_be_rvi_call\n")
409    XSDebug(cond, p"------------------------------- \n")
410  }
411
412}
413
414class FTBEntryWithTag(implicit p: Parameters) extends XSBundle with FTBParams with BPUUtils {
415  val entry = new FTBEntry
416  val tag   = UInt(tagSize.W)
417  def display(cond: Bool): Unit = {
418    entry.display(cond)
419    XSDebug(cond, p"tag is ${Hexadecimal(tag)}\n------------------------------- \n")
420  }
421}
422
423class FTBMeta(implicit p: Parameters) extends XSBundle with FTBParams {
424  val writeWay   = UInt(log2Ceil(numWays).W)
425  val hit        = Bool()
426  val pred_cycle = if (!env.FPGAPlatform) Some(UInt(64.W)) else None
427}
428
429object FTBMeta {
430  def apply(writeWay: UInt, hit: Bool, pred_cycle: UInt)(implicit p: Parameters): FTBMeta = {
431    val e = Wire(new FTBMeta)
432    e.writeWay := writeWay
433    e.hit      := hit
434    e.pred_cycle.map(_ := pred_cycle)
435    e
436  }
437}
438
439// class UpdateQueueEntry(implicit p: Parameters) extends XSBundle with FTBParams {
440//   val pc = UInt(VAddrBits.W)
441//   val ftb_entry = new FTBEntry
442//   val hit = Bool()
443//   val hit_way = UInt(log2Ceil(numWays).W)
444// }
445//
446// object UpdateQueueEntry {
447//   def apply(pc: UInt, fe: FTBEntry, hit: Bool, hit_way: UInt)(implicit p: Parameters): UpdateQueueEntry = {
448//     val e = Wire(new UpdateQueueEntry)
449//     e.pc := pc
450//     e.ftb_entry := fe
451//     e.hit := hit
452//     e.hit_way := hit_way
453//     e
454//   }
455// }
456
457class FTBTableAddr(val idxBits: Int, val banks: Int, val skewedBits: Int)(implicit p: Parameters) extends XSBundle {
458  val addr = new TableAddr(idxBits, banks)
459  def getIdx(x: UInt) = addr.getIdx(x) ^ Cat(addr.getTag(x), addr.getIdx(x))(idxBits + skewedBits - 1, skewedBits)
460  def getTag(x: UInt) = addr.getTag(x)
461}
462
463class FTB(implicit p: Parameters) extends BasePredictor with FTBParams with BPUUtils
464    with HasCircularQueuePtrHelper with HasPerfEvents {
465  override val meta_size = WireInit(0.U.asTypeOf(new FTBMeta)).getWidth
466
467  val ftbAddr = new FTBTableAddr(log2Up(numSets), 1, 3)
468
469  class FTBBank(val numSets: Int, val nWays: Int) extends XSModule with BPUUtils {
470    val io = IO(new Bundle {
471      val s1_fire = Input(Bool())
472
473      // when ftb hit, read_hits.valid is true, and read_hits.bits is OH of hit way
474      // when ftb not hit, read_hits.valid is false, and read_hits is OH of allocWay
475      // val read_hits = Valid(Vec(numWays, Bool()))
476      val req_pc    = Flipped(DecoupledIO(UInt(VAddrBits.W)))
477      val read_resp = Output(new FTBEntry)
478      val read_hits = Valid(UInt(log2Ceil(numWays).W))
479
480      val read_multi_entry = Output(new FTBEntry)
481      val read_multi_hits  = Valid(UInt(log2Ceil(numWays).W))
482
483      val u_req_pc      = Flipped(DecoupledIO(UInt(VAddrBits.W)))
484      val update_hits   = Valid(UInt(log2Ceil(numWays).W))
485      val update_access = Input(Bool())
486
487      val update_pc          = Input(UInt(VAddrBits.W))
488      val update_write_data  = Flipped(Valid(new FTBEntryWithTag))
489      val update_write_way   = Input(UInt(log2Ceil(numWays).W))
490      val update_write_alloc = Input(Bool())
491    })
492
493    // Extract holdRead logic to fix bug that update read override predict read result
494    val ftb = Module(new SRAMTemplate(
495      new FTBEntryWithTag,
496      set = numSets,
497      way = numWays,
498      shouldReset = true,
499      holdRead = false,
500      singlePort = true
501    ))
502    val ftb_r_entries = ftb.io.r.resp.data.map(_.entry)
503
504    val pred_rdata = HoldUnless(
505      ftb.io.r.resp.data,
506      RegNext(io.req_pc.valid && !io.update_access),
507      init = Some(VecInit.fill(numWays)(0.U.asTypeOf(new FTBEntryWithTag)))
508    ) // rdata has ftb_entry.valid, shoud reset
509    ftb.io.r.req.valid := io.req_pc.valid || io.u_req_pc.valid // io.s0_fire
510    ftb.io.r.req.bits.setIdx := Mux(
511      io.u_req_pc.valid,
512      ftbAddr.getIdx(io.u_req_pc.bits),
513      ftbAddr.getIdx(io.req_pc.bits)
514    ) // s0_idx
515
516    assert(!(io.req_pc.valid && io.u_req_pc.valid))
517
518    io.req_pc.ready   := ftb.io.r.req.ready
519    io.u_req_pc.ready := ftb.io.r.req.ready
520
521    val req_tag = RegEnable(ftbAddr.getTag(io.req_pc.bits)(tagSize - 1, 0), io.req_pc.valid)
522    val req_idx = RegEnable(ftbAddr.getIdx(io.req_pc.bits), io.req_pc.valid)
523
524    val u_req_tag = RegEnable(ftbAddr.getTag(io.u_req_pc.bits)(tagSize - 1, 0), io.u_req_pc.valid)
525
526    val read_entries = pred_rdata.map(_.entry)
527    val read_tags    = pred_rdata.map(_.tag)
528
529    val total_hits =
530      VecInit((0 until numWays).map(b => read_tags(b) === req_tag && read_entries(b).valid && io.s1_fire))
531    val hit = total_hits.reduce(_ || _)
532    // val hit_way_1h = VecInit(PriorityEncoderOH(total_hits))
533    val hit_way = OHToUInt(total_hits)
534
535    // There may be two hits in the four paths of the ftbBank, and the OHToUInt will fail.
536    // If there is a redirect in s2 at this time, the wrong FTBEntry will be used to calculate the target,
537    // resulting in an address error and affecting performance.
538    // The solution is to select a hit entry during multi hit as the entry for s2.
539    // Considering timing, use this entry in s3 and trigger s3-redirect.
540    val total_hits_reg   = RegEnable(total_hits, io.s1_fire)
541    val read_entries_reg = read_entries.map(w => RegEnable(w, io.s1_fire))
542
543    val multi_hit = VecInit((0 until numWays).map {
544      i =>
545        (0 until numWays).map { j =>
546          if (i < j) total_hits_reg(i) && total_hits_reg(j)
547          else false.B
548        }.reduce(_ || _)
549    }).reduce(_ || _)
550    val multi_way = PriorityMux(Seq.tabulate(numWays)(i => (total_hits_reg(i)) -> i.asUInt(log2Ceil(numWays).W)))
551    val multi_hit_selectEntry = PriorityMux(Seq.tabulate(numWays)(i => (total_hits_reg(i)) -> read_entries_reg(i)))
552
553    // Check if the entry read by ftbBank is legal.
554    for (n <- 0 to numWays - 1) {
555      val req_pc_reg       = RegEnable(io.req_pc.bits, 0.U.asTypeOf(io.req_pc.bits), io.req_pc.valid)
556      val req_pc_reg_lower = Cat(0.U(1.W), req_pc_reg(instOffsetBits + log2Ceil(PredictWidth) - 1, instOffsetBits))
557      val ftbEntryEndLowerwithCarry = Cat(read_entries(n).carry, read_entries(n).pftAddr)
558      val fallThroughErr            = req_pc_reg_lower + PredictWidth.U >= ftbEntryEndLowerwithCarry
559      when(read_entries(n).valid && total_hits(n) && io.s1_fire) {
560        assert(fallThroughErr, s"FTB read sram entry in way${n} fallThrough address error!")
561      }
562    }
563
564    val u_total_hits = VecInit((0 until numWays).map(b =>
565      ftb.io.r.resp.data(b).tag === u_req_tag && ftb.io.r.resp.data(b).entry.valid && RegNext(io.update_access)
566    ))
567    val u_hit = u_total_hits.reduce(_ || _)
568    // val hit_way_1h = VecInit(PriorityEncoderOH(total_hits))
569    val u_hit_way = OHToUInt(u_total_hits)
570
571    // assert(PopCount(total_hits) === 1.U || PopCount(total_hits) === 0.U)
572    // assert(PopCount(u_total_hits) === 1.U || PopCount(u_total_hits) === 0.U)
573    for (n <- 1 to numWays) {
574      XSPerfAccumulate(f"ftb_pred_${n}_way_hit", PopCount(total_hits) === n.U)
575      XSPerfAccumulate(f"ftb_update_${n}_way_hit", PopCount(u_total_hits) === n.U)
576    }
577
578    val replacer = ReplacementPolicy.fromString(Some("setplru"), numWays, numSets)
579    // val allocWriteWay = replacer.way(req_idx)
580
581    val touch_set = Seq.fill(1)(Wire(UInt(log2Ceil(numSets).W)))
582    val touch_way = Seq.fill(1)(Wire(Valid(UInt(log2Ceil(numWays).W))))
583
584    val write_set = Wire(UInt(log2Ceil(numSets).W))
585    val write_way = Wire(Valid(UInt(log2Ceil(numWays).W)))
586
587    val read_set = Wire(UInt(log2Ceil(numSets).W))
588    val read_way = Wire(Valid(UInt(log2Ceil(numWays).W)))
589
590    read_set       := req_idx
591    read_way.valid := hit
592    read_way.bits  := hit_way
593
594    // Read replacer access is postponed for 1 cycle
595    // this helps timing
596    touch_set(0)       := Mux(write_way.valid, write_set, RegNext(read_set))
597    touch_way(0).valid := write_way.valid || RegNext(read_way.valid)
598    touch_way(0).bits  := Mux(write_way.valid, write_way.bits, RegNext(read_way.bits))
599
600    replacer.access(touch_set, touch_way)
601
602    // Select the update allocate way
603    // Selection logic:
604    //    1. if any entries within the same index is not valid, select it
605    //    2. if all entries is valid, use replacer
606    def allocWay(valids: UInt, idx: UInt): UInt =
607      if (numWays > 1) {
608        val w     = Wire(UInt(log2Up(numWays).W))
609        val valid = WireInit(valids.andR)
610        w := Mux(valid, replacer.way(idx), PriorityEncoder(~valids))
611        w
612      } else {
613        val w = WireInit(0.U(log2Up(numWays).W))
614        w
615      }
616
617    io.read_resp       := Mux1H(total_hits, read_entries) // Mux1H
618    io.read_hits.valid := hit
619    io.read_hits.bits  := hit_way
620
621    io.read_multi_entry      := multi_hit_selectEntry
622    io.read_multi_hits.valid := multi_hit
623    io.read_multi_hits.bits  := multi_way
624
625    io.update_hits.valid := u_hit
626    io.update_hits.bits  := u_hit_way
627
628    // Update logic
629    val u_valid       = io.update_write_data.valid
630    val u_data        = io.update_write_data.bits
631    val u_idx         = ftbAddr.getIdx(io.update_pc)
632    val allocWriteWay = allocWay(RegNext(VecInit(ftb_r_entries.map(_.valid))).asUInt, u_idx)
633    val u_way         = Mux(io.update_write_alloc, allocWriteWay, io.update_write_way)
634    val u_mask        = UIntToOH(u_way)
635
636    for (i <- 0 until numWays) {
637      XSPerfAccumulate(f"ftb_replace_way$i", u_valid && io.update_write_alloc && u_way === i.U)
638      XSPerfAccumulate(
639        f"ftb_replace_way${i}_has_empty",
640        u_valid && io.update_write_alloc && !ftb_r_entries.map(_.valid).reduce(_ && _) && u_way === i.U
641      )
642      XSPerfAccumulate(f"ftb_hit_way$i", hit && !io.update_access && hit_way === i.U)
643    }
644
645    ftb.io.w.apply(u_valid, u_data, u_idx, u_mask)
646
647    // for replacer
648    write_set       := u_idx
649    write_way.valid := u_valid
650    write_way.bits  := Mux(io.update_write_alloc, allocWriteWay, io.update_write_way)
651
652    // print hit entry info
653    Mux1H(total_hits, ftb.io.r.resp.data).display(true.B)
654  } // FTBBank
655
656  // FTB switch register & temporary storage of fauftb prediction results
657  val s0_close_ftb_req            = RegInit(false.B)
658  val s1_close_ftb_req            = RegEnable(s0_close_ftb_req, false.B, io.s0_fire(0))
659  val s2_close_ftb_req            = RegEnable(s1_close_ftb_req, false.B, io.s1_fire(0))
660  val s2_fauftb_ftb_entry_dup     = io.s1_fire.map(f => RegEnable(io.fauftb_entry_in, f))
661  val s2_fauftb_ftb_entry_hit_dup = io.s1_fire.map(f => RegEnable(io.fauftb_entry_hit_in, f))
662
663  val ftbBank = Module(new FTBBank(numSets, numWays))
664
665  // for close ftb read_req
666  ftbBank.io.req_pc.valid := io.s0_fire(0) && !s0_close_ftb_req
667  ftbBank.io.req_pc.bits  := s0_pc_dup(0)
668
669  val s2_multi_hit        = ftbBank.io.read_multi_hits.valid && io.s2_fire(0)
670  val s2_multi_hit_way    = ftbBank.io.read_multi_hits.bits
671  val s2_multi_hit_entry  = ftbBank.io.read_multi_entry
672  val s2_multi_hit_enable = s2_multi_hit && !s2_close_ftb_req
673  XSPerfAccumulate("ftb_s2_multi_hit", s2_multi_hit)
674  XSPerfAccumulate("ftb_s2_multi_hit_enable", s2_multi_hit_enable)
675
676  // After closing ftb, the entry output from s2 is the entry of FauFTB cached in s1
677  val btb_enable_dup   = dup(RegNext(io.ctrl.btb_enable))
678  val s1_read_resp     = Mux(s1_close_ftb_req, io.fauftb_entry_in, ftbBank.io.read_resp)
679  val s2_ftbBank_dup   = io.s1_fire.map(f => RegEnable(ftbBank.io.read_resp, f))
680  val s2_ftb_entry_dup = dup(0.U.asTypeOf(new FTBEntry))
681  for (
682    ((s2_fauftb_entry, s2_ftbBank_entry), s2_ftb_entry) <-
683      s2_fauftb_ftb_entry_dup zip s2_ftbBank_dup zip s2_ftb_entry_dup
684  ) {
685    s2_ftb_entry := Mux(s2_close_ftb_req, s2_fauftb_entry, s2_ftbBank_entry)
686  }
687  val s3_ftb_entry_dup = io.s2_fire.zip(s2_ftb_entry_dup).map { case (f, e) =>
688    RegEnable(Mux(s2_multi_hit_enable, s2_multi_hit_entry, e), f)
689  }
690  val real_s2_ftb_entry         = Mux(s2_multi_hit_enable, s2_multi_hit_entry, s2_ftb_entry_dup(0))
691  val real_s2_pc                = s2_pc_dup(0).getAddr()
692  val real_s2_startLower        = Cat(0.U(1.W), real_s2_pc(instOffsetBits + log2Ceil(PredictWidth) - 1, instOffsetBits))
693  val real_s2_endLowerwithCarry = Cat(real_s2_ftb_entry.carry, real_s2_ftb_entry.pftAddr)
694  val real_s2_fallThroughErr =
695    real_s2_startLower >= real_s2_endLowerwithCarry || real_s2_endLowerwithCarry > (real_s2_startLower + PredictWidth.U)
696  val real_s3_fallThroughErr_dup = io.s2_fire.map(f => RegEnable(real_s2_fallThroughErr, f))
697
698  // After closing ftb, the hit output from s2 is the hit of FauFTB cached in s1.
699  // s1_hit is the ftbBank hit.
700  val s1_hit         = Mux(s1_close_ftb_req, false.B, ftbBank.io.read_hits.valid && io.ctrl.btb_enable)
701  val s2_ftb_hit_dup = io.s1_fire.map(f => RegEnable(s1_hit, 0.B, f))
702  val s2_hit_dup     = dup(0.U.asTypeOf(Bool()))
703  for (
704    ((s2_fauftb_hit, s2_ftb_hit), s2_hit) <-
705      s2_fauftb_ftb_entry_hit_dup zip s2_ftb_hit_dup zip s2_hit_dup
706  ) {
707    s2_hit := Mux(s2_close_ftb_req, s2_fauftb_hit, s2_ftb_hit)
708  }
709  val s3_hit_dup = io.s2_fire.zip(s2_hit_dup).map { case (f, h) =>
710    RegEnable(Mux(s2_multi_hit_enable, s2_multi_hit, h), 0.B, f)
711  }
712  val s3_multi_hit_dup  = io.s2_fire.map(f => RegEnable(s2_multi_hit_enable, f))
713  val writeWay          = Mux(s1_close_ftb_req, 0.U, ftbBank.io.read_hits.bits)
714  val s2_ftb_meta       = RegEnable(FTBMeta(writeWay.asUInt, s1_hit, GTimer()).asUInt, io.s1_fire(0))
715  val s2_multi_hit_meta = FTBMeta(s2_multi_hit_way.asUInt, s2_multi_hit, GTimer()).asUInt
716
717  // Consistent count of entries for fauftb and ftb
718  val fauftb_ftb_entry_consistent_counter = RegInit(0.U(FTBCLOSE_THRESHOLD_SZ.W))
719  val fauftb_ftb_entry_consistent         = s2_fauftb_ftb_entry_dup(0).entryConsistent(s2_ftbBank_dup(0))
720
721  // if close ftb_req, the counter need keep
722  when(io.s2_fire(0) && s2_fauftb_ftb_entry_hit_dup(0) && s2_ftb_hit_dup(0)) {
723    fauftb_ftb_entry_consistent_counter := Mux(
724      fauftb_ftb_entry_consistent,
725      fauftb_ftb_entry_consistent_counter + 1.U,
726      0.U
727    )
728  }.elsewhen(io.s2_fire(0) && !s2_fauftb_ftb_entry_hit_dup(0) && s2_ftb_hit_dup(0)) {
729    fauftb_ftb_entry_consistent_counter := 0.U
730  }
731
732  when((fauftb_ftb_entry_consistent_counter >= FTBCLOSE_THRESHOLD) && io.s0_fire(0)) {
733    s0_close_ftb_req := true.B
734  }
735
736  // Clear counter during false_hit or ifuRedirect
737  val ftb_false_hit = WireInit(false.B)
738  val needReopen    = s0_close_ftb_req && (ftb_false_hit || io.redirectFromIFU)
739  ftb_false_hit := io.update.valid && io.update.bits.false_hit
740  when(needReopen) {
741    fauftb_ftb_entry_consistent_counter := 0.U
742    s0_close_ftb_req                    := false.B
743  }
744
745  val s2_close_consistent     = s2_fauftb_ftb_entry_dup(0).entryConsistent(s2_ftb_entry_dup(0))
746  val s2_not_close_consistent = s2_ftbBank_dup(0).entryConsistent(s2_ftb_entry_dup(0))
747
748  when(s2_close_ftb_req && io.s2_fire(0)) {
749    assert(s2_close_consistent, s"Entry inconsistency after ftb req is closed!")
750  }.elsewhen(!s2_close_ftb_req && io.s2_fire(0)) {
751    assert(s2_not_close_consistent, s"Entry inconsistency after ftb req is not closed!")
752  }
753
754  val reopenCounter         = !s1_close_ftb_req && s2_close_ftb_req && io.s2_fire(0)
755  val falseHitReopenCounter = ftb_false_hit && s1_close_ftb_req
756  XSPerfAccumulate("ftb_req_reopen_counter", reopenCounter)
757  XSPerfAccumulate("false_hit_reopen_Counter", falseHitReopenCounter)
758  XSPerfAccumulate("ifuRedirec_needReopen", s1_close_ftb_req && io.redirectFromIFU)
759  XSPerfAccumulate("this_cycle_is_close", s2_close_ftb_req && io.s2_fire(0))
760  XSPerfAccumulate("this_cycle_is_open", !s2_close_ftb_req && io.s2_fire(0))
761
762  // io.out.bits.resp := RegEnable(io.in.bits.resp_in(0), 0.U.asTypeOf(new BranchPredictionResp), io.s1_fire)
763  io.out := io.in.bits.resp_in(0)
764
765  io.out.s2.full_pred.map { case fp => fp.multiHit := false.B }
766
767  io.out.s2.full_pred.zip(s2_hit_dup).map { case (fp, h) => fp.hit := h }
768  for (
769    full_pred & s2_ftb_entry & s2_pc & s1_pc & s1_fire <-
770      io.out.s2.full_pred zip s2_ftb_entry_dup zip s2_pc_dup zip s1_pc_dup zip io.s1_fire
771  ) {
772    full_pred.fromFtbEntry(
773      s2_ftb_entry,
774      s2_pc.getAddr(),
775      // Previous stage meta for better timing
776      Some(s1_pc, s1_fire),
777      Some(s1_read_resp, s1_fire)
778    )
779  }
780
781  io.out.s3.full_pred.zip(s3_hit_dup).map { case (fp, h) => fp.hit := h }
782  io.out.s3.full_pred.zip(s3_multi_hit_dup).map { case (fp, m) => fp.multiHit := m }
783  for (
784    full_pred & s3_ftb_entry & s3_pc & s2_pc & s2_fire <-
785      io.out.s3.full_pred zip s3_ftb_entry_dup zip s3_pc_dup zip s2_pc_dup zip io.s2_fire
786  )
787    full_pred.fromFtbEntry(s3_ftb_entry, s3_pc.getAddr(), Some((s2_pc.getAddr(), s2_fire)))
788
789  // Overwrite the fallThroughErr value
790  io.out.s3.full_pred.zipWithIndex.map { case (fp, i) => fp.fallThroughErr := real_s3_fallThroughErr_dup(i) }
791
792  io.out.last_stage_ftb_entry := s3_ftb_entry_dup(0)
793  io.out.last_stage_meta      := RegEnable(Mux(s2_multi_hit_enable, s2_multi_hit_meta, s2_ftb_meta), io.s2_fire(0))
794  io.out.s1_ftbCloseReq       := s1_close_ftb_req
795  io.out.s1_uftbHit           := io.fauftb_entry_hit_in
796  val s1_uftbHasIndirect = io.fauftb_entry_in.jmpValid &&
797    io.fauftb_entry_in.isJalr && !io.fauftb_entry_in.isRet // uFTB determines that it's real JALR, RET and JAL are excluded
798  io.out.s1_uftbHasIndirect := s1_uftbHasIndirect
799
800  // always taken logic
801  for (i <- 0 until numBr) {
802    for (
803      out_fp & in_fp & s2_hit & s2_ftb_entry <-
804        io.out.s2.full_pred zip io.in.bits.resp_in(0).s2.full_pred zip s2_hit_dup zip s2_ftb_entry_dup
805    )
806      out_fp.br_taken_mask(i) := in_fp.br_taken_mask(i) || s2_hit && s2_ftb_entry.strong_bias(i)
807    for (
808      out_fp & in_fp & s3_hit & s3_ftb_entry <-
809        io.out.s3.full_pred zip io.in.bits.resp_in(0).s3.full_pred zip s3_hit_dup zip s3_ftb_entry_dup
810    )
811      out_fp.br_taken_mask(i) := in_fp.br_taken_mask(i) || s3_hit && s3_ftb_entry.strong_bias(i)
812  }
813
814  val s3_pc_diff       = s3_pc_dup(0).getAddr()
815  val s3_pc_startLower = Cat(0.U(1.W), s3_pc_diff(instOffsetBits + log2Ceil(PredictWidth) - 1, instOffsetBits))
816  val s3_ftb_entry_endLowerwithCarry = Cat(s3_ftb_entry_dup(0).carry, s3_ftb_entry_dup(0).pftAddr)
817  val fallThroughErr =
818    s3_pc_startLower >= s3_ftb_entry_endLowerwithCarry || s3_ftb_entry_endLowerwithCarry > (s3_pc_startLower + PredictWidth.U)
819  XSError(
820    s3_ftb_entry_dup(0).valid && s3_hit_dup(0) && io.s3_fire(0) && fallThroughErr,
821    "FTB read sram entry in s3 fallThrough address error!"
822  )
823
824  // Update logic
825  val update = io.update.bits
826
827  val u_meta  = update.meta.asTypeOf(new FTBMeta)
828  val u_valid = io.update.valid && !io.update.bits.old_entry && !s0_close_ftb_req
829
830  val (_, delay2_pc)    = DelayNWithValid(update.pc, u_valid, 2)
831  val (_, delay2_entry) = DelayNWithValid(update.ftb_entry, u_valid, 2)
832
833  val update_now       = u_valid && u_meta.hit
834  val update_need_read = u_valid && !u_meta.hit
835  // stall one more cycle because we use a whole cycle to do update read tag hit
836  io.s1_ready := ftbBank.io.req_pc.ready && !update_need_read && !RegNext(update_need_read)
837
838  ftbBank.io.u_req_pc.valid := update_need_read
839  ftbBank.io.u_req_pc.bits  := update.pc
840
841  val ftb_write = Wire(new FTBEntryWithTag)
842  ftb_write.entry := Mux(update_now, update.ftb_entry, delay2_entry)
843  ftb_write.tag   := ftbAddr.getTag(Mux(update_now, update.pc, delay2_pc))(tagSize - 1, 0)
844
845  val write_valid = update_now || DelayN(u_valid && !u_meta.hit, 2)
846  val write_pc    = Mux(update_now, update.pc, delay2_pc)
847
848  ftbBank.io.update_write_data.valid := write_valid
849  ftbBank.io.update_write_data.bits  := ftb_write
850  ftbBank.io.update_pc               := write_pc
851  ftbBank.io.update_write_way := Mux(
852    update_now,
853    u_meta.writeWay,
854    RegNext(ftbBank.io.update_hits.bits)
855  ) // use it one cycle later
856  ftbBank.io.update_write_alloc := Mux(
857    update_now,
858    false.B,
859    RegNext(!ftbBank.io.update_hits.valid)
860  ) // use it one cycle later
861  ftbBank.io.update_access := u_valid && !u_meta.hit
862  ftbBank.io.s1_fire       := io.s1_fire(0)
863
864  val ftb_write_fallThrough = ftb_write.entry.getFallThrough(write_pc)
865  when(write_valid) {
866    assert(write_pc + (FetchWidth * 4).U >= ftb_write_fallThrough, s"FTB write_entry fallThrough address error!")
867  }
868
869  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)
870  XSDebug("s2_hit=%b, hit_way=%b\n", s2_hit_dup(0), writeWay.asUInt)
871  XSDebug(
872    "s2_br_taken_mask=%b, s2_real_taken_mask=%b\n",
873    io.in.bits.resp_in(0).s2.full_pred(0).br_taken_mask.asUInt,
874    io.out.s2.full_pred(0).real_slot_taken_mask().asUInt
875  )
876  XSDebug("s2_target=%x\n", io.out.s2.getTarget(0))
877
878  s2_ftb_entry_dup(0).display(true.B)
879
880  XSPerfAccumulate("ftb_read_hits", RegNext(io.s0_fire(0)) && s1_hit)
881  XSPerfAccumulate("ftb_read_misses", RegNext(io.s0_fire(0)) && !s1_hit)
882
883  XSPerfAccumulate("ftb_commit_hits", io.update.valid && u_meta.hit)
884  XSPerfAccumulate("ftb_commit_misses", io.update.valid && !u_meta.hit)
885
886  XSPerfAccumulate("ftb_update_req", io.update.valid)
887  XSPerfAccumulate("ftb_update_ignored", io.update.valid && io.update.bits.old_entry)
888  XSPerfAccumulate("ftb_updated", u_valid)
889  XSPerfAccumulate("ftb_closing_update_counter", s0_close_ftb_req && u_valid)
890
891  override val perfEvents = Seq(
892    ("ftb_commit_hits            ", io.update.valid && u_meta.hit),
893    ("ftb_commit_misses          ", io.update.valid && !u_meta.hit)
894  )
895  generatePerfEvent()
896}
897