xref: /XiangShan/src/main/scala/xiangshan/frontend/FrontendBundle.scala (revision d2b20d1a96e238e36a849bd253f65ec7b6a5db38)
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._
27*d2b20d1aSTang Haojinimport java.util.ResourceBundle.Control
28*d2b20d1aSTang Haojin
29*d2b20d1aSTang Haojinclass FrontendTopDownBundle(implicit p: Parameters) extends XSBundle {
30*d2b20d1aSTang Haojin  val reasons = Vec(TopDownCounters.NumStallReasons.id, Bool())
31*d2b20d1aSTang Haojin  val stallWidth = UInt(log2Ceil(PredictWidth).W)
32*d2b20d1aSTang 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
45*d2b20d1aSTang Haojin  val topdown_info    = new FrontendTopDownBundle
46*d2b20d1aSTang 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))
85*d2b20d1aSTang Haojin  val topdownIcacheMiss = Output(Bool())
86*d2b20d1aSTang 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)
134*d2b20d1aSTang Haojin
135*d2b20d1aSTang 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
438eeb5ff92SLingrui98  def br_slot_valids = slot_valids.init
439eeb5ff92SLingrui98  def tail_slot_valid = slot_valids.last
440eeb5ff92SLingrui98
441eeb5ff92SLingrui98  def br_valids = {
442b37e4b45SLingrui98    VecInit(br_slot_valids :+ (tail_slot_valid && is_br_sharing))
443eeb5ff92SLingrui98  }
444eeb5ff92SLingrui98
445eeb5ff92SLingrui98  def taken_mask_on_slot = {
446eeb5ff92SLingrui98    VecInit(
447eeb5ff92SLingrui98      (br_slot_valids zip br_taken_mask.init).map{ case (t, v) => t && v } :+ (
448b30c10d6SLingrui98        tail_slot_valid && (
449b30c10d6SLingrui98          is_br_sharing && br_taken_mask.last || !is_br_sharing
450b30c10d6SLingrui98        )
451eeb5ff92SLingrui98      )
452eeb5ff92SLingrui98    )
453eeb5ff92SLingrui98  }
454eeb5ff92SLingrui98
455b37e4b45SLingrui98  def real_slot_taken_mask(): Vec[Bool] = {
456b37e4b45SLingrui98    VecInit(taken_mask_on_slot.map(_ && hit))
457b37e4b45SLingrui98  }
458b37e4b45SLingrui98
459b37e4b45SLingrui98  // len numBr
460b37e4b45SLingrui98  def real_br_taken_mask(): Vec[Bool] = {
461b37e4b45SLingrui98    VecInit(
462b37e4b45SLingrui98      taken_mask_on_slot.map(_ && hit).init :+
463b37e4b45SLingrui98      (br_taken_mask.last && tail_slot_valid && is_br_sharing && hit)
464b37e4b45SLingrui98    )
465b37e4b45SLingrui98  }
466b37e4b45SLingrui98
467b37e4b45SLingrui98  // the vec indicating if ghr should shift on each branch
468b37e4b45SLingrui98  def shouldShiftVec =
469b37e4b45SLingrui98    VecInit(br_valids.zipWithIndex.map{ case (v, i) =>
470b37e4b45SLingrui98      v && !real_br_taken_mask.take(i).reduceOption(_||_).getOrElse(false.B)})
471b37e4b45SLingrui98
472b37e4b45SLingrui98  def lastBrPosOH =
473b37e4b45SLingrui98    VecInit((!hit || !br_valids.reduce(_||_)) +: // not hit or no brs in entry
474b37e4b45SLingrui98      (0 until numBr).map(i =>
475b37e4b45SLingrui98        br_valids(i) &&
476b37e4b45SLingrui98        !real_br_taken_mask.take(i).reduceOption(_||_).getOrElse(false.B) && // no brs taken in front it
477b37e4b45SLingrui98        (real_br_taken_mask()(i) || !br_valids.drop(i+1).reduceOption(_||_).getOrElse(false.B)) && // no brs behind it
478b37e4b45SLingrui98        hit
479b37e4b45SLingrui98      )
480b37e4b45SLingrui98    )
481b37e4b45SLingrui98
48286d9c530SLingrui98  def brTaken = (br_valids zip br_taken_mask).map{ case (a, b) => a && b && hit}.reduce(_||_)
483b37e4b45SLingrui98
484b37e4b45SLingrui98  def target(pc: UInt): UInt = {
485d3854a00SLingrui98    val targetVec = targets :+ fallThroughAddr :+ (pc + (FetchWidth * 4).U)
486d3854a00SLingrui98    val tm = taken_mask_on_slot
487d3854a00SLingrui98    val selVecOH =
488d3854a00SLingrui98      tm.zipWithIndex.map{ case (t, i) => !tm.take(i).fold(false.B)(_||_) && t && hit} :+
489d3854a00SLingrui98      (!tm.asUInt.orR && hit) :+ !hit
490d3854a00SLingrui98    Mux1H(selVecOH, targetVec)
491b37e4b45SLingrui98  }
492b37e4b45SLingrui98
493b37e4b45SLingrui98  def fallThruError: Bool = hit && fallThroughErr
494b37e4b45SLingrui98
495b37e4b45SLingrui98  def hit_taken_on_jmp =
496b37e4b45SLingrui98    !real_slot_taken_mask().init.reduce(_||_) &&
497b37e4b45SLingrui98    real_slot_taken_mask().last && !is_br_sharing
498b37e4b45SLingrui98  def hit_taken_on_call = hit_taken_on_jmp && is_call
499b37e4b45SLingrui98  def hit_taken_on_ret  = hit_taken_on_jmp && is_ret
500b37e4b45SLingrui98  def hit_taken_on_jalr = hit_taken_on_jmp && is_jalr
501b37e4b45SLingrui98
502b37e4b45SLingrui98  def cfiIndex = {
503b37e4b45SLingrui98    val cfiIndex = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
504b37e4b45SLingrui98    cfiIndex.valid := real_slot_taken_mask().asUInt.orR
505b37e4b45SLingrui98    // when no takens, set cfiIndex to PredictWidth-1
506b37e4b45SLingrui98    cfiIndex.bits :=
507b37e4b45SLingrui98      ParallelPriorityMux(real_slot_taken_mask(), offsets) |
508b37e4b45SLingrui98      Fill(log2Ceil(PredictWidth), (!real_slot_taken_mask().asUInt.orR).asUInt)
509b37e4b45SLingrui98    cfiIndex
510b37e4b45SLingrui98  }
511b37e4b45SLingrui98
512eeb5ff92SLingrui98  def taken = br_taken_mask.reduce(_||_) || slot_valids.last // || (is_jal || is_jalr)
51309c6f1ddSLingrui98
514b30c10d6SLingrui98  def fromFtbEntry(entry: FTBEntry, pc: UInt, last_stage: Option[Tuple2[UInt, Bool]] = None) = {
515eeb5ff92SLingrui98    slot_valids := entry.brSlots.map(_.valid) :+ entry.tailSlot.valid
516eeb5ff92SLingrui98    targets := entry.getTargetVec(pc)
517b30c10d6SLingrui98    jalr_target := targets.last
518a229ab6cSLingrui98    offsets := entry.getOffsetVec
519eeb5ff92SLingrui98    is_jal := entry.tailSlot.valid && entry.isJal
520eeb5ff92SLingrui98    is_jalr := entry.tailSlot.valid && entry.isJalr
521eeb5ff92SLingrui98    is_call := entry.tailSlot.valid && entry.isCall
522eeb5ff92SLingrui98    is_ret := entry.tailSlot.valid && entry.isRet
523f4ebc4b2SLingrui98    last_may_be_rvi_call := entry.last_may_be_rvi_call
524eeb5ff92SLingrui98    is_br_sharing := entry.tailSlot.valid && entry.tailSlot.sharing
525a229ab6cSLingrui98
526a60a2901SLingrui98    val startLower        = Cat(0.U(1.W),    pc(instOffsetBits+log2Ceil(PredictWidth)-1, instOffsetBits))
527b37e4b45SLingrui98    val endLowerwithCarry = Cat(entry.carry, entry.pftAddr)
528a60a2901SLingrui98    fallThroughErr := startLower >= endLowerwithCarry
52986d9c530SLingrui98    fallThroughAddr := Mux(fallThroughErr, pc + (FetchWidth * 4).U, entry.getFallThrough(pc))
530a229ab6cSLingrui98  }
53109c6f1ddSLingrui98
53209c6f1ddSLingrui98  def display(cond: Bool): Unit = {
533eeb5ff92SLingrui98    XSDebug(cond, p"[taken_mask] ${Binary(br_taken_mask.asUInt)} [hit] $hit\n")
53409c6f1ddSLingrui98  }
53509c6f1ddSLingrui98}
53609c6f1ddSLingrui98
537803124a6SLingrui98class SpeculativeInfo(implicit p: Parameters) extends XSBundle
538803124a6SLingrui98  with HasBPUConst with BPUUtils {
539803124a6SLingrui98  val folded_hist = new AllFoldedHistories(foldedGHistInfos)
540803124a6SLingrui98  val afhob = new AllAheadFoldedHistoryOldestBits(foldedGHistInfos)
541803124a6SLingrui98  val lastBrNumOH = UInt((numBr+1).W)
542803124a6SLingrui98  val histPtr = new CGHPtr
543803124a6SLingrui98  val rasSp = UInt(log2Ceil(RasSize).W)
544803124a6SLingrui98  val rasTop = new RASEntry
545803124a6SLingrui98}
546803124a6SLingrui98
547bf358e08SLingrui98@chiselName
548b37e4b45SLingrui98class BranchPredictionBundle(implicit p: Parameters) extends XSBundle
549b37e4b45SLingrui98  with HasBPUConst with BPUUtils {
55009c6f1ddSLingrui98  val pc = UInt(VAddrBits.W)
55109c6f1ddSLingrui98  val valid = Bool()
55209c6f1ddSLingrui98  val hasRedirect = Bool()
55309c6f1ddSLingrui98  val ftq_idx = new FtqPtr
554b37e4b45SLingrui98  val full_pred = new FullBranchPrediction
555b37e4b45SLingrui98
55609c6f1ddSLingrui98
557c5e28a9aSLingrui98  def target(pc: UInt) = full_pred.target(pc)
558c5e28a9aSLingrui98  def cfiIndex         = full_pred.cfiIndex
559c5e28a9aSLingrui98  def lastBrPosOH      = full_pred.lastBrPosOH
560c5e28a9aSLingrui98  def brTaken          = full_pred.brTaken
561c5e28a9aSLingrui98  def shouldShiftVec   = full_pred.shouldShiftVec
562c5e28a9aSLingrui98  def fallThruError    = full_pred.fallThruError
563eeb5ff92SLingrui98
564b37e4b45SLingrui98  def getTarget = target(pc)
565b37e4b45SLingrui98  def taken = cfiIndex.valid
56609c6f1ddSLingrui98
56709c6f1ddSLingrui98  def display(cond: Bool): Unit = {
56809c6f1ddSLingrui98    XSDebug(cond, p"[pc] ${Hexadecimal(pc)}\n")
569b37e4b45SLingrui98    full_pred.display(cond)
57009c6f1ddSLingrui98  }
57109c6f1ddSLingrui98}
57209c6f1ddSLingrui98
573bf358e08SLingrui98@chiselName
57409c6f1ddSLingrui98class BranchPredictionResp(implicit p: Parameters) extends XSBundle with HasBPUConst {
57509c6f1ddSLingrui98  // val valids = Vec(3, Bool())
576b37e4b45SLingrui98  val s1 = new BranchPredictionBundle
577b37e4b45SLingrui98  val s2 = new BranchPredictionBundle
578cb4f77ceSLingrui98  val s3 = new BranchPredictionBundle
57909c6f1ddSLingrui98
580c2d1ec7dSLingrui98  val last_stage_meta = UInt(MaxMetaLength.W)
581c2d1ec7dSLingrui98  val last_stage_spec_info = new SpeculativeInfo
582c2d1ec7dSLingrui98  val last_stage_ftb_entry = new FTBEntry
583c2d1ec7dSLingrui98
584*d2b20d1aSTang Haojin  val topdown_info = new FrontendTopDownBundle
585*d2b20d1aSTang Haojin
586b37e4b45SLingrui98  def selectedResp ={
587b37e4b45SLingrui98    val res =
58809c6f1ddSLingrui98      PriorityMux(Seq(
589cb4f77ceSLingrui98        ((s3.valid && s3.hasRedirect) -> s3),
59009c6f1ddSLingrui98        ((s2.valid && s2.hasRedirect) -> s2),
59109c6f1ddSLingrui98        (s1.valid -> s1)
59209c6f1ddSLingrui98      ))
593b37e4b45SLingrui98    res
594b37e4b45SLingrui98  }
59509c6f1ddSLingrui98  def selectedRespIdx =
59609c6f1ddSLingrui98    PriorityMux(Seq(
597cb4f77ceSLingrui98      ((s3.valid && s3.hasRedirect) -> BP_S3),
59809c6f1ddSLingrui98      ((s2.valid && s2.hasRedirect) -> BP_S2),
59909c6f1ddSLingrui98      (s1.valid -> BP_S1)
60009c6f1ddSLingrui98    ))
601cb4f77ceSLingrui98  def lastStage = s3
60209c6f1ddSLingrui98}
60309c6f1ddSLingrui98
604c2d1ec7dSLingrui98class BpuToFtqBundle(implicit p: Parameters) extends BranchPredictionResp {}
60509c6f1ddSLingrui98
606803124a6SLingrui98class BranchPredictionUpdate(implicit p: Parameters) extends XSBundle with HasBPUConst {
607803124a6SLingrui98  val pc = UInt(VAddrBits.W)
608803124a6SLingrui98  val spec_info = new SpeculativeInfo
609803124a6SLingrui98  val ftb_entry = new FTBEntry()
610803124a6SLingrui98
611803124a6SLingrui98  val cfi_idx = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))
612803124a6SLingrui98  val br_taken_mask = Vec(numBr, Bool())
613cc2d1573SEaston Man  val br_committed = Vec(numBr, Bool()) // High only when br valid && br committed
614803124a6SLingrui98  val jmp_taken = Bool()
61509c6f1ddSLingrui98  val mispred_mask = Vec(numBr+1, Bool())
616edc18578SLingrui98  val pred_hit = Bool()
61709c6f1ddSLingrui98  val false_hit = Bool()
61809c6f1ddSLingrui98  val new_br_insert_pos = Vec(numBr, Bool())
61909c6f1ddSLingrui98  val old_entry = Bool()
62009c6f1ddSLingrui98  val meta = UInt(MaxMetaLength.W)
621abdbe4b7SLingrui98  val full_target = UInt(VAddrBits.W)
622edc18578SLingrui98  val from_stage = UInt(2.W)
62386d9c530SLingrui98  val ghist = UInt(HistoryLength.W)
62409c6f1ddSLingrui98
625803124a6SLingrui98  def is_jal = ftb_entry.tailSlot.valid && ftb_entry.isJal
626803124a6SLingrui98  def is_jalr = ftb_entry.tailSlot.valid && ftb_entry.isJalr
627803124a6SLingrui98  def is_call = ftb_entry.tailSlot.valid && ftb_entry.isCall
628803124a6SLingrui98  def is_ret = ftb_entry.tailSlot.valid && ftb_entry.isRet
629803124a6SLingrui98
630803124a6SLingrui98  def display(cond: Bool) = {
63109c6f1ddSLingrui98    XSDebug(cond, p"-----------BranchPredictionUpdate-----------\n")
63209c6f1ddSLingrui98    XSDebug(cond, p"[mispred_mask] ${Binary(mispred_mask.asUInt)} [false_hit] $false_hit\n")
63309c6f1ddSLingrui98    XSDebug(cond, p"[new_br_insert_pos] ${Binary(new_br_insert_pos.asUInt)}\n")
63409c6f1ddSLingrui98    XSDebug(cond, p"--------------------------------------------\n")
63509c6f1ddSLingrui98  }
63609c6f1ddSLingrui98}
63709c6f1ddSLingrui98
63809c6f1ddSLingrui98class BranchPredictionRedirect(implicit p: Parameters) extends Redirect with HasBPUConst {
63909c6f1ddSLingrui98  // override def toPrintable: Printable = {
64009c6f1ddSLingrui98  //   p"-----------BranchPredictionRedirect----------- " +
64109c6f1ddSLingrui98  //     p"-----------cfiUpdate----------- " +
64209c6f1ddSLingrui98  //     p"[pc] ${Hexadecimal(cfiUpdate.pc)} " +
64309c6f1ddSLingrui98  //     p"[predTaken] ${cfiUpdate.predTaken}, [taken] ${cfiUpdate.taken}, [isMisPred] ${cfiUpdate.isMisPred} " +
64409c6f1ddSLingrui98  //     p"[target] ${Hexadecimal(cfiUpdate.target)} " +
64509c6f1ddSLingrui98  //     p"------------------------------- " +
6469aca92b9SYinan Xu  //     p"[robPtr] f=${robIdx.flag} v=${robIdx.value} " +
64709c6f1ddSLingrui98  //     p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} " +
64809c6f1ddSLingrui98  //     p"[ftqOffset] ${ftqOffset} " +
64909c6f1ddSLingrui98  //     p"[level] ${level}, [interrupt] ${interrupt} " +
65009c6f1ddSLingrui98  //     p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value} " +
65109c6f1ddSLingrui98  //     p"[stFtqOffset] ${stFtqOffset} " +
65209c6f1ddSLingrui98  //     p"\n"
65309c6f1ddSLingrui98
65409c6f1ddSLingrui98  // }
65509c6f1ddSLingrui98
656*d2b20d1aSTang Haojin  // TODO: backend should pass topdown signals here
657*d2b20d1aSTang Haojin  // must not change its parent since BPU has used asTypeOf(this type) from its parent class
658*d2b20d1aSTang Haojin  require(isInstanceOf[Redirect])
659*d2b20d1aSTang Haojin  val BTBMissBubble = Bool()
660*d2b20d1aSTang Haojin  def ControlRedirectBubble = debugIsCtrl
661*d2b20d1aSTang Haojin  // if mispred br not in ftb, count as BTB miss
662*d2b20d1aSTang Haojin  def ControlBTBMissBubble = ControlRedirectBubble && !cfiUpdate.br_hit && !cfiUpdate.jr_hit
663*d2b20d1aSTang Haojin  def TAGEMissBubble = ControlRedirectBubble && cfiUpdate.br_hit && !cfiUpdate.sc_hit
664*d2b20d1aSTang Haojin  def SCMissBubble = ControlRedirectBubble && cfiUpdate.br_hit && cfiUpdate.sc_hit
665*d2b20d1aSTang Haojin  def ITTAGEMissBubble = ControlRedirectBubble && cfiUpdate.jr_hit && !cfiUpdate.pd.isRet
666*d2b20d1aSTang Haojin  def RASMissBubble = ControlRedirectBubble && cfiUpdate.jr_hit && cfiUpdate.pd.isRet
667*d2b20d1aSTang Haojin  def MemVioRedirectBubble = debugIsMemVio
668*d2b20d1aSTang Haojin  def OtherRedirectBubble = !debugIsCtrl && !debugIsMemVio
669*d2b20d1aSTang Haojin
670*d2b20d1aSTang Haojin  def connectRedirect(source: Redirect): Unit = {
671*d2b20d1aSTang Haojin    for ((name, data) <- this.elements) {
672*d2b20d1aSTang Haojin      if (source.elements.contains(name)) {
673*d2b20d1aSTang Haojin        data := source.elements(name)
674*d2b20d1aSTang Haojin      }
675*d2b20d1aSTang Haojin    }
676*d2b20d1aSTang Haojin  }
677*d2b20d1aSTang Haojin
67809c6f1ddSLingrui98  def display(cond: Bool): Unit = {
67909c6f1ddSLingrui98    XSDebug(cond, p"-----------BranchPredictionRedirect----------- \n")
68009c6f1ddSLingrui98    XSDebug(cond, p"-----------cfiUpdate----------- \n")
68109c6f1ddSLingrui98    XSDebug(cond, p"[pc] ${Hexadecimal(cfiUpdate.pc)}\n")
682c2ad24ebSLingrui98    // XSDebug(cond, p"[hist] ${Binary(cfiUpdate.hist.predHist)}\n")
68309c6f1ddSLingrui98    XSDebug(cond, p"[br_hit] ${cfiUpdate.br_hit} [isMisPred] ${cfiUpdate.isMisPred}\n")
68409c6f1ddSLingrui98    XSDebug(cond, p"[pred_taken] ${cfiUpdate.predTaken} [taken] ${cfiUpdate.taken} [isMisPred] ${cfiUpdate.isMisPred}\n")
68509c6f1ddSLingrui98    XSDebug(cond, p"[target] ${Hexadecimal(cfiUpdate.target)} \n")
68609c6f1ddSLingrui98    XSDebug(cond, p"[shift] ${cfiUpdate.shift}\n")
68709c6f1ddSLingrui98    XSDebug(cond, p"------------------------------- \n")
6889aca92b9SYinan Xu    XSDebug(cond, p"[robPtr] f=${robIdx.flag} v=${robIdx.value}\n")
68909c6f1ddSLingrui98    XSDebug(cond, p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} \n")
69009c6f1ddSLingrui98    XSDebug(cond, p"[ftqOffset] ${ftqOffset} \n")
69109c6f1ddSLingrui98    XSDebug(cond, p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value}\n")
69209c6f1ddSLingrui98    XSDebug(cond, p"[stFtqOffset] ${stFtqOffset}\n")
69309c6f1ddSLingrui98    XSDebug(cond, p"---------------------------------------------- \n")
69409c6f1ddSLingrui98  }
69509c6f1ddSLingrui98}
696