xref: /XiangShan/src/main/scala/xiangshan/frontend/IFU.scala (revision 4d53e0efbe5daf676b4a4bfc064ec7f80daa0232)
109c6f1ddSLingrui98/***************************************************************************************
2e3da8badSTang Haojin* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC)
3e3da8badSTang Haojin* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences
409c6f1ddSLingrui98* Copyright (c) 2020-2021 Peng Cheng Laboratory
509c6f1ddSLingrui98*
609c6f1ddSLingrui98* XiangShan is licensed under Mulan PSL v2.
709c6f1ddSLingrui98* You can use this software according to the terms and conditions of the Mulan PSL v2.
809c6f1ddSLingrui98* You may obtain a copy of Mulan PSL v2 at:
909c6f1ddSLingrui98*          http://license.coscl.org.cn/MulanPSL2
1009c6f1ddSLingrui98*
1109c6f1ddSLingrui98* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
1209c6f1ddSLingrui98* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
1309c6f1ddSLingrui98* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
1409c6f1ddSLingrui98*
1509c6f1ddSLingrui98* See the Mulan PSL v2 for more details.
1609c6f1ddSLingrui98***************************************************************************************/
1709c6f1ddSLingrui98
1809c6f1ddSLingrui98package xiangshan.frontend
1909c6f1ddSLingrui98
2009c6f1ddSLingrui98import chisel3._
2109c6f1ddSLingrui98import chisel3.util._
22cf7d6b7aSMuziimport org.chipsalliance.cde.config.Parameters
23cf7d6b7aSMuziimport utility._
24cf7d6b7aSMuziimport utility.ChiselDB
2509c6f1ddSLingrui98import xiangshan._
26cf7d6b7aSMuziimport xiangshan.backend.GPAMemEntry
2709c6f1ddSLingrui98import xiangshan.cache.mmu._
281d8f4dcbSJayimport xiangshan.frontend.icache._
2909c6f1ddSLingrui98
3009c6f1ddSLingrui98trait HasInstrMMIOConst extends HasXSParameter with HasIFUConst {
3109c6f1ddSLingrui98  def mmioBusWidth = 64
3209c6f1ddSLingrui98  def mmioBusBytes = mmioBusWidth / 8
330be662e4SJay  def maxInstrLen  = 32
3409c6f1ddSLingrui98}
3509c6f1ddSLingrui98
3609c6f1ddSLingrui98trait HasIFUConst extends HasXSParameter {
37cf7d6b7aSMuzi  def addrAlign(addr: UInt, bytes: Int, highest: Int): UInt =
38cf7d6b7aSMuzi    Cat(addr(highest - 1, log2Ceil(bytes)), 0.U(log2Ceil(bytes).W))
391d8f4dcbSJay  def fetchQueueSize = 2
401d8f4dcbSJay
412a3050c2SJay  def getBasicBlockIdx(pc: UInt, start: UInt): UInt = {
422a3050c2SJay    val byteOffset = pc - start
432a3050c2SJay    (byteOffset - instBytes.U)(log2Ceil(PredictWidth), instOffsetBits)
441d8f4dcbSJay  }
4509c6f1ddSLingrui98}
4609c6f1ddSLingrui98
4709c6f1ddSLingrui98class IfuToFtqIO(implicit p: Parameters) extends XSBundle {
4809c6f1ddSLingrui98  val pdWb = Valid(new PredecodeWritebackBundle)
4909c6f1ddSLingrui98}
5009c6f1ddSLingrui98
51d7ac23a3SEaston Manclass IfuToBackendIO(implicit p: Parameters) extends XSBundle {
52d7ac23a3SEaston Man  // write to backend gpaddr mem
53d7ac23a3SEaston Man  val gpaddrMem_wen   = Output(Bool())
54d7ac23a3SEaston Man  val gpaddrMem_waddr = Output(UInt(log2Ceil(FtqSize).W)) // Ftq Ptr
55d7ac23a3SEaston Man  // 2 gpaddrs, correspond to startAddr & nextLineAddr in bundle FtqICacheInfo
56d7ac23a3SEaston Man  // TODO: avoid cross page entry in Ftq
57ad415ae0SXiaokun-Pei  val gpaddrMem_wdata = Output(new GPAMemEntry)
58d7ac23a3SEaston Man}
59d7ac23a3SEaston Man
6009c6f1ddSLingrui98class FtqInterface(implicit p: Parameters) extends XSBundle {
6109c6f1ddSLingrui98  val fromFtq = Flipped(new FtqToIfuIO)
6209c6f1ddSLingrui98  val toFtq   = new IfuToFtqIO
6309c6f1ddSLingrui98}
6409c6f1ddSLingrui98
650be662e4SJayclass UncacheInterface(implicit p: Parameters) extends XSBundle {
660be662e4SJay  val fromUncache = Flipped(DecoupledIO(new InsUncacheResp))
670be662e4SJay  val toUncache   = DecoupledIO(new InsUncacheReq)
680be662e4SJay}
691d1e6d4dSJenius
7009c6f1ddSLingrui98class NewIFUIO(implicit p: Parameters) extends XSBundle {
7109c6f1ddSLingrui98  val ftqInter        = new FtqInterface
7250780602SJenius  val icacheInter     = Flipped(new IFUICacheIO)
731d8f4dcbSJay  val icacheStop      = Output(Bool())
741d8f4dcbSJay  val icachePerfInfo  = Input(new ICachePerfInfo)
7509c6f1ddSLingrui98  val toIbuffer       = Decoupled(new FetchToIBuffer)
76d7ac23a3SEaston Man  val toBackend       = new IfuToBackendIO
770be662e4SJay  val uncacheInter    = new UncacheInterface
7872951335SLi Qianruo  val frontendTrigger = Flipped(new FrontendTdataDistributeIO)
79a37fbf10SJay  val rob_commits     = Flipped(Vec(CommitWidth, Valid(new RobCommitInfo)))
80f1fe8698SLemover  val iTLBInter       = new TlbRequestIO
8156788a33SJinYue  val pmp             = new ICachePMPBundle
821d1e6d4dSJenius  val mmioCommitRead  = new mmioCommitRead
8371b6c42eSxu_zh  val csr_fsIsOff     = Input(Bool())
8409c6f1ddSLingrui98}
8509c6f1ddSLingrui98
8609c6f1ddSLingrui98// record the situation in which fallThruAddr falls into
8709c6f1ddSLingrui98// the middle of an RVI inst
8809c6f1ddSLingrui98class LastHalfInfo(implicit p: Parameters) extends XSBundle {
8909c6f1ddSLingrui98  val valid    = Bool()
9009c6f1ddSLingrui98  val middlePC = UInt(VAddrBits.W)
9109c6f1ddSLingrui98  def matchThisBlock(startAddr: UInt) = valid && middlePC === startAddr
9209c6f1ddSLingrui98}
9309c6f1ddSLingrui98
9409c6f1ddSLingrui98class IfuToPreDecode(implicit p: Parameters) extends XSBundle {
9509c6f1ddSLingrui98  val data            = if (HasCExtension) Vec(PredictWidth + 1, UInt(16.W)) else Vec(PredictWidth, UInt(32.W))
9672951335SLi Qianruo  val frontendTrigger = new FrontendTdataDistributeIO
972a3050c2SJay  val pc              = Vec(PredictWidth, UInt(VAddrBits.W))
9809c6f1ddSLingrui98}
9909c6f1ddSLingrui98
1002a3050c2SJayclass IfuToPredChecker(implicit p: Parameters) extends XSBundle {
1012a3050c2SJay  val ftqOffset  = Valid(UInt(log2Ceil(PredictWidth).W))
1022a3050c2SJay  val jumpOffset = Vec(PredictWidth, UInt(XLEN.W))
1032a3050c2SJay  val target     = UInt(VAddrBits.W)
1042a3050c2SJay  val instrRange = Vec(PredictWidth, Bool())
1052a3050c2SJay  val instrValid = Vec(PredictWidth, Bool())
1062a3050c2SJay  val pds        = Vec(PredictWidth, new PreDecodeInfo)
1072a3050c2SJay  val pc         = Vec(PredictWidth, UInt(VAddrBits.W))
1080c70648eSEaston Man  val fire_in    = Bool()
1092a3050c2SJay}
1102a3050c2SJay
11151532d8bSGuokai Chenclass FetchToIBufferDB extends Bundle {
11251532d8bSGuokai Chen  val start_addr   = UInt(39.W)
11351532d8bSGuokai Chen  val instr_count  = UInt(32.W)
11451532d8bSGuokai Chen  val exception    = Bool()
11551532d8bSGuokai Chen  val is_cache_hit = Bool()
11651532d8bSGuokai Chen}
11751532d8bSGuokai Chen
11851532d8bSGuokai Chenclass IfuWbToFtqDB extends Bundle {
11951532d8bSGuokai Chen  val start_addr        = UInt(39.W)
12051532d8bSGuokai Chen  val is_miss_pred      = Bool()
12151532d8bSGuokai Chen  val miss_pred_offset  = UInt(32.W)
12251532d8bSGuokai Chen  val checkJalFault     = Bool()
12351532d8bSGuokai Chen  val checkRetFault     = Bool()
12451532d8bSGuokai Chen  val checkTargetFault  = Bool()
12551532d8bSGuokai Chen  val checkNotCFIFault  = Bool()
12651532d8bSGuokai Chen  val checkInvalidTaken = Bool()
12751532d8bSGuokai Chen}
12851532d8bSGuokai Chen
1292a3050c2SJayclass NewIFU(implicit p: Parameters) extends XSModule
1302a3050c2SJay    with HasICacheParameters
131aeedc8eeSGuokai Chen    with HasXSParameter
1322a3050c2SJay    with HasIFUConst
1332a3050c2SJay    with HasPdConst
134167bcd01SJay    with HasCircularQueuePtrHelper
1352a3050c2SJay    with HasPerfEvents
136cf7d6b7aSMuzi    with HasTlbConst {
13709c6f1ddSLingrui98  val io                       = IO(new NewIFUIO)
13809c6f1ddSLingrui98  val (toFtq, fromFtq)         = (io.ftqInter.toFtq, io.ftqInter.fromFtq)
139c5c5edaeSJenius  val fromICache               = io.icacheInter.resp
1400be662e4SJay  val (toUncache, fromUncache) = (io.uncacheInter.toUncache, io.uncacheInter.fromUncache)
14109c6f1ddSLingrui98
14209c6f1ddSLingrui98  def isCrossLineReq(start: UInt, end: UInt): Bool = start(blockOffBits) ^ end(blockOffBits)
14309c6f1ddSLingrui98
144d2b20d1aSTang Haojin  def numOfStage = 3
145e4d2f6a9Smy-mayfly  // equal lower_result overflow bit
146e4d2f6a9Smy-mayfly  def PcCutPoint = (VAddrBits / 4) - 1
147cf7d6b7aSMuzi  def CatPC(low: UInt, high: UInt, high1: UInt): UInt =
148e4d2f6a9Smy-mayfly    Mux(
149e4d2f6a9Smy-mayfly      low(PcCutPoint),
150e4d2f6a9Smy-mayfly      Cat(high1, low(PcCutPoint - 1, 0)),
151e4d2f6a9Smy-mayfly      Cat(high, low(PcCutPoint - 1, 0))
152e4d2f6a9Smy-mayfly    )
153e4d2f6a9Smy-mayfly  def CatPC(lowVec: Vec[UInt], high: UInt, high1: UInt): Vec[UInt] = VecInit(lowVec.map(CatPC(_, high, high1)))
154d2b20d1aSTang Haojin  require(numOfStage > 1, "BPU numOfStage must be greater than 1")
155d2b20d1aSTang Haojin  val topdown_stages = RegInit(VecInit(Seq.fill(numOfStage)(0.U.asTypeOf(new FrontendTopDownBundle))))
156d2b20d1aSTang Haojin  // bubble events in IFU, only happen in stage 1
157d2b20d1aSTang Haojin  val icacheMissBubble = Wire(Bool())
158d2b20d1aSTang Haojin  val itlbMissBubble   = Wire(Bool())
159d2b20d1aSTang Haojin
160d2b20d1aSTang Haojin  // only driven by clock, not valid-ready
161d2b20d1aSTang Haojin  topdown_stages(0) := fromFtq.req.bits.topdown_info
162d2b20d1aSTang Haojin  for (i <- 1 until numOfStage) {
163d2b20d1aSTang Haojin    topdown_stages(i) := topdown_stages(i - 1)
164d2b20d1aSTang Haojin  }
165d2b20d1aSTang Haojin  when(icacheMissBubble) {
166d2b20d1aSTang Haojin    topdown_stages(1).reasons(TopDownCounters.ICacheMissBubble.id) := true.B
167d2b20d1aSTang Haojin  }
168d2b20d1aSTang Haojin  when(itlbMissBubble) {
169d2b20d1aSTang Haojin    topdown_stages(1).reasons(TopDownCounters.ITLBMissBubble.id) := true.B
170d2b20d1aSTang Haojin  }
171d2b20d1aSTang Haojin  io.toIbuffer.bits.topdown_info := topdown_stages(numOfStage - 1)
172d2b20d1aSTang Haojin  when(fromFtq.topdown_redirect.valid) {
173d2b20d1aSTang Haojin    // only redirect from backend, IFU redirect itself is handled elsewhere
174d2b20d1aSTang Haojin    when(fromFtq.topdown_redirect.bits.debugIsCtrl) {
175d2b20d1aSTang Haojin      /*
176d2b20d1aSTang Haojin      for (i <- 0 until numOfStage) {
177d2b20d1aSTang Haojin        topdown_stages(i).reasons(TopDownCounters.ControlRedirectBubble.id) := true.B
178d2b20d1aSTang Haojin      }
179d2b20d1aSTang Haojin      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.ControlRedirectBubble.id) := true.B
180d2b20d1aSTang Haojin       */
181d2b20d1aSTang Haojin      when(fromFtq.topdown_redirect.bits.ControlBTBMissBubble) {
182d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
183d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.BTBMissBubble.id) := true.B
184d2b20d1aSTang Haojin        }
185d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.BTBMissBubble.id) := true.B
186d2b20d1aSTang Haojin      }.elsewhen(fromFtq.topdown_redirect.bits.TAGEMissBubble) {
187d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
188d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.TAGEMissBubble.id) := true.B
189d2b20d1aSTang Haojin        }
190d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.TAGEMissBubble.id) := true.B
191d2b20d1aSTang Haojin      }.elsewhen(fromFtq.topdown_redirect.bits.SCMissBubble) {
192d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
193d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.SCMissBubble.id) := true.B
194d2b20d1aSTang Haojin        }
195d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.SCMissBubble.id) := true.B
196d2b20d1aSTang Haojin      }.elsewhen(fromFtq.topdown_redirect.bits.ITTAGEMissBubble) {
197d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
198d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.ITTAGEMissBubble.id) := true.B
199d2b20d1aSTang Haojin        }
200d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.ITTAGEMissBubble.id) := true.B
201d2b20d1aSTang Haojin      }.elsewhen(fromFtq.topdown_redirect.bits.RASMissBubble) {
202d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
203d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.RASMissBubble.id) := true.B
204d2b20d1aSTang Haojin        }
205d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.RASMissBubble.id) := true.B
206d2b20d1aSTang Haojin      }
207d2b20d1aSTang Haojin    }.elsewhen(fromFtq.topdown_redirect.bits.debugIsMemVio) {
208d2b20d1aSTang Haojin      for (i <- 0 until numOfStage) {
209d2b20d1aSTang Haojin        topdown_stages(i).reasons(TopDownCounters.MemVioRedirectBubble.id) := true.B
210d2b20d1aSTang Haojin      }
211d2b20d1aSTang Haojin      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.MemVioRedirectBubble.id) := true.B
212d2b20d1aSTang Haojin    }.otherwise {
213d2b20d1aSTang Haojin      for (i <- 0 until numOfStage) {
214d2b20d1aSTang Haojin        topdown_stages(i).reasons(TopDownCounters.OtherRedirectBubble.id) := true.B
215d2b20d1aSTang Haojin      }
216d2b20d1aSTang Haojin      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.OtherRedirectBubble.id) := true.B
217d2b20d1aSTang Haojin    }
218d2b20d1aSTang Haojin  }
219d2b20d1aSTang Haojin
2201d8f4dcbSJay  class TlbExept(implicit p: Parameters) extends XSBundle {
2211d8f4dcbSJay    val pageFault   = Bool()
2221d8f4dcbSJay    val accessFault = Bool()
2231d8f4dcbSJay    val mmio        = Bool()
224b005f7c6SJay  }
22509c6f1ddSLingrui98
226a61a35e0Sssszwic  val preDecoder = Module(new PreDecode)
227dc270d3bSJenius
2282a3050c2SJay  val predChecker     = Module(new PredChecker)
2292a3050c2SJay  val frontendTrigger = Module(new FrontendTrigger)
230cf7d6b7aSMuzi  val (checkerIn, checkerOutStage1, checkerOutStage2) =
231cf7d6b7aSMuzi    (predChecker.io.in, predChecker.io.out.stage1Out, predChecker.io.out.stage2Out)
2321d8f4dcbSJay
23358dbdfc2SJay  /**
23458dbdfc2SJay    ******************************************************************************
23558dbdfc2SJay    * IFU Stage 0
23658dbdfc2SJay    * - send cacheline fetch request to ICacheMainPipe
23758dbdfc2SJay    ******************************************************************************
23858dbdfc2SJay    */
23909c6f1ddSLingrui98
24009c6f1ddSLingrui98  val f0_valid      = fromFtq.req.valid
24109c6f1ddSLingrui98  val f0_ftq_req    = fromFtq.req.bits
2426ce52296SJinYue  val f0_doubleLine = fromFtq.req.bits.crossCacheline
243cf7d6b7aSMuzi  val f0_vSetIdx    = VecInit(get_idx(f0_ftq_req.startAddr), get_idx(f0_ftq_req.nextlineStart))
244935edac4STang Haojin  val f0_fire       = fromFtq.req.fire
24509c6f1ddSLingrui98
24609c6f1ddSLingrui98  val f0_flush, f1_flush, f2_flush, f3_flush                                     = WireInit(false.B)
24709c6f1ddSLingrui98  val from_bpu_f0_flush, from_bpu_f1_flush, from_bpu_f2_flush, from_bpu_f3_flush = WireInit(false.B)
24809c6f1ddSLingrui98
249cb4f77ceSLingrui98  from_bpu_f0_flush := fromFtq.flushFromBpu.shouldFlushByStage2(f0_ftq_req.ftqIdx) ||
250cb4f77ceSLingrui98    fromFtq.flushFromBpu.shouldFlushByStage3(f0_ftq_req.ftqIdx)
25109c6f1ddSLingrui98
2522a3050c2SJay  val wb_redirect, mmio_redirect, backend_redirect = WireInit(false.B)
2532a3050c2SJay  val f3_wb_not_flush                              = WireInit(false.B)
2542a3050c2SJay
2552a3050c2SJay  backend_redirect := fromFtq.redirect.valid
2562a3050c2SJay  f3_flush         := backend_redirect || (wb_redirect && !f3_wb_not_flush)
2572a3050c2SJay  f2_flush         := backend_redirect || mmio_redirect || wb_redirect
25809c6f1ddSLingrui98  f1_flush         := f2_flush || from_bpu_f1_flush
25909c6f1ddSLingrui98  f0_flush         := f1_flush || from_bpu_f0_flush
26009c6f1ddSLingrui98
26109c6f1ddSLingrui98  val f1_ready, f2_ready, f3_ready = WireInit(false.B)
26209c6f1ddSLingrui98
26350780602SJenius  fromFtq.req.ready := f1_ready && io.icacheInter.icacheReady
26409c6f1ddSLingrui98
265d2b20d1aSTang Haojin  when(wb_redirect) {
266d2b20d1aSTang Haojin    when(f3_wb_not_flush) {
267d2b20d1aSTang Haojin      topdown_stages(2).reasons(TopDownCounters.BTBMissBubble.id) := true.B
268d2b20d1aSTang Haojin    }
269d2b20d1aSTang Haojin    for (i <- 0 until numOfStage - 1) {
270d2b20d1aSTang Haojin      topdown_stages(i).reasons(TopDownCounters.BTBMissBubble.id) := true.B
271d2b20d1aSTang Haojin    }
272d2b20d1aSTang Haojin  }
273d2b20d1aSTang Haojin
27458dbdfc2SJay  /** <PERF> f0 fetch bubble */
275f7c29b0aSJinYue
27600240ba6SJay  XSPerfAccumulate("fetch_bubble_ftq_not_valid", !fromFtq.req.valid && fromFtq.req.ready)
277c5c5edaeSJenius  // XSPerfAccumulate("fetch_bubble_pipe_stall",    f0_valid && toICache(0).ready && toICache(1).ready && !f1_ready )
278c5c5edaeSJenius  // XSPerfAccumulate("fetch_bubble_icache_0_busy",   f0_valid && !toICache(0).ready  )
279c5c5edaeSJenius  // XSPerfAccumulate("fetch_bubble_icache_1_busy",   f0_valid && !toICache(1).ready  )
28000240ba6SJay  XSPerfAccumulate("fetch_flush_backend_redirect", backend_redirect)
28100240ba6SJay  XSPerfAccumulate("fetch_flush_wb_redirect", wb_redirect)
28200240ba6SJay  XSPerfAccumulate("fetch_flush_bpu_f1_flush", from_bpu_f1_flush)
28300240ba6SJay  XSPerfAccumulate("fetch_flush_bpu_f0_flush", from_bpu_f0_flush)
28458dbdfc2SJay
28558dbdfc2SJay  /**
28658dbdfc2SJay    ******************************************************************************
28758dbdfc2SJay    * IFU Stage 1
28858dbdfc2SJay    * - calculate pc/half_pc/cut_ptr for every instruction
28958dbdfc2SJay    ******************************************************************************
29058dbdfc2SJay    */
29109c6f1ddSLingrui98
29209c6f1ddSLingrui98  val f1_valid   = RegInit(false.B)
293005e809bSJiuyang Liu  val f1_ftq_req = RegEnable(f0_ftq_req, f0_fire)
294005e809bSJiuyang Liu  // val f1_situation  = RegEnable(f0_situation,  f0_fire)
295005e809bSJiuyang Liu  val f1_doubleLine = RegEnable(f0_doubleLine, f0_fire)
296005e809bSJiuyang Liu  val f1_vSetIdx    = RegEnable(f0_vSetIdx, f0_fire)
297625ecd17SJenius  val f1_fire       = f1_valid && f2_ready
29809c6f1ddSLingrui98
299625ecd17SJenius  f1_ready := f1_fire || !f1_valid
30009c6f1ddSLingrui98
3010d756c48SJinYue  from_bpu_f1_flush := fromFtq.flushFromBpu.shouldFlushByStage3(f1_ftq_req.ftqIdx) && f1_valid
302cb4f77ceSLingrui98  // from_bpu_f1_flush := false.B
30309c6f1ddSLingrui98
304cf7d6b7aSMuzi  when(f1_flush)(f1_valid := false.B)
305cf7d6b7aSMuzi    .elsewhen(f0_fire && !f0_flush)(f1_valid := true.B)
306cf7d6b7aSMuzi    .elsewhen(f1_fire)(f1_valid := false.B)
30709c6f1ddSLingrui98
308e4d2f6a9Smy-mayfly  val f1_pc_high       = f1_ftq_req.startAddr(VAddrBits - 1, PcCutPoint)
309f2f493deSstride  val f1_pc_high_plus1 = f1_pc_high + 1.U
310f2f493deSstride
311e4d2f6a9Smy-mayfly  /**
312e4d2f6a9Smy-mayfly   * In order to reduce power consumption, avoid calculating the full PC value in the first level.
313e4d2f6a9Smy-mayfly   * code of original logic, this code has been deprecated
314e4d2f6a9Smy-mayfly   * val f1_pc                 = VecInit(f1_pc_lower_result.map{ i =>
315e4d2f6a9Smy-mayfly   *  Mux(i(f1_pc_adder_cut_point), Cat(f1_pc_high_plus1,i(f1_pc_adder_cut_point-1,0)), Cat(f1_pc_high,i(f1_pc_adder_cut_point-1,0)))})
316e4d2f6a9Smy-mayfly   */
317cf7d6b7aSMuzi  val f1_pc_lower_result = VecInit((0 until PredictWidth).map(i =>
318cf7d6b7aSMuzi    Cat(0.U(1.W), f1_ftq_req.startAddr(PcCutPoint - 1, 0)) + (i * 2).U
319cf7d6b7aSMuzi  )) // cat with overflow bit
320f2f493deSstride
321e4d2f6a9Smy-mayfly  val f1_pc = CatPC(f1_pc_lower_result, f1_pc_high, f1_pc_high_plus1)
322e4d2f6a9Smy-mayfly
323cf7d6b7aSMuzi  val f1_half_snpc_lower_result = VecInit((0 until PredictWidth).map(i =>
324cf7d6b7aSMuzi    Cat(0.U(1.W), f1_ftq_req.startAddr(PcCutPoint - 1, 0)) + ((i + 2) * 2).U
325cf7d6b7aSMuzi  )) // cat with overflow bit
326e4d2f6a9Smy-mayfly  val f1_half_snpc = CatPC(f1_half_snpc_lower_result, f1_pc_high, f1_pc_high_plus1)
327f2f493deSstride
328f2f493deSstride  if (env.FPGAPlatform) {
329f2f493deSstride    val f1_pc_diff        = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + (i * 2).U))
330f2f493deSstride    val f1_half_snpc_diff = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + ((i + 2) * 2).U))
331f2f493deSstride
332cf7d6b7aSMuzi    XSError(
333cf7d6b7aSMuzi      f1_pc.zip(f1_pc_diff).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _),
334cf7d6b7aSMuzi      "f1_half_snpc adder cut fail"
335cf7d6b7aSMuzi    )
336cf7d6b7aSMuzi    XSError(
337cf7d6b7aSMuzi      f1_half_snpc.zip(f1_half_snpc_diff).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _),
338cf7d6b7aSMuzi      "f1_half_snpc adder cut fail"
339cf7d6b7aSMuzi    )
340f2f493deSstride  }
341f2f493deSstride
342cf7d6b7aSMuzi  val f1_cut_ptr = if (HasCExtension)
343cf7d6b7aSMuzi    VecInit((0 until PredictWidth + 1).map(i => Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits - 1, 1)) + i.U))
344b92f8445Sssszwic  else VecInit((0 until PredictWidth).map(i => Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits - 1, 2)) + i.U))
34509c6f1ddSLingrui98
34658dbdfc2SJay  /**
34758dbdfc2SJay    ******************************************************************************
34858dbdfc2SJay    * IFU Stage 2
34958dbdfc2SJay    * - icache response data (latched for pipeline stop)
35058dbdfc2SJay    * - generate exceprion bits for every instruciton (page fault/access fault/mmio)
35158dbdfc2SJay    * - generate predicted instruction range (1 means this instruciton is in this fetch packet)
35258dbdfc2SJay    * - cut data from cachlines to packet instruction code
35358dbdfc2SJay    * - instruction predecode and RVC expand
35458dbdfc2SJay    ******************************************************************************
35558dbdfc2SJay    */
35658dbdfc2SJay
3571d8f4dcbSJay  val icacheRespAllValid = WireInit(false.B)
35809c6f1ddSLingrui98
35909c6f1ddSLingrui98  val f2_valid   = RegInit(false.B)
360005e809bSJiuyang Liu  val f2_ftq_req = RegEnable(f1_ftq_req, f1_fire)
361005e809bSJiuyang Liu  // val f2_situation  = RegEnable(f1_situation,  f1_fire)
362005e809bSJiuyang Liu  val f2_doubleLine = RegEnable(f1_doubleLine, f1_fire)
363005e809bSJiuyang Liu  val f2_vSetIdx    = RegEnable(f1_vSetIdx, f1_fire)
364625ecd17SJenius  val f2_fire       = f2_valid && f3_ready && icacheRespAllValid
3651d8f4dcbSJay
366625ecd17SJenius  f2_ready := f2_fire || !f2_valid
3671d8f4dcbSJay  // TODO: addr compare may be timing critical
368cf7d6b7aSMuzi  val f2_icache_all_resp_wire =
3694690c88aSxu_zh    fromICache.valid &&
3704690c88aSxu_zh      fromICache.bits.vaddr(0) === f2_ftq_req.startAddr &&
3714690c88aSxu_zh      (fromICache.bits.doubleline && fromICache.bits.vaddr(1) === f2_ftq_req.nextlineStart || !f2_doubleLine)
3721d8f4dcbSJay  val f2_icache_all_resp_reg = RegInit(false.B)
3731d8f4dcbSJay
3741d8f4dcbSJay  icacheRespAllValid := f2_icache_all_resp_reg || f2_icache_all_resp_wire
3751d8f4dcbSJay
376d2b20d1aSTang Haojin  icacheMissBubble := io.icacheInter.topdownIcacheMiss
377d2b20d1aSTang Haojin  itlbMissBubble   := io.icacheInter.topdownItlbMiss
378d2b20d1aSTang Haojin
3791d8f4dcbSJay  io.icacheStop := !f3_ready
3801d8f4dcbSJay
381cf7d6b7aSMuzi  when(f2_flush)(f2_icache_all_resp_reg := false.B)
382cf7d6b7aSMuzi    .elsewhen(f2_valid && f2_icache_all_resp_wire && !f3_ready)(f2_icache_all_resp_reg := true.B)
383cf7d6b7aSMuzi    .elsewhen(f2_fire && f2_icache_all_resp_reg)(f2_icache_all_resp_reg := false.B)
38409c6f1ddSLingrui98
385cf7d6b7aSMuzi  when(f2_flush)(f2_valid := false.B)
386cf7d6b7aSMuzi    .elsewhen(f1_fire && !f1_flush)(f2_valid := true.B)
387cf7d6b7aSMuzi    .elsewhen(f2_fire)(f2_valid := false.B)
38809c6f1ddSLingrui98
3894690c88aSxu_zh  val f2_exception_in     = fromICache.bits.exception
3904690c88aSxu_zh  val f2_backendException = fromICache.bits.backendException
391d7ac23a3SEaston Man  // paddr and gpaddr of [startAddr, nextLineAddr]
3924690c88aSxu_zh  val f2_paddrs            = fromICache.bits.paddr
3934690c88aSxu_zh  val f2_gpaddr            = fromICache.bits.gpaddr
3944690c88aSxu_zh  val f2_isForVSnonLeafPTE = fromICache.bits.isForVSnonLeafPTE
395002c10a4SYanqin Li
396211986abSxu_zh  // FIXME: raise af if one fetch block crosses the cacheable-noncacheable boundary, might not correct
39735850f17Sxu_zh  val f2_mmio_mismatch_exception = VecInit(Seq(
39835850f17Sxu_zh    ExceptionType.none, // mark the exception only on the second line
39935850f17Sxu_zh    Mux(
400211986abSxu_zh      // not double-line, skip check
4014690c88aSxu_zh      !fromICache.bits.doubleline || (
402211986abSxu_zh        // is double-line, ask for consistent pmp_mmio and itlb_pbmt value
4034690c88aSxu_zh        fromICache.bits.pmp_mmio(0) === fromICache.bits.pmp_mmio(1) &&
4044690c88aSxu_zh          fromICache.bits.itlb_pbmt(0) === fromICache.bits.itlb_pbmt(1)
4054690c88aSxu_zh      ),
406211986abSxu_zh      ExceptionType.none,
407211986abSxu_zh      ExceptionType.af
40835850f17Sxu_zh    )
40935850f17Sxu_zh  ))
410211986abSxu_zh
411211986abSxu_zh  // merge exceptions
412211986abSxu_zh  val f2_exception = ExceptionType.merge(f2_exception_in, f2_mmio_mismatch_exception)
413211986abSxu_zh
414211986abSxu_zh  // we need only the first port, as the second is asked to be the same
4154690c88aSxu_zh  val f2_pmp_mmio  = fromICache.bits.pmp_mmio(0)
4164690c88aSxu_zh  val f2_itlb_pbmt = fromICache.bits.itlb_pbmt(0)
417002c10a4SYanqin Li
418e4d2f6a9Smy-mayfly  /**
419e4d2f6a9Smy-mayfly    * reduce the number of registers, origin code
420e4d2f6a9Smy-mayfly    * f2_pc = RegEnable(f1_pc, f1_fire)
421e4d2f6a9Smy-mayfly    */
422e4d2f6a9Smy-mayfly  val f2_pc_lower_result = RegEnable(f1_pc_lower_result, f1_fire)
423e4d2f6a9Smy-mayfly  val f2_pc_high         = RegEnable(f1_pc_high, f1_fire)
424e4d2f6a9Smy-mayfly  val f2_pc_high_plus1   = RegEnable(f1_pc_high_plus1, f1_fire)
425e4d2f6a9Smy-mayfly  val f2_pc              = CatPC(f2_pc_lower_result, f2_pc_high, f2_pc_high_plus1)
426a37fbf10SJay
427e4d2f6a9Smy-mayfly  val f2_cut_ptr      = RegEnable(f1_cut_ptr, f1_fire)
428005e809bSJiuyang Liu  val f2_resend_vaddr = RegEnable(f1_ftq_req.startAddr + 2.U, f1_fire)
4292a3050c2SJay
430cf7d6b7aSMuzi  def isNextLine(pc: UInt, startAddr: UInt) =
4312a3050c2SJay    startAddr(blockOffBits) ^ pc(blockOffBits)
43209c6f1ddSLingrui98
433cf7d6b7aSMuzi  def isLastInLine(pc: UInt) =
4342a3050c2SJay    pc(blockOffBits - 1, 0) === "b111110".U
43509c6f1ddSLingrui98
4362a3050c2SJay  val f2_foldpc = VecInit(f2_pc.map(i => XORFold(i(VAddrBits - 1, 1), MemPredPCWidth)))
437cf7d6b7aSMuzi  val f2_jump_range =
438cf7d6b7aSMuzi    Fill(PredictWidth, !f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~f2_ftq_req.ftqOffset.bits
439*4d53e0efSzhou tao  require(
440*4d53e0efSzhou tao    isPow2(PredictWidth),
441*4d53e0efSzhou tao    "If PredictWidth does not satisfy the power of 2," +
442*4d53e0efSzhou tao      "expression: Fill(PredictWidth, 1.U(1.W)) >> ~f2_ftq_req.ftqOffset.bits is not right !!"
443*4d53e0efSzhou tao  )
444cf7d6b7aSMuzi  val f2_ftr_range = Fill(PredictWidth, f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~getBasicBlockIdx(
445cf7d6b7aSMuzi    f2_ftq_req.nextStartAddr,
446cf7d6b7aSMuzi    f2_ftq_req.startAddr
447cf7d6b7aSMuzi  )
4482a3050c2SJay  val f2_instr_range = f2_jump_range & f2_ftr_range
449cf7d6b7aSMuzi  val f2_exception_vec = VecInit((0 until PredictWidth).map(i =>
450cf7d6b7aSMuzi    MuxCase(
451cf7d6b7aSMuzi      ExceptionType.none,
452cf7d6b7aSMuzi      Seq(
45388895b11Sxu_zh        !isNextLine(f2_pc(i), f2_ftq_req.startAddr)                   -> f2_exception(0),
45488895b11Sxu_zh        (isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_doubleLine) -> f2_exception(1)
455cf7d6b7aSMuzi      )
456cf7d6b7aSMuzi    )
457cf7d6b7aSMuzi  ))
4581d8f4dcbSJay  val f2_perf_info = io.icachePerfInfo
45909c6f1ddSLingrui98
4602a3050c2SJay  def cut(cacheline: UInt, cutPtr: Vec[UInt]): Vec[UInt] = {
461d558bd61SJenius    require(HasCExtension)
462d558bd61SJenius    // if(HasCExtension){
46309c6f1ddSLingrui98    val result  = Wire(Vec(PredictWidth + 1, UInt(16.W)))
464b92f8445Sssszwic    val dataVec = cacheline.asTypeOf(Vec(blockBytes, UInt(16.W))) // 32 16-bit data vector
46509c6f1ddSLingrui98    (0 until PredictWidth + 1).foreach(i =>
466d558bd61SJenius      result(i) := dataVec(cutPtr(i)) // the max ptr is 3*blockBytes/4-1
46709c6f1ddSLingrui98    )
46809c6f1ddSLingrui98    result
469d558bd61SJenius    // } else {
470d558bd61SJenius    //   val result   = Wire(Vec(PredictWidth, UInt(32.W)) )
471d558bd61SJenius    //   val dataVec  = cacheline.asTypeOf(Vec(blockBytes * 2/ 4, UInt(32.W)))
472d558bd61SJenius    //   (0 until PredictWidth).foreach( i =>
473d558bd61SJenius    //     result(i) := dataVec(cutPtr(i))
474d558bd61SJenius    //   )
475d558bd61SJenius    //   result
476d558bd61SJenius    // }
47709c6f1ddSLingrui98  }
47809c6f1ddSLingrui98
4794690c88aSxu_zh  /* NOTE: the following `Cat(_data, _data)` *is* intentional.
48096d0318bSxu_zh   * Explanation:
48196d0318bSxu_zh   * In the old design, IFU is responsible for selecting requested data from two adjacent cachelines,
48296d0318bSxu_zh   *    so IFU has to receive 2*64B (2cacheline * 64B) data from ICache, and do `Cat(_data(1), _data(0))` here.
48396d0318bSxu_zh   * However, a fetch block is 34B at max, sending 2*64B is quiet a waste of power.
48496d0318bSxu_zh   * In current design (2024.06~), ICacheDataArray is responsible for selecting data from two adjacent cachelines,
4854690c88aSxu_zh   *    so IFU only need to receive 40B (5bank * 8B) valid data, and use only one port is enough.
48696d0318bSxu_zh   * For example, when pc falls on the 6th bank in cacheline0(so this is a doubleline request):
48796d0318bSxu_zh   *                                MSB                                         LSB
48896d0318bSxu_zh   *                  cacheline 1 || 1-7 | 1-6 | 1-5 | 1-4 | 1-3 | 1-2 | 1-1 | 1-0 ||
48996d0318bSxu_zh   *                  cacheline 0 || 0-7 | 0-6 | 0-5 | 0-4 | 0-3 | 0-2 | 0-1 | 0-0 ||
49096d0318bSxu_zh   *    and ICacheDataArray will respond:
4914690c88aSxu_zh   *         fromICache.bits.data || 0-7 | 0-6 | xxx | xxx | xxx | 1-2 | 1-1 | 1-0 ||
49296d0318bSxu_zh   *    therefore simply make a copy of the response and `Cat` together, and obtain the requested data from centre:
49396d0318bSxu_zh   *          f2_data_2_cacheline || 0-7 | 0-6 | xxx | xxx | xxx | 1-2 | 1-1 | 1-0 | 0-7 | 0-6 | xxx | xxx | xxx | 1-2 | 1-1 | 1-0 ||
49496d0318bSxu_zh   *                                             requested data: ^-----------------------------^
49596d0318bSxu_zh   * For another example, pc falls on the 1st bank in cacheline 0, we have:
4964690c88aSxu_zh   *         fromICache.bits.data || xxx | xxx | 0-5 | 0-4 | 0-3 | 0-2 | 0-1 | xxx ||
49796d0318bSxu_zh   *          f2_data_2_cacheline || xxx | xxx | 0-5 | 0-4 | 0-3 | 0-2 | 0-1 | xxx | xxx | xxx | 0-5 | 0-4 | 0-3 | 0-2 | 0-1 | xxx ||
49896d0318bSxu_zh   *                                                                           requested data: ^-----------------------------^
49996d0318bSxu_zh   * Each "| x-y |" block is a 8B bank from cacheline(x).bank(y)
50096d0318bSxu_zh   * Please also refer to:
50196d0318bSxu_zh   * - DataArray selects data:
50296d0318bSxu_zh   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICache.scala#L355-L381
50396d0318bSxu_zh   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICache.scala#L149-L161
50496d0318bSxu_zh   * - ICache respond to IFU:
50596d0318bSxu_zh   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICacheMainPipe.scala#L473
50696d0318bSxu_zh   */
5074690c88aSxu_zh  val f2_data_2_cacheline = Cat(fromICache.bits.data, fromICache.bits.data)
508dc270d3bSJenius
509a61a35e0Sssszwic  val f2_cut_data = cut(f2_data_2_cacheline, f2_cut_ptr)
51009c6f1ddSLingrui98
51158dbdfc2SJay  /** predecode (include RVC expander) */
512dc270d3bSJenius  // preDecoderRegIn.data := f2_reg_cut_data
513dc270d3bSJenius  // preDecoderRegInIn.frontendTrigger := io.frontendTrigger
514dc270d3bSJenius  // preDecoderRegInIn.csrTriggerEnable := io.csrTriggerEnable
515dc270d3bSJenius  // preDecoderRegIn.pc  := f2_pc
516dc270d3bSJenius
517a61a35e0Sssszwic  val preDecoderIn = preDecoder.io.in
5189afa8a47STang Haojin  preDecoderIn.valid                := f2_valid
5199afa8a47STang Haojin  preDecoderIn.bits.data            := f2_cut_data
5209afa8a47STang Haojin  preDecoderIn.bits.frontendTrigger := io.frontendTrigger
5219afa8a47STang Haojin  preDecoderIn.bits.pc              := f2_pc
522a61a35e0Sssszwic  val preDecoderOut = preDecoder.io.out
52309c6f1ddSLingrui98
52448a62719SJenius  // val f2_expd_instr     = preDecoderOut.expInstr
52548a62719SJenius  val f2_instr        = preDecoderOut.instr
5262a3050c2SJay  val f2_pd           = preDecoderOut.pd
5272a3050c2SJay  val f2_jump_offset  = preDecoderOut.jumpOffset
5282a3050c2SJay  val f2_hasHalfValid = preDecoderOut.hasHalfValid
529a2568a60Sxu_zh  /* if there is a cross-page RVI instruction, and the former page has no exception,
530a2568a60Sxu_zh   * whether it has exception is actually depends on the latter page
531a2568a60Sxu_zh   */
532cf7d6b7aSMuzi  val f2_crossPage_exception_vec = VecInit((0 until PredictWidth).map { i =>
533cf7d6b7aSMuzi    Mux(
534dd02bc3fSxu_zh      isLastInLine(f2_pc(i)) && !f2_pd(i).isRVC && f2_doubleLine && !ExceptionType.hasException(f2_exception(0)),
535a2568a60Sxu_zh      f2_exception(1),
536a2568a60Sxu_zh      ExceptionType.none
537cf7d6b7aSMuzi    )
538cf7d6b7aSMuzi  })
53900240ba6SJay  XSPerfAccumulate("fetch_bubble_icache_not_resp", f2_valid && !icacheRespAllValid)
54000240ba6SJay
54158dbdfc2SJay  /**
54258dbdfc2SJay    ******************************************************************************
54358dbdfc2SJay    * IFU Stage 3
54458dbdfc2SJay    * - handle MMIO instruciton
54558dbdfc2SJay    *  -send request to Uncache fetch Unit
54658dbdfc2SJay    *  -every packet include 1 MMIO instruction
54758dbdfc2SJay    *  -MMIO instructions will stop fetch pipeline until commiting from RoB
54858dbdfc2SJay    *  -flush to snpc (send ifu_redirect to Ftq)
54958dbdfc2SJay    * - Ibuffer enqueue
55058dbdfc2SJay    * - check predict result in Frontend (jalFault/retFault/notCFIFault/invalidTakenFault/targetFault)
55158dbdfc2SJay    * - handle last half RVI instruction
55258dbdfc2SJay    ******************************************************************************
55358dbdfc2SJay    */
55458dbdfc2SJay
55592c61038SXuan Hu  val expanders = Seq.fill(PredictWidth)(Module(new RVCExpander))
55692c61038SXuan Hu
55709c6f1ddSLingrui98  val f3_valid   = RegInit(false.B)
558005e809bSJiuyang Liu  val f3_ftq_req = RegEnable(f2_ftq_req, f2_fire)
559005e809bSJiuyang Liu  // val f3_situation      = RegEnable(f2_situation,  f2_fire)
560005e809bSJiuyang Liu  val f3_doubleLine = RegEnable(f2_doubleLine, f2_fire)
561935edac4STang Haojin  val f3_fire       = io.toIbuffer.fire
5621d8f4dcbSJay
563a61a35e0Sssszwic  val f3_cut_data = RegEnable(f2_cut_data, f2_fire)
5641d8f4dcbSJay
56588895b11Sxu_zh  val f3_exception        = RegEnable(f2_exception, f2_fire)
566211986abSxu_zh  val f3_pmp_mmio         = RegEnable(f2_pmp_mmio, f2_fire)
567211986abSxu_zh  val f3_itlb_pbmt        = RegEnable(f2_itlb_pbmt, f2_fire)
568fbdb359dSMuzi  val f3_backendException = RegEnable(f2_backendException, f2_fire)
56909c6f1ddSLingrui98
570935edac4STang Haojin  val f3_instr = RegEnable(f2_instr, f2_fire)
571aeedc8eeSGuokai Chen
57292c61038SXuan Hu  expanders.zipWithIndex.foreach { case (expander, i) =>
57392c61038SXuan Hu    expander.io.in      := f3_instr(i)
57471b6c42eSxu_zh    expander.io.fsIsOff := io.csr_fsIsOff
57592c61038SXuan Hu  }
57692c61038SXuan Hu  // Use expanded instruction only when input is legal.
57792c61038SXuan Hu  // Otherwise use origin illegal RVC instruction.
57892c61038SXuan Hu  val f3_expd_instr = VecInit(expanders.map { expander: RVCExpander =>
57992c61038SXuan Hu    Mux(expander.io.ill, expander.io.in, expander.io.out.bits)
58092c61038SXuan Hu  })
58192c61038SXuan Hu  val f3_ill = VecInit(expanders.map(_.io.ill))
58248a62719SJenius
583935edac4STang Haojin  val f3_pd_wire                 = RegEnable(f2_pd, f2_fire)
584330aad7fSGuokai Chen  val f3_pd                      = WireInit(f3_pd_wire)
585935edac4STang Haojin  val f3_jump_offset             = RegEnable(f2_jump_offset, f2_fire)
58688895b11Sxu_zh  val f3_exception_vec           = RegEnable(f2_exception_vec, f2_fire)
587a2568a60Sxu_zh  val f3_crossPage_exception_vec = RegEnable(f2_crossPage_exception_vec, f2_fire)
588e4d2f6a9Smy-mayfly
589e4d2f6a9Smy-mayfly  val f3_pc_lower_result = RegEnable(f2_pc_lower_result, f2_fire)
590e4d2f6a9Smy-mayfly  val f3_pc_high         = RegEnable(f2_pc_high, f2_fire)
591e4d2f6a9Smy-mayfly  val f3_pc_high_plus1   = RegEnable(f2_pc_high_plus1, f2_fire)
592e4d2f6a9Smy-mayfly  val f3_pc              = CatPC(f3_pc_lower_result, f3_pc_high, f3_pc_high_plus1)
593e4d2f6a9Smy-mayfly
594e4d2f6a9Smy-mayfly  val f3_pc_last_lower_result_plus2 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 2.U, f2_fire)
595e4d2f6a9Smy-mayfly  val f3_pc_last_lower_result_plus4 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 4.U, f2_fire)
596e4d2f6a9Smy-mayfly  // val f3_half_snpc      = RegEnable(f2_half_snpc,   f2_fire)
597e4d2f6a9Smy-mayfly
598e4d2f6a9Smy-mayfly  /**
599e4d2f6a9Smy-mayfly    ***********************************************************************
600e4d2f6a9Smy-mayfly    * Half snpc(i) is larger than pc(i) by 4. Using pc to calculate half snpc may be a good choice.
601e4d2f6a9Smy-mayfly    ***********************************************************************
602e4d2f6a9Smy-mayfly    */
603e4d2f6a9Smy-mayfly  val f3_half_snpc = Wire(Vec(PredictWidth, UInt(VAddrBits.W)))
604e4d2f6a9Smy-mayfly  for (i <- 0 until PredictWidth) {
605e4d2f6a9Smy-mayfly    if (i == (PredictWidth - 2)) {
606e4d2f6a9Smy-mayfly      f3_half_snpc(i) := CatPC(f3_pc_last_lower_result_plus2, f3_pc_high, f3_pc_high_plus1)
607e4d2f6a9Smy-mayfly    } else if (i == (PredictWidth - 1)) {
608e4d2f6a9Smy-mayfly      f3_half_snpc(i) := CatPC(f3_pc_last_lower_result_plus4, f3_pc_high, f3_pc_high_plus1)
609e4d2f6a9Smy-mayfly    } else {
610e4d2f6a9Smy-mayfly      f3_half_snpc(i) := f3_pc(i + 2)
611e4d2f6a9Smy-mayfly    }
612e4d2f6a9Smy-mayfly  }
613e4d2f6a9Smy-mayfly
614935edac4STang Haojin  val f3_instr_range       = RegEnable(f2_instr_range, f2_fire)
615935edac4STang Haojin  val f3_foldpc            = RegEnable(f2_foldpc, f2_fire)
616935edac4STang Haojin  val f3_hasHalfValid      = RegEnable(f2_hasHalfValid, f2_fire)
617d7ac23a3SEaston Man  val f3_paddrs            = RegEnable(f2_paddrs, f2_fire)
61891946104Sxu_zh  val f3_gpaddr            = RegEnable(f2_gpaddr, f2_fire)
619ad415ae0SXiaokun-Pei  val f3_isForVSnonLeafPTE = RegEnable(f2_isForVSnonLeafPTE, f2_fire)
620005e809bSJiuyang Liu  val f3_resend_vaddr      = RegEnable(f2_resend_vaddr, f2_fire)
621ee175d78SJay
622cb6e5d3cSssszwic  // Expand 1 bit to prevent overflow when assert
623cb6e5d3cSssszwic  val f3_ftq_req_startAddr     = Cat(0.U(1.W), f3_ftq_req.startAddr)
624cb6e5d3cSssszwic  val f3_ftq_req_nextStartAddr = Cat(0.U(1.W), f3_ftq_req.nextStartAddr)
625330aad7fSGuokai Chen  // brType, isCall and isRet generation is delayed to f3 stage
626330aad7fSGuokai Chen  val f3Predecoder = Module(new F3Predecoder)
627330aad7fSGuokai Chen
628330aad7fSGuokai Chen  f3Predecoder.io.in.instr := f3_instr
629330aad7fSGuokai Chen
630330aad7fSGuokai Chen  f3_pd.zipWithIndex.map { case (pd, i) =>
631330aad7fSGuokai Chen    pd.brType := f3Predecoder.io.out.pd(i).brType
632330aad7fSGuokai Chen    pd.isCall := f3Predecoder.io.out.pd(i).isCall
633330aad7fSGuokai Chen    pd.isRet  := f3Predecoder.io.out.pd(i).isRet
634330aad7fSGuokai Chen  }
635330aad7fSGuokai Chen
636330aad7fSGuokai Chen  val f3PdDiff = f3_pd_wire.zip(f3_pd).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _)
637330aad7fSGuokai Chen  XSError(f3_valid && f3PdDiff, "f3 pd diff")
638330aad7fSGuokai Chen
6391d011975SJinYue  when(f3_valid && !f3_ftq_req.ftqOffset.valid) {
640cf7d6b7aSMuzi    assert(
641cf7d6b7aSMuzi      f3_ftq_req_startAddr + (2 * PredictWidth).U >= f3_ftq_req_nextStartAddr,
642cf7d6b7aSMuzi      s"More tha ${2 * PredictWidth} Bytes fetch is not allowed!"
643cf7d6b7aSMuzi    )
6441d011975SJinYue  }
645a1351e5dSJay
6462a3050c2SJay  /*** MMIO State Machine***/
647ee175d78SJay  val f3_mmio_data          = Reg(Vec(2, UInt(16.W)))
648ee175d78SJay  val mmio_is_RVC           = RegInit(false.B)
649ee175d78SJay  val mmio_resend_addr      = RegInit(0.U(PAddrBits.W))
65088895b11Sxu_zh  val mmio_resend_exception = RegInit(0.U(ExceptionType.width.W))
651dd980d61SXu, Zefan  // NOTE: we dont use GPAddrBits here, refer to ICacheMainPipe.scala L43-48 and PR#3795
652dd980d61SXu, Zefan  val mmio_resend_gpaddr            = RegInit(0.U(PAddrBitsMax.W))
653ad415ae0SXiaokun-Pei  val mmio_resend_isForVSnonLeafPTE = RegInit(false.B)
654c3b2d83aSJay
6551d1e6d4dSJenius  // last instuction finish
6561d1e6d4dSJenius  val is_first_instr = RegInit(true.B)
657cf7d6b7aSMuzi
658ba5ba1dcSmy-mayfly  /*** Determine whether the MMIO instruction is executable based on the previous prediction block ***/
659ba5ba1dcSmy-mayfly  io.mmioCommitRead.mmioFtqPtr := RegNext(f3_ftq_req.ftqIdx - 1.U)
660a37fbf10SJay
661cf7d6b7aSMuzi  val m_idle :: m_waitLastCmt :: m_sendReq :: m_waitResp :: m_sendTLB :: m_tlbResp :: m_sendPMP :: m_resendReq :: m_waitResendResp :: m_waitCommit :: m_commited :: Nil =
662cf7d6b7aSMuzi    Enum(11)
663ee175d78SJay  val mmio_state = RegInit(m_idle)
664a37fbf10SJay
665211986abSxu_zh  // do mmio fetch only when pmp/pbmt shows it is a uncacheable address and no exception occurs
666211986abSxu_zh  /* FIXME: we do not distinguish pbmt is NC or IO now
667211986abSxu_zh   *        but we actually can do speculative execution if pbmt is NC, maybe fix this later for performance
668211986abSxu_zh   */
669211986abSxu_zh  val f3_req_is_mmio =
670211986abSxu_zh    f3_valid && (f3_pmp_mmio || Pbmt.isUncache(f3_itlb_pbmt)) && !ExceptionType.hasException(f3_exception)
671cf7d6b7aSMuzi  val mmio_commit = VecInit(io.rob_commits.map { commit =>
672cf7d6b7aSMuzi    commit.valid && commit.bits.ftqIdx === f3_ftq_req.ftqIdx && commit.bits.ftqOffset === 0.U
673cf7d6b7aSMuzi  }).asUInt.orR
674ee175d78SJay  val f3_mmio_req_commit = f3_req_is_mmio && mmio_state === m_commited
675a37fbf10SJay
676ee175d78SJay  val f3_mmio_to_commit      = f3_req_is_mmio && mmio_state === m_waitCommit
677a37fbf10SJay  val f3_mmio_to_commit_next = RegNext(f3_mmio_to_commit)
678a37fbf10SJay  val f3_mmio_can_go         = f3_mmio_to_commit && !f3_mmio_to_commit_next
679a37fbf10SJay
6800c70648eSEaston Man  val fromFtqRedirectReg = Wire(fromFtq.redirect.cloneType)
681cf7d6b7aSMuzi  fromFtqRedirectReg.bits := RegEnable(
682cf7d6b7aSMuzi    fromFtq.redirect.bits,
683cf7d6b7aSMuzi    0.U.asTypeOf(fromFtq.redirect.bits),
684cf7d6b7aSMuzi    fromFtq.redirect.valid
685cf7d6b7aSMuzi  )
6860c70648eSEaston Man  fromFtqRedirectReg.valid := RegNext(fromFtq.redirect.valid, init = false.B)
6874a74a727SJenius  val mmioF3Flush           = RegNext(f3_flush, init = false.B)
68856788a33SJinYue  val f3_ftq_flush_self     = fromFtqRedirectReg.valid && RedirectLevel.flushItself(fromFtqRedirectReg.bits.level)
68956788a33SJinYue  val f3_ftq_flush_by_older = fromFtqRedirectReg.valid && isBefore(fromFtqRedirectReg.bits.ftqIdx, f3_ftq_req.ftqIdx)
6909bae7d6eSJay
69156788a33SJinYue  val f3_need_not_flush = f3_req_is_mmio && fromFtqRedirectReg.valid && !f3_ftq_flush_self && !f3_ftq_flush_by_older
6929bae7d6eSJay
693ba5ba1dcSmy-mayfly  /**
694ba5ba1dcSmy-mayfly    **********************************************************************************
695ba5ba1dcSmy-mayfly    * We want to defer instruction fetching when encountering MMIO instructions to ensure that the MMIO region is not negatively impacted.
696ba5ba1dcSmy-mayfly    * This is the exception when the first instruction is an MMIO instruction.
697ba5ba1dcSmy-mayfly    **********************************************************************************
698ba5ba1dcSmy-mayfly    */
699ba5ba1dcSmy-mayfly  when(is_first_instr && f3_fire) {
7001d1e6d4dSJenius    is_first_instr := false.B
7011d1e6d4dSJenius  }
7021d1e6d4dSJenius
703cf7d6b7aSMuzi  when(f3_flush && !f3_req_is_mmio)(f3_valid := false.B)
704cf7d6b7aSMuzi    .elsewhen(mmioF3Flush && f3_req_is_mmio && !f3_need_not_flush)(f3_valid := false.B)
705cf7d6b7aSMuzi    .elsewhen(f2_fire && !f2_flush)(f3_valid := true.B)
706cf7d6b7aSMuzi    .elsewhen(io.toIbuffer.fire && !f3_req_is_mmio)(f3_valid := false.B)
707cf7d6b7aSMuzi    .elsewhen(f3_req_is_mmio && f3_mmio_req_commit)(f3_valid := false.B)
708a37fbf10SJay
709a37fbf10SJay  val f3_mmio_use_seq_pc = RegInit(false.B)
710a37fbf10SJay
71156788a33SJinYue  val (redirect_ftqIdx, redirect_ftqOffset) = (fromFtqRedirectReg.bits.ftqIdx, fromFtqRedirectReg.bits.ftqOffset)
712cf7d6b7aSMuzi  val redirect_mmio_req =
713cf7d6b7aSMuzi    fromFtqRedirectReg.valid && redirect_ftqIdx === f3_ftq_req.ftqIdx && redirect_ftqOffset === 0.U
714a37fbf10SJay
715cf7d6b7aSMuzi  when(RegNext(f2_fire && !f2_flush) && f3_req_is_mmio)(f3_mmio_use_seq_pc := true.B)
716cf7d6b7aSMuzi    .elsewhen(redirect_mmio_req)(f3_mmio_use_seq_pc := false.B)
717a37fbf10SJay
7188c192ff7Sxu_zh  f3_ready := (io.toIbuffer.ready && (f3_mmio_req_commit || !f3_req_is_mmio)) || !f3_valid
719a37fbf10SJay
7201d1e6d4dSJenius  // mmio state machine
721a37fbf10SJay  switch(mmio_state) {
722ee175d78SJay    is(m_idle) {
7239bae7d6eSJay      when(f3_req_is_mmio) {
7247d889d88Sxu_zh        // in idempotent spaces, we can send request directly (i.e. can do speculative fetch)
7257d889d88Sxu_zh        mmio_state := Mux(f3_itlb_pbmt === Pbmt.nc, m_sendReq, m_waitLastCmt)
7261d1e6d4dSJenius      }
7271d1e6d4dSJenius    }
7281d1e6d4dSJenius
7291d1e6d4dSJenius    is(m_waitLastCmt) {
7301d1e6d4dSJenius      when(is_first_instr) {
731ee175d78SJay        mmio_state := m_sendReq
7321d1e6d4dSJenius      }.otherwise {
7331d1e6d4dSJenius        mmio_state := Mux(io.mmioCommitRead.mmioLastCommit, m_sendReq, m_waitLastCmt)
734a37fbf10SJay      }
735a37fbf10SJay    }
736a37fbf10SJay
737ee175d78SJay    is(m_sendReq) {
738935edac4STang Haojin      mmio_state := Mux(toUncache.fire, m_waitResp, m_sendReq)
739a37fbf10SJay    }
740a37fbf10SJay
741ee175d78SJay    is(m_waitResp) {
742935edac4STang Haojin      when(fromUncache.fire) {
743a37fbf10SJay        val isRVC      = fromUncache.bits.data(1, 0) =/= 3.U
744d7ac23a3SEaston Man        val needResend = !isRVC && f3_paddrs(0)(2, 1) === 3.U
745ee175d78SJay        mmio_state      := Mux(needResend, m_sendTLB, m_waitCommit)
746ee175d78SJay        mmio_is_RVC     := isRVC
747ee175d78SJay        f3_mmio_data(0) := fromUncache.bits.data(15, 0)
748ee175d78SJay        f3_mmio_data(1) := fromUncache.bits.data(31, 16)
749a37fbf10SJay      }
750a37fbf10SJay    }
751a37fbf10SJay
752ee175d78SJay    is(m_sendTLB) {
7537b7232f9Sxu_zh      mmio_state := Mux(io.iTLBInter.req.fire, m_tlbResp, m_sendTLB)
754c3b2d83aSJay    }
755a37fbf10SJay
756ee175d78SJay    is(m_tlbResp) {
7577b7232f9Sxu_zh      when(io.iTLBInter.resp.fire) {
7587b7232f9Sxu_zh        // we are using a blocked tlb, so resp.fire must have !resp.bits.miss
7597b7232f9Sxu_zh        assert(!io.iTLBInter.resp.bits.miss, "blocked mode iTLB miss when resp.fire")
76088895b11Sxu_zh        val tlb_exception = ExceptionType.fromTlbResp(io.iTLBInter.resp.bits)
761211986abSxu_zh        // if itlb re-check respond pbmt mismatch with previous check, must be access fault
762211986abSxu_zh        val pbmt_mismatch_exception = Mux(
763211986abSxu_zh          io.iTLBInter.resp.bits.pbmt(0) =/= f3_itlb_pbmt,
764211986abSxu_zh          ExceptionType.af,
765211986abSxu_zh          ExceptionType.none
766211986abSxu_zh        )
767211986abSxu_zh        val exception = ExceptionType.merge(tlb_exception, pbmt_mismatch_exception)
7687b7232f9Sxu_zh        // if tlb has exception, abort checking pmp, just send instr & exception to ibuffer and wait for commit
769211986abSxu_zh        mmio_state := Mux(ExceptionType.hasException(exception), m_waitCommit, m_sendPMP)
7707b7232f9Sxu_zh        // also save itlb response
77103efd994Shappy-lx        mmio_resend_addr              := io.iTLBInter.resp.bits.paddr(0)
772211986abSxu_zh        mmio_resend_exception         := exception
773b5a614b9Sxu_zh        mmio_resend_gpaddr            := io.iTLBInter.resp.bits.gpaddr(0)
774ad415ae0SXiaokun-Pei        mmio_resend_isForVSnonLeafPTE := io.iTLBInter.resp.bits.isForVSnonLeafPTE(0)
775ee175d78SJay      }
7767b7232f9Sxu_zh    }
777ee175d78SJay
778ee175d78SJay    is(m_sendPMP) {
779211986abSxu_zh      val pmp_exception = ExceptionType.fromPMPResp(io.pmp.resp)
780211986abSxu_zh      // if pmp re-check respond mismatch with previous check, must be access fault
781211986abSxu_zh      val mmio_mismatch_exception = Mux(
782211986abSxu_zh        io.pmp.resp.mmio =/= f3_pmp_mmio,
783211986abSxu_zh        ExceptionType.af,
784211986abSxu_zh        ExceptionType.none
785211986abSxu_zh      )
786211986abSxu_zh      val exception = ExceptionType.merge(pmp_exception, mmio_mismatch_exception)
78788895b11Sxu_zh      // if pmp has exception, abort sending request, just send instr & exception to ibuffer and wait for commit
788211986abSxu_zh      mmio_state := Mux(ExceptionType.hasException(exception), m_waitCommit, m_resendReq)
78988895b11Sxu_zh      // also save pmp response
790211986abSxu_zh      mmio_resend_exception := exception
791ee175d78SJay    }
792ee175d78SJay
793ee175d78SJay    is(m_resendReq) {
794935edac4STang Haojin      mmio_state := Mux(toUncache.fire, m_waitResendResp, m_resendReq)
795ee175d78SJay    }
796ee175d78SJay
797ee175d78SJay    is(m_waitResendResp) {
798935edac4STang Haojin      when(fromUncache.fire) {
799ee175d78SJay        mmio_state      := m_waitCommit
800ee175d78SJay        f3_mmio_data(1) := fromUncache.bits.data(15, 0)
801a37fbf10SJay      }
802a37fbf10SJay    }
803a37fbf10SJay
804ee175d78SJay    is(m_waitCommit) {
8057d889d88Sxu_zh      // in idempotent spaces, we can skip waiting for commit (i.e. can do speculative fetch)
8067d889d88Sxu_zh      // but we do not skip m_waitCommit state, as other signals (e.g. f3_mmio_can_go relies on this)
8077d889d88Sxu_zh      mmio_state := Mux(mmio_commit || f3_itlb_pbmt === Pbmt.nc, m_commited, m_waitCommit)
808a37fbf10SJay    }
8092a3050c2SJay
810ee175d78SJay    // normal mmio instruction
811ee175d78SJay    is(m_commited) {
812ee175d78SJay      mmio_state                    := m_idle
813ee175d78SJay      mmio_is_RVC                   := false.B
814ee175d78SJay      mmio_resend_addr              := 0.U
81588895b11Sxu_zh      mmio_resend_exception         := ExceptionType.none
816b5a614b9Sxu_zh      mmio_resend_gpaddr            := 0.U
817ad415ae0SXiaokun-Pei      mmio_resend_isForVSnonLeafPTE := false.B
8182a3050c2SJay    }
819a37fbf10SJay  }
820a37fbf10SJay
8218abe1810SEaston Man  // Exception or flush by older branch prediction
8228abe1810SEaston Man  // Condition is from RegNext(fromFtq.redirect), 1 cycle after backend rediect
823167bcd01SJay  when(f3_ftq_flush_self || f3_ftq_flush_by_older) {
824ee175d78SJay    mmio_state                    := m_idle
825ee175d78SJay    mmio_is_RVC                   := false.B
826ee175d78SJay    mmio_resend_addr              := 0.U
82788895b11Sxu_zh    mmio_resend_exception         := ExceptionType.none
828b5a614b9Sxu_zh    mmio_resend_gpaddr            := 0.U
829ad415ae0SXiaokun-Pei    mmio_resend_isForVSnonLeafPTE := false.B
830ee175d78SJay    f3_mmio_data.map(_ := 0.U)
8319bae7d6eSJay  }
8329bae7d6eSJay
833ee175d78SJay  toUncache.valid     := ((mmio_state === m_sendReq) || (mmio_state === m_resendReq)) && f3_req_is_mmio
834cf7d6b7aSMuzi  toUncache.bits.addr := Mux(mmio_state === m_resendReq, mmio_resend_addr, f3_paddrs(0))
835a37fbf10SJay  fromUncache.ready   := true.B
836a37fbf10SJay
8377b7232f9Sxu_zh  // send itlb request in m_sendTLB state
838ee175d78SJay  io.iTLBInter.req.valid                   := (mmio_state === m_sendTLB) && f3_req_is_mmio
839ee175d78SJay  io.iTLBInter.req.bits.size               := 3.U
840ee175d78SJay  io.iTLBInter.req.bits.vaddr              := f3_resend_vaddr
841ee175d78SJay  io.iTLBInter.req.bits.debug.pc           := f3_resend_vaddr
8427b7232f9Sxu_zh  io.iTLBInter.req.bits.cmd                := TlbCmd.exec
8438a4dab4dSHaoyuan Feng  io.iTLBInter.req.bits.isPrefetch         := false.B
8447b7232f9Sxu_zh  io.iTLBInter.req.bits.kill               := false.B // IFU use itlb for mmio, doesn't need sync, set it to false
8457b7232f9Sxu_zh  io.iTLBInter.req.bits.no_translate       := false.B
846db6cfb5aSHaoyuan Feng  io.iTLBInter.req.bits.fullva             := 0.U
847db6cfb5aSHaoyuan Feng  io.iTLBInter.req.bits.checkfullva        := false.B
848d0de7e4aSpeixiaokun  io.iTLBInter.req.bits.hyperinst          := DontCare
849d0de7e4aSpeixiaokun  io.iTLBInter.req.bits.hlvx               := DontCare
8508744445eSMaxpicca-Li  io.iTLBInter.req.bits.memidx             := DontCare
851f1fe8698SLemover  io.iTLBInter.req.bits.debug.robIdx       := DontCare
852ee175d78SJay  io.iTLBInter.req.bits.debug.isFirstIssue := DontCare
853149a2326Sweiding liu  io.iTLBInter.req.bits.pmp_addr           := DontCare
8547b7232f9Sxu_zh  // whats the difference between req_kill and req.bits.kill?
8557b7232f9Sxu_zh  io.iTLBInter.req_kill := false.B
8567b7232f9Sxu_zh  // wait for itlb response in m_tlbResp state
8577b7232f9Sxu_zh  io.iTLBInter.resp.ready := (mmio_state === m_tlbResp) && f3_req_is_mmio
858ee175d78SJay
859ee175d78SJay  io.pmp.req.valid     := (mmio_state === m_sendPMP) && f3_req_is_mmio
860ee175d78SJay  io.pmp.req.bits.addr := mmio_resend_addr
861ee175d78SJay  io.pmp.req.bits.size := 3.U
862ee175d78SJay  io.pmp.req.bits.cmd  := TlbCmd.exec
863f7c29b0aSJinYue
8642a3050c2SJay  val f3_lastHalf = RegInit(0.U.asTypeOf(new LastHalfInfo))
86509c6f1ddSLingrui98
86609c6f1ddSLingrui98  val f3_predecode_range = VecInit(preDecoderOut.pd.map(inst => inst.valid)).asUInt
8670be662e4SJay  val f3_mmio_range      = VecInit((0 until PredictWidth).map(i => if (i == 0) true.B else false.B))
8682a3050c2SJay  val f3_instr_valid     = Wire(Vec(PredictWidth, Bool()))
86909c6f1ddSLingrui98
8702a3050c2SJay  /*** prediction result check   ***/
8712a3050c2SJay  checkerIn.ftqOffset  := f3_ftq_req.ftqOffset
8722a3050c2SJay  checkerIn.jumpOffset := f3_jump_offset
8736ce52296SJinYue  checkerIn.target     := f3_ftq_req.nextStartAddr
8742a3050c2SJay  checkerIn.instrRange := f3_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
8752a3050c2SJay  checkerIn.instrValid := f3_instr_valid.asTypeOf(Vec(PredictWidth, Bool()))
8762a3050c2SJay  checkerIn.pds        := f3_pd
8772a3050c2SJay  checkerIn.pc         := f3_pc
8780c70648eSEaston Man  checkerIn.fire_in    := RegNext(f2_fire, init = false.B)
8792a3050c2SJay
88058dbdfc2SJay  /*** handle half RVI in the last 2 Bytes  ***/
8812a3050c2SJay
882cf7d6b7aSMuzi  def hasLastHalf(idx: UInt) =
8835995c9e7SJenius    // !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(idx) && !checkerOutStage2.fixedMissPred(idx) && ! f3_req_is_mmio
884cf7d6b7aSMuzi    !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(
885cf7d6b7aSMuzi      idx
886cf7d6b7aSMuzi    ) && !f3_req_is_mmio
8872a3050c2SJay
888b665b650STang Haojin  val f3_last_validIdx = ParallelPosteriorityEncoder(checkerOutStage1.fixedRange)
8892a3050c2SJay
8902a3050c2SJay  val f3_hasLastHalf    = hasLastHalf((PredictWidth - 1).U)
8912a3050c2SJay  val f3_false_lastHalf = hasLastHalf(f3_last_validIdx)
8922a3050c2SJay  val f3_false_snpc     = f3_half_snpc(f3_last_validIdx)
8932a3050c2SJay
894935edac4STang Haojin  val f3_lastHalf_mask    = VecInit((0 until PredictWidth).map(i => if (i == 0) false.B else true.B)).asUInt
8953f785aa3SJenius  val f3_lastHalf_disable = RegInit(false.B)
8962a3050c2SJay
897804985a5SJenius  when(f3_flush || (f3_fire && f3_lastHalf_disable)) {
898804985a5SJenius    f3_lastHalf_disable := false.B
899804985a5SJenius  }
900804985a5SJenius
9012a3050c2SJay  when(f3_flush) {
9022a3050c2SJay    f3_lastHalf.valid := false.B
9032a3050c2SJay  }.elsewhen(f3_fire) {
9043f785aa3SJenius    f3_lastHalf.valid    := f3_hasLastHalf && !f3_lastHalf_disable
9056ce52296SJinYue    f3_lastHalf.middlePC := f3_ftq_req.nextStartAddr
9062a3050c2SJay  }
9072a3050c2SJay
9082a3050c2SJay  f3_instr_valid := Mux(f3_lastHalf.valid, f3_hasHalfValid, VecInit(f3_pd.map(inst => inst.valid)))
9092a3050c2SJay
9102a3050c2SJay  /*** frontend Trigger  ***/
9112a3050c2SJay  frontendTrigger.io.pds  := f3_pd
9122a3050c2SJay  frontendTrigger.io.pc   := f3_pc
9132a3050c2SJay  frontendTrigger.io.data := f3_cut_data
9142a3050c2SJay
9152a3050c2SJay  frontendTrigger.io.frontendTrigger := io.frontendTrigger
9162a3050c2SJay
9172a3050c2SJay  val f3_triggered       = frontendTrigger.io.triggered
91891946104Sxu_zh  val f3_toIbuffer_valid = f3_valid && (!f3_req_is_mmio || f3_mmio_can_go) && !f3_flush
9192a3050c2SJay
9202a3050c2SJay  /*** send to Ibuffer  ***/
92191946104Sxu_zh  io.toIbuffer.valid          := f3_toIbuffer_valid
9222a3050c2SJay  io.toIbuffer.bits.instrs    := f3_expd_instr
9232a3050c2SJay  io.toIbuffer.bits.valid     := f3_instr_valid.asUInt
9245995c9e7SJenius  io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt
9252a3050c2SJay  io.toIbuffer.bits.pd        := f3_pd
92609c6f1ddSLingrui98  io.toIbuffer.bits.ftqPtr    := f3_ftq_req.ftqIdx
9272a3050c2SJay  io.toIbuffer.bits.pc        := f3_pc
928c72c955dSEaston Man  // Find last using PriorityMux
929948e8159SEaston Man  io.toIbuffer.bits.isLastInFtqEntry := Reverse(PriorityEncoderOH(Reverse(io.toIbuffer.bits.enqEnable))).asBools
930cf7d6b7aSMuzi  io.toIbuffer.bits.ftqOffset.zipWithIndex.map { case (a, i) =>
931cf7d6b7aSMuzi    a.bits := i.U; a.valid := checkerOutStage1.fixedTaken(i) && !f3_req_is_mmio
932cf7d6b7aSMuzi  }
9332a3050c2SJay  io.toIbuffer.bits.foldpc        := f3_foldpc
934a2568a60Sxu_zh  io.toIbuffer.bits.exceptionType := ExceptionType.merge(f3_exception_vec, f3_crossPage_exception_vec)
935fbdb359dSMuzi  // backendException only needs to be set for the first instruction.
936c1b28b66STang Haojin  // Other instructions in the same block may have pf or af set,
937c1b28b66STang Haojin  // which is a side effect of the first instruction and actually not necessary.
938fbdb359dSMuzi  io.toIbuffer.bits.backendException := (0 until PredictWidth).map {
939fbdb359dSMuzi    case 0 => f3_backendException
940c1b28b66STang Haojin    case _ => false.B
941c1b28b66STang Haojin  }
942dd02bc3fSxu_zh  io.toIbuffer.bits.crossPageIPFFix := f3_crossPage_exception_vec.map(ExceptionType.hasException)
94392c61038SXuan Hu  io.toIbuffer.bits.illegalInstr    := f3_ill
9442a3050c2SJay  io.toIbuffer.bits.triggered       := f3_triggered
9452a3050c2SJay
9462a3050c2SJay  when(f3_lastHalf.valid) {
9475995c9e7SJenius    io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt & f3_lastHalf_mask
9482a3050c2SJay    io.toIbuffer.bits.valid     := f3_lastHalf_mask & f3_instr_valid.asUInt
9492a3050c2SJay  }
9502a3050c2SJay
951d7ac23a3SEaston Man  /** to backend */
95291946104Sxu_zh  // f3_gpaddr is valid iff gpf is detected
953b5a614b9Sxu_zh  io.toBackend.gpaddrMem_wen := f3_toIbuffer_valid && Mux(
954b5a614b9Sxu_zh    f3_req_is_mmio,
95588895b11Sxu_zh    mmio_resend_exception === ExceptionType.gpf,
95688895b11Sxu_zh    f3_exception.map(_ === ExceptionType.gpf).reduce(_ || _)
957b5a614b9Sxu_zh  )
958d7ac23a3SEaston Man  io.toBackend.gpaddrMem_waddr        := f3_ftq_req.ftqIdx.value
959ad415ae0SXiaokun-Pei  io.toBackend.gpaddrMem_wdata.gpaddr := Mux(f3_req_is_mmio, mmio_resend_gpaddr, f3_gpaddr)
960cf7d6b7aSMuzi  io.toBackend.gpaddrMem_wdata.isForVSnonLeafPTE := Mux(
961cf7d6b7aSMuzi    f3_req_is_mmio,
962cf7d6b7aSMuzi    mmio_resend_isForVSnonLeafPTE,
963cf7d6b7aSMuzi    f3_isForVSnonLeafPTE
964cf7d6b7aSMuzi  )
96509c6f1ddSLingrui98
96609c6f1ddSLingrui98  // Write back to Ftq
967a37fbf10SJay  val f3_cache_fetch     = f3_valid && !(f2_fire && !f2_flush)
968a37fbf10SJay  val finishFetchMaskReg = RegNext(f3_cache_fetch)
969a37fbf10SJay
9702a3050c2SJay  val mmioFlushWb        = Wire(Valid(new PredecodeWritebackBundle))
9710be662e4SJay  val f3_mmio_missOffset = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
972a37fbf10SJay  f3_mmio_missOffset.valid := f3_req_is_mmio
9730be662e4SJay  f3_mmio_missOffset.bits  := 0.U
9740be662e4SJay
9758abe1810SEaston Man  // Send mmioFlushWb back to FTQ 1 cycle after uncache fetch return
9768abe1810SEaston Man  // When backend redirect, mmio_state reset after 1 cycle.
9778abe1810SEaston Man  // In this case, mask .valid to avoid overriding backend redirect
9788abe1810SEaston Man  mmioFlushWb.valid := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) &&
9798abe1810SEaston Man    f3_mmio_use_seq_pc && !f3_ftq_flush_self && !f3_ftq_flush_by_older)
9802a3050c2SJay  mmioFlushWb.bits.pc := f3_pc
9812a3050c2SJay  mmioFlushWb.bits.pd := f3_pd
9822a3050c2SJay  mmioFlushWb.bits.pd.zipWithIndex.map { case (instr, i) => instr.valid := f3_mmio_range(i) }
9832a3050c2SJay  mmioFlushWb.bits.ftqIdx     := f3_ftq_req.ftqIdx
9842a3050c2SJay  mmioFlushWb.bits.ftqOffset  := f3_ftq_req.ftqOffset.bits
9852a3050c2SJay  mmioFlushWb.bits.misOffset  := f3_mmio_missOffset
9862a3050c2SJay  mmioFlushWb.bits.cfiOffset  := DontCare
987ee175d78SJay  mmioFlushWb.bits.target     := Mux(mmio_is_RVC, f3_ftq_req.startAddr + 2.U, f3_ftq_req.startAddr + 4.U)
9882a3050c2SJay  mmioFlushWb.bits.jalTarget  := DontCare
9892a3050c2SJay  mmioFlushWb.bits.instrRange := f3_mmio_range
99009c6f1ddSLingrui98
99173e96011SXuan Hu  val mmioRVCExpander = Module(new RVCExpander)
99273e96011SXuan Hu  mmioRVCExpander.io.in      := Mux(f3_req_is_mmio, Cat(f3_mmio_data(1), f3_mmio_data(0)), 0.U)
99371b6c42eSxu_zh  mmioRVCExpander.io.fsIsOff := io.csr_fsIsOff
99473e96011SXuan Hu
9952dfa9e76SJenius  /** external predecode for MMIO instruction */
9962dfa9e76SJenius  when(f3_req_is_mmio) {
9972dfa9e76SJenius    val inst         = Cat(f3_mmio_data(1), f3_mmio_data(0))
9982dfa9e76SJenius    val currentIsRVC = isRVC(inst)
9992dfa9e76SJenius
10002dfa9e76SJenius    val brType :: isCall :: isRet :: Nil = brInfo(inst)
10012dfa9e76SJenius    val jalOffset                        = jal_offset(inst, currentIsRVC)
10022dfa9e76SJenius    val brOffset                         = br_offset(inst, currentIsRVC)
10032dfa9e76SJenius
100473e96011SXuan Hu    io.toIbuffer.bits.instrs(0) := Mux(mmioRVCExpander.io.ill, mmioRVCExpander.io.in, mmioRVCExpander.io.out.bits)
10052dfa9e76SJenius
10062dfa9e76SJenius    io.toIbuffer.bits.pd(0).valid  := true.B
10072dfa9e76SJenius    io.toIbuffer.bits.pd(0).isRVC  := currentIsRVC
10082dfa9e76SJenius    io.toIbuffer.bits.pd(0).brType := brType
10092dfa9e76SJenius    io.toIbuffer.bits.pd(0).isCall := isCall
10102dfa9e76SJenius    io.toIbuffer.bits.pd(0).isRet  := isRet
10112dfa9e76SJenius
101288895b11Sxu_zh    io.toIbuffer.bits.exceptionType(0)   := mmio_resend_exception
1013dd02bc3fSxu_zh    io.toIbuffer.bits.crossPageIPFFix(0) := ExceptionType.hasException(mmio_resend_exception)
101473e96011SXuan Hu    io.toIbuffer.bits.illegalInstr(0)    := mmioRVCExpander.io.ill
10152dfa9e76SJenius
10162dfa9e76SJenius    io.toIbuffer.bits.enqEnable := f3_mmio_range.asUInt
10172dfa9e76SJenius
10182dfa9e76SJenius    mmioFlushWb.bits.pd(0).valid  := true.B
10192dfa9e76SJenius    mmioFlushWb.bits.pd(0).isRVC  := currentIsRVC
10202dfa9e76SJenius    mmioFlushWb.bits.pd(0).brType := brType
10212dfa9e76SJenius    mmioFlushWb.bits.pd(0).isCall := isCall
10222dfa9e76SJenius    mmioFlushWb.bits.pd(0).isRet  := isRet
10232dfa9e76SJenius  }
10242dfa9e76SJenius
1025935edac4STang Haojin  mmio_redirect := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) && f3_mmio_use_seq_pc)
102609c6f1ddSLingrui98
102700240ba6SJay  XSPerfAccumulate("fetch_bubble_ibuffer_not_ready", io.toIbuffer.valid && !io.toIbuffer.ready)
102800240ba6SJay
102958dbdfc2SJay  /**
103058dbdfc2SJay    ******************************************************************************
103158dbdfc2SJay    * IFU Write Back Stage
103258dbdfc2SJay    * - write back predecode information to Ftq to update
103358dbdfc2SJay    * - redirect if found fault prediction
103458dbdfc2SJay    * - redirect if has false hit last half (last PC is not start + 32 Bytes, but in the midle of an notCFI RVI instruction)
103558dbdfc2SJay    ******************************************************************************
10362a3050c2SJay    */
10370c70648eSEaston Man  val wb_enable  = RegNext(f2_fire && !f2_flush) && !f3_req_is_mmio && !f3_flush
10380c70648eSEaston Man  val wb_valid   = RegNext(wb_enable, init = false.B)
10390c70648eSEaston Man  val wb_ftq_req = RegEnable(f3_ftq_req, wb_enable)
104058dbdfc2SJay
10410c70648eSEaston Man  val wb_check_result_stage1 = RegEnable(checkerOutStage1, wb_enable)
10425995c9e7SJenius  val wb_check_result_stage2 = checkerOutStage2
10430c70648eSEaston Man  val wb_instr_range         = RegEnable(io.toIbuffer.bits.enqEnable, wb_enable)
1044e4d2f6a9Smy-mayfly
1045e4d2f6a9Smy-mayfly  val wb_pc_lower_result = RegEnable(f3_pc_lower_result, wb_enable)
1046e4d2f6a9Smy-mayfly  val wb_pc_high         = RegEnable(f3_pc_high, wb_enable)
1047e4d2f6a9Smy-mayfly  val wb_pc_high_plus1   = RegEnable(f3_pc_high_plus1, wb_enable)
1048e4d2f6a9Smy-mayfly  val wb_pc              = CatPC(wb_pc_lower_result, wb_pc_high, wb_pc_high_plus1)
1049e4d2f6a9Smy-mayfly
1050e4d2f6a9Smy-mayfly  // val wb_pc             = RegEnable(f3_pc, wb_enable)
10510c70648eSEaston Man  val wb_pd          = RegEnable(f3_pd, wb_enable)
10520c70648eSEaston Man  val wb_instr_valid = RegEnable(f3_instr_valid, wb_enable)
10532a3050c2SJay
10542a3050c2SJay  /* false hit lastHalf */
10550c70648eSEaston Man  val wb_lastIdx        = RegEnable(f3_last_validIdx, wb_enable)
10560c70648eSEaston Man  val wb_false_lastHalf = RegEnable(f3_false_lastHalf, wb_enable) && wb_lastIdx =/= (PredictWidth - 1).U
10570c70648eSEaston Man  val wb_false_target   = RegEnable(f3_false_snpc, wb_enable)
10582a3050c2SJay
10592a3050c2SJay  val wb_half_flush  = wb_false_lastHalf
10602a3050c2SJay  val wb_half_target = wb_false_target
10612a3050c2SJay
1062a1351e5dSJay  /* false oversize */
1063a1351e5dSJay  val lastIsRVC = wb_instr_range.asTypeOf(Vec(PredictWidth, Bool())).last && wb_pd.last.isRVC
1064a1351e5dSJay  val lastIsRVI = wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))(PredictWidth - 2) && !wb_pd(PredictWidth - 2).isRVC
10655995c9e7SJenius  val lastTaken = wb_check_result_stage1.fixedTaken.last
1066a1351e5dSJay
10672a3050c2SJay  f3_wb_not_flush := wb_ftq_req.ftqIdx === f3_ftq_req.ftqIdx && f3_valid && wb_valid
10682a3050c2SJay
10693f785aa3SJenius  /** if a req with a last half but miss predicted enters in wb stage, and this cycle f3 stalls,
10703f785aa3SJenius    * we set a flag to notify f3 that the last half flag need not to be set.
10713f785aa3SJenius    */
1072804985a5SJenius  // f3_fire is after wb_valid
1073076dea5fSJenius  when(wb_valid && RegNext(f3_hasLastHalf, init = false.B)
1074cf7d6b7aSMuzi    && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && !f3_fire && !RegNext(
1075cf7d6b7aSMuzi      f3_fire,
1076cf7d6b7aSMuzi      init = false.B
1077cf7d6b7aSMuzi    ) && !f3_flush) {
10783f785aa3SJenius    f3_lastHalf_disable := true.B
1079ab6202e2SJenius  }
1080ab6202e2SJenius
1081804985a5SJenius  // wb_valid and f3_fire are in same cycle
1082076dea5fSJenius  when(wb_valid && RegNext(f3_hasLastHalf, init = false.B)
1083cf7d6b7aSMuzi    && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && f3_fire) {
1084804985a5SJenius    f3_lastHalf.valid := false.B
1085804985a5SJenius  }
1086804985a5SJenius
10872a3050c2SJay  val checkFlushWb = Wire(Valid(new PredecodeWritebackBundle))
1088cf7d6b7aSMuzi  val checkFlushWbjalTargetIdx = ParallelPriorityEncoder(VecInit(wb_pd.zip(wb_instr_valid).map { case (pd, v) =>
1089cf7d6b7aSMuzi    v && pd.isJal
1090cf7d6b7aSMuzi  }))
1091b665b650STang Haojin  val checkFlushWbTargetIdx = ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
10922a3050c2SJay  checkFlushWb.valid   := wb_valid
10932a3050c2SJay  checkFlushWb.bits.pc := wb_pc
10942a3050c2SJay  checkFlushWb.bits.pd := wb_pd
10952a3050c2SJay  checkFlushWb.bits.pd.zipWithIndex.map { case (instr, i) => instr.valid := wb_instr_valid(i) }
10962a3050c2SJay  checkFlushWb.bits.ftqIdx          := wb_ftq_req.ftqIdx
10972a3050c2SJay  checkFlushWb.bits.ftqOffset       := wb_ftq_req.ftqOffset.bits
10985995c9e7SJenius  checkFlushWb.bits.misOffset.valid := ParallelOR(wb_check_result_stage2.fixedMissPred) || wb_half_flush
1099cf7d6b7aSMuzi  checkFlushWb.bits.misOffset.bits := Mux(
1100cf7d6b7aSMuzi    wb_half_flush,
1101cf7d6b7aSMuzi    wb_lastIdx,
1102cf7d6b7aSMuzi    ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
1103cf7d6b7aSMuzi  )
11045995c9e7SJenius  checkFlushWb.bits.cfiOffset.valid := ParallelOR(wb_check_result_stage1.fixedTaken)
11055995c9e7SJenius  checkFlushWb.bits.cfiOffset.bits  := ParallelPriorityEncoder(wb_check_result_stage1.fixedTaken)
1106cf7d6b7aSMuzi  checkFlushWb.bits.target := Mux(
1107cf7d6b7aSMuzi    wb_half_flush,
1108cf7d6b7aSMuzi    wb_half_target,
1109cf7d6b7aSMuzi    wb_check_result_stage2.fixedTarget(checkFlushWbTargetIdx)
1110cf7d6b7aSMuzi  )
1111d10ddd67SGuokai Chen  checkFlushWb.bits.jalTarget  := wb_check_result_stage2.jalTarget(checkFlushWbjalTargetIdx)
11122a3050c2SJay  checkFlushWb.bits.instrRange := wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
11132a3050c2SJay
1114bccc5520SJenius  toFtq.pdWb := Mux(wb_valid, checkFlushWb, mmioFlushWb)
11152a3050c2SJay
11162a3050c2SJay  wb_redirect := checkFlushWb.bits.misOffset.valid && wb_valid
111709c6f1ddSLingrui98
11185b3c20f7SJinYue  /*write back flush type*/
11195995c9e7SJenius  val checkFaultType    = wb_check_result_stage2.faultType
11205b3c20f7SJinYue  val checkJalFault     = wb_valid && checkFaultType.map(_.isjalFault).reduce(_ || _)
11215b3c20f7SJinYue  val checkRetFault     = wb_valid && checkFaultType.map(_.isRetFault).reduce(_ || _)
11225b3c20f7SJinYue  val checkTargetFault  = wb_valid && checkFaultType.map(_.istargetFault).reduce(_ || _)
11235b3c20f7SJinYue  val checkNotCFIFault  = wb_valid && checkFaultType.map(_.notCFIFault).reduce(_ || _)
11245b3c20f7SJinYue  val checkInvalidTaken = wb_valid && checkFaultType.map(_.invalidTakenFault).reduce(_ || _)
11255b3c20f7SJinYue
11265b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_jalFault", checkJalFault)
11275b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_retFault", checkRetFault)
11285b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_targetFault", checkTargetFault)
11295b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_notCFIFault", checkNotCFIFault)
11305b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_incalidTakenFault", checkInvalidTaken)
11315b3c20f7SJinYue
11325b3c20f7SJinYue  when(checkRetFault) {
1133cf7d6b7aSMuzi    XSDebug(
1134cf7d6b7aSMuzi      "startAddr:%x  nextstartAddr:%x  taken:%d    takenIdx:%d\n",
1135cf7d6b7aSMuzi      wb_ftq_req.startAddr,
1136cf7d6b7aSMuzi      wb_ftq_req.nextStartAddr,
1137cf7d6b7aSMuzi      wb_ftq_req.ftqOffset.valid,
1138cf7d6b7aSMuzi      wb_ftq_req.ftqOffset.bits
1139cf7d6b7aSMuzi    )
11405b3c20f7SJinYue  }
11415b3c20f7SJinYue
11421d8f4dcbSJay  /** performance counter */
1143005e809bSJiuyang Liu  val f3_perf_info = RegEnable(f2_perf_info, f2_fire)
1144935edac4STang Haojin  val f3_req_0     = io.toIbuffer.fire
1145935edac4STang Haojin  val f3_req_1     = io.toIbuffer.fire && f3_doubleLine
1146935edac4STang Haojin  val f3_hit_0     = io.toIbuffer.fire && f3_perf_info.bank_hit(0)
1147935edac4STang Haojin  val f3_hit_1     = io.toIbuffer.fire && f3_doubleLine & f3_perf_info.bank_hit(1)
11481d8f4dcbSJay  val f3_hit       = f3_perf_info.hit
1149cd365d4cSrvcoresjw  val perfEvents = Seq(
11502a3050c2SJay    ("frontendFlush                ", wb_redirect),
1151935edac4STang Haojin    ("ifu_req                      ", io.toIbuffer.fire),
1152935edac4STang Haojin    ("ifu_miss                     ", io.toIbuffer.fire && !f3_perf_info.hit),
1153cd365d4cSrvcoresjw    ("ifu_req_cacheline_0          ", f3_req_0),
1154cd365d4cSrvcoresjw    ("ifu_req_cacheline_1          ", f3_req_1),
1155cd365d4cSrvcoresjw    ("ifu_req_cacheline_0_hit      ", f3_hit_1),
1156cd365d4cSrvcoresjw    ("ifu_req_cacheline_1_hit      ", f3_hit_1),
1157935edac4STang Haojin    ("only_0_hit                   ", f3_perf_info.only_0_hit && io.toIbuffer.fire),
1158935edac4STang Haojin    ("only_0_miss                  ", f3_perf_info.only_0_miss && io.toIbuffer.fire),
1159935edac4STang Haojin    ("hit_0_hit_1                  ", f3_perf_info.hit_0_hit_1 && io.toIbuffer.fire),
1160935edac4STang Haojin    ("hit_0_miss_1                 ", f3_perf_info.hit_0_miss_1 && io.toIbuffer.fire),
1161935edac4STang Haojin    ("miss_0_hit_1                 ", f3_perf_info.miss_0_hit_1 && io.toIbuffer.fire),
1162cf7d6b7aSMuzi    ("miss_0_miss_1                ", f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire)
1163cd365d4cSrvcoresjw  )
11641ca0e4f3SYinan Xu  generatePerfEvent()
116509c6f1ddSLingrui98
1166935edac4STang Haojin  XSPerfAccumulate("ifu_req", io.toIbuffer.fire)
1167935edac4STang Haojin  XSPerfAccumulate("ifu_miss", io.toIbuffer.fire && !f3_hit)
1168f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_0", f3_req_0)
1169f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_1", f3_req_1)
1170f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_0_hit", f3_hit_0)
1171f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_1_hit", f3_hit_1)
11722a3050c2SJay  XSPerfAccumulate("frontendFlush", wb_redirect)
1173935edac4STang Haojin  XSPerfAccumulate("only_0_hit", f3_perf_info.only_0_hit && io.toIbuffer.fire)
1174935edac4STang Haojin  XSPerfAccumulate("only_0_miss", f3_perf_info.only_0_miss && io.toIbuffer.fire)
1175935edac4STang Haojin  XSPerfAccumulate("hit_0_hit_1", f3_perf_info.hit_0_hit_1 && io.toIbuffer.fire)
1176935edac4STang Haojin  XSPerfAccumulate("hit_0_miss_1", f3_perf_info.hit_0_miss_1 && io.toIbuffer.fire)
1177935edac4STang Haojin  XSPerfAccumulate("miss_0_hit_1", f3_perf_info.miss_0_hit_1 && io.toIbuffer.fire)
1178935edac4STang Haojin  XSPerfAccumulate("miss_0_miss_1", f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire)
1179935edac4STang Haojin  XSPerfAccumulate("hit_0_except_1", f3_perf_info.hit_0_except_1 && io.toIbuffer.fire)
1180935edac4STang Haojin  XSPerfAccumulate("miss_0_except_1", f3_perf_info.miss_0_except_1 && io.toIbuffer.fire)
1181935edac4STang Haojin  XSPerfAccumulate("except_0", f3_perf_info.except_0 && io.toIbuffer.fire)
1182cf7d6b7aSMuzi  XSPerfHistogram(
1183cf7d6b7aSMuzi    "ifu2ibuffer_validCnt",
1184cf7d6b7aSMuzi    PopCount(io.toIbuffer.bits.valid & io.toIbuffer.bits.enqEnable),
1185cf7d6b7aSMuzi    io.toIbuffer.fire,
1186cf7d6b7aSMuzi    0,
1187cf7d6b7aSMuzi    PredictWidth + 1,
1188cf7d6b7aSMuzi    1
1189cf7d6b7aSMuzi  )
119051532d8bSGuokai Chen
1191c686adcdSYinan Xu  val hartId                     = p(XSCoreParamsKey).HartId
1192c686adcdSYinan Xu  val isWriteFetchToIBufferTable = Constantin.createRecord(s"isWriteFetchToIBufferTable$hartId")
1193c686adcdSYinan Xu  val isWriteIfuWbToFtqTable     = Constantin.createRecord(s"isWriteIfuWbToFtqTable$hartId")
1194c686adcdSYinan Xu  val fetchToIBufferTable        = ChiselDB.createTable(s"FetchToIBuffer$hartId", new FetchToIBufferDB)
1195c686adcdSYinan Xu  val ifuWbToFtqTable            = ChiselDB.createTable(s"IfuWbToFtq$hartId", new IfuWbToFtqDB)
119651532d8bSGuokai Chen
119751532d8bSGuokai Chen  val fetchIBufferDumpData = Wire(new FetchToIBufferDB)
119851532d8bSGuokai Chen  fetchIBufferDumpData.start_addr  := f3_ftq_req.startAddr
119951532d8bSGuokai Chen  fetchIBufferDumpData.instr_count := PopCount(io.toIbuffer.bits.enqEnable)
1200935edac4STang Haojin  fetchIBufferDumpData.exception := (f3_perf_info.except_0 && io.toIbuffer.fire) || (f3_perf_info.hit_0_except_1 && io.toIbuffer.fire) || (f3_perf_info.miss_0_except_1 && io.toIbuffer.fire)
120151532d8bSGuokai Chen  fetchIBufferDumpData.is_cache_hit := f3_hit
120251532d8bSGuokai Chen
120351532d8bSGuokai Chen  val ifuWbToFtqDumpData = Wire(new IfuWbToFtqDB)
120451532d8bSGuokai Chen  ifuWbToFtqDumpData.start_addr        := wb_ftq_req.startAddr
120551532d8bSGuokai Chen  ifuWbToFtqDumpData.is_miss_pred      := checkFlushWb.bits.misOffset.valid
120651532d8bSGuokai Chen  ifuWbToFtqDumpData.miss_pred_offset  := checkFlushWb.bits.misOffset.bits
120751532d8bSGuokai Chen  ifuWbToFtqDumpData.checkJalFault     := checkJalFault
120851532d8bSGuokai Chen  ifuWbToFtqDumpData.checkRetFault     := checkRetFault
120951532d8bSGuokai Chen  ifuWbToFtqDumpData.checkTargetFault  := checkTargetFault
121051532d8bSGuokai Chen  ifuWbToFtqDumpData.checkNotCFIFault  := checkNotCFIFault
121151532d8bSGuokai Chen  ifuWbToFtqDumpData.checkInvalidTaken := checkInvalidTaken
121251532d8bSGuokai Chen
121351532d8bSGuokai Chen  fetchToIBufferTable.log(
121451532d8bSGuokai Chen    data = fetchIBufferDumpData,
1215da3bf434SMaxpicca-Li    en = isWriteFetchToIBufferTable.orR && io.toIbuffer.fire,
121651532d8bSGuokai Chen    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
121751532d8bSGuokai Chen    clock = clock,
121851532d8bSGuokai Chen    reset = reset
121951532d8bSGuokai Chen  )
122051532d8bSGuokai Chen  ifuWbToFtqTable.log(
122151532d8bSGuokai Chen    data = ifuWbToFtqDumpData,
1222da3bf434SMaxpicca-Li    en = isWriteIfuWbToFtqTable.orR && checkFlushWb.valid,
122351532d8bSGuokai Chen    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
122451532d8bSGuokai Chen    clock = clock,
122551532d8bSGuokai Chen    reset = reset
122651532d8bSGuokai Chen  )
122751532d8bSGuokai Chen
122809c6f1ddSLingrui98}
1229