xref: /XiangShan/src/main/scala/xiangshan/frontend/FrontendBundle.scala (revision 209a4caf7d429bd4ffd58c831447ae38b1d84f04)
109c6f1ddSLingrui98/***************************************************************************************
209c6f1ddSLingrui98* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
309c6f1ddSLingrui98* Copyright (c) 2020-2021 Peng Cheng Laboratory
409c6f1ddSLingrui98*
509c6f1ddSLingrui98* XiangShan is licensed under Mulan PSL v2.
609c6f1ddSLingrui98* You can use this software according to the terms and conditions of the Mulan PSL v2.
709c6f1ddSLingrui98* You may obtain a copy of Mulan PSL v2 at:
809c6f1ddSLingrui98*          http://license.coscl.org.cn/MulanPSL2
909c6f1ddSLingrui98*
1009c6f1ddSLingrui98* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
1109c6f1ddSLingrui98* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
1209c6f1ddSLingrui98* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
1309c6f1ddSLingrui98*
1409c6f1ddSLingrui98* See the Mulan PSL v2 for more details.
1509c6f1ddSLingrui98***************************************************************************************/
1609c6f1ddSLingrui98package xiangshan.frontend
1709c6f1ddSLingrui98
1809c6f1ddSLingrui98import chipsalliance.rocketchip.config.Parameters
1909c6f1ddSLingrui98import chisel3._
2009c6f1ddSLingrui98import chisel3.util._
21bf358e08SLingrui98import chisel3.experimental.chiselName
2209c6f1ddSLingrui98import xiangshan._
2350780602SJeniusimport xiangshan.frontend.icache._
2409c6f1ddSLingrui98import utils._
253c02ee8fSwakafaimport utility._
26c2ad24ebSLingrui98import scala.math._
27d2b20d1aSTang Haojinimport java.util.ResourceBundle.Control
28d2b20d1aSTang Haojin
29d2b20d1aSTang Haojinclass FrontendTopDownBundle(implicit p: Parameters) extends XSBundle {
30d2b20d1aSTang Haojin  val reasons = Vec(TopDownCounters.NumStallReasons.id, Bool())
31d2b20d1aSTang Haojin  val stallWidth = UInt(log2Ceil(PredictWidth).W)
32d2b20d1aSTang Haojin}
3309c6f1ddSLingrui98
34bf358e08SLingrui98@chiselName
35b37e4b45SLingrui98class FetchRequestBundle(implicit p: Parameters) extends XSBundle with HasICacheParameters {
36c5c5edaeSJenius
37c5c5edaeSJenius  //fast path: Timing critical
3809c6f1ddSLingrui98  val startAddr       = UInt(VAddrBits.W)
3934a88126SJinYue  val nextlineStart   = UInt(VAddrBits.W)
40c5c5edaeSJenius  val nextStartAddr   = UInt(VAddrBits.W)
41c5c5edaeSJenius  //slow path
4209c6f1ddSLingrui98  val ftqIdx          = new FtqPtr
4309c6f1ddSLingrui98  val ftqOffset       = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
4409c6f1ddSLingrui98
45d2b20d1aSTang Haojin  val topdown_info    = new FrontendTopDownBundle
46d2b20d1aSTang Haojin
476ce52296SJinYue  def crossCacheline =  startAddr(blockOffBits - 1) === 1.U
486ce52296SJinYue
4909c6f1ddSLingrui98  def fromFtqPcBundle(b: Ftq_RF_Components) = {
5009c6f1ddSLingrui98    this.startAddr := b.startAddr
51b37e4b45SLingrui98    this.nextlineStart := b.nextLineAddr
52b37e4b45SLingrui98    when (b.fallThruError) {
53b37e4b45SLingrui98      val nextBlockHigherTemp = Mux(startAddr(log2Ceil(PredictWidth)+instOffsetBits), b.startAddr, b.nextLineAddr)
54b37e4b45SLingrui98      val nextBlockHigher = nextBlockHigherTemp(VAddrBits-1, log2Ceil(PredictWidth)+instOffsetBits+1)
55b37e4b45SLingrui98      this.nextStartAddr :=
56b37e4b45SLingrui98        Cat(nextBlockHigher,
57b37e4b45SLingrui98          startAddr(log2Ceil(PredictWidth)+instOffsetBits) ^ 1.U(1.W),
58b37e4b45SLingrui98          startAddr(log2Ceil(PredictWidth)+instOffsetBits-1, instOffsetBits),
59b37e4b45SLingrui98          0.U(instOffsetBits.W)
60b37e4b45SLingrui98        )
6109c6f1ddSLingrui98    }
6209c6f1ddSLingrui98    this
6309c6f1ddSLingrui98  }
6409c6f1ddSLingrui98  override def toPrintable: Printable = {
65b37e4b45SLingrui98    p"[start] ${Hexadecimal(startAddr)} [next] ${Hexadecimal(nextlineStart)}" +
66b37e4b45SLingrui98      p"[tgt] ${Hexadecimal(nextStartAddr)} [ftqIdx] $ftqIdx [jmp] v:${ftqOffset.valid}" +
6709c6f1ddSLingrui98      p" offset: ${ftqOffset.bits}\n"
6809c6f1ddSLingrui98  }
6909c6f1ddSLingrui98}
7009c6f1ddSLingrui98
71f22cf846SJeniusclass FtqICacheInfo(implicit p: Parameters)extends XSBundle with HasICacheParameters{
72c5c5edaeSJenius  val startAddr           = UInt(VAddrBits.W)
73c5c5edaeSJenius  val nextlineStart       = UInt(VAddrBits.W)
74c5c5edaeSJenius  def crossCacheline =  startAddr(blockOffBits - 1) === 1.U
75b004fa13SJenius  def fromFtqPcBundle(b: Ftq_RF_Components) = {
76b004fa13SJenius    this.startAddr := b.startAddr
77b004fa13SJenius    this.nextlineStart := b.nextLineAddr
78b004fa13SJenius    this
79b004fa13SJenius  }
80f22cf846SJenius}
81f22cf846SJenius
8250780602SJeniusclass IFUICacheIO(implicit p: Parameters)extends XSBundle with HasICacheParameters{
8350780602SJenius  val icacheReady       = Output(Bool())
8450780602SJenius  val resp              = Vec(PortNumber, ValidIO(new ICacheMainPipeResp))
85d2b20d1aSTang Haojin  val topdownIcacheMiss = Output(Bool())
86d2b20d1aSTang Haojin  val topdownItlbMiss = Output(Bool())
8750780602SJenius}
8850780602SJenius
89f22cf846SJeniusclass FtqToICacheRequestBundle(implicit p: Parameters)extends XSBundle with HasICacheParameters{
90f56177cbSJenius  val pcMemRead           = Vec(5, new FtqICacheInfo)
91dc270d3bSJenius  val readValid           = Vec(5, Bool())
92c5c5edaeSJenius}
93c5c5edaeSJenius
94c5c5edaeSJenius
9509c6f1ddSLingrui98class PredecodeWritebackBundle(implicit p:Parameters) extends XSBundle {
9609c6f1ddSLingrui98  val pc           = Vec(PredictWidth, UInt(VAddrBits.W))
9709c6f1ddSLingrui98  val pd           = Vec(PredictWidth, new PreDecodeInfo) // TODO: redefine Predecode
9809c6f1ddSLingrui98  val ftqIdx       = new FtqPtr
9909c6f1ddSLingrui98  val ftqOffset    = UInt(log2Ceil(PredictWidth).W)
10009c6f1ddSLingrui98  val misOffset    = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
10109c6f1ddSLingrui98  val cfiOffset    = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
10209c6f1ddSLingrui98  val target       = UInt(VAddrBits.W)
10309c6f1ddSLingrui98  val jalTarget    = UInt(VAddrBits.W)
10409c6f1ddSLingrui98  val instrRange   = Vec(PredictWidth, Bool())
10509c6f1ddSLingrui98}
10609c6f1ddSLingrui98
1077052722fSJay// Ftq send req to Prefetch
1087052722fSJayclass PrefetchRequest(implicit p:Parameters) extends XSBundle {
1097052722fSJay  val target          = UInt(VAddrBits.W)
1107052722fSJay}
11109c6f1ddSLingrui98
1127052722fSJayclass FtqPrefechBundle(implicit p:Parameters) extends XSBundle {
1137052722fSJay  val req = DecoupledIO(new PrefetchRequest)
11409c6f1ddSLingrui98}
11509c6f1ddSLingrui98
1161d1e6d4dSJeniusclass mmioCommitRead(implicit p: Parameters) extends XSBundle {
1171d1e6d4dSJenius  val mmioFtqPtr = Output(new FtqPtr)
1181d1e6d4dSJenius  val mmioLastCommit = Input(Bool())
1191d1e6d4dSJenius}
1201d1e6d4dSJenius
12109c6f1ddSLingrui98class FetchToIBuffer(implicit p: Parameters) extends XSBundle {
12209c6f1ddSLingrui98  val instrs    = Vec(PredictWidth, UInt(32.W))
12309c6f1ddSLingrui98  val valid     = UInt(PredictWidth.W)
1242a3050c2SJay  val enqEnable = UInt(PredictWidth.W)
12509c6f1ddSLingrui98  val pd        = Vec(PredictWidth, new PreDecodeInfo)
12609c6f1ddSLingrui98  val pc        = Vec(PredictWidth, UInt(VAddrBits.W))
12709c6f1ddSLingrui98  val foldpc    = Vec(PredictWidth, UInt(MemPredPCWidth.W))
12809c6f1ddSLingrui98  val ftqPtr       = new FtqPtr
12909c6f1ddSLingrui98  val ftqOffset    = Vec(PredictWidth, ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
13009c6f1ddSLingrui98  val ipf          = Vec(PredictWidth, Bool())
13109c6f1ddSLingrui98  val acf          = Vec(PredictWidth, Bool())
13209c6f1ddSLingrui98  val crossPageIPFFix = Vec(PredictWidth, Bool())
13372951335SLi Qianruo  val triggered    = Vec(PredictWidth, new TriggerCf)
134d2b20d1aSTang Haojin
135d2b20d1aSTang Haojin  val topdown_info = new FrontendTopDownBundle
13609c6f1ddSLingrui98}
13709c6f1ddSLingrui98
138c2ad24ebSLingrui98// class BitWiseUInt(val width: Int, val init: UInt) extends Module {
139c2ad24ebSLingrui98//   val io = IO(new Bundle {
140c2ad24ebSLingrui98//     val set
141c2ad24ebSLingrui98//   })
142c2ad24ebSLingrui98// }
14309c6f1ddSLingrui98// Move from BPU
144c2ad24ebSLingrui98abstract class GlobalHistory(implicit p: Parameters) extends XSBundle with HasBPUConst {
145c2ad24ebSLingrui98  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): GlobalHistory
146c2ad24ebSLingrui98}
147c2ad24ebSLingrui98
148c2ad24ebSLingrui98class ShiftingGlobalHistory(implicit p: Parameters) extends GlobalHistory {
14909c6f1ddSLingrui98  val predHist = UInt(HistoryLength.W)
15009c6f1ddSLingrui98
151c2ad24ebSLingrui98  def update(shift: UInt, taken: Bool, hist: UInt = this.predHist): ShiftingGlobalHistory = {
152c2ad24ebSLingrui98    val g = Wire(new ShiftingGlobalHistory)
15309c6f1ddSLingrui98    g.predHist := (hist << shift) | taken
15409c6f1ddSLingrui98    g
15509c6f1ddSLingrui98  }
15609c6f1ddSLingrui98
157c2ad24ebSLingrui98  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): ShiftingGlobalHistory = {
158eeb5ff92SLingrui98    require(br_valids.length == numBr)
159eeb5ff92SLingrui98    require(real_taken_mask.length == numBr)
160eeb5ff92SLingrui98    val last_valid_idx = PriorityMux(
161eeb5ff92SLingrui98      br_valids.reverse :+ true.B,
162eeb5ff92SLingrui98      (numBr to 0 by -1).map(_.U(log2Ceil(numBr+1).W))
163eeb5ff92SLingrui98    )
164eeb5ff92SLingrui98    val first_taken_idx = PriorityEncoder(false.B +: real_taken_mask)
165eeb5ff92SLingrui98    val smaller = Mux(last_valid_idx < first_taken_idx,
166eeb5ff92SLingrui98      last_valid_idx,
167eeb5ff92SLingrui98      first_taken_idx
168eeb5ff92SLingrui98    )
169eeb5ff92SLingrui98    val shift = smaller
170eeb5ff92SLingrui98    val taken = real_taken_mask.reduce(_||_)
171eeb5ff92SLingrui98    update(shift, taken, this.predHist)
172eeb5ff92SLingrui98  }
173eeb5ff92SLingrui98
174c2ad24ebSLingrui98  // static read
175c2ad24ebSLingrui98  def read(n: Int): Bool = predHist.asBools()(n)
176c2ad24ebSLingrui98
177c2ad24ebSLingrui98  final def === (that: ShiftingGlobalHistory): Bool = {
17809c6f1ddSLingrui98    predHist === that.predHist
17909c6f1ddSLingrui98  }
18009c6f1ddSLingrui98
181c2ad24ebSLingrui98  final def =/= (that: ShiftingGlobalHistory): Bool = !(this === that)
182c2ad24ebSLingrui98}
18309c6f1ddSLingrui98
184c2ad24ebSLingrui98// circular global history pointer
185c2ad24ebSLingrui98class CGHPtr(implicit p: Parameters) extends CircularQueuePtr[CGHPtr](
186c2ad24ebSLingrui98  p => p(XSCoreParamsKey).HistoryLength
187c2ad24ebSLingrui98){
188c2ad24ebSLingrui98}
189c7fabd05SSteve Gou
190c7fabd05SSteve Gouobject CGHPtr {
191c7fabd05SSteve Gou  def apply(f: Bool, v: UInt)(implicit p: Parameters): CGHPtr = {
192c7fabd05SSteve Gou    val ptr = Wire(new CGHPtr)
193c7fabd05SSteve Gou    ptr.flag := f
194c7fabd05SSteve Gou    ptr.value := v
195c7fabd05SSteve Gou    ptr
196c7fabd05SSteve Gou  }
197c7fabd05SSteve Gou  def inverse(ptr: CGHPtr)(implicit p: Parameters): CGHPtr = {
198c7fabd05SSteve Gou    apply(!ptr.flag, ptr.value)
199c7fabd05SSteve Gou  }
200c7fabd05SSteve Gou}
201c7fabd05SSteve Gou
202c2ad24ebSLingrui98class CircularGlobalHistory(implicit p: Parameters) extends GlobalHistory {
203c2ad24ebSLingrui98  val buffer = Vec(HistoryLength, Bool())
204c2ad24ebSLingrui98  type HistPtr = UInt
205c2ad24ebSLingrui98  def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): CircularGlobalHistory = {
206c2ad24ebSLingrui98    this
207c2ad24ebSLingrui98  }
208c2ad24ebSLingrui98}
209c2ad24ebSLingrui98
210dd6c0695SLingrui98class FoldedHistory(val len: Int, val compLen: Int, val max_update_num: Int)(implicit p: Parameters)
211c2ad24ebSLingrui98  extends XSBundle with HasBPUConst {
212dd6c0695SLingrui98  require(compLen >= 1)
213c2ad24ebSLingrui98  require(len > 0)
214c2ad24ebSLingrui98  // require(folded_len <= len)
215dd6c0695SLingrui98  require(compLen >= max_update_num)
216dd6c0695SLingrui98  val folded_hist = UInt(compLen.W)
217dd6c0695SLingrui98
21867402d75SLingrui98  def need_oldest_bits = len > compLen
219dd6c0695SLingrui98  def info = (len, compLen)
220c2ad24ebSLingrui98  def oldest_bit_to_get_from_ghr = (0 until max_update_num).map(len - _ - 1)
221c2ad24ebSLingrui98  def oldest_bit_pos_in_folded = oldest_bit_to_get_from_ghr map (_ % compLen)
222c2ad24ebSLingrui98  def oldest_bit_wrap_around = oldest_bit_to_get_from_ghr map (_ / compLen > 0)
223c2ad24ebSLingrui98  def oldest_bit_start = oldest_bit_pos_in_folded.head
224c2ad24ebSLingrui98
225dd6c0695SLingrui98  def get_oldest_bits_from_ghr(ghr: Vec[Bool], histPtr: CGHPtr) = {
226c2ad24ebSLingrui98    // TODO: wrap inc for histPtr value
227dd6c0695SLingrui98    oldest_bit_to_get_from_ghr.map(i => ghr((histPtr + (i+1).U).value))
228c2ad24ebSLingrui98  }
229c2ad24ebSLingrui98
230ab890bfeSLingrui98  def circular_shift_left(src: UInt, shamt: Int) = {
231c2ad24ebSLingrui98    val srcLen = src.getWidth
232c2ad24ebSLingrui98    val src_doubled = Cat(src, src)
233ab890bfeSLingrui98    val shifted = src_doubled(srcLen*2-1-shamt, srcLen-shamt)
234ab890bfeSLingrui98    shifted
235c2ad24ebSLingrui98  }
236c2ad24ebSLingrui98
23767402d75SLingrui98  // slow path, read bits from ghr
238ab890bfeSLingrui98  def update(ghr: Vec[Bool], histPtr: CGHPtr, num: Int, taken: Bool): FoldedHistory = {
23967402d75SLingrui98    val oldest_bits = VecInit(get_oldest_bits_from_ghr(ghr, histPtr))
24067402d75SLingrui98    update(oldest_bits, num, taken)
24167402d75SLingrui98  }
24267402d75SLingrui98
24367402d75SLingrui98
24467402d75SLingrui98  // fast path, use pre-read oldest bits
24567402d75SLingrui98  def update(ob: Vec[Bool], num: Int, taken: Bool): FoldedHistory = {
246c2ad24ebSLingrui98    // do xors for several bitsets at specified bits
247c2ad24ebSLingrui98    def bitsets_xor(len: Int, bitsets: Seq[Seq[Tuple2[Int, Bool]]]) = {
248c2ad24ebSLingrui98      val res = Wire(Vec(len, Bool()))
249c2ad24ebSLingrui98      // println(f"num bitsets: ${bitsets.length}")
250c2ad24ebSLingrui98      // println(f"bitsets $bitsets")
251c2ad24ebSLingrui98      val resArr = Array.fill(len)(List[Bool]())
252c2ad24ebSLingrui98      for (bs <- bitsets) {
253c2ad24ebSLingrui98        for ((n, b) <- bs) {
254c2ad24ebSLingrui98          resArr(n) = b :: resArr(n)
255c2ad24ebSLingrui98        }
256c2ad24ebSLingrui98      }
257c2ad24ebSLingrui98      // println(f"${resArr.mkString}")
258c2ad24ebSLingrui98      // println(f"histLen: ${this.len}, foldedLen: $folded_len")
259c2ad24ebSLingrui98      for (i <- 0 until len) {
260c2ad24ebSLingrui98        // println(f"bit[$i], ${resArr(i).mkString}")
261c2ad24ebSLingrui98        if (resArr(i).length > 2) {
262c2ad24ebSLingrui98          println(f"[warning] update logic of foldest history has two or more levels of xor gates! " +
26386d9c530SLingrui98            f"histlen:${this.len}, compLen:$compLen, at bit $i")
264c2ad24ebSLingrui98        }
265c2ad24ebSLingrui98        if (resArr(i).length == 0) {
266dd6c0695SLingrui98          println(f"[error] bits $i is not assigned in folded hist update logic! histlen:${this.len}, compLen:$compLen")
267c2ad24ebSLingrui98        }
268c2ad24ebSLingrui98        res(i) := resArr(i).foldLeft(false.B)(_^_)
269c2ad24ebSLingrui98      }
270c2ad24ebSLingrui98      res.asUInt
271c2ad24ebSLingrui98    }
272c2ad24ebSLingrui98
27367402d75SLingrui98    val new_folded_hist = if (need_oldest_bits) {
27467402d75SLingrui98      val oldest_bits = ob
27567402d75SLingrui98      require(oldest_bits.length == max_update_num)
276c2ad24ebSLingrui98      // mask off bits that do not update
277c2ad24ebSLingrui98      val oldest_bits_masked = oldest_bits.zipWithIndex.map{
278ab890bfeSLingrui98        case (ob, i) => ob && (i < num).B
279c2ad24ebSLingrui98      }
280c2ad24ebSLingrui98      // if a bit does not wrap around, it should not be xored when it exits
281c2ad24ebSLingrui98      val oldest_bits_set = (0 until max_update_num).filter(oldest_bit_wrap_around).map(i => (oldest_bit_pos_in_folded(i), oldest_bits_masked(i)))
282c2ad24ebSLingrui98
283c2ad24ebSLingrui98      // println(f"old bits pos ${oldest_bits_set.map(_._1)}")
284c2ad24ebSLingrui98
285c2ad24ebSLingrui98      // only the last bit could be 1, as we have at most one taken branch at a time
286ab890bfeSLingrui98      val newest_bits_masked = VecInit((0 until max_update_num).map(i => taken && ((i+1) == num).B)).asUInt
287c2ad24ebSLingrui98      // if a bit does not wrap around, newest bits should not be xored onto it either
288e992912cSLingrui98      val newest_bits_set = (0 until max_update_num).map(i => (compLen-1-i, newest_bits_masked(i)))
289c2ad24ebSLingrui98
290c2ad24ebSLingrui98      // println(f"new bits set ${newest_bits_set.map(_._1)}")
291c2ad24ebSLingrui98      //
292c2ad24ebSLingrui98      val original_bits_masked = VecInit(folded_hist.asBools.zipWithIndex.map{
293ab890bfeSLingrui98        case (fb, i) => fb && !(num >= (len-i)).B
294c2ad24ebSLingrui98      })
295c2ad24ebSLingrui98      val original_bits_set = (0 until compLen).map(i => (i, original_bits_masked(i)))
296c2ad24ebSLingrui98
297c2ad24ebSLingrui98      // do xor then shift
298c2ad24ebSLingrui98      val xored = bitsets_xor(compLen, Seq(original_bits_set, oldest_bits_set, newest_bits_set))
299ab890bfeSLingrui98      circular_shift_left(xored, num)
30067402d75SLingrui98    } else {
30167402d75SLingrui98      // histLen too short to wrap around
30267402d75SLingrui98      ((folded_hist << num) | taken)(compLen-1,0)
303c2ad24ebSLingrui98    }
30467402d75SLingrui98
305c2ad24ebSLingrui98    val fh = WireInit(this)
306c2ad24ebSLingrui98    fh.folded_hist := new_folded_hist
307c2ad24ebSLingrui98    fh
308c2ad24ebSLingrui98  }
30909c6f1ddSLingrui98}
31009c6f1ddSLingrui98
31167402d75SLingrui98class AheadFoldedHistoryOldestBits(val len: Int, val max_update_num: Int)(implicit p: Parameters) extends XSBundle {
31267402d75SLingrui98  val bits = Vec(max_update_num*2, Bool())
31367402d75SLingrui98  // def info = (len, compLen)
31467402d75SLingrui98  def getRealOb(brNumOH: UInt): Vec[Bool] = {
31567402d75SLingrui98    val ob = Wire(Vec(max_update_num, Bool()))
31667402d75SLingrui98    for (i <- 0 until max_update_num) {
31767402d75SLingrui98      ob(i) := Mux1H(brNumOH, bits.drop(i).take(numBr+1))
31867402d75SLingrui98    }
31967402d75SLingrui98    ob
32067402d75SLingrui98  }
32167402d75SLingrui98}
32267402d75SLingrui98
32367402d75SLingrui98class AllAheadFoldedHistoryOldestBits(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle with HasBPUConst {
32467402d75SLingrui98  val afhob = MixedVec(gen.filter(t => t._1 > t._2).map{_._1}
32567402d75SLingrui98    .toSet.toList.map(l => new AheadFoldedHistoryOldestBits(l, numBr))) // remove duplicates
32667402d75SLingrui98  require(gen.toSet.toList.equals(gen))
32767402d75SLingrui98  def getObWithInfo(info: Tuple2[Int, Int]) = {
32867402d75SLingrui98    val selected = afhob.filter(_.len == info._1)
32967402d75SLingrui98    require(selected.length == 1)
33067402d75SLingrui98    selected(0)
33167402d75SLingrui98  }
33267402d75SLingrui98  def read(ghv: Vec[Bool], ptr: CGHPtr) = {
33367402d75SLingrui98    val hisLens = afhob.map(_.len)
33467402d75SLingrui98    val bitsToRead = hisLens.flatMap(l => (0 until numBr*2).map(i => l-i-1)).toSet // remove duplicates
33567402d75SLingrui98    val bitsWithInfo = bitsToRead.map(pos => (pos, ghv((ptr+(pos+1).U).value)))
33667402d75SLingrui98    for (ob <- afhob) {
33767402d75SLingrui98      for (i <- 0 until numBr*2) {
33867402d75SLingrui98        val pos = ob.len - i - 1
33967402d75SLingrui98        val bit_found = bitsWithInfo.filter(_._1 == pos).toList
34067402d75SLingrui98        require(bit_found.length == 1)
34167402d75SLingrui98        ob.bits(i) := bit_found(0)._2
34267402d75SLingrui98      }
34367402d75SLingrui98    }
34467402d75SLingrui98  }
34567402d75SLingrui98}
34667402d75SLingrui98
34767402d75SLingrui98class AllFoldedHistories(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle with HasBPUConst {
34867402d75SLingrui98  val hist = MixedVec(gen.map{case (l, cl) => new FoldedHistory(l, cl, numBr)})
34967402d75SLingrui98  // println(gen.mkString)
35067402d75SLingrui98  require(gen.toSet.toList.equals(gen))
35167402d75SLingrui98  def getHistWithInfo(info: Tuple2[Int, Int]) = {
35267402d75SLingrui98    val selected = hist.filter(_.info.equals(info))
35367402d75SLingrui98    require(selected.length == 1)
35467402d75SLingrui98    selected(0)
35567402d75SLingrui98  }
35667402d75SLingrui98  def autoConnectFrom(that: AllFoldedHistories) = {
35767402d75SLingrui98    require(this.hist.length <= that.hist.length)
35867402d75SLingrui98    for (h <- this.hist) {
35967402d75SLingrui98      h := that.getHistWithInfo(h.info)
36067402d75SLingrui98    }
36167402d75SLingrui98  }
36267402d75SLingrui98  def update(ghv: Vec[Bool], ptr: CGHPtr, shift: Int, taken: Bool): AllFoldedHistories = {
36367402d75SLingrui98    val res = WireInit(this)
36467402d75SLingrui98    for (i <- 0 until this.hist.length) {
36567402d75SLingrui98      res.hist(i) := this.hist(i).update(ghv, ptr, shift, taken)
36667402d75SLingrui98    }
36767402d75SLingrui98    res
36867402d75SLingrui98  }
36967402d75SLingrui98  def update(afhob: AllAheadFoldedHistoryOldestBits, lastBrNumOH: UInt, shift: Int, taken: Bool): AllFoldedHistories = {
37067402d75SLingrui98    val res = WireInit(this)
37167402d75SLingrui98    for (i <- 0 until this.hist.length) {
37267402d75SLingrui98      val fh = this.hist(i)
37367402d75SLingrui98      if (fh.need_oldest_bits) {
37467402d75SLingrui98        val info = fh.info
37567402d75SLingrui98        val selectedAfhob = afhob.getObWithInfo(info)
37667402d75SLingrui98        val ob = selectedAfhob.getRealOb(lastBrNumOH)
37767402d75SLingrui98        res.hist(i) := this.hist(i).update(ob, shift, taken)
37867402d75SLingrui98      } else {
37967402d75SLingrui98        val dumb = Wire(Vec(numBr, Bool())) // not needed
38067402d75SLingrui98        dumb := DontCare
38167402d75SLingrui98        res.hist(i) := this.hist(i).update(dumb, shift, taken)
38267402d75SLingrui98      }
38367402d75SLingrui98    }
38467402d75SLingrui98    res
38567402d75SLingrui98  }
38667402d75SLingrui98
38767402d75SLingrui98  def display(cond: Bool) = {
38867402d75SLingrui98    for (h <- hist) {
38967402d75SLingrui98      XSDebug(cond, p"hist len ${h.len}, folded len ${h.compLen}, value ${Binary(h.folded_hist)}\n")
39067402d75SLingrui98    }
39167402d75SLingrui98  }
39267402d75SLingrui98}
39367402d75SLingrui98
39409c6f1ddSLingrui98class TableAddr(val idxBits: Int, val banks: Int)(implicit p: Parameters) extends XSBundle{
39509c6f1ddSLingrui98  def tagBits = VAddrBits - idxBits - instOffsetBits
39609c6f1ddSLingrui98
39709c6f1ddSLingrui98  val tag = UInt(tagBits.W)
39809c6f1ddSLingrui98  val idx = UInt(idxBits.W)
39909c6f1ddSLingrui98  val offset = UInt(instOffsetBits.W)
40009c6f1ddSLingrui98
40109c6f1ddSLingrui98  def fromUInt(x: UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this)
40209c6f1ddSLingrui98  def getTag(x: UInt) = fromUInt(x).tag
40309c6f1ddSLingrui98  def getIdx(x: UInt) = fromUInt(x).idx
40409c6f1ddSLingrui98  def getBank(x: UInt) = if (banks > 1) getIdx(x)(log2Up(banks) - 1, 0) else 0.U
40509c6f1ddSLingrui98  def getBankIdx(x: UInt) = if (banks > 1) getIdx(x)(idxBits - 1, log2Up(banks)) else getIdx(x)
40609c6f1ddSLingrui98}
407eeb5ff92SLingrui98
408b37e4b45SLingrui98trait BasicPrediction extends HasXSParameter {
409b37e4b45SLingrui98  def cfiIndex: ValidUndirectioned[UInt]
410b37e4b45SLingrui98  def target(pc: UInt): UInt
411b37e4b45SLingrui98  def lastBrPosOH: Vec[Bool]
412b37e4b45SLingrui98  def brTaken: Bool
413b37e4b45SLingrui98  def shouldShiftVec: Vec[Bool]
414b37e4b45SLingrui98  def fallThruError: Bool
415b37e4b45SLingrui98}
416eeb5ff92SLingrui98@chiselName
417b37e4b45SLingrui98class FullBranchPrediction(implicit p: Parameters) extends XSBundle with HasBPUConst with BasicPrediction {
418eeb5ff92SLingrui98  val br_taken_mask = Vec(numBr, Bool())
41909c6f1ddSLingrui98
420eeb5ff92SLingrui98  val slot_valids = Vec(totalSlot, Bool())
42109c6f1ddSLingrui98
422eeb5ff92SLingrui98  val targets = Vec(totalSlot, UInt(VAddrBits.W))
423b30c10d6SLingrui98  val jalr_target = UInt(VAddrBits.W) // special path for indirect predictors
424a229ab6cSLingrui98  val offsets = Vec(totalSlot, UInt(log2Ceil(PredictWidth).W))
425a229ab6cSLingrui98  val fallThroughAddr = UInt(VAddrBits.W)
426b37e4b45SLingrui98  val fallThroughErr = Bool()
42709c6f1ddSLingrui98
42809c6f1ddSLingrui98  val is_jal = Bool()
42909c6f1ddSLingrui98  val is_jalr = Bool()
43009c6f1ddSLingrui98  val is_call = Bool()
43109c6f1ddSLingrui98  val is_ret = Bool()
432f4ebc4b2SLingrui98  val last_may_be_rvi_call = Bool()
433eeb5ff92SLingrui98  val is_br_sharing = Bool()
43409c6f1ddSLingrui98
43509c6f1ddSLingrui98  // val call_is_rvc = Bool()
43609c6f1ddSLingrui98  val hit = Bool()
43709c6f1ddSLingrui98
438*209a4cafSSteve Gou  val predCycle = if (!env.FPGAPlatform) Some(UInt(64.W)) else None
439*209a4cafSSteve Gou
440eeb5ff92SLingrui98  def br_slot_valids = slot_valids.init
441eeb5ff92SLingrui98  def tail_slot_valid = slot_valids.last
442eeb5ff92SLingrui98
443eeb5ff92SLingrui98  def br_valids = {
444b37e4b45SLingrui98    VecInit(br_slot_valids :+ (tail_slot_valid && is_br_sharing))
445eeb5ff92SLingrui98  }
446eeb5ff92SLingrui98
447eeb5ff92SLingrui98  def taken_mask_on_slot = {
448eeb5ff92SLingrui98    VecInit(
449eeb5ff92SLingrui98      (br_slot_valids zip br_taken_mask.init).map{ case (t, v) => t && v } :+ (
450b30c10d6SLingrui98        tail_slot_valid && (
451b30c10d6SLingrui98          is_br_sharing && br_taken_mask.last || !is_br_sharing
452b30c10d6SLingrui98        )
453eeb5ff92SLingrui98      )
454eeb5ff92SLingrui98    )
455eeb5ff92SLingrui98  }
456eeb5ff92SLingrui98
457b37e4b45SLingrui98  def real_slot_taken_mask(): Vec[Bool] = {
458b37e4b45SLingrui98    VecInit(taken_mask_on_slot.map(_ && hit))
459b37e4b45SLingrui98  }
460b37e4b45SLingrui98
461b37e4b45SLingrui98  // len numBr
462b37e4b45SLingrui98  def real_br_taken_mask(): Vec[Bool] = {
463b37e4b45SLingrui98    VecInit(
464b37e4b45SLingrui98      taken_mask_on_slot.map(_ && hit).init :+
465b37e4b45SLingrui98      (br_taken_mask.last && tail_slot_valid && is_br_sharing && hit)
466b37e4b45SLingrui98    )
467b37e4b45SLingrui98  }
468b37e4b45SLingrui98
469b37e4b45SLingrui98  // the vec indicating if ghr should shift on each branch
470b37e4b45SLingrui98  def shouldShiftVec =
471b37e4b45SLingrui98    VecInit(br_valids.zipWithIndex.map{ case (v, i) =>
472b37e4b45SLingrui98      v && !real_br_taken_mask.take(i).reduceOption(_||_).getOrElse(false.B)})
473b37e4b45SLingrui98
474b37e4b45SLingrui98  def lastBrPosOH =
475b37e4b45SLingrui98    VecInit((!hit || !br_valids.reduce(_||_)) +: // not hit or no brs in entry
476b37e4b45SLingrui98      (0 until numBr).map(i =>
477b37e4b45SLingrui98        br_valids(i) &&
478b37e4b45SLingrui98        !real_br_taken_mask.take(i).reduceOption(_||_).getOrElse(false.B) && // no brs taken in front it
479b37e4b45SLingrui98        (real_br_taken_mask()(i) || !br_valids.drop(i+1).reduceOption(_||_).getOrElse(false.B)) && // no brs behind it
480b37e4b45SLingrui98        hit
481b37e4b45SLingrui98      )
482b37e4b45SLingrui98    )
483b37e4b45SLingrui98
48486d9c530SLingrui98  def brTaken = (br_valids zip br_taken_mask).map{ case (a, b) => a && b && hit}.reduce(_||_)
485b37e4b45SLingrui98
486b37e4b45SLingrui98  def target(pc: UInt): UInt = {
487d3854a00SLingrui98    val targetVec = targets :+ fallThroughAddr :+ (pc + (FetchWidth * 4).U)
488d3854a00SLingrui98    val tm = taken_mask_on_slot
489d3854a00SLingrui98    val selVecOH =
490d3854a00SLingrui98      tm.zipWithIndex.map{ case (t, i) => !tm.take(i).fold(false.B)(_||_) && t && hit} :+
491d3854a00SLingrui98      (!tm.asUInt.orR && hit) :+ !hit
492d3854a00SLingrui98    Mux1H(selVecOH, targetVec)
493b37e4b45SLingrui98  }
494b37e4b45SLingrui98
495b37e4b45SLingrui98  def fallThruError: Bool = hit && fallThroughErr
496b37e4b45SLingrui98
497b37e4b45SLingrui98  def hit_taken_on_jmp =
498b37e4b45SLingrui98    !real_slot_taken_mask().init.reduce(_||_) &&
499b37e4b45SLingrui98    real_slot_taken_mask().last && !is_br_sharing
500b37e4b45SLingrui98  def hit_taken_on_call = hit_taken_on_jmp && is_call
501b37e4b45SLingrui98  def hit_taken_on_ret  = hit_taken_on_jmp && is_ret
502b37e4b45SLingrui98  def hit_taken_on_jalr = hit_taken_on_jmp && is_jalr
503b37e4b45SLingrui98
504b37e4b45SLingrui98  def cfiIndex = {
505b37e4b45SLingrui98    val cfiIndex = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
506b37e4b45SLingrui98    cfiIndex.valid := real_slot_taken_mask().asUInt.orR
507b37e4b45SLingrui98    // when no takens, set cfiIndex to PredictWidth-1
508b37e4b45SLingrui98    cfiIndex.bits :=
509b37e4b45SLingrui98      ParallelPriorityMux(real_slot_taken_mask(), offsets) |
510b37e4b45SLingrui98      Fill(log2Ceil(PredictWidth), (!real_slot_taken_mask().asUInt.orR).asUInt)
511b37e4b45SLingrui98    cfiIndex
512b37e4b45SLingrui98  }
513b37e4b45SLingrui98
514eeb5ff92SLingrui98  def taken = br_taken_mask.reduce(_||_) || slot_valids.last // || (is_jal || is_jalr)
51509c6f1ddSLingrui98
51647c003a9SEaston Man  def fromFtbEntry(
51747c003a9SEaston Man                    entry: FTBEntry,
51847c003a9SEaston Man                    pc: UInt,
51947c003a9SEaston Man                    last_stage_pc: Option[Tuple2[UInt, Bool]] = None,
52047c003a9SEaston Man                    last_stage_entry: Option[Tuple2[FTBEntry, Bool]] = None
52147c003a9SEaston Man                  ) = {
522eeb5ff92SLingrui98    slot_valids := entry.brSlots.map(_.valid) :+ entry.tailSlot.valid
52347c003a9SEaston Man    targets := entry.getTargetVec(pc, last_stage_pc) // Use previous stage pc for better timing
524b30c10d6SLingrui98    jalr_target := targets.last
525a229ab6cSLingrui98    offsets := entry.getOffsetVec
526eeb5ff92SLingrui98    is_jal := entry.tailSlot.valid && entry.isJal
527eeb5ff92SLingrui98    is_jalr := entry.tailSlot.valid && entry.isJalr
528eeb5ff92SLingrui98    is_call := entry.tailSlot.valid && entry.isCall
529eeb5ff92SLingrui98    is_ret := entry.tailSlot.valid && entry.isRet
530f4ebc4b2SLingrui98    last_may_be_rvi_call := entry.last_may_be_rvi_call
531eeb5ff92SLingrui98    is_br_sharing := entry.tailSlot.valid && entry.tailSlot.sharing
532*209a4cafSSteve Gou    predCycle.map(_ := GTimer())
533a229ab6cSLingrui98
534a60a2901SLingrui98    val startLower        = Cat(0.U(1.W),    pc(instOffsetBits+log2Ceil(PredictWidth)-1, instOffsetBits))
535b37e4b45SLingrui98    val endLowerwithCarry = Cat(entry.carry, entry.pftAddr)
536a60a2901SLingrui98    fallThroughErr := startLower >= endLowerwithCarry
53747c003a9SEaston Man    fallThroughAddr := Mux(fallThroughErr, pc + (FetchWidth * 4).U, entry.getFallThrough(pc, last_stage_entry))
538a229ab6cSLingrui98  }
53909c6f1ddSLingrui98
54009c6f1ddSLingrui98  def display(cond: Bool): Unit = {
541eeb5ff92SLingrui98    XSDebug(cond, p"[taken_mask] ${Binary(br_taken_mask.asUInt)} [hit] $hit\n")
54209c6f1ddSLingrui98  }
54309c6f1ddSLingrui98}
54409c6f1ddSLingrui98
545803124a6SLingrui98class SpeculativeInfo(implicit p: Parameters) extends XSBundle
546803124a6SLingrui98  with HasBPUConst with BPUUtils {
547803124a6SLingrui98  val folded_hist = new AllFoldedHistories(foldedGHistInfos)
548803124a6SLingrui98  val afhob = new AllAheadFoldedHistoryOldestBits(foldedGHistInfos)
549803124a6SLingrui98  val lastBrNumOH = UInt((numBr+1).W)
550803124a6SLingrui98  val histPtr = new CGHPtr
551803124a6SLingrui98  val rasSp = UInt(log2Ceil(RasSize).W)
552803124a6SLingrui98  val rasTop = new RASEntry
553803124a6SLingrui98}
554803124a6SLingrui98
555bf358e08SLingrui98@chiselName
556b37e4b45SLingrui98class BranchPredictionBundle(implicit p: Parameters) extends XSBundle
557b37e4b45SLingrui98  with HasBPUConst with BPUUtils {
558adc0b8dfSGuokai Chen  val pc    = Vec(numDup, UInt(VAddrBits.W))
559adc0b8dfSGuokai Chen  val valid = Vec(numDup, Bool())
560adc0b8dfSGuokai Chen  val hasRedirect  = Vec(numDup, Bool())
56109c6f1ddSLingrui98  val ftq_idx = new FtqPtr
562adc0b8dfSGuokai Chen  val full_pred    = Vec(numDup, new FullBranchPrediction)
563b37e4b45SLingrui98
56409c6f1ddSLingrui98
565adc0b8dfSGuokai Chen  def target(pc: UInt) = VecInit(full_pred.map(_.target(pc)))
566adc0b8dfSGuokai Chen  def targets(pc: Vec[UInt]) = VecInit(pc.zipWithIndex.map{case (a, i) => full_pred(i).target(a)})
567adc0b8dfSGuokai Chen  def cfiIndex         = VecInit(full_pred.map(_.cfiIndex))
568adc0b8dfSGuokai Chen  def lastBrPosOH      = VecInit(full_pred.map(_.lastBrPosOH))
569adc0b8dfSGuokai Chen  def brTaken          = VecInit(full_pred.map(_.brTaken))
570adc0b8dfSGuokai Chen  def shouldShiftVec   = VecInit(full_pred.map(_.shouldShiftVec))
571adc0b8dfSGuokai Chen  def fallThruError    = VecInit(full_pred.map(_.fallThruError))
572eeb5ff92SLingrui98
573adc0b8dfSGuokai Chen  def taken = VecInit(cfiIndex.map(_.valid))
574adc0b8dfSGuokai Chen
575adc0b8dfSGuokai Chen  def getTarget = targets(pc)
57609c6f1ddSLingrui98
57709c6f1ddSLingrui98  def display(cond: Bool): Unit = {
578adc0b8dfSGuokai Chen    XSDebug(cond, p"[pc] ${Hexadecimal(pc(0))}\n")
579adc0b8dfSGuokai Chen    full_pred(0).display(cond)
58009c6f1ddSLingrui98  }
58109c6f1ddSLingrui98}
58209c6f1ddSLingrui98
583bf358e08SLingrui98@chiselName
58409c6f1ddSLingrui98class BranchPredictionResp(implicit p: Parameters) extends XSBundle with HasBPUConst {
58509c6f1ddSLingrui98  // val valids = Vec(3, Bool())
586b37e4b45SLingrui98  val s1 = new BranchPredictionBundle
587b37e4b45SLingrui98  val s2 = new BranchPredictionBundle
588cb4f77ceSLingrui98  val s3 = new BranchPredictionBundle
58909c6f1ddSLingrui98
590c2d1ec7dSLingrui98  val last_stage_meta = UInt(MaxMetaLength.W)
591c2d1ec7dSLingrui98  val last_stage_spec_info = new SpeculativeInfo
592c2d1ec7dSLingrui98  val last_stage_ftb_entry = new FTBEntry
593c2d1ec7dSLingrui98
594d2b20d1aSTang Haojin  val topdown_info = new FrontendTopDownBundle
595d2b20d1aSTang Haojin
596b37e4b45SLingrui98  def selectedResp ={
597b37e4b45SLingrui98    val res =
59809c6f1ddSLingrui98      PriorityMux(Seq(
599adc0b8dfSGuokai Chen        ((s3.valid(3) && s3.hasRedirect(3)) -> s3),
600adc0b8dfSGuokai Chen        ((s2.valid(3) && s2.hasRedirect(3)) -> s2),
601adc0b8dfSGuokai Chen        (s1.valid(3) -> s1)
60209c6f1ddSLingrui98      ))
603b37e4b45SLingrui98    res
604b37e4b45SLingrui98  }
605adc0b8dfSGuokai Chen  def selectedRespIdxForFtq =
60609c6f1ddSLingrui98    PriorityMux(Seq(
607adc0b8dfSGuokai Chen      ((s3.valid(3) && s3.hasRedirect(3)) -> BP_S3),
608adc0b8dfSGuokai Chen      ((s2.valid(3) && s2.hasRedirect(3)) -> BP_S2),
609adc0b8dfSGuokai Chen      (s1.valid(3) -> BP_S1)
61009c6f1ddSLingrui98    ))
611cb4f77ceSLingrui98  def lastStage = s3
61209c6f1ddSLingrui98}
61309c6f1ddSLingrui98
614c2d1ec7dSLingrui98class BpuToFtqBundle(implicit p: Parameters) extends BranchPredictionResp {}
61509c6f1ddSLingrui98
616803124a6SLingrui98class BranchPredictionUpdate(implicit p: Parameters) extends XSBundle with HasBPUConst {
617803124a6SLingrui98  val pc = UInt(VAddrBits.W)
618803124a6SLingrui98  val spec_info = new SpeculativeInfo
619803124a6SLingrui98  val ftb_entry = new FTBEntry()
620803124a6SLingrui98
621803124a6SLingrui98  val cfi_idx = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
622803124a6SLingrui98  val br_taken_mask = Vec(numBr, Bool())
623cc2d1573SEaston Man  val br_committed = Vec(numBr, Bool()) // High only when br valid && br committed
624803124a6SLingrui98  val jmp_taken = Bool()
62509c6f1ddSLingrui98  val mispred_mask = Vec(numBr+1, Bool())
626edc18578SLingrui98  val pred_hit = Bool()
62709c6f1ddSLingrui98  val false_hit = Bool()
62809c6f1ddSLingrui98  val new_br_insert_pos = Vec(numBr, Bool())
62909c6f1ddSLingrui98  val old_entry = Bool()
63009c6f1ddSLingrui98  val meta = UInt(MaxMetaLength.W)
631abdbe4b7SLingrui98  val full_target = UInt(VAddrBits.W)
632edc18578SLingrui98  val from_stage = UInt(2.W)
63386d9c530SLingrui98  val ghist = UInt(HistoryLength.W)
63409c6f1ddSLingrui98
635803124a6SLingrui98  def is_jal = ftb_entry.tailSlot.valid && ftb_entry.isJal
636803124a6SLingrui98  def is_jalr = ftb_entry.tailSlot.valid && ftb_entry.isJalr
637803124a6SLingrui98  def is_call = ftb_entry.tailSlot.valid && ftb_entry.isCall
638803124a6SLingrui98  def is_ret = ftb_entry.tailSlot.valid && ftb_entry.isRet
639803124a6SLingrui98
640803124a6SLingrui98  def display(cond: Bool) = {
64109c6f1ddSLingrui98    XSDebug(cond, p"-----------BranchPredictionUpdate-----------\n")
64209c6f1ddSLingrui98    XSDebug(cond, p"[mispred_mask] ${Binary(mispred_mask.asUInt)} [false_hit] $false_hit\n")
64309c6f1ddSLingrui98    XSDebug(cond, p"[new_br_insert_pos] ${Binary(new_br_insert_pos.asUInt)}\n")
64409c6f1ddSLingrui98    XSDebug(cond, p"--------------------------------------------\n")
64509c6f1ddSLingrui98  }
64609c6f1ddSLingrui98}
64709c6f1ddSLingrui98
64809c6f1ddSLingrui98class BranchPredictionRedirect(implicit p: Parameters) extends Redirect with HasBPUConst {
64909c6f1ddSLingrui98  // override def toPrintable: Printable = {
65009c6f1ddSLingrui98  //   p"-----------BranchPredictionRedirect----------- " +
65109c6f1ddSLingrui98  //     p"-----------cfiUpdate----------- " +
65209c6f1ddSLingrui98  //     p"[pc] ${Hexadecimal(cfiUpdate.pc)} " +
65309c6f1ddSLingrui98  //     p"[predTaken] ${cfiUpdate.predTaken}, [taken] ${cfiUpdate.taken}, [isMisPred] ${cfiUpdate.isMisPred} " +
65409c6f1ddSLingrui98  //     p"[target] ${Hexadecimal(cfiUpdate.target)} " +
65509c6f1ddSLingrui98  //     p"------------------------------- " +
6569aca92b9SYinan Xu  //     p"[robPtr] f=${robIdx.flag} v=${robIdx.value} " +
65709c6f1ddSLingrui98  //     p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} " +
65809c6f1ddSLingrui98  //     p"[ftqOffset] ${ftqOffset} " +
65909c6f1ddSLingrui98  //     p"[level] ${level}, [interrupt] ${interrupt} " +
66009c6f1ddSLingrui98  //     p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value} " +
66109c6f1ddSLingrui98  //     p"[stFtqOffset] ${stFtqOffset} " +
66209c6f1ddSLingrui98  //     p"\n"
66309c6f1ddSLingrui98
66409c6f1ddSLingrui98  // }
66509c6f1ddSLingrui98
666d2b20d1aSTang Haojin  // TODO: backend should pass topdown signals here
667d2b20d1aSTang Haojin  // must not change its parent since BPU has used asTypeOf(this type) from its parent class
668d2b20d1aSTang Haojin  require(isInstanceOf[Redirect])
669d2b20d1aSTang Haojin  val BTBMissBubble = Bool()
670d2b20d1aSTang Haojin  def ControlRedirectBubble = debugIsCtrl
671d2b20d1aSTang Haojin  // if mispred br not in ftb, count as BTB miss
672d2b20d1aSTang Haojin  def ControlBTBMissBubble = ControlRedirectBubble && !cfiUpdate.br_hit && !cfiUpdate.jr_hit
673d2b20d1aSTang Haojin  def TAGEMissBubble = ControlRedirectBubble && cfiUpdate.br_hit && !cfiUpdate.sc_hit
674d2b20d1aSTang Haojin  def SCMissBubble = ControlRedirectBubble && cfiUpdate.br_hit && cfiUpdate.sc_hit
675d2b20d1aSTang Haojin  def ITTAGEMissBubble = ControlRedirectBubble && cfiUpdate.jr_hit && !cfiUpdate.pd.isRet
676d2b20d1aSTang Haojin  def RASMissBubble = ControlRedirectBubble && cfiUpdate.jr_hit && cfiUpdate.pd.isRet
677d2b20d1aSTang Haojin  def MemVioRedirectBubble = debugIsMemVio
678d2b20d1aSTang Haojin  def OtherRedirectBubble = !debugIsCtrl && !debugIsMemVio
679d2b20d1aSTang Haojin
680d2b20d1aSTang Haojin  def connectRedirect(source: Redirect): Unit = {
681d2b20d1aSTang Haojin    for ((name, data) <- this.elements) {
682d2b20d1aSTang Haojin      if (source.elements.contains(name)) {
683d2b20d1aSTang Haojin        data := source.elements(name)
684d2b20d1aSTang Haojin      }
685d2b20d1aSTang Haojin    }
686d2b20d1aSTang Haojin  }
687d2b20d1aSTang Haojin
68809c6f1ddSLingrui98  def display(cond: Bool): Unit = {
68909c6f1ddSLingrui98    XSDebug(cond, p"-----------BranchPredictionRedirect----------- \n")
69009c6f1ddSLingrui98    XSDebug(cond, p"-----------cfiUpdate----------- \n")
69109c6f1ddSLingrui98    XSDebug(cond, p"[pc] ${Hexadecimal(cfiUpdate.pc)}\n")
692c2ad24ebSLingrui98    // XSDebug(cond, p"[hist] ${Binary(cfiUpdate.hist.predHist)}\n")
69309c6f1ddSLingrui98    XSDebug(cond, p"[br_hit] ${cfiUpdate.br_hit} [isMisPred] ${cfiUpdate.isMisPred}\n")
69409c6f1ddSLingrui98    XSDebug(cond, p"[pred_taken] ${cfiUpdate.predTaken} [taken] ${cfiUpdate.taken} [isMisPred] ${cfiUpdate.isMisPred}\n")
69509c6f1ddSLingrui98    XSDebug(cond, p"[target] ${Hexadecimal(cfiUpdate.target)} \n")
69609c6f1ddSLingrui98    XSDebug(cond, p"[shift] ${cfiUpdate.shift}\n")
69709c6f1ddSLingrui98    XSDebug(cond, p"------------------------------- \n")
6989aca92b9SYinan Xu    XSDebug(cond, p"[robPtr] f=${robIdx.flag} v=${robIdx.value}\n")
69909c6f1ddSLingrui98    XSDebug(cond, p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} \n")
70009c6f1ddSLingrui98    XSDebug(cond, p"[ftqOffset] ${ftqOffset} \n")
70109c6f1ddSLingrui98    XSDebug(cond, p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value}\n")
70209c6f1ddSLingrui98    XSDebug(cond, p"[stFtqOffset] ${stFtqOffset}\n")
70309c6f1ddSLingrui98    XSDebug(cond, p"---------------------------------------------- \n")
70409c6f1ddSLingrui98  }
70509c6f1ddSLingrui98}
706