xref: /XiangShan/src/main/scala/xiangshan/frontend/FrontendBundle.scala (revision fbdb359d442176ec2670ab8d683605e70e56fcb8)
1/***************************************************************************************
2* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC)
3* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences
4* Copyright (c) 2020-2021 Peng Cheng Laboratory
5*
6* XiangShan is licensed under Mulan PSL v2.
7* You can use this software according to the terms and conditions of the Mulan PSL v2.
8* You may obtain a copy of Mulan PSL v2 at:
9*          http://license.coscl.org.cn/MulanPSL2
10*
11* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
12* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
13* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
14*
15* See the Mulan PSL v2 for more details.
16***************************************************************************************/
17package xiangshan.frontend
18
19import chisel3._
20import chisel3.util._
21import org.chipsalliance.cde.config.Parameters
22import utility._
23import xiangshan._
24import xiangshan.backend.fu.PMPRespBundle
25import xiangshan.cache.mmu.TlbResp
26import xiangshan.frontend.icache._
27
28class FrontendTopDownBundle(implicit p: Parameters) extends XSBundle {
29  val reasons    = Vec(TopDownCounters.NumStallReasons.id, Bool())
30  val stallWidth = UInt(log2Ceil(PredictWidth).W)
31}
32
33class FetchRequestBundle(implicit p: Parameters) extends XSBundle with HasICacheParameters {
34
35  // fast path: Timing critical
36  val startAddr     = UInt(VAddrBits.W)
37  val nextlineStart = UInt(VAddrBits.W)
38  val nextStartAddr = UInt(VAddrBits.W)
39  // slow path
40  val ftqIdx    = new FtqPtr
41  val ftqOffset = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
42
43  val topdown_info = new FrontendTopDownBundle
44
45  def crossCacheline = startAddr(blockOffBits - 1) === 1.U
46
47  def fromFtqPcBundle(b: Ftq_RF_Components) = {
48    this.startAddr     := b.startAddr
49    this.nextlineStart := b.nextLineAddr
50    // when (b.fallThruError) {
51    //   val nextBlockHigherTemp = Mux(startAddr(log2Ceil(PredictWidth)+instOffsetBits), b.nextLineAddr, b.startAddr)
52    //   val nextBlockHigher = nextBlockHigherTemp(VAddrBits-1, log2Ceil(PredictWidth)+instOffsetBits+1)
53    //   this.nextStartAddr :=
54    //     Cat(nextBlockHigher,
55    //       startAddr(log2Ceil(PredictWidth)+instOffsetBits) ^ 1.U(1.W),
56    //       startAddr(log2Ceil(PredictWidth)+instOffsetBits-1, instOffsetBits),
57    //       0.U(instOffsetBits.W)
58    //     )
59    // }
60    this
61  }
62  override def toPrintable: Printable =
63    p"[start] ${Hexadecimal(startAddr)} [next] ${Hexadecimal(nextlineStart)}" +
64      p"[tgt] ${Hexadecimal(nextStartAddr)} [ftqIdx] $ftqIdx [jmp] v:${ftqOffset.valid}" +
65      p" offset: ${ftqOffset.bits}\n"
66}
67
68class FtqICacheInfo(implicit p: Parameters) extends XSBundle with HasICacheParameters {
69  val startAddr      = UInt(VAddrBits.W)
70  val nextlineStart  = UInt(VAddrBits.W)
71  val ftqIdx         = new FtqPtr
72  def crossCacheline = startAddr(blockOffBits - 1) === 1.U
73  def fromFtqPcBundle(b: Ftq_RF_Components) = {
74    this.startAddr     := b.startAddr
75    this.nextlineStart := b.nextLineAddr
76    this
77  }
78}
79
80class IFUICacheIO(implicit p: Parameters) extends XSBundle with HasICacheParameters {
81  val icacheReady       = Output(Bool())
82  val resp              = Vec(PortNumber, ValidIO(new ICacheMainPipeResp))
83  val topdownIcacheMiss = Output(Bool())
84  val topdownItlbMiss   = Output(Bool())
85}
86
87class FtqToICacheRequestBundle(implicit p: Parameters) extends XSBundle with HasICacheParameters {
88  val pcMemRead        = Vec(5, new FtqICacheInfo)
89  val readValid        = Vec(5, Bool())
90  val backendException = Bool()
91}
92
93class PredecodeWritebackBundle(implicit p: Parameters) extends XSBundle {
94  val pc         = Vec(PredictWidth, UInt(VAddrBits.W))
95  val pd         = Vec(PredictWidth, new PreDecodeInfo) // TODO: redefine Predecode
96  val ftqIdx     = new FtqPtr
97  val ftqOffset  = UInt(log2Ceil(PredictWidth).W)
98  val misOffset  = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
99  val cfiOffset  = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
100  val target     = UInt(VAddrBits.W)
101  val jalTarget  = UInt(VAddrBits.W)
102  val instrRange = Vec(PredictWidth, Bool())
103}
104
105class mmioCommitRead(implicit p: Parameters) extends XSBundle {
106  val mmioFtqPtr     = Output(new FtqPtr)
107  val mmioLastCommit = Input(Bool())
108}
109
110object ExceptionType {
111  def none:  UInt = "b00".U
112  def pf:    UInt = "b01".U // instruction page fault
113  def gpf:   UInt = "b10".U // instruction guest page fault
114  def af:    UInt = "b11".U // instruction access fault
115  def width: Int  = 2
116
117  def hasException(e: UInt): Bool = e =/= none
118
119  def fromOH(has_pf: Bool, has_gpf: Bool, has_af: Bool): UInt = {
120    assert(
121      PopCount(VecInit(has_pf, has_gpf, has_af)) <= 1.U,
122      "ExceptionType.fromOH receives input that is not one-hot: pf=%d, gpf=%d, af=%d",
123      has_pf,
124      has_gpf,
125      has_af
126    )
127    // input is at-most-one-hot encoded, so we don't worry about priority here.
128    MuxCase(
129      none,
130      Seq(
131        has_pf  -> pf,
132        has_gpf -> gpf,
133        has_af  -> af
134      )
135    )
136  }
137
138  // raise pf/gpf/af according to itlb response
139  def fromTlbResp(resp: TlbResp, useDup: Int = 0): UInt = {
140    require(useDup >= 0 && useDup < resp.excp.length)
141    // itlb is guaranteed to respond at most one exception
142    fromOH(
143      resp.excp(useDup).pf.instr,
144      resp.excp(useDup).gpf.instr,
145      resp.excp(useDup).af.instr
146    )
147  }
148
149  // raise af if pmp check failed
150  def fromPMPResp(resp: PMPRespBundle): UInt =
151    Mux(resp.instr, af, none)
152
153  // raise af if meta/data array ecc check failed or l2 cache respond with tilelink corrupt
154  /* FIXME: RISC-V Machine ISA v1.13 (draft) introduced a "hardware error" exception, described as:
155   * > A Hardware Error exception is a synchronous exception triggered when corrupted or
156   * > uncorrectable data is accessed explicitly or implicitly by an instruction. In this context,
157   * > "data" encompasses all types of information used within a RISC-V hart. Upon a hardware
158   * > error exception, the xepc register is set to the address of the instruction that attempted to
159   * > access corrupted data, while the xtval register is set either to 0 or to the virtual address
160   * > of an instruction fetch, load, or store that attempted to access corrupted data. The priority
161   * > of Hardware Error exception is implementation-defined, but any given occurrence is
162   * > generally expected to be recognized at the point in the overall priority order at which the
163   * > hardware error is discovered.
164   * Maybe it's better to raise hardware error instead of access fault when ECC check failed.
165   * But it's draft and XiangShan backend does not implement this exception code yet, so we still raise af here.
166   */
167  def fromECC(enable: Bool, corrupt: Bool): UInt =
168    Mux(enable && corrupt, af, none)
169
170  /**Generates exception mux tree
171   *
172   * Exceptions that are further to the left in the parameter list have higher priority
173   * @example
174   * {{{
175   *   val itlb_exception = ExceptionType.fromTlbResp(io.itlb.resp.bits)
176   *   // so as pmp_exception, meta_corrupt
177   *   // ExceptionType.merge(itlb_exception, pmp_exception, meta_corrupt) is equivalent to:
178   *   Mux(
179   *     itlb_exception =/= none,
180   *     itlb_exception,
181   *     Mux(pmp_exception =/= none, pmp_exception, meta_corrupt)
182   *   )
183   * }}}
184   */
185  def merge(exceptions: UInt*): UInt = {
186//    // recursively generate mux tree
187//    if (exceptions.length == 1) {
188//      require(exceptions.head.getWidth == width)
189//      exceptions.head
190//    } else {
191//      Mux(exceptions.head =/= none, exceptions.head, merge(exceptions.tail: _*))
192//    }
193    // use MuxCase with default
194    exceptions.foreach(e => require(e.getWidth == width))
195    val mapping = exceptions.init.map(e => (e =/= none) -> e)
196    val default = exceptions.last
197    MuxCase(default, mapping)
198  }
199
200  /**Generates exception mux tree for multi-port exception vectors
201   *
202   * Exceptions that are further to the left in the parameter list have higher priority
203   * @example
204   * {{{
205   *   val itlb_exception = VecInit((0 until PortNumber).map(i => ExceptionType.fromTlbResp(io.itlb(i).resp.bits)))
206   *   // so as pmp_exception, meta_corrupt
207   *   // ExceptionType.merge(itlb_exception, pmp_exception, meta_corrupt) is equivalent to:
208   *   VecInit((0 until PortNumber).map(i => Mux(
209   *     itlb_exception(i) =/= none,
210   *     itlb_exception(i),
211   *     Mux(pmp_exception(i) =/= none, pmp_exception(i), meta_corrupt(i))
212   *   ))
213   * }}}
214   */
215  def merge(exceptionVecs: Vec[UInt]*): Vec[UInt] = {
216//    // recursively generate mux tree
217//    if (exceptionVecs.length == 1) {
218//      exceptionVecs.head.foreach(e => require(e.getWidth == width))
219//      exceptionVecs.head
220//    } else {
221//      require(exceptionVecs.head.length == exceptionVecs.last.length)
222//      VecInit((exceptionVecs.head zip merge(exceptionVecs.tail: _*)).map{ case (high, low) =>
223//        Mux(high =/= none, high, low)
224//      })
225//    }
226    // merge port-by-port
227    val length = exceptionVecs.head.length
228    exceptionVecs.tail.foreach(vec => require(vec.length == length))
229    VecInit((0 until length).map(i => merge(exceptionVecs.map(_(i)): _*)))
230  }
231}
232
233class FetchToIBuffer(implicit p: Parameters) extends XSBundle {
234  val instrs           = Vec(PredictWidth, UInt(32.W))
235  val valid            = UInt(PredictWidth.W)
236  val enqEnable        = UInt(PredictWidth.W)
237  val pd               = Vec(PredictWidth, new PreDecodeInfo)
238  val foldpc           = Vec(PredictWidth, UInt(MemPredPCWidth.W))
239  val ftqOffset        = Vec(PredictWidth, ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
240  val backendException = Vec(PredictWidth, Bool())
241  val exceptionType    = Vec(PredictWidth, UInt(ExceptionType.width.W))
242  val crossPageIPFFix  = Vec(PredictWidth, Bool())
243  val illegalInstr     = Vec(PredictWidth, Bool())
244  val triggered        = Vec(PredictWidth, TriggerAction())
245  val isLastInFtqEntry = Vec(PredictWidth, Bool())
246
247  val pc           = Vec(PredictWidth, UInt(VAddrBits.W))
248  val ftqPtr       = new FtqPtr
249  val topdown_info = new FrontendTopDownBundle
250}
251
252// class BitWiseUInt(val width: Int, val init: UInt) extends Module {
253//   val io = IO(new Bundle {
254//     val set
255//   })
256// }
257// Move from BPU
258abstract class GlobalHistory(implicit p: Parameters) extends XSBundle with HasBPUConst {
259  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): GlobalHistory
260}
261
262class ShiftingGlobalHistory(implicit p: Parameters) extends GlobalHistory {
263  val predHist = UInt(HistoryLength.W)
264
265  def update(shift: UInt, taken: Bool, hist: UInt = this.predHist): ShiftingGlobalHistory = {
266    val g = Wire(new ShiftingGlobalHistory)
267    g.predHist := (hist << shift) | taken
268    g
269  }
270
271  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): ShiftingGlobalHistory = {
272    require(br_valids.length == numBr)
273    require(real_taken_mask.length == numBr)
274    val last_valid_idx = PriorityMux(
275      br_valids.reverse :+ true.B,
276      (numBr to 0 by -1).map(_.U(log2Ceil(numBr + 1).W))
277    )
278    val first_taken_idx = PriorityEncoder(false.B +: real_taken_mask)
279    val smaller         = Mux(last_valid_idx < first_taken_idx, last_valid_idx, first_taken_idx)
280    val shift           = smaller
281    val taken           = real_taken_mask.reduce(_ || _)
282    update(shift, taken, this.predHist)
283  }
284
285  // static read
286  def read(n: Int): Bool = predHist.asBools(n)
287
288  final def ===(that: ShiftingGlobalHistory): Bool =
289    predHist === that.predHist
290
291  final def =/=(that: ShiftingGlobalHistory): Bool = !(this === that)
292}
293
294// circular global history pointer
295class CGHPtr(implicit p: Parameters) extends CircularQueuePtr[CGHPtr](p => p(XSCoreParamsKey).HistoryLength) {}
296
297object CGHPtr {
298  def apply(f: Bool, v: UInt)(implicit p: Parameters): CGHPtr = {
299    val ptr = Wire(new CGHPtr)
300    ptr.flag  := f
301    ptr.value := v
302    ptr
303  }
304  def inverse(ptr: CGHPtr)(implicit p: Parameters): CGHPtr =
305    apply(!ptr.flag, ptr.value)
306}
307
308class CircularGlobalHistory(implicit p: Parameters) extends GlobalHistory {
309  val buffer = Vec(HistoryLength, Bool())
310  type HistPtr = UInt
311  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): CircularGlobalHistory =
312    this
313}
314
315class FoldedHistory(val len: Int, val compLen: Int, val max_update_num: Int)(implicit p: Parameters)
316    extends XSBundle with HasBPUConst {
317  require(compLen >= 1)
318  require(len > 0)
319  // require(folded_len <= len)
320  require(compLen >= max_update_num)
321  val folded_hist = UInt(compLen.W)
322
323  def need_oldest_bits           = len > compLen
324  def info                       = (len, compLen)
325  def oldest_bit_to_get_from_ghr = (0 until max_update_num).map(len - _ - 1)
326  def oldest_bit_pos_in_folded   = oldest_bit_to_get_from_ghr map (_ % compLen)
327  def oldest_bit_wrap_around     = oldest_bit_to_get_from_ghr map (_ / compLen > 0)
328  def oldest_bit_start           = oldest_bit_pos_in_folded.head
329
330  def get_oldest_bits_from_ghr(ghr: Vec[Bool], histPtr: CGHPtr) =
331    // TODO: wrap inc for histPtr value
332    oldest_bit_to_get_from_ghr.map(i => ghr((histPtr + (i + 1).U).value))
333
334  def circular_shift_left(src: UInt, shamt: Int) = {
335    val srcLen      = src.getWidth
336    val src_doubled = Cat(src, src)
337    val shifted     = src_doubled(srcLen * 2 - 1 - shamt, srcLen - shamt)
338    shifted
339  }
340
341  // slow path, read bits from ghr
342  def update(ghr: Vec[Bool], histPtr: CGHPtr, num: Int, taken: Bool): FoldedHistory = {
343    val oldest_bits = VecInit(get_oldest_bits_from_ghr(ghr, histPtr))
344    update(oldest_bits, num, taken)
345  }
346
347  // fast path, use pre-read oldest bits
348  def update(ob: Vec[Bool], num: Int, taken: Bool): FoldedHistory = {
349    // do xors for several bitsets at specified bits
350    def bitsets_xor(len: Int, bitsets: Seq[Seq[Tuple2[Int, Bool]]]) = {
351      val res = Wire(Vec(len, Bool()))
352      // println(f"num bitsets: ${bitsets.length}")
353      // println(f"bitsets $bitsets")
354      val resArr = Array.fill(len)(List[Bool]())
355      for (bs <- bitsets) {
356        for ((n, b) <- bs) {
357          resArr(n) = b :: resArr(n)
358        }
359      }
360      // println(f"${resArr.mkString}")
361      // println(f"histLen: ${this.len}, foldedLen: $folded_len")
362      for (i <- 0 until len) {
363        // println(f"bit[$i], ${resArr(i).mkString}")
364        if (resArr(i).length == 0) {
365          println(f"[error] bits $i is not assigned in folded hist update logic! histlen:${this.len}, compLen:$compLen")
366        }
367        res(i) := resArr(i).foldLeft(false.B)(_ ^ _)
368      }
369      res.asUInt
370    }
371
372    val new_folded_hist = if (need_oldest_bits) {
373      val oldest_bits = ob
374      require(oldest_bits.length == max_update_num)
375      // mask off bits that do not update
376      val oldest_bits_masked = oldest_bits.zipWithIndex.map {
377        case (ob, i) => ob && (i < num).B
378      }
379      // if a bit does not wrap around, it should not be xored when it exits
380      val oldest_bits_set = (0 until max_update_num).filter(oldest_bit_wrap_around).map(i =>
381        (oldest_bit_pos_in_folded(i), oldest_bits_masked(i))
382      )
383
384      // println(f"old bits pos ${oldest_bits_set.map(_._1)}")
385
386      // only the last bit could be 1, as we have at most one taken branch at a time
387      val newest_bits_masked = VecInit((0 until max_update_num).map(i => taken && ((i + 1) == num).B)).asUInt
388      // if a bit does not wrap around, newest bits should not be xored onto it either
389      val newest_bits_set = (0 until max_update_num).map(i => (compLen - 1 - i, newest_bits_masked(i)))
390
391      // println(f"new bits set ${newest_bits_set.map(_._1)}")
392      //
393      val original_bits_masked = VecInit(folded_hist.asBools.zipWithIndex.map {
394        case (fb, i) => fb && !(num >= (len - i)).B
395      })
396      val original_bits_set = (0 until compLen).map(i => (i, original_bits_masked(i)))
397
398      // do xor then shift
399      val xored = bitsets_xor(compLen, Seq(original_bits_set, oldest_bits_set, newest_bits_set))
400      circular_shift_left(xored, num)
401    } else {
402      // histLen too short to wrap around
403      ((folded_hist << num) | taken)(compLen - 1, 0)
404    }
405
406    val fh = WireInit(this)
407    fh.folded_hist := new_folded_hist
408    fh
409  }
410}
411
412class AheadFoldedHistoryOldestBits(val len: Int, val max_update_num: Int)(implicit p: Parameters) extends XSBundle {
413  val bits = Vec(max_update_num * 2, Bool())
414  // def info = (len, compLen)
415  def getRealOb(brNumOH: UInt): Vec[Bool] = {
416    val ob = Wire(Vec(max_update_num, Bool()))
417    for (i <- 0 until max_update_num) {
418      ob(i) := Mux1H(brNumOH, bits.drop(i).take(numBr + 1))
419    }
420    ob
421  }
422}
423
424class AllAheadFoldedHistoryOldestBits(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle
425    with HasBPUConst {
426  val afhob = MixedVec(gen.filter(t => t._1 > t._2).map(_._1)
427    .toSet.toList.map(l => new AheadFoldedHistoryOldestBits(l, numBr))) // remove duplicates
428  require(gen.toSet.toList.equals(gen))
429  def getObWithInfo(info: Tuple2[Int, Int]) = {
430    val selected = afhob.filter(_.len == info._1)
431    require(selected.length == 1)
432    selected(0)
433  }
434  def read(ghv: Vec[Bool], ptr: CGHPtr) = {
435    val hisLens      = afhob.map(_.len)
436    val bitsToRead   = hisLens.flatMap(l => (0 until numBr * 2).map(i => l - i - 1)).toSet // remove duplicates
437    val bitsWithInfo = bitsToRead.map(pos => (pos, ghv((ptr + (pos + 1).U).value)))
438    for (ob <- afhob) {
439      for (i <- 0 until numBr * 2) {
440        val pos       = ob.len - i - 1
441        val bit_found = bitsWithInfo.filter(_._1 == pos).toList
442        require(bit_found.length == 1)
443        ob.bits(i) := bit_found(0)._2
444      }
445    }
446  }
447}
448
449class AllFoldedHistories(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle with HasBPUConst {
450  val hist = MixedVec(gen.map { case (l, cl) => new FoldedHistory(l, cl, numBr) })
451  // println(gen.mkString)
452  require(gen.toSet.toList.equals(gen))
453  def getHistWithInfo(info: Tuple2[Int, Int]) = {
454    val selected = hist.filter(_.info.equals(info))
455    require(selected.length == 1)
456    selected(0)
457  }
458  def autoConnectFrom(that: AllFoldedHistories) = {
459    require(this.hist.length <= that.hist.length)
460    for (h <- this.hist) {
461      h := that.getHistWithInfo(h.info)
462    }
463  }
464  def update(ghv: Vec[Bool], ptr: CGHPtr, shift: Int, taken: Bool): AllFoldedHistories = {
465    val res = WireInit(this)
466    for (i <- 0 until this.hist.length) {
467      res.hist(i) := this.hist(i).update(ghv, ptr, shift, taken)
468    }
469    res
470  }
471  def update(afhob: AllAheadFoldedHistoryOldestBits, lastBrNumOH: UInt, shift: Int, taken: Bool): AllFoldedHistories = {
472    val res = WireInit(this)
473    for (i <- 0 until this.hist.length) {
474      val fh = this.hist(i)
475      if (fh.need_oldest_bits) {
476        val info          = fh.info
477        val selectedAfhob = afhob.getObWithInfo(info)
478        val ob            = selectedAfhob.getRealOb(lastBrNumOH)
479        res.hist(i) := this.hist(i).update(ob, shift, taken)
480      } else {
481        val dumb = Wire(Vec(numBr, Bool())) // not needed
482        dumb        := DontCare
483        res.hist(i) := this.hist(i).update(dumb, shift, taken)
484      }
485    }
486    res
487  }
488
489  def display(cond: Bool) =
490    for (h <- hist) {
491      XSDebug(cond, p"hist len ${h.len}, folded len ${h.compLen}, value ${Binary(h.folded_hist)}\n")
492    }
493}
494
495class TableAddr(val idxBits: Int, val banks: Int)(implicit p: Parameters) extends XSBundle {
496  def tagBits = VAddrBits - idxBits - instOffsetBits
497
498  val tag    = UInt(tagBits.W)
499  val idx    = UInt(idxBits.W)
500  val offset = UInt(instOffsetBits.W)
501
502  def fromUInt(x:   UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this)
503  def getTag(x:     UInt) = fromUInt(x).tag
504  def getIdx(x:     UInt) = fromUInt(x).idx
505  def getBank(x:    UInt) = if (banks > 1) getIdx(x)(log2Up(banks) - 1, 0) else 0.U
506  def getBankIdx(x: UInt) = if (banks > 1) getIdx(x)(idxBits - 1, log2Up(banks)) else getIdx(x)
507}
508
509trait BasicPrediction extends HasXSParameter {
510  def cfiIndex: ValidUndirectioned[UInt]
511  def target(pc: UInt): UInt
512  def lastBrPosOH:    Vec[Bool]
513  def brTaken:        Bool
514  def shouldShiftVec: Vec[Bool]
515  def fallThruError:  Bool
516}
517
518// selectByTaken selects some data according to takenMask
519// allTargets should be in a Vec, like [taken0, taken1, ..., not taken, not hit]
520object selectByTaken {
521  def apply[T <: Data](takenMask: Vec[Bool], hit: Bool, allTargets: Vec[T]): T = {
522    val selVecOH =
523      takenMask.zipWithIndex.map { case (t, i) =>
524        !takenMask.take(i).fold(false.B)(_ || _) && t && hit
525      } :+
526        (!takenMask.asUInt.orR && hit) :+ !hit
527    Mux1H(selVecOH, allTargets)
528  }
529}
530
531class FullBranchPrediction(val isNotS3: Boolean)(implicit p: Parameters) extends XSBundle with HasBPUConst
532    with BasicPrediction {
533  val br_taken_mask = Vec(numBr, Bool())
534
535  val slot_valids = Vec(totalSlot, Bool())
536
537  val targets         = Vec(totalSlot, UInt(VAddrBits.W))
538  val jalr_target     = UInt(VAddrBits.W) // special path for indirect predictors
539  val offsets         = Vec(totalSlot, UInt(log2Ceil(PredictWidth).W))
540  val fallThroughAddr = UInt(VAddrBits.W)
541  val fallThroughErr  = Bool()
542  val multiHit        = Bool()
543
544  val is_jal               = Bool()
545  val is_jalr              = Bool()
546  val is_call              = Bool()
547  val is_ret               = Bool()
548  val last_may_be_rvi_call = Bool()
549  val is_br_sharing        = Bool()
550
551  // val call_is_rvc = Bool()
552  val hit = Bool()
553
554  val predCycle = if (!env.FPGAPlatform) Some(UInt(64.W)) else None
555
556  def br_slot_valids  = slot_valids.init
557  def tail_slot_valid = slot_valids.last
558
559  def br_valids =
560    VecInit(br_slot_valids :+ (tail_slot_valid && is_br_sharing))
561
562  def taken_mask_on_slot =
563    VecInit(
564      (br_slot_valids zip br_taken_mask.init).map { case (t, v) => t && v } :+ (
565        tail_slot_valid && (
566          is_br_sharing && br_taken_mask.last || !is_br_sharing
567        )
568      )
569    )
570
571  def real_slot_taken_mask(): Vec[Bool] =
572    VecInit(taken_mask_on_slot.map(_ && hit))
573
574  // len numBr
575  def real_br_taken_mask(): Vec[Bool] =
576    VecInit(
577      taken_mask_on_slot.map(_ && hit).init :+
578        (br_taken_mask.last && tail_slot_valid && is_br_sharing && hit)
579    )
580
581  // the vec indicating if ghr should shift on each branch
582  def shouldShiftVec =
583    VecInit(br_valids.zipWithIndex.map { case (v, i) =>
584      v && hit && !real_br_taken_mask().take(i).reduceOption(_ || _).getOrElse(false.B)
585    })
586
587  def lastBrPosOH =
588    VecInit((!hit || !br_valids.reduce(_ || _)) +: // not hit or no brs in entry
589      (0 until numBr).map(i =>
590        br_valids(i) &&
591          !real_br_taken_mask().take(i).reduceOption(_ || _).getOrElse(false.B) && // no brs taken in front it
592          (real_br_taken_mask()(i) || !br_valids.drop(i + 1).reduceOption(_ || _).getOrElse(
593            false.B
594          )) && // no brs behind it
595          hit
596      ))
597
598  def brTaken = (br_valids zip br_taken_mask).map { case (a, b) => a && b && hit }.reduce(_ || _)
599
600  def target(pc: UInt): UInt =
601    if (isNotS3) {
602      selectByTaken(taken_mask_on_slot, hit, allTarget(pc))
603    } else {
604      selectByTaken(taken_mask_on_slot, hit && !fallThroughErr, allTarget(pc))
605    }
606
607  // allTarget return a Vec of all possible target of a BP stage
608  // in the following order: [taken_target0, taken_target1, ..., fallThroughAddr, not hit (plus fetch width)]
609  //
610  // This exposes internal targets for timing optimization,
611  // since usually targets are generated quicker than taken
612  def allTarget(pc: UInt): Vec[UInt] =
613    VecInit(targets :+ fallThroughAddr :+ (pc + (FetchWidth * 4).U))
614
615  def fallThruError: Bool = hit && fallThroughErr
616  def ftbMultiHit:   Bool = hit && multiHit
617
618  def hit_taken_on_jmp =
619    !real_slot_taken_mask().init.reduce(_ || _) &&
620      real_slot_taken_mask().last && !is_br_sharing
621  def hit_taken_on_call = hit_taken_on_jmp && is_call
622  def hit_taken_on_ret  = hit_taken_on_jmp && is_ret
623  def hit_taken_on_jalr = hit_taken_on_jmp && is_jalr
624
625  def cfiIndex = {
626    val cfiIndex = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
627    cfiIndex.valid := real_slot_taken_mask().asUInt.orR
628    // when no takens, set cfiIndex to PredictWidth-1
629    cfiIndex.bits :=
630      ParallelPriorityMux(real_slot_taken_mask(), offsets) |
631        Fill(log2Ceil(PredictWidth), (!real_slot_taken_mask().asUInt.orR).asUInt)
632    cfiIndex
633  }
634
635  def taken = br_taken_mask.reduce(_ || _) || slot_valids.last // || (is_jal || is_jalr)
636
637  def fromFtbEntry(
638      entry:            FTBEntry,
639      pc:               UInt,
640      last_stage_pc:    Option[Tuple2[UInt, Bool]] = None,
641      last_stage_entry: Option[Tuple2[FTBEntry, Bool]] = None
642  ) = {
643    slot_valids          := entry.brSlots.map(_.valid) :+ entry.tailSlot.valid
644    targets              := entry.getTargetVec(pc, last_stage_pc) // Use previous stage pc for better timing
645    jalr_target          := targets.last
646    offsets              := entry.getOffsetVec
647    is_jal               := entry.tailSlot.valid && entry.isJal
648    is_jalr              := entry.tailSlot.valid && entry.isJalr
649    is_call              := entry.tailSlot.valid && entry.isCall
650    is_ret               := entry.tailSlot.valid && entry.isRet
651    last_may_be_rvi_call := entry.last_may_be_rvi_call
652    is_br_sharing        := entry.tailSlot.valid && entry.tailSlot.sharing
653    predCycle.map(_ := GTimer())
654
655    val startLower        = Cat(0.U(1.W), pc(instOffsetBits + log2Ceil(PredictWidth) - 1, instOffsetBits))
656    val endLowerwithCarry = Cat(entry.carry, entry.pftAddr)
657    fallThroughErr  := startLower >= endLowerwithCarry || endLowerwithCarry > (startLower + PredictWidth.U)
658    fallThroughAddr := Mux(fallThroughErr, pc + (FetchWidth * 4).U, entry.getFallThrough(pc, last_stage_entry))
659  }
660
661  def display(cond: Bool): Unit =
662    XSDebug(cond, p"[taken_mask] ${Binary(br_taken_mask.asUInt)} [hit] $hit\n")
663}
664
665class SpeculativeInfo(implicit p: Parameters) extends XSBundle
666    with HasBPUConst with BPUUtils {
667  val histPtr = new CGHPtr
668  val ssp     = UInt(log2Up(RasSize).W)
669  val sctr    = UInt(RasCtrSize.W)
670  val TOSW    = new RASPtr
671  val TOSR    = new RASPtr
672  val NOS     = new RASPtr
673  val topAddr = UInt(VAddrBits.W)
674}
675
676//
677class BranchPredictionBundle(val isNotS3: Boolean)(implicit p: Parameters) extends XSBundle
678    with HasBPUConst with BPUUtils {
679  val pc          = Vec(numDup, UInt(VAddrBits.W))
680  val valid       = Vec(numDup, Bool())
681  val hasRedirect = Vec(numDup, Bool())
682  val ftq_idx     = new FtqPtr
683  val full_pred   = Vec(numDup, new FullBranchPrediction(isNotS3))
684
685  def target(pc:     UInt)      = VecInit(full_pred.map(_.target(pc)))
686  def targets(pc:    Vec[UInt]) = VecInit(pc.zipWithIndex.map { case (pc, idx) => full_pred(idx).target(pc) })
687  def allTargets(pc: Vec[UInt]) = VecInit(pc.zipWithIndex.map { case (pc, idx) => full_pred(idx).allTarget(pc) })
688  def cfiIndex       = VecInit(full_pred.map(_.cfiIndex))
689  def lastBrPosOH    = VecInit(full_pred.map(_.lastBrPosOH))
690  def brTaken        = VecInit(full_pred.map(_.brTaken))
691  def shouldShiftVec = VecInit(full_pred.map(_.shouldShiftVec))
692  def fallThruError  = VecInit(full_pred.map(_.fallThruError))
693  def ftbMultiHit    = VecInit(full_pred.map(_.ftbMultiHit))
694
695  def taken = VecInit(cfiIndex.map(_.valid))
696
697  def getTarget     = targets(pc)
698  def getAllTargets = allTargets(pc)
699
700  def display(cond: Bool): Unit = {
701    XSDebug(cond, p"[pc] ${Hexadecimal(pc(0))}\n")
702    full_pred(0).display(cond)
703  }
704}
705
706class BranchPredictionResp(implicit p: Parameters) extends XSBundle with HasBPUConst {
707  val s1 = new BranchPredictionBundle(isNotS3 = true)
708  val s2 = new BranchPredictionBundle(isNotS3 = true)
709  val s3 = new BranchPredictionBundle(isNotS3 = false)
710
711  val s1_uftbHit         = Bool()
712  val s1_uftbHasIndirect = Bool()
713  val s1_ftbCloseReq     = Bool()
714
715  val last_stage_meta      = UInt(MaxMetaLength.W)
716  val last_stage_spec_info = new Ftq_Redirect_SRAMEntry
717  val last_stage_ftb_entry = new FTBEntry
718
719  val topdown_info = new FrontendTopDownBundle
720
721  def selectedResp = {
722    val res =
723      PriorityMux(Seq(
724        (s3.valid(3) && s3.hasRedirect(3)) -> s3,
725        (s2.valid(3) && s2.hasRedirect(3)) -> s2,
726        s1.valid(3)                        -> s1
727      ))
728    res
729  }
730  def selectedRespIdxForFtq =
731    PriorityMux(Seq(
732      (s3.valid(3) && s3.hasRedirect(3)) -> BP_S3,
733      (s2.valid(3) && s2.hasRedirect(3)) -> BP_S2,
734      s1.valid(3)                        -> BP_S1
735    ))
736  def lastStage = s3
737}
738
739class BpuToFtqBundle(implicit p: Parameters) extends BranchPredictionResp {}
740
741class BranchPredictionUpdate(implicit p: Parameters) extends XSBundle with HasBPUConst {
742  val pc        = UInt(VAddrBits.W)
743  val spec_info = new SpeculativeInfo
744  val ftb_entry = new FTBEntry()
745
746  val cfi_idx           = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
747  val br_taken_mask     = Vec(numBr, Bool())
748  val br_committed      = Vec(numBr, Bool()) // High only when br valid && br committed
749  val jmp_taken         = Bool()
750  val mispred_mask      = Vec(numBr + 1, Bool())
751  val pred_hit          = Bool()
752  val false_hit         = Bool()
753  val new_br_insert_pos = Vec(numBr, Bool())
754  val old_entry         = Bool()
755  val meta              = UInt(MaxMetaLength.W)
756  val full_target       = UInt(VAddrBits.W)
757  val from_stage        = UInt(2.W)
758  val ghist             = UInt(HistoryLength.W)
759
760  def is_jal  = ftb_entry.tailSlot.valid && ftb_entry.isJal
761  def is_jalr = ftb_entry.tailSlot.valid && ftb_entry.isJalr
762  def is_call = ftb_entry.tailSlot.valid && ftb_entry.isCall
763  def is_ret  = ftb_entry.tailSlot.valid && ftb_entry.isRet
764
765  def is_call_taken = is_call && jmp_taken && cfi_idx.valid && cfi_idx.bits === ftb_entry.tailSlot.offset
766  def is_ret_taken  = is_ret && jmp_taken && cfi_idx.valid && cfi_idx.bits === ftb_entry.tailSlot.offset
767
768  def display(cond: Bool) = {
769    XSDebug(cond, p"-----------BranchPredictionUpdate-----------\n")
770    XSDebug(cond, p"[mispred_mask] ${Binary(mispred_mask.asUInt)} [false_hit] $false_hit\n")
771    XSDebug(cond, p"[new_br_insert_pos] ${Binary(new_br_insert_pos.asUInt)}\n")
772    XSDebug(cond, p"--------------------------------------------\n")
773  }
774}
775
776class BranchPredictionRedirect(implicit p: Parameters) extends Redirect with HasBPUConst {
777  // override def toPrintable: Printable = {
778  //   p"-----------BranchPredictionRedirect----------- " +
779  //     p"-----------cfiUpdate----------- " +
780  //     p"[pc] ${Hexadecimal(cfiUpdate.pc)} " +
781  //     p"[predTaken] ${cfiUpdate.predTaken}, [taken] ${cfiUpdate.taken}, [isMisPred] ${cfiUpdate.isMisPred} " +
782  //     p"[target] ${Hexadecimal(cfiUpdate.target)} " +
783  //     p"------------------------------- " +
784  //     p"[robPtr] f=${robIdx.flag} v=${robIdx.value} " +
785  //     p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} " +
786  //     p"[ftqOffset] ${ftqOffset} " +
787  //     p"[level] ${level}, [interrupt] ${interrupt} " +
788  //     p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value} " +
789  //     p"[stFtqOffset] ${stFtqOffset} " +
790  //     p"\n"
791
792  // }
793
794  // TODO: backend should pass topdown signals here
795  // must not change its parent since BPU has used asTypeOf(this type) from its parent class
796  require(isInstanceOf[Redirect])
797  val BTBMissBubble         = Bool()
798  def ControlRedirectBubble = debugIsCtrl
799  // if mispred br not in ftb, count as BTB miss
800  def ControlBTBMissBubble = ControlRedirectBubble && !cfiUpdate.br_hit && !cfiUpdate.jr_hit
801  def TAGEMissBubble       = ControlRedirectBubble && cfiUpdate.br_hit && !cfiUpdate.sc_hit
802  def SCMissBubble         = ControlRedirectBubble && cfiUpdate.br_hit && cfiUpdate.sc_hit
803  def ITTAGEMissBubble     = ControlRedirectBubble && cfiUpdate.jr_hit && !cfiUpdate.pd.isRet
804  def RASMissBubble        = ControlRedirectBubble && cfiUpdate.jr_hit && cfiUpdate.pd.isRet
805  def MemVioRedirectBubble = debugIsMemVio
806  def OtherRedirectBubble  = !debugIsCtrl && !debugIsMemVio
807
808  def connectRedirect(source: Redirect): Unit =
809    for ((name, data) <- this.elements) {
810      if (source.elements.contains(name)) {
811        data := source.elements(name)
812      }
813    }
814
815  def display(cond: Bool): Unit = {
816    XSDebug(cond, p"-----------BranchPredictionRedirect----------- \n")
817    XSDebug(cond, p"-----------cfiUpdate----------- \n")
818    XSDebug(cond, p"[pc] ${Hexadecimal(cfiUpdate.pc)}\n")
819    // XSDebug(cond, p"[hist] ${Binary(cfiUpdate.hist.predHist)}\n")
820    XSDebug(cond, p"[br_hit] ${cfiUpdate.br_hit} [isMisPred] ${cfiUpdate.isMisPred}\n")
821    XSDebug(
822      cond,
823      p"[pred_taken] ${cfiUpdate.predTaken} [taken] ${cfiUpdate.taken} [isMisPred] ${cfiUpdate.isMisPred}\n"
824    )
825    XSDebug(cond, p"[target] ${Hexadecimal(cfiUpdate.target)} \n")
826    XSDebug(cond, p"[shift] ${cfiUpdate.shift}\n")
827    XSDebug(cond, p"------------------------------- \n")
828    XSDebug(cond, p"[robPtr] f=${robIdx.flag} v=${robIdx.value}\n")
829    XSDebug(cond, p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} \n")
830    XSDebug(cond, p"[ftqOffset] ${ftqOffset} \n")
831    XSDebug(cond, p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value}\n")
832    XSDebug(cond, p"[stFtqOffset] ${stFtqOffset}\n")
833    XSDebug(cond, p"---------------------------------------------- \n")
834  }
835}
836