xref: /XiangShan/src/main/scala/xiangshan/frontend/IFU.scala (revision aeedc8ee24c606b62f87b4a2382c7af1cca1fcd7)
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
208891a219SYinan Xuimport org.chipsalliance.cde.config.Parameters
2109c6f1ddSLingrui98import chisel3._
2209c6f1ddSLingrui98import chisel3.util._
232a3050c2SJayimport freechips.rocketchip.rocket.RVCDecoder
2409c6f1ddSLingrui98import xiangshan._
2509c6f1ddSLingrui98import xiangshan.cache.mmu._
261d8f4dcbSJayimport xiangshan.frontend.icache._
2709c6f1ddSLingrui98import utils._
283c02ee8fSwakafaimport utility._
29b6982e83SLemoverimport xiangshan.backend.fu.{PMPReqBundle, PMPRespBundle}
303c02ee8fSwakafaimport utility.ChiselDB
3109c6f1ddSLingrui98
3209c6f1ddSLingrui98trait HasInstrMMIOConst extends HasXSParameter with HasIFUConst{
3309c6f1ddSLingrui98  def mmioBusWidth = 64
3409c6f1ddSLingrui98  def mmioBusBytes = mmioBusWidth / 8
350be662e4SJay  def maxInstrLen = 32
3609c6f1ddSLingrui98}
3709c6f1ddSLingrui98
3809c6f1ddSLingrui98trait HasIFUConst extends HasXSParameter{
391d8f4dcbSJay  def addrAlign(addr: UInt, bytes: Int, highest: Int): UInt = Cat(addr(highest-1, log2Ceil(bytes)), 0.U(log2Ceil(bytes).W))
401d8f4dcbSJay  def fetchQueueSize = 2
411d8f4dcbSJay
422a3050c2SJay  def getBasicBlockIdx( pc: UInt, start:  UInt ): UInt = {
432a3050c2SJay    val byteOffset = pc - start
442a3050c2SJay    (byteOffset - instBytes.U)(log2Ceil(PredictWidth),instOffsetBits)
451d8f4dcbSJay  }
4609c6f1ddSLingrui98}
4709c6f1ddSLingrui98
4809c6f1ddSLingrui98class IfuToFtqIO(implicit p:Parameters) extends XSBundle {
4909c6f1ddSLingrui98  val pdWb = Valid(new PredecodeWritebackBundle)
5009c6f1ddSLingrui98}
5109c6f1ddSLingrui98
52d7ac23a3SEaston Manclass IfuToBackendIO(implicit p:Parameters) extends XSBundle {
53d7ac23a3SEaston Man  // write to backend gpaddr mem
54d7ac23a3SEaston Man  val gpaddrMem_wen = Output(Bool())
55d7ac23a3SEaston Man  val gpaddrMem_waddr = Output(UInt(log2Ceil(FtqSize).W)) // Ftq Ptr
56d7ac23a3SEaston Man  // 2 gpaddrs, correspond to startAddr & nextLineAddr in bundle FtqICacheInfo
57d7ac23a3SEaston Man  // TODO: avoid cross page entry in Ftq
58bad60841SXiaokun-Pei  val gpaddrMem_wdata = Output(UInt(GPAddrBits.W))
59d7ac23a3SEaston Man}
60d7ac23a3SEaston Man
6109c6f1ddSLingrui98class FtqInterface(implicit p: Parameters) extends XSBundle {
6209c6f1ddSLingrui98  val fromFtq = Flipped(new FtqToIfuIO)
6309c6f1ddSLingrui98  val toFtq   = new IfuToFtqIO
6409c6f1ddSLingrui98}
6509c6f1ddSLingrui98
660be662e4SJayclass UncacheInterface(implicit p: Parameters) extends XSBundle {
670be662e4SJay  val fromUncache = Flipped(DecoupledIO(new InsUncacheResp))
680be662e4SJay  val toUncache   = DecoupledIO( new InsUncacheReq )
690be662e4SJay}
701d1e6d4dSJenius
7109c6f1ddSLingrui98class NewIFUIO(implicit p: Parameters) extends XSBundle {
7209c6f1ddSLingrui98  val ftqInter         = new FtqInterface
7350780602SJenius  val icacheInter      = Flipped(new IFUICacheIO)
741d8f4dcbSJay  val icacheStop       = Output(Bool())
751d8f4dcbSJay  val icachePerfInfo   = Input(new ICachePerfInfo)
7609c6f1ddSLingrui98  val toIbuffer        = Decoupled(new FetchToIBuffer)
77d7ac23a3SEaston Man  val toBackend        = new IfuToBackendIO
780be662e4SJay  val uncacheInter     = new UncacheInterface
7972951335SLi Qianruo  val frontendTrigger  = Flipped(new FrontendTdataDistributeIO)
80a37fbf10SJay  val rob_commits      = Flipped(Vec(CommitWidth, Valid(new RobCommitInfo)))
81f1fe8698SLemover  val iTLBInter        = new TlbRequestIO
8256788a33SJinYue  val pmp              = new ICachePMPBundle
831d1e6d4dSJenius  val mmioCommitRead   = new mmioCommitRead
84*aeedc8eeSGuokai Chen  val illBuf          = Output(UInt(32.W))
8509c6f1ddSLingrui98}
8609c6f1ddSLingrui98
8709c6f1ddSLingrui98// record the situation in which fallThruAddr falls into
8809c6f1ddSLingrui98// the middle of an RVI inst
8909c6f1ddSLingrui98class LastHalfInfo(implicit p: Parameters) extends XSBundle {
9009c6f1ddSLingrui98  val valid = Bool()
9109c6f1ddSLingrui98  val middlePC = UInt(VAddrBits.W)
9209c6f1ddSLingrui98  def matchThisBlock(startAddr: UInt) = valid && middlePC === startAddr
9309c6f1ddSLingrui98}
9409c6f1ddSLingrui98
9509c6f1ddSLingrui98class IfuToPreDecode(implicit p: Parameters) extends XSBundle {
9609c6f1ddSLingrui98  val data                =  if(HasCExtension) Vec(PredictWidth + 1, UInt(16.W)) else Vec(PredictWidth, UInt(32.W))
9772951335SLi Qianruo  val frontendTrigger     = new FrontendTdataDistributeIO
982a3050c2SJay  val pc                  = Vec(PredictWidth, UInt(VAddrBits.W))
9909c6f1ddSLingrui98}
10009c6f1ddSLingrui98
1012a3050c2SJay
1022a3050c2SJayclass IfuToPredChecker(implicit p: Parameters) extends XSBundle {
1032a3050c2SJay  val ftqOffset     = Valid(UInt(log2Ceil(PredictWidth).W))
1042a3050c2SJay  val jumpOffset    = Vec(PredictWidth, UInt(XLEN.W))
1052a3050c2SJay  val target        = UInt(VAddrBits.W)
1062a3050c2SJay  val instrRange    = Vec(PredictWidth, Bool())
1072a3050c2SJay  val instrValid    = Vec(PredictWidth, Bool())
1082a3050c2SJay  val pds           = Vec(PredictWidth, new PreDecodeInfo)
1092a3050c2SJay  val pc            = Vec(PredictWidth, UInt(VAddrBits.W))
1100c70648eSEaston Man  val fire_in       = Bool()
1112a3050c2SJay}
1122a3050c2SJay
11351532d8bSGuokai Chenclass FetchToIBufferDB extends Bundle {
11451532d8bSGuokai Chen  val start_addr = UInt(39.W)
11551532d8bSGuokai Chen  val instr_count = UInt(32.W)
11651532d8bSGuokai Chen  val exception = Bool()
11751532d8bSGuokai Chen  val is_cache_hit = Bool()
11851532d8bSGuokai Chen}
11951532d8bSGuokai Chen
12051532d8bSGuokai Chenclass IfuWbToFtqDB extends Bundle {
12151532d8bSGuokai Chen  val start_addr = UInt(39.W)
12251532d8bSGuokai Chen  val is_miss_pred = Bool()
12351532d8bSGuokai Chen  val miss_pred_offset = UInt(32.W)
12451532d8bSGuokai Chen  val checkJalFault = Bool()
12551532d8bSGuokai Chen  val checkRetFault = Bool()
12651532d8bSGuokai Chen  val checkTargetFault = Bool()
12751532d8bSGuokai Chen  val checkNotCFIFault = Bool()
12851532d8bSGuokai Chen  val checkInvalidTaken = Bool()
12951532d8bSGuokai Chen}
13051532d8bSGuokai Chen
1312a3050c2SJayclass NewIFU(implicit p: Parameters) extends XSModule
1322a3050c2SJay  with HasICacheParameters
133*aeedc8eeSGuokai Chen  with HasXSParameter
1342a3050c2SJay  with HasIFUConst
1352a3050c2SJay  with HasPdConst
136167bcd01SJay  with HasCircularQueuePtrHelper
1372a3050c2SJay  with HasPerfEvents
13821ae6bc4Speixiaokun  with HasTlbConst
13909c6f1ddSLingrui98{
14009c6f1ddSLingrui98  val io = IO(new NewIFUIO)
14109c6f1ddSLingrui98  val (toFtq, fromFtq)    = (io.ftqInter.toFtq, io.ftqInter.fromFtq)
142c5c5edaeSJenius  val fromICache = io.icacheInter.resp
1430be662e4SJay  val (toUncache, fromUncache) = (io.uncacheInter.toUncache , io.uncacheInter.fromUncache)
14409c6f1ddSLingrui98
14509c6f1ddSLingrui98  def isCrossLineReq(start: UInt, end: UInt): Bool = start(blockOffBits) ^ end(blockOffBits)
14609c6f1ddSLingrui98
147d2b20d1aSTang Haojin  def numOfStage = 3
148e4d2f6a9Smy-mayfly  // equal lower_result overflow bit
149e4d2f6a9Smy-mayfly  def PcCutPoint = (VAddrBits/4) - 1
150e4d2f6a9Smy-mayfly  def CatPC(low: UInt, high: UInt, high1: UInt): UInt = {
151e4d2f6a9Smy-mayfly    Mux(
152e4d2f6a9Smy-mayfly      low(PcCutPoint),
153e4d2f6a9Smy-mayfly      Cat(high1, low(PcCutPoint-1, 0)),
154e4d2f6a9Smy-mayfly      Cat(high, low(PcCutPoint-1, 0))
155e4d2f6a9Smy-mayfly    )
156e4d2f6a9Smy-mayfly  }
157e4d2f6a9Smy-mayfly  def CatPC(lowVec: Vec[UInt], high: UInt, high1: UInt): Vec[UInt] = VecInit(lowVec.map(CatPC(_, high, high1)))
158d2b20d1aSTang Haojin  require(numOfStage > 1, "BPU numOfStage must be greater than 1")
159d2b20d1aSTang Haojin  val topdown_stages = RegInit(VecInit(Seq.fill(numOfStage)(0.U.asTypeOf(new FrontendTopDownBundle))))
160d2b20d1aSTang Haojin  // bubble events in IFU, only happen in stage 1
161d2b20d1aSTang Haojin  val icacheMissBubble = Wire(Bool())
162d2b20d1aSTang Haojin  val itlbMissBubble =Wire(Bool())
163d2b20d1aSTang Haojin
164d2b20d1aSTang Haojin  // only driven by clock, not valid-ready
165d2b20d1aSTang Haojin  topdown_stages(0) := fromFtq.req.bits.topdown_info
166d2b20d1aSTang Haojin  for (i <- 1 until numOfStage) {
167d2b20d1aSTang Haojin    topdown_stages(i) := topdown_stages(i - 1)
168d2b20d1aSTang Haojin  }
169d2b20d1aSTang Haojin  when (icacheMissBubble) {
170d2b20d1aSTang Haojin    topdown_stages(1).reasons(TopDownCounters.ICacheMissBubble.id) := true.B
171d2b20d1aSTang Haojin  }
172d2b20d1aSTang Haojin  when (itlbMissBubble) {
173d2b20d1aSTang Haojin    topdown_stages(1).reasons(TopDownCounters.ITLBMissBubble.id) := true.B
174d2b20d1aSTang Haojin  }
175d2b20d1aSTang Haojin  io.toIbuffer.bits.topdown_info := topdown_stages(numOfStage - 1)
176d2b20d1aSTang Haojin  when (fromFtq.topdown_redirect.valid) {
177d2b20d1aSTang Haojin    // only redirect from backend, IFU redirect itself is handled elsewhere
178d2b20d1aSTang Haojin    when (fromFtq.topdown_redirect.bits.debugIsCtrl) {
179d2b20d1aSTang Haojin      /*
180d2b20d1aSTang Haojin      for (i <- 0 until numOfStage) {
181d2b20d1aSTang Haojin        topdown_stages(i).reasons(TopDownCounters.ControlRedirectBubble.id) := true.B
182d2b20d1aSTang Haojin      }
183d2b20d1aSTang Haojin      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.ControlRedirectBubble.id) := true.B
184d2b20d1aSTang Haojin      */
185d2b20d1aSTang Haojin      when (fromFtq.topdown_redirect.bits.ControlBTBMissBubble) {
186d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
187d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.BTBMissBubble.id) := true.B
188d2b20d1aSTang Haojin        }
189d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.BTBMissBubble.id) := true.B
190d2b20d1aSTang Haojin      } .elsewhen (fromFtq.topdown_redirect.bits.TAGEMissBubble) {
191d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
192d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.TAGEMissBubble.id) := true.B
193d2b20d1aSTang Haojin        }
194d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.TAGEMissBubble.id) := true.B
195d2b20d1aSTang Haojin      } .elsewhen (fromFtq.topdown_redirect.bits.SCMissBubble) {
196d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
197d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.SCMissBubble.id) := true.B
198d2b20d1aSTang Haojin        }
199d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.SCMissBubble.id) := true.B
200d2b20d1aSTang Haojin      } .elsewhen (fromFtq.topdown_redirect.bits.ITTAGEMissBubble) {
201d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
202d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.ITTAGEMissBubble.id) := true.B
203d2b20d1aSTang Haojin        }
204d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.ITTAGEMissBubble.id) := true.B
205d2b20d1aSTang Haojin      } .elsewhen (fromFtq.topdown_redirect.bits.RASMissBubble) {
206d2b20d1aSTang Haojin        for (i <- 0 until numOfStage) {
207d2b20d1aSTang Haojin          topdown_stages(i).reasons(TopDownCounters.RASMissBubble.id) := true.B
208d2b20d1aSTang Haojin        }
209d2b20d1aSTang Haojin        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.RASMissBubble.id) := true.B
210d2b20d1aSTang Haojin      }
211d2b20d1aSTang Haojin    } .elsewhen (fromFtq.topdown_redirect.bits.debugIsMemVio) {
212d2b20d1aSTang Haojin      for (i <- 0 until numOfStage) {
213d2b20d1aSTang Haojin        topdown_stages(i).reasons(TopDownCounters.MemVioRedirectBubble.id) := true.B
214d2b20d1aSTang Haojin      }
215d2b20d1aSTang Haojin      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.MemVioRedirectBubble.id) := true.B
216d2b20d1aSTang Haojin    } .otherwise {
217d2b20d1aSTang Haojin      for (i <- 0 until numOfStage) {
218d2b20d1aSTang Haojin        topdown_stages(i).reasons(TopDownCounters.OtherRedirectBubble.id) := true.B
219d2b20d1aSTang Haojin      }
220d2b20d1aSTang Haojin      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.OtherRedirectBubble.id) := true.B
221d2b20d1aSTang Haojin    }
222d2b20d1aSTang Haojin  }
223d2b20d1aSTang Haojin
2241d8f4dcbSJay  class TlbExept(implicit p: Parameters) extends XSBundle{
2251d8f4dcbSJay    val pageFault = Bool()
2261d8f4dcbSJay    val accessFault = Bool()
2271d8f4dcbSJay    val mmio = Bool()
228b005f7c6SJay  }
22909c6f1ddSLingrui98
230a61a35e0Sssszwic  val preDecoder       = Module(new PreDecode)
231dc270d3bSJenius
2322a3050c2SJay  val predChecker     = Module(new PredChecker)
2332a3050c2SJay  val frontendTrigger = Module(new FrontendTrigger)
2345995c9e7SJenius  val (checkerIn, checkerOutStage1, checkerOutStage2)         = (predChecker.io.in, predChecker.io.out.stage1Out,predChecker.io.out.stage2Out)
2351d8f4dcbSJay
23658dbdfc2SJay  /**
23758dbdfc2SJay    ******************************************************************************
23858dbdfc2SJay    * IFU Stage 0
23958dbdfc2SJay    * - send cacheline fetch request to ICacheMainPipe
24058dbdfc2SJay    ******************************************************************************
24158dbdfc2SJay    */
24209c6f1ddSLingrui98
24309c6f1ddSLingrui98  val f0_valid                             = fromFtq.req.valid
24409c6f1ddSLingrui98  val f0_ftq_req                           = fromFtq.req.bits
2456ce52296SJinYue  val f0_doubleLine                        = fromFtq.req.bits.crossCacheline
24634a88126SJinYue  val f0_vSetIdx                           = VecInit(get_idx((f0_ftq_req.startAddr)), get_idx(f0_ftq_req.nextlineStart))
247935edac4STang Haojin  val f0_fire                              = fromFtq.req.fire
24809c6f1ddSLingrui98
24909c6f1ddSLingrui98  val f0_flush, f1_flush, f2_flush, f3_flush = WireInit(false.B)
25009c6f1ddSLingrui98  val from_bpu_f0_flush, from_bpu_f1_flush, from_bpu_f2_flush, from_bpu_f3_flush = WireInit(false.B)
25109c6f1ddSLingrui98
252cb4f77ceSLingrui98  from_bpu_f0_flush := fromFtq.flushFromBpu.shouldFlushByStage2(f0_ftq_req.ftqIdx) ||
253cb4f77ceSLingrui98                       fromFtq.flushFromBpu.shouldFlushByStage3(f0_ftq_req.ftqIdx)
25409c6f1ddSLingrui98
2552a3050c2SJay  val wb_redirect , mmio_redirect,  backend_redirect= WireInit(false.B)
2562a3050c2SJay  val f3_wb_not_flush = WireInit(false.B)
2572a3050c2SJay
2582a3050c2SJay  backend_redirect := fromFtq.redirect.valid
2592a3050c2SJay  f3_flush := backend_redirect || (wb_redirect && !f3_wb_not_flush)
2602a3050c2SJay  f2_flush := backend_redirect || mmio_redirect || wb_redirect
26109c6f1ddSLingrui98  f1_flush := f2_flush || from_bpu_f1_flush
26209c6f1ddSLingrui98  f0_flush := f1_flush || from_bpu_f0_flush
26309c6f1ddSLingrui98
26409c6f1ddSLingrui98  val f1_ready, f2_ready, f3_ready         = WireInit(false.B)
26509c6f1ddSLingrui98
26650780602SJenius  fromFtq.req.ready := f1_ready && io.icacheInter.icacheReady
26709c6f1ddSLingrui98
268d2b20d1aSTang Haojin
269d2b20d1aSTang Haojin  when (wb_redirect) {
270d2b20d1aSTang Haojin    when (f3_wb_not_flush) {
271d2b20d1aSTang Haojin      topdown_stages(2).reasons(TopDownCounters.BTBMissBubble.id) := true.B
272d2b20d1aSTang Haojin    }
273d2b20d1aSTang Haojin    for (i <- 0 until numOfStage - 1) {
274d2b20d1aSTang Haojin      topdown_stages(i).reasons(TopDownCounters.BTBMissBubble.id) := true.B
275d2b20d1aSTang Haojin    }
276d2b20d1aSTang Haojin  }
277d2b20d1aSTang Haojin
27858dbdfc2SJay  /** <PERF> f0 fetch bubble */
279f7c29b0aSJinYue
28000240ba6SJay  XSPerfAccumulate("fetch_bubble_ftq_not_valid",   !fromFtq.req.valid && fromFtq.req.ready  )
281c5c5edaeSJenius  // XSPerfAccumulate("fetch_bubble_pipe_stall",    f0_valid && toICache(0).ready && toICache(1).ready && !f1_ready )
282c5c5edaeSJenius  // XSPerfAccumulate("fetch_bubble_icache_0_busy",   f0_valid && !toICache(0).ready  )
283c5c5edaeSJenius  // XSPerfAccumulate("fetch_bubble_icache_1_busy",   f0_valid && !toICache(1).ready  )
28400240ba6SJay  XSPerfAccumulate("fetch_flush_backend_redirect",   backend_redirect  )
28500240ba6SJay  XSPerfAccumulate("fetch_flush_wb_redirect",    wb_redirect  )
28600240ba6SJay  XSPerfAccumulate("fetch_flush_bpu_f1_flush",   from_bpu_f1_flush  )
28700240ba6SJay  XSPerfAccumulate("fetch_flush_bpu_f0_flush",   from_bpu_f0_flush  )
28858dbdfc2SJay
28958dbdfc2SJay
29058dbdfc2SJay  /**
29158dbdfc2SJay    ******************************************************************************
29258dbdfc2SJay    * IFU Stage 1
29358dbdfc2SJay    * - calculate pc/half_pc/cut_ptr for every instruction
29458dbdfc2SJay    ******************************************************************************
29558dbdfc2SJay    */
29609c6f1ddSLingrui98
29709c6f1ddSLingrui98  val f1_valid      = RegInit(false.B)
298005e809bSJiuyang Liu  val f1_ftq_req    = RegEnable(f0_ftq_req,    f0_fire)
299005e809bSJiuyang Liu  // val f1_situation  = RegEnable(f0_situation,  f0_fire)
300005e809bSJiuyang Liu  val f1_doubleLine = RegEnable(f0_doubleLine, f0_fire)
301005e809bSJiuyang Liu  val f1_vSetIdx    = RegEnable(f0_vSetIdx,    f0_fire)
302625ecd17SJenius  val f1_fire       = f1_valid && f2_ready
30309c6f1ddSLingrui98
304625ecd17SJenius  f1_ready := f1_fire || !f1_valid
30509c6f1ddSLingrui98
3060d756c48SJinYue  from_bpu_f1_flush := fromFtq.flushFromBpu.shouldFlushByStage3(f1_ftq_req.ftqIdx) && f1_valid
307cb4f77ceSLingrui98  // from_bpu_f1_flush := false.B
30809c6f1ddSLingrui98
30909c6f1ddSLingrui98  when(f1_flush)                  {f1_valid  := false.B}
31009c6f1ddSLingrui98  .elsewhen(f0_fire && !f0_flush) {f1_valid  := true.B}
31109c6f1ddSLingrui98  .elsewhen(f1_fire)              {f1_valid  := false.B}
31209c6f1ddSLingrui98
313e4d2f6a9Smy-mayfly  val f1_pc_high            = f1_ftq_req.startAddr(VAddrBits-1, PcCutPoint)
314f2f493deSstride  val f1_pc_high_plus1      = f1_pc_high + 1.U
315f2f493deSstride
316e4d2f6a9Smy-mayfly  /**
317e4d2f6a9Smy-mayfly   * In order to reduce power consumption, avoid calculating the full PC value in the first level.
318e4d2f6a9Smy-mayfly   * code of original logic, this code has been deprecated
319e4d2f6a9Smy-mayfly   * val f1_pc                 = VecInit(f1_pc_lower_result.map{ i =>
320e4d2f6a9Smy-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)))})
321e4d2f6a9Smy-mayfly   *
322e4d2f6a9Smy-mayfly   */
323e4d2f6a9Smy-mayfly  val f1_pc_lower_result    = VecInit((0 until PredictWidth).map(i => Cat(0.U(1.W), f1_ftq_req.startAddr(PcCutPoint-1, 0)) + (i * 2).U)) // cat with overflow bit
324f2f493deSstride
325e4d2f6a9Smy-mayfly  val f1_pc                 = CatPC(f1_pc_lower_result, f1_pc_high, f1_pc_high_plus1)
326e4d2f6a9Smy-mayfly
327e4d2f6a9Smy-mayfly  val f1_half_snpc_lower_result = VecInit((0 until PredictWidth).map(i => Cat(0.U(1.W), f1_ftq_req.startAddr(PcCutPoint-1, 0)) + ((i+2) * 2).U)) // cat with overflow bit
328e4d2f6a9Smy-mayfly  val f1_half_snpc            = CatPC(f1_half_snpc_lower_result, f1_pc_high, f1_pc_high_plus1)
329f2f493deSstride
330f2f493deSstride  if (env.FPGAPlatform){
331f2f493deSstride    val f1_pc_diff          = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + (i * 2).U))
332f2f493deSstride    val f1_half_snpc_diff   = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + ((i+2) * 2).U))
333f2f493deSstride
334f2f493deSstride    XSError(f1_pc.zip(f1_pc_diff).map{ case (a,b) => a.asUInt =/= b.asUInt }.reduce(_||_), "f1_half_snpc adder cut fail")
335f2f493deSstride    XSError(f1_half_snpc.zip(f1_half_snpc_diff).map{ case (a,b) => a.asUInt =/= b.asUInt }.reduce(_||_),  "f1_half_snpc adder cut fail")
336f2f493deSstride  }
337f2f493deSstride
338b92f8445Sssszwic  val f1_cut_ptr            = if(HasCExtension)  VecInit((0 until PredictWidth + 1).map(i =>  Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits-1, 1)) + i.U ))
339b92f8445Sssszwic                                  else           VecInit((0 until PredictWidth).map(i =>     Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits-1, 2)) + i.U ))
34009c6f1ddSLingrui98
34158dbdfc2SJay  /**
34258dbdfc2SJay    ******************************************************************************
34358dbdfc2SJay    * IFU Stage 2
34458dbdfc2SJay    * - icache response data (latched for pipeline stop)
34558dbdfc2SJay    * - generate exceprion bits for every instruciton (page fault/access fault/mmio)
34658dbdfc2SJay    * - generate predicted instruction range (1 means this instruciton is in this fetch packet)
34758dbdfc2SJay    * - cut data from cachlines to packet instruction code
34858dbdfc2SJay    * - instruction predecode and RVC expand
34958dbdfc2SJay    ******************************************************************************
35058dbdfc2SJay    */
35158dbdfc2SJay
3521d8f4dcbSJay  val icacheRespAllValid = WireInit(false.B)
35309c6f1ddSLingrui98
35409c6f1ddSLingrui98  val f2_valid      = RegInit(false.B)
355005e809bSJiuyang Liu  val f2_ftq_req    = RegEnable(f1_ftq_req,    f1_fire)
356005e809bSJiuyang Liu  // val f2_situation  = RegEnable(f1_situation,  f1_fire)
357005e809bSJiuyang Liu  val f2_doubleLine = RegEnable(f1_doubleLine, f1_fire)
358005e809bSJiuyang Liu  val f2_vSetIdx    = RegEnable(f1_vSetIdx,    f1_fire)
359625ecd17SJenius  val f2_fire       = f2_valid && f3_ready && icacheRespAllValid
3601d8f4dcbSJay
361625ecd17SJenius  f2_ready := f2_fire || !f2_valid
3621d8f4dcbSJay  //TODO: addr compare may be timing critical
36334a88126SJinYue  val f2_icache_all_resp_wire       =  fromICache(0).valid && (fromICache(0).bits.vaddr ===  f2_ftq_req.startAddr) && ((fromICache(1).valid && (fromICache(1).bits.vaddr ===  f2_ftq_req.nextlineStart)) || !f2_doubleLine)
3641d8f4dcbSJay  val f2_icache_all_resp_reg        = RegInit(false.B)
3651d8f4dcbSJay
3661d8f4dcbSJay  icacheRespAllValid := f2_icache_all_resp_reg || f2_icache_all_resp_wire
3671d8f4dcbSJay
368d2b20d1aSTang Haojin  icacheMissBubble := io.icacheInter.topdownIcacheMiss
369d2b20d1aSTang Haojin  itlbMissBubble   := io.icacheInter.topdownItlbMiss
370d2b20d1aSTang Haojin
3711d8f4dcbSJay  io.icacheStop := !f3_ready
3721d8f4dcbSJay
3731d8f4dcbSJay  when(f2_flush)                                              {f2_icache_all_resp_reg := false.B}
3741d8f4dcbSJay  .elsewhen(f2_valid && f2_icache_all_resp_wire && !f3_ready) {f2_icache_all_resp_reg := true.B}
3751d8f4dcbSJay  .elsewhen(f2_fire && f2_icache_all_resp_reg)                {f2_icache_all_resp_reg := false.B}
37609c6f1ddSLingrui98
37709c6f1ddSLingrui98  when(f2_flush)                  {f2_valid := false.B}
37809c6f1ddSLingrui98  .elsewhen(f1_fire && !f1_flush) {f2_valid := true.B }
37909c6f1ddSLingrui98  .elsewhen(f2_fire)              {f2_valid := false.B}
38009c6f1ddSLingrui98
38188895b11Sxu_zh  val f2_exception    = VecInit((0 until PortNumber).map(i => fromICache(i).bits.exception))
382d7ac23a3SEaston Man  // paddr and gpaddr of [startAddr, nextLineAddr]
383d7ac23a3SEaston Man  val f2_paddrs       = VecInit((0 until PortNumber).map(i => fromICache(i).bits.paddr))
38491946104Sxu_zh  val f2_gpaddr       = fromICache(0).bits.gpaddr
385002c10a4SYanqin Li
386002c10a4SYanqin Li  // FIXME: what if port 0 is not mmio, but port 1 is?
38788895b11Sxu_zh  // cancel mmio fetch if exception occurs
388002c10a4SYanqin Li  val f2_mmio         = f2_exception(0) === ExceptionType.none && (
389002c10a4SYanqin Li    fromICache(0).bits.pmp_mmio ||
390002c10a4SYanqin Li      // currently, we do not distinguish between Pbmt.nc and Pbmt.io
391002c10a4SYanqin Li      // anyway, they are both non-cacheable, and should be handled with mmio fsm and sent to Uncache module
392002c10a4SYanqin Li      Pbmt.isUncache(fromICache(0).bits.itlb_pbmt)
393002c10a4SYanqin Li  )
394002c10a4SYanqin Li
3950be662e4SJay
396e4d2f6a9Smy-mayfly  /**
397e4d2f6a9Smy-mayfly    * reduce the number of registers, origin code
398e4d2f6a9Smy-mayfly    * f2_pc = RegEnable(f1_pc, f1_fire)
399e4d2f6a9Smy-mayfly    */
400e4d2f6a9Smy-mayfly  val f2_pc_lower_result        = RegEnable(f1_pc_lower_result, f1_fire)
401e4d2f6a9Smy-mayfly  val f2_pc_high                = RegEnable(f1_pc_high, f1_fire)
402e4d2f6a9Smy-mayfly  val f2_pc_high_plus1          = RegEnable(f1_pc_high_plus1, f1_fire)
403e4d2f6a9Smy-mayfly  val f2_pc                     = CatPC(f2_pc_lower_result, f2_pc_high, f2_pc_high_plus1)
404a37fbf10SJay
405e4d2f6a9Smy-mayfly  val f2_cut_ptr                = RegEnable(f1_cut_ptr, f1_fire)
406005e809bSJiuyang Liu  val f2_resend_vaddr           = RegEnable(f1_ftq_req.startAddr + 2.U, f1_fire)
4072a3050c2SJay
4082a3050c2SJay  def isNextLine(pc: UInt, startAddr: UInt) = {
4092a3050c2SJay    startAddr(blockOffBits) ^ pc(blockOffBits)
410b6982e83SLemover  }
41109c6f1ddSLingrui98
4122a3050c2SJay  def isLastInLine(pc: UInt) = {
4132a3050c2SJay    pc(blockOffBits - 1, 0) === "b111110".U
41409c6f1ddSLingrui98  }
41509c6f1ddSLingrui98
4162a3050c2SJay  val f2_foldpc = VecInit(f2_pc.map(i => XORFold(i(VAddrBits-1,1), MemPredPCWidth)))
4172a3050c2SJay  val f2_jump_range = Fill(PredictWidth, !f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~f2_ftq_req.ftqOffset.bits
4181d011975SJinYue  val f2_ftr_range  = Fill(PredictWidth,  f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~getBasicBlockIdx(f2_ftq_req.nextStartAddr, f2_ftq_req.startAddr)
4192a3050c2SJay  val f2_instr_range = f2_jump_range & f2_ftr_range
42088895b11Sxu_zh  val f2_exception_vec = VecInit((0 until PredictWidth).map( i => MuxCase(ExceptionType.none, Seq(
42188895b11Sxu_zh      !isNextLine(f2_pc(i), f2_ftq_req.startAddr)                   -> f2_exception(0),
42288895b11Sxu_zh      (isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_doubleLine) -> f2_exception(1)
42388895b11Sxu_zh  ))))
4241d8f4dcbSJay  val f2_perf_info    = io.icachePerfInfo
42509c6f1ddSLingrui98
4262a3050c2SJay  def cut(cacheline: UInt, cutPtr: Vec[UInt]) : Vec[UInt] ={
427d558bd61SJenius    require(HasCExtension)
428d558bd61SJenius    // if(HasCExtension){
42909c6f1ddSLingrui98      val result   = Wire(Vec(PredictWidth + 1, UInt(16.W)))
430b92f8445Sssszwic      val dataVec  = cacheline.asTypeOf(Vec(blockBytes, UInt(16.W))) //32 16-bit data vector
43109c6f1ddSLingrui98      (0 until PredictWidth + 1).foreach( i =>
432d558bd61SJenius        result(i) := dataVec(cutPtr(i)) //the max ptr is 3*blockBytes/4-1
43309c6f1ddSLingrui98      )
43409c6f1ddSLingrui98      result
435d558bd61SJenius    // } else {
436d558bd61SJenius    //   val result   = Wire(Vec(PredictWidth, UInt(32.W)) )
437d558bd61SJenius    //   val dataVec  = cacheline.asTypeOf(Vec(blockBytes * 2/ 4, UInt(32.W)))
438d558bd61SJenius    //   (0 until PredictWidth).foreach( i =>
439d558bd61SJenius    //     result(i) := dataVec(cutPtr(i))
440d558bd61SJenius    //   )
441d558bd61SJenius    //   result
442d558bd61SJenius    // }
44309c6f1ddSLingrui98  }
44409c6f1ddSLingrui98
445a61a35e0Sssszwic  val f2_cache_response_data = fromICache.map(_.bits.data)
446b92f8445Sssszwic  val f2_data_2_cacheline = Cat(f2_cache_response_data(0), f2_cache_response_data(0))
447dc270d3bSJenius
448a61a35e0Sssszwic  val f2_cut_data   = cut(f2_data_2_cacheline, f2_cut_ptr)
44909c6f1ddSLingrui98
45058dbdfc2SJay  /** predecode (include RVC expander) */
451dc270d3bSJenius  // preDecoderRegIn.data := f2_reg_cut_data
452dc270d3bSJenius  // preDecoderRegInIn.frontendTrigger := io.frontendTrigger
453dc270d3bSJenius  // preDecoderRegInIn.csrTriggerEnable := io.csrTriggerEnable
454dc270d3bSJenius  // preDecoderRegIn.pc  := f2_pc
455dc270d3bSJenius
456a61a35e0Sssszwic  val preDecoderIn  = preDecoder.io.in
4579afa8a47STang Haojin  preDecoderIn.valid := f2_valid
4589afa8a47STang Haojin  preDecoderIn.bits.data := f2_cut_data
4599afa8a47STang Haojin  preDecoderIn.bits.frontendTrigger := io.frontendTrigger
4609afa8a47STang Haojin  preDecoderIn.bits.pc  := f2_pc
461a61a35e0Sssszwic  val preDecoderOut = preDecoder.io.out
46209c6f1ddSLingrui98
46348a62719SJenius  //val f2_expd_instr     = preDecoderOut.expInstr
46448a62719SJenius  val f2_instr          = preDecoderOut.instr
4652a3050c2SJay  val f2_pd             = preDecoderOut.pd
4662a3050c2SJay  val f2_jump_offset    = preDecoderOut.jumpOffset
4672a3050c2SJay  val f2_hasHalfValid   =  preDecoderOut.hasHalfValid
468a2568a60Sxu_zh  /* if there is a cross-page RVI instruction, and the former page has no exception,
469a2568a60Sxu_zh   * whether it has exception is actually depends on the latter page
470a2568a60Sxu_zh   */
471a2568a60Sxu_zh  val f2_crossPage_exception_vec = VecInit((0 until PredictWidth).map { i => Mux(
472a2568a60Sxu_zh    isLastInLine(f2_pc(i)) && !f2_pd(i).isRVC && f2_doubleLine && f2_exception(0) === ExceptionType.none,
473a2568a60Sxu_zh    f2_exception(1),
474a2568a60Sxu_zh    ExceptionType.none
475a2568a60Sxu_zh  )})
47600240ba6SJay  XSPerfAccumulate("fetch_bubble_icache_not_resp",   f2_valid && !icacheRespAllValid )
47700240ba6SJay
47809c6f1ddSLingrui98
47958dbdfc2SJay  /**
48058dbdfc2SJay    ******************************************************************************
48158dbdfc2SJay    * IFU Stage 3
48258dbdfc2SJay    * - handle MMIO instruciton
48358dbdfc2SJay    *  -send request to Uncache fetch Unit
48458dbdfc2SJay    *  -every packet include 1 MMIO instruction
48558dbdfc2SJay    *  -MMIO instructions will stop fetch pipeline until commiting from RoB
48658dbdfc2SJay    *  -flush to snpc (send ifu_redirect to Ftq)
48758dbdfc2SJay    * - Ibuffer enqueue
48858dbdfc2SJay    * - check predict result in Frontend (jalFault/retFault/notCFIFault/invalidTakenFault/targetFault)
48958dbdfc2SJay    * - handle last half RVI instruction
49058dbdfc2SJay    ******************************************************************************
49158dbdfc2SJay    */
49258dbdfc2SJay
49309c6f1ddSLingrui98  val f3_valid          = RegInit(false.B)
494005e809bSJiuyang Liu  val f3_ftq_req        = RegEnable(f2_ftq_req,    f2_fire)
495005e809bSJiuyang Liu  // val f3_situation      = RegEnable(f2_situation,  f2_fire)
496005e809bSJiuyang Liu  val f3_doubleLine     = RegEnable(f2_doubleLine, f2_fire)
497935edac4STang Haojin  val f3_fire           = io.toIbuffer.fire
4981d8f4dcbSJay
499a61a35e0Sssszwic  val f3_cut_data       = RegEnable(f2_cut_data,   f2_fire)
5001d8f4dcbSJay
50188895b11Sxu_zh  val f3_exception      = RegEnable(f2_exception,  f2_fire)
502005e809bSJiuyang Liu  val f3_mmio           = RegEnable(f2_mmio,       f2_fire)
50309c6f1ddSLingrui98
504935edac4STang Haojin  //val f3_expd_instr     = RegEnable(f2_expd_instr,  f2_fire)
505935edac4STang Haojin  val f3_instr          = RegEnable(f2_instr, f2_fire)
506*aeedc8eeSGuokai Chen  val f3_expd           = (0 until PredictWidth).map{ i =>
50748a62719SJenius    val expander       = Module(new RVCExpander)
50848a62719SJenius    expander.io.in := f3_instr(i)
509*aeedc8eeSGuokai Chen    (expander.io.out.bits, expander.io.ill)
510*aeedc8eeSGuokai Chen  }
511*aeedc8eeSGuokai Chen  val f3_expd_instr     = VecInit(f3_expd.map(_._1))
512*aeedc8eeSGuokai Chen  val f3_ill_raw        = VecInit(f3_expd.map(_._2))
513*aeedc8eeSGuokai Chen
51448a62719SJenius
515935edac4STang Haojin  val f3_pd_wire         = RegEnable(f2_pd,            f2_fire)
516330aad7fSGuokai Chen  val f3_pd              = WireInit(f3_pd_wire)
517935edac4STang Haojin  val f3_jump_offset     = RegEnable(f2_jump_offset,   f2_fire)
51888895b11Sxu_zh  val f3_exception_vec   = RegEnable(f2_exception_vec, f2_fire)
519a2568a60Sxu_zh  val f3_crossPage_exception_vec = RegEnable(f2_crossPage_exception_vec, f2_fire)
520e4d2f6a9Smy-mayfly
521e4d2f6a9Smy-mayfly  val f3_pc_lower_result = RegEnable(f2_pc_lower_result, f2_fire)
522e4d2f6a9Smy-mayfly  val f3_pc_high         = RegEnable(f2_pc_high, f2_fire)
523e4d2f6a9Smy-mayfly  val f3_pc_high_plus1   = RegEnable(f2_pc_high_plus1, f2_fire)
524e4d2f6a9Smy-mayfly  val f3_pc              = CatPC(f3_pc_lower_result, f3_pc_high, f3_pc_high_plus1)
525e4d2f6a9Smy-mayfly
526e4d2f6a9Smy-mayfly  val f3_pc_last_lower_result_plus2 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 2.U, f2_fire)
527e4d2f6a9Smy-mayfly  val f3_pc_last_lower_result_plus4 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 4.U, f2_fire)
528e4d2f6a9Smy-mayfly  //val f3_half_snpc      = RegEnable(f2_half_snpc,   f2_fire)
529e4d2f6a9Smy-mayfly
530e4d2f6a9Smy-mayfly  /**
531e4d2f6a9Smy-mayfly    ***********************************************************************
532e4d2f6a9Smy-mayfly    * Half snpc(i) is larger than pc(i) by 4. Using pc to calculate half snpc may be a good choice.
533e4d2f6a9Smy-mayfly    ***********************************************************************
534e4d2f6a9Smy-mayfly    */
535e4d2f6a9Smy-mayfly  val f3_half_snpc      = Wire(Vec(PredictWidth,UInt(VAddrBits.W)))
536e4d2f6a9Smy-mayfly  for(i <- 0 until PredictWidth){
537e4d2f6a9Smy-mayfly    if(i == (PredictWidth - 2)){
538e4d2f6a9Smy-mayfly      f3_half_snpc(i)   := CatPC(f3_pc_last_lower_result_plus2, f3_pc_high, f3_pc_high_plus1)
539e4d2f6a9Smy-mayfly    } else if (i == (PredictWidth - 1)){
540e4d2f6a9Smy-mayfly      f3_half_snpc(i)   := CatPC(f3_pc_last_lower_result_plus4, f3_pc_high, f3_pc_high_plus1)
541e4d2f6a9Smy-mayfly    } else {
542e4d2f6a9Smy-mayfly      f3_half_snpc(i)   := f3_pc(i+2)
543e4d2f6a9Smy-mayfly    }
544e4d2f6a9Smy-mayfly  }
545e4d2f6a9Smy-mayfly
546935edac4STang Haojin  val f3_instr_range    = RegEnable(f2_instr_range, f2_fire)
547935edac4STang Haojin  val f3_foldpc         = RegEnable(f2_foldpc,      f2_fire)
548935edac4STang Haojin  val f3_hasHalfValid   = RegEnable(f2_hasHalfValid,             f2_fire)
549d7ac23a3SEaston Man  val f3_paddrs         = RegEnable(f2_paddrs,  f2_fire)
55091946104Sxu_zh  val f3_gpaddr         = RegEnable(f2_gpaddr,  f2_fire)
551005e809bSJiuyang Liu  val f3_resend_vaddr   = RegEnable(f2_resend_vaddr,             f2_fire)
552ee175d78SJay
553cb6e5d3cSssszwic  // Expand 1 bit to prevent overflow when assert
554cb6e5d3cSssszwic  val f3_ftq_req_startAddr      = Cat(0.U(1.W), f3_ftq_req.startAddr)
555cb6e5d3cSssszwic  val f3_ftq_req_nextStartAddr  = Cat(0.U(1.W), f3_ftq_req.nextStartAddr)
556330aad7fSGuokai Chen  // brType, isCall and isRet generation is delayed to f3 stage
557330aad7fSGuokai Chen  val f3Predecoder = Module(new F3Predecoder)
558330aad7fSGuokai Chen
559330aad7fSGuokai Chen  f3Predecoder.io.in.instr := f3_instr
560330aad7fSGuokai Chen
561330aad7fSGuokai Chen  f3_pd.zipWithIndex.map{ case (pd,i) =>
562330aad7fSGuokai Chen    pd.brType := f3Predecoder.io.out.pd(i).brType
563330aad7fSGuokai Chen    pd.isCall := f3Predecoder.io.out.pd(i).isCall
564330aad7fSGuokai Chen    pd.isRet  := f3Predecoder.io.out.pd(i).isRet
565330aad7fSGuokai Chen  }
566330aad7fSGuokai Chen
567330aad7fSGuokai Chen  val f3PdDiff = f3_pd_wire.zip(f3_pd).map{ case (a,b) => a.asUInt =/= b.asUInt }.reduce(_||_)
568330aad7fSGuokai Chen  XSError(f3_valid && f3PdDiff, "f3 pd diff")
569330aad7fSGuokai Chen
5701d011975SJinYue  when(f3_valid && !f3_ftq_req.ftqOffset.valid){
571cb6e5d3cSssszwic    assert(f3_ftq_req_startAddr + (2*PredictWidth).U >= f3_ftq_req_nextStartAddr, s"More tha ${2*PredictWidth} Bytes fetch is not allowed!")
5721d011975SJinYue  }
573a1351e5dSJay
5742a3050c2SJay  /*** MMIO State Machine***/
575ee175d78SJay  val f3_mmio_data          = Reg(Vec(2, UInt(16.W)))
576ee175d78SJay  val mmio_is_RVC           = RegInit(false.B)
577ee175d78SJay  val mmio_resend_addr      = RegInit(0.U(PAddrBits.W))
57888895b11Sxu_zh  val mmio_resend_exception = RegInit(0.U(ExceptionType.width.W))
579b5a614b9Sxu_zh  val mmio_resend_gpaddr    = RegInit(0.U(GPAddrBits.W))
580c3b2d83aSJay
5811d1e6d4dSJenius  //last instuction finish
5821d1e6d4dSJenius  val is_first_instr = RegInit(true.B)
583ba5ba1dcSmy-mayfly  /*** Determine whether the MMIO instruction is executable based on the previous prediction block ***/
584ba5ba1dcSmy-mayfly  io.mmioCommitRead.mmioFtqPtr := RegNext(f3_ftq_req.ftqIdx - 1.U)
585a37fbf10SJay
5861d1e6d4dSJenius  val m_idle :: m_waitLastCmt:: m_sendReq :: m_waitResp :: m_sendTLB :: m_tlbResp :: m_sendPMP :: m_resendReq :: m_waitResendResp :: m_waitCommit :: m_commited :: Nil = Enum(11)
587ee175d78SJay  val mmio_state = RegInit(m_idle)
588a37fbf10SJay
5899bae7d6eSJay  val f3_req_is_mmio     = f3_mmio && f3_valid
5902a3050c2SJay  val mmio_commit = VecInit(io.rob_commits.map{commit => commit.valid && commit.bits.ftqIdx === f3_ftq_req.ftqIdx &&  commit.bits.ftqOffset === 0.U}).asUInt.orR
591ee175d78SJay  val f3_mmio_req_commit = f3_req_is_mmio && mmio_state === m_commited
592a37fbf10SJay
593ee175d78SJay  val f3_mmio_to_commit =  f3_req_is_mmio && mmio_state === m_waitCommit
594a37fbf10SJay  val f3_mmio_to_commit_next = RegNext(f3_mmio_to_commit)
595a37fbf10SJay  val f3_mmio_can_go      = f3_mmio_to_commit && !f3_mmio_to_commit_next
596a37fbf10SJay
5970c70648eSEaston Man  val fromFtqRedirectReg = Wire(fromFtq.redirect.cloneType)
5980c70648eSEaston Man  fromFtqRedirectReg.bits := RegEnable(fromFtq.redirect.bits, 0.U.asTypeOf(fromFtq.redirect.bits), fromFtq.redirect.valid)
5990c70648eSEaston Man  fromFtqRedirectReg.valid := RegNext(fromFtq.redirect.valid, init = false.B)
6004a74a727SJenius  val mmioF3Flush           = RegNext(f3_flush,init = false.B)
60156788a33SJinYue  val f3_ftq_flush_self     = fromFtqRedirectReg.valid && RedirectLevel.flushItself(fromFtqRedirectReg.bits.level)
60256788a33SJinYue  val f3_ftq_flush_by_older = fromFtqRedirectReg.valid && isBefore(fromFtqRedirectReg.bits.ftqIdx, f3_ftq_req.ftqIdx)
6039bae7d6eSJay
60456788a33SJinYue  val f3_need_not_flush = f3_req_is_mmio && fromFtqRedirectReg.valid && !f3_ftq_flush_self && !f3_ftq_flush_by_older
6059bae7d6eSJay
606ba5ba1dcSmy-mayfly  /**
607ba5ba1dcSmy-mayfly    **********************************************************************************
608ba5ba1dcSmy-mayfly    * We want to defer instruction fetching when encountering MMIO instructions to ensure that the MMIO region is not negatively impacted.
609ba5ba1dcSmy-mayfly    * This is the exception when the first instruction is an MMIO instruction.
610ba5ba1dcSmy-mayfly    **********************************************************************************
611ba5ba1dcSmy-mayfly    */
612ba5ba1dcSmy-mayfly  when(is_first_instr && f3_fire){
6131d1e6d4dSJenius    is_first_instr := false.B
6141d1e6d4dSJenius  }
6151d1e6d4dSJenius
6164a74a727SJenius  when(f3_flush && !f3_req_is_mmio)                                                 {f3_valid := false.B}
6174a74a727SJenius  .elsewhen(mmioF3Flush && f3_req_is_mmio && !f3_need_not_flush)                    {f3_valid := false.B}
618a37fbf10SJay  .elsewhen(f2_fire && !f2_flush )                                                  {f3_valid := true.B }
619935edac4STang Haojin  .elsewhen(io.toIbuffer.fire && !f3_req_is_mmio)                                   {f3_valid := false.B}
620a37fbf10SJay  .elsewhen{f3_req_is_mmio && f3_mmio_req_commit}                                   {f3_valid := false.B}
621a37fbf10SJay
622a37fbf10SJay  val f3_mmio_use_seq_pc = RegInit(false.B)
623a37fbf10SJay
62456788a33SJinYue  val (redirect_ftqIdx, redirect_ftqOffset)  = (fromFtqRedirectReg.bits.ftqIdx,fromFtqRedirectReg.bits.ftqOffset)
62556788a33SJinYue  val redirect_mmio_req = fromFtqRedirectReg.valid && redirect_ftqIdx === f3_ftq_req.ftqIdx && redirect_ftqOffset === 0.U
626a37fbf10SJay
627a37fbf10SJay  when(RegNext(f2_fire && !f2_flush) && f3_req_is_mmio)        { f3_mmio_use_seq_pc := true.B  }
628a37fbf10SJay  .elsewhen(redirect_mmio_req)                                 { f3_mmio_use_seq_pc := false.B }
629a37fbf10SJay
6308c192ff7Sxu_zh  f3_ready := (io.toIbuffer.ready && (f3_mmio_req_commit || !f3_req_is_mmio)) || !f3_valid
631a37fbf10SJay
6321d1e6d4dSJenius  // mmio state machine
633a37fbf10SJay  switch(mmio_state){
634ee175d78SJay    is(m_idle){
6359bae7d6eSJay      when(f3_req_is_mmio){
6361d1e6d4dSJenius        mmio_state := m_waitLastCmt
6371d1e6d4dSJenius      }
6381d1e6d4dSJenius    }
6391d1e6d4dSJenius
6401d1e6d4dSJenius    is(m_waitLastCmt){
6411d1e6d4dSJenius      when(is_first_instr){
642ee175d78SJay        mmio_state := m_sendReq
6431d1e6d4dSJenius      }.otherwise{
6441d1e6d4dSJenius        mmio_state := Mux(io.mmioCommitRead.mmioLastCommit, m_sendReq, m_waitLastCmt)
645a37fbf10SJay      }
646a37fbf10SJay    }
647a37fbf10SJay
648ee175d78SJay    is(m_sendReq){
649935edac4STang Haojin      mmio_state := Mux(toUncache.fire, m_waitResp, m_sendReq)
650a37fbf10SJay    }
651a37fbf10SJay
652ee175d78SJay    is(m_waitResp){
653935edac4STang Haojin      when(fromUncache.fire){
654a37fbf10SJay          val isRVC = fromUncache.bits.data(1,0) =/= 3.U
655d7ac23a3SEaston Man          val needResend = !isRVC && f3_paddrs(0)(2,1) === 3.U
656ee175d78SJay          mmio_state      := Mux(needResend, m_sendTLB, m_waitCommit)
657ee175d78SJay          mmio_is_RVC     := isRVC
658ee175d78SJay          f3_mmio_data(0) := fromUncache.bits.data(15,0)
659ee175d78SJay          f3_mmio_data(1) := fromUncache.bits.data(31,16)
660a37fbf10SJay      }
661a37fbf10SJay    }
662a37fbf10SJay
663ee175d78SJay    is(m_sendTLB){
6647b7232f9Sxu_zh      mmio_state := Mux(io.iTLBInter.req.fire, m_tlbResp, m_sendTLB)
665c3b2d83aSJay    }
666a37fbf10SJay
667ee175d78SJay    is(m_tlbResp){
6687b7232f9Sxu_zh      when(io.iTLBInter.resp.fire) {
6697b7232f9Sxu_zh        // we are using a blocked tlb, so resp.fire must have !resp.bits.miss
6707b7232f9Sxu_zh        assert(!io.iTLBInter.resp.bits.miss, "blocked mode iTLB miss when resp.fire")
67188895b11Sxu_zh        val tlb_exception = ExceptionType.fromTlbResp(io.iTLBInter.resp.bits)
6727b7232f9Sxu_zh        // if tlb has exception, abort checking pmp, just send instr & exception to ibuffer and wait for commit
67388895b11Sxu_zh        mmio_state := Mux(tlb_exception === ExceptionType.none, m_sendPMP, m_waitCommit)
6747b7232f9Sxu_zh        // also save itlb response
67503efd994Shappy-lx        mmio_resend_addr      := io.iTLBInter.resp.bits.paddr(0)
67688895b11Sxu_zh        mmio_resend_exception := tlb_exception
677b5a614b9Sxu_zh        mmio_resend_gpaddr    := io.iTLBInter.resp.bits.gpaddr(0)
678ee175d78SJay      }
6797b7232f9Sxu_zh    }
680ee175d78SJay
681ee175d78SJay    is(m_sendPMP){
68288895b11Sxu_zh      // if pmp re-check does not respond mmio, must be access fault
68388895b11Sxu_zh      val pmp_exception = Mux(io.pmp.resp.mmio, ExceptionType.fromPMPResp(io.pmp.resp), ExceptionType.af)
68488895b11Sxu_zh      // if pmp has exception, abort sending request, just send instr & exception to ibuffer and wait for commit
68588895b11Sxu_zh      mmio_state := Mux(pmp_exception === ExceptionType.none, m_resendReq, m_waitCommit)
68688895b11Sxu_zh      // also save pmp response
68788895b11Sxu_zh      mmio_resend_exception := pmp_exception
688ee175d78SJay    }
689ee175d78SJay
690ee175d78SJay    is(m_resendReq){
691935edac4STang Haojin      mmio_state := Mux(toUncache.fire, m_waitResendResp, m_resendReq)
692ee175d78SJay    }
693ee175d78SJay
694ee175d78SJay    is(m_waitResendResp) {
695935edac4STang Haojin      when(fromUncache.fire) {
696ee175d78SJay        mmio_state      := m_waitCommit
697ee175d78SJay        f3_mmio_data(1) := fromUncache.bits.data(15,0)
698a37fbf10SJay      }
699a37fbf10SJay    }
700a37fbf10SJay
701ee175d78SJay    is(m_waitCommit) {
7027b7232f9Sxu_zh      mmio_state := Mux(mmio_commit, m_commited, m_waitCommit)
703a37fbf10SJay    }
7042a3050c2SJay
705ee175d78SJay    //normal mmio instruction
706ee175d78SJay    is(m_commited) {
707ee175d78SJay      mmio_state            := m_idle
708ee175d78SJay      mmio_is_RVC           := false.B
709ee175d78SJay      mmio_resend_addr      := 0.U
71088895b11Sxu_zh      mmio_resend_exception := ExceptionType.none
711b5a614b9Sxu_zh      mmio_resend_gpaddr    := 0.U
7122a3050c2SJay    }
713a37fbf10SJay  }
714a37fbf10SJay
7158abe1810SEaston Man  // Exception or flush by older branch prediction
7168abe1810SEaston Man  // Condition is from RegNext(fromFtq.redirect), 1 cycle after backend rediect
717167bcd01SJay  when(f3_ftq_flush_self || f3_ftq_flush_by_older) {
718ee175d78SJay    mmio_state            := m_idle
719ee175d78SJay    mmio_is_RVC           := false.B
720ee175d78SJay    mmio_resend_addr      := 0.U
72188895b11Sxu_zh    mmio_resend_exception := ExceptionType.none
722b5a614b9Sxu_zh    mmio_resend_gpaddr    := 0.U
723ee175d78SJay    f3_mmio_data.map(_ := 0.U)
7249bae7d6eSJay  }
7259bae7d6eSJay
726ee175d78SJay  toUncache.valid     := ((mmio_state === m_sendReq) || (mmio_state === m_resendReq)) && f3_req_is_mmio
727d7ac23a3SEaston Man  toUncache.bits.addr := Mux((mmio_state === m_resendReq), mmio_resend_addr, f3_paddrs(0))
728a37fbf10SJay  fromUncache.ready   := true.B
729a37fbf10SJay
7307b7232f9Sxu_zh  // send itlb request in m_sendTLB state
731ee175d78SJay  io.iTLBInter.req.valid                   := (mmio_state === m_sendTLB) && f3_req_is_mmio
732ee175d78SJay  io.iTLBInter.req.bits.size               := 3.U
733ee175d78SJay  io.iTLBInter.req.bits.vaddr              := f3_resend_vaddr
734ee175d78SJay  io.iTLBInter.req.bits.debug.pc           := f3_resend_vaddr
7357b7232f9Sxu_zh  io.iTLBInter.req.bits.cmd                := TlbCmd.exec
7367b7232f9Sxu_zh  io.iTLBInter.req.bits.kill               := false.B // IFU use itlb for mmio, doesn't need sync, set it to false
7377b7232f9Sxu_zh  io.iTLBInter.req.bits.no_translate       := false.B
738d0de7e4aSpeixiaokun  io.iTLBInter.req.bits.hyperinst          := DontCare
739d0de7e4aSpeixiaokun  io.iTLBInter.req.bits.hlvx               := DontCare
7408744445eSMaxpicca-Li  io.iTLBInter.req.bits.memidx             := DontCare
741f1fe8698SLemover  io.iTLBInter.req.bits.debug.robIdx       := DontCare
742ee175d78SJay  io.iTLBInter.req.bits.debug.isFirstIssue := DontCare
743149a2326Sweiding liu  io.iTLBInter.req.bits.pmp_addr           := DontCare
7447b7232f9Sxu_zh  // whats the difference between req_kill and req.bits.kill?
7457b7232f9Sxu_zh  io.iTLBInter.req_kill := false.B
7467b7232f9Sxu_zh  // wait for itlb response in m_tlbResp state
7477b7232f9Sxu_zh  io.iTLBInter.resp.ready := (mmio_state === m_tlbResp) && f3_req_is_mmio
748ee175d78SJay
749ee175d78SJay  io.pmp.req.valid := (mmio_state === m_sendPMP) && f3_req_is_mmio
750ee175d78SJay  io.pmp.req.bits.addr  := mmio_resend_addr
751ee175d78SJay  io.pmp.req.bits.size  := 3.U
752ee175d78SJay  io.pmp.req.bits.cmd   := TlbCmd.exec
753f7c29b0aSJinYue
7542a3050c2SJay  val f3_lastHalf       = RegInit(0.U.asTypeOf(new LastHalfInfo))
75509c6f1ddSLingrui98
75609c6f1ddSLingrui98  val f3_predecode_range = VecInit(preDecoderOut.pd.map(inst => inst.valid)).asUInt
7570be662e4SJay  val f3_mmio_range      = VecInit((0 until PredictWidth).map(i => if(i ==0) true.B else false.B))
7582a3050c2SJay  val f3_instr_valid     = Wire(Vec(PredictWidth, Bool()))
75909c6f1ddSLingrui98
760*aeedc8eeSGuokai Chen  // Illegal instruction record
761*aeedc8eeSGuokai Chen  val f3_ill            = VecInit((0 until PredictWidth).map{ i =>
762*aeedc8eeSGuokai Chen    f3_ill_raw(i) && f3_instr_valid(i)
763*aeedc8eeSGuokai Chen  })
764*aeedc8eeSGuokai Chen  val f4_instr = RegEnable(f3_instr, f3_fire)
765*aeedc8eeSGuokai Chen  val f4_ill = RegEnable(f3_ill, f3_fire)
766*aeedc8eeSGuokai Chen  val illegalBuf = RegInit(0.U(32.W))
767*aeedc8eeSGuokai Chen
768*aeedc8eeSGuokai Chen  val illBufClear = RegInit(true.B)
769*aeedc8eeSGuokai Chen
770*aeedc8eeSGuokai Chen  dontTouch(illegalBuf)
771*aeedc8eeSGuokai Chen  when (f4_ill.asUInt.orR && RegNext(f3_fire) && illBufClear) {
772*aeedc8eeSGuokai Chen    illegalBuf := ParallelPriorityMux(f4_ill, f4_instr)
773*aeedc8eeSGuokai Chen    illBufClear := false.B
774*aeedc8eeSGuokai Chen  }
775*aeedc8eeSGuokai Chen
776*aeedc8eeSGuokai Chen  when (backend_redirect || wb_redirect) {
777*aeedc8eeSGuokai Chen    illBufClear := true.B
778*aeedc8eeSGuokai Chen  }
779*aeedc8eeSGuokai Chen
780*aeedc8eeSGuokai Chen  io.illBuf := illegalBuf
781*aeedc8eeSGuokai Chen
7822a3050c2SJay  /*** prediction result check   ***/
7832a3050c2SJay  checkerIn.ftqOffset   := f3_ftq_req.ftqOffset
7842a3050c2SJay  checkerIn.jumpOffset  := f3_jump_offset
7856ce52296SJinYue  checkerIn.target      := f3_ftq_req.nextStartAddr
7862a3050c2SJay  checkerIn.instrRange  := f3_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
7872a3050c2SJay  checkerIn.instrValid  := f3_instr_valid.asTypeOf(Vec(PredictWidth, Bool()))
7882a3050c2SJay  checkerIn.pds         := f3_pd
7892a3050c2SJay  checkerIn.pc          := f3_pc
7900c70648eSEaston Man  checkerIn.fire_in     := RegNext(f2_fire, init = false.B)
7912a3050c2SJay
79258dbdfc2SJay  /*** handle half RVI in the last 2 Bytes  ***/
7932a3050c2SJay
7942a3050c2SJay  def hasLastHalf(idx: UInt) = {
7955995c9e7SJenius    //!f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(idx) && !checkerOutStage2.fixedMissPred(idx) && ! f3_req_is_mmio
7965995c9e7SJenius    !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(idx) && ! f3_req_is_mmio
7972a3050c2SJay  }
7982a3050c2SJay
799b665b650STang Haojin  val f3_last_validIdx       = ParallelPosteriorityEncoder(checkerOutStage1.fixedRange)
8002a3050c2SJay
8012a3050c2SJay  val f3_hasLastHalf         = hasLastHalf((PredictWidth - 1).U)
8022a3050c2SJay  val f3_false_lastHalf      = hasLastHalf(f3_last_validIdx)
8032a3050c2SJay  val f3_false_snpc          = f3_half_snpc(f3_last_validIdx)
8042a3050c2SJay
805935edac4STang Haojin  val f3_lastHalf_mask    = VecInit((0 until PredictWidth).map( i => if(i ==0) false.B else true.B )).asUInt
8063f785aa3SJenius  val f3_lastHalf_disable = RegInit(false.B)
8072a3050c2SJay
808804985a5SJenius  when(f3_flush || (f3_fire && f3_lastHalf_disable)){
809804985a5SJenius    f3_lastHalf_disable := false.B
810804985a5SJenius  }
811804985a5SJenius
8122a3050c2SJay  when (f3_flush) {
8132a3050c2SJay    f3_lastHalf.valid := false.B
8142a3050c2SJay  }.elsewhen (f3_fire) {
8153f785aa3SJenius    f3_lastHalf.valid := f3_hasLastHalf && !f3_lastHalf_disable
8166ce52296SJinYue    f3_lastHalf.middlePC := f3_ftq_req.nextStartAddr
8172a3050c2SJay  }
8182a3050c2SJay
8192a3050c2SJay  f3_instr_valid := Mux(f3_lastHalf.valid,f3_hasHalfValid ,VecInit(f3_pd.map(inst => inst.valid)))
8202a3050c2SJay
8212a3050c2SJay  /*** frontend Trigger  ***/
8222a3050c2SJay  frontendTrigger.io.pds  := f3_pd
8232a3050c2SJay  frontendTrigger.io.pc   := f3_pc
8242a3050c2SJay  frontendTrigger.io.data   := f3_cut_data
8252a3050c2SJay
8262a3050c2SJay  frontendTrigger.io.frontendTrigger  := io.frontendTrigger
8272a3050c2SJay
8282a3050c2SJay  val f3_triggered = frontendTrigger.io.triggered
82991946104Sxu_zh  val f3_toIbuffer_valid = f3_valid && (!f3_req_is_mmio || f3_mmio_can_go) && !f3_flush
8302a3050c2SJay
8312a3050c2SJay  /*** send to Ibuffer  ***/
83291946104Sxu_zh  io.toIbuffer.valid            := f3_toIbuffer_valid
8332a3050c2SJay  io.toIbuffer.bits.instrs      := f3_expd_instr
8342a3050c2SJay  io.toIbuffer.bits.valid       := f3_instr_valid.asUInt
8355995c9e7SJenius  io.toIbuffer.bits.enqEnable   := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt
8362a3050c2SJay  io.toIbuffer.bits.pd          := f3_pd
83709c6f1ddSLingrui98  io.toIbuffer.bits.ftqPtr      := f3_ftq_req.ftqIdx
8382a3050c2SJay  io.toIbuffer.bits.pc          := f3_pc
8395995c9e7SJenius  io.toIbuffer.bits.ftqOffset.zipWithIndex.map{case(a, i) => a.bits := i.U; a.valid := checkerOutStage1.fixedTaken(i) && !f3_req_is_mmio}
8402a3050c2SJay  io.toIbuffer.bits.foldpc      := f3_foldpc
841a2568a60Sxu_zh  io.toIbuffer.bits.exceptionType := ExceptionType.merge(f3_exception_vec, f3_crossPage_exception_vec)
842a2568a60Sxu_zh  io.toIbuffer.bits.crossPageIPFFix := f3_crossPage_exception_vec.map(_ =/= ExceptionType.none)
8432a3050c2SJay  io.toIbuffer.bits.triggered   := f3_triggered
8442a3050c2SJay
8452a3050c2SJay  when(f3_lastHalf.valid){
8465995c9e7SJenius    io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt & f3_lastHalf_mask
8472a3050c2SJay    io.toIbuffer.bits.valid     := f3_lastHalf_mask & f3_instr_valid.asUInt
8482a3050c2SJay  }
8492a3050c2SJay
850d7ac23a3SEaston Man  /** to backend */
85191946104Sxu_zh  // f3_gpaddr is valid iff gpf is detected
852b5a614b9Sxu_zh  io.toBackend.gpaddrMem_wen   := f3_toIbuffer_valid && Mux(
853b5a614b9Sxu_zh    f3_req_is_mmio,
85488895b11Sxu_zh    mmio_resend_exception === ExceptionType.gpf,
85588895b11Sxu_zh    f3_exception.map(_ === ExceptionType.gpf).reduce(_||_)
856b5a614b9Sxu_zh  )
857d7ac23a3SEaston Man  io.toBackend.gpaddrMem_waddr := f3_ftq_req.ftqIdx.value
858b5a614b9Sxu_zh  io.toBackend.gpaddrMem_wdata := Mux(f3_req_is_mmio, mmio_resend_gpaddr, f3_gpaddr)
85909c6f1ddSLingrui98
86009c6f1ddSLingrui98  //Write back to Ftq
861a37fbf10SJay  val f3_cache_fetch = f3_valid && !(f2_fire && !f2_flush)
862a37fbf10SJay  val finishFetchMaskReg = RegNext(f3_cache_fetch)
863a37fbf10SJay
8642a3050c2SJay  val mmioFlushWb = Wire(Valid(new PredecodeWritebackBundle))
8650be662e4SJay  val f3_mmio_missOffset = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
866a37fbf10SJay  f3_mmio_missOffset.valid := f3_req_is_mmio
8670be662e4SJay  f3_mmio_missOffset.bits  := 0.U
8680be662e4SJay
8698abe1810SEaston Man  // Send mmioFlushWb back to FTQ 1 cycle after uncache fetch return
8708abe1810SEaston Man  // When backend redirect, mmio_state reset after 1 cycle.
8718abe1810SEaston Man  // In this case, mask .valid to avoid overriding backend redirect
8728abe1810SEaston Man  mmioFlushWb.valid           := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) &&
8738abe1810SEaston Man    f3_mmio_use_seq_pc && !f3_ftq_flush_self && !f3_ftq_flush_by_older)
8742a3050c2SJay  mmioFlushWb.bits.pc         := f3_pc
8752a3050c2SJay  mmioFlushWb.bits.pd         := f3_pd
8762a3050c2SJay  mmioFlushWb.bits.pd.zipWithIndex.map{case(instr,i) => instr.valid :=  f3_mmio_range(i)}
8772a3050c2SJay  mmioFlushWb.bits.ftqIdx     := f3_ftq_req.ftqIdx
8782a3050c2SJay  mmioFlushWb.bits.ftqOffset  := f3_ftq_req.ftqOffset.bits
8792a3050c2SJay  mmioFlushWb.bits.misOffset  := f3_mmio_missOffset
8802a3050c2SJay  mmioFlushWb.bits.cfiOffset  := DontCare
881ee175d78SJay  mmioFlushWb.bits.target     := Mux(mmio_is_RVC, f3_ftq_req.startAddr + 2.U , f3_ftq_req.startAddr + 4.U)
8822a3050c2SJay  mmioFlushWb.bits.jalTarget  := DontCare
8832a3050c2SJay  mmioFlushWb.bits.instrRange := f3_mmio_range
88409c6f1ddSLingrui98
8852dfa9e76SJenius  /** external predecode for MMIO instruction */
8862dfa9e76SJenius  when(f3_req_is_mmio){
8872dfa9e76SJenius    val inst  = Cat(f3_mmio_data(1), f3_mmio_data(0))
8882dfa9e76SJenius    val currentIsRVC   = isRVC(inst)
8892dfa9e76SJenius
8902dfa9e76SJenius    val brType::isCall::isRet::Nil = brInfo(inst)
8912dfa9e76SJenius    val jalOffset = jal_offset(inst, currentIsRVC)
8922dfa9e76SJenius    val brOffset  = br_offset(inst, currentIsRVC)
8932dfa9e76SJenius
894195ef4a5STang Haojin    io.toIbuffer.bits.instrs(0) := new RVCDecoder(inst, XLEN, fLen, useAddiForMv = true).decode.bits
8952dfa9e76SJenius
8962dfa9e76SJenius
8972dfa9e76SJenius    io.toIbuffer.bits.pd(0).valid   := true.B
8982dfa9e76SJenius    io.toIbuffer.bits.pd(0).isRVC   := currentIsRVC
8992dfa9e76SJenius    io.toIbuffer.bits.pd(0).brType  := brType
9002dfa9e76SJenius    io.toIbuffer.bits.pd(0).isCall  := isCall
9012dfa9e76SJenius    io.toIbuffer.bits.pd(0).isRet   := isRet
9022dfa9e76SJenius
90388895b11Sxu_zh    io.toIbuffer.bits.exceptionType(0)   := mmio_resend_exception
904a2568a60Sxu_zh    io.toIbuffer.bits.crossPageIPFFix(0) := mmio_resend_exception =/= ExceptionType.none
9052dfa9e76SJenius
9062dfa9e76SJenius    io.toIbuffer.bits.enqEnable   := f3_mmio_range.asUInt
9072dfa9e76SJenius
9082dfa9e76SJenius    mmioFlushWb.bits.pd(0).valid   := true.B
9092dfa9e76SJenius    mmioFlushWb.bits.pd(0).isRVC   := currentIsRVC
9102dfa9e76SJenius    mmioFlushWb.bits.pd(0).brType  := brType
9112dfa9e76SJenius    mmioFlushWb.bits.pd(0).isCall  := isCall
9122dfa9e76SJenius    mmioFlushWb.bits.pd(0).isRet   := isRet
9132dfa9e76SJenius  }
9142dfa9e76SJenius
915935edac4STang Haojin  mmio_redirect := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire)  && f3_mmio_use_seq_pc)
91609c6f1ddSLingrui98
91700240ba6SJay  XSPerfAccumulate("fetch_bubble_ibuffer_not_ready",   io.toIbuffer.valid && !io.toIbuffer.ready )
91800240ba6SJay
91900240ba6SJay
92058dbdfc2SJay  /**
92158dbdfc2SJay    ******************************************************************************
92258dbdfc2SJay    * IFU Write Back Stage
92358dbdfc2SJay    * - write back predecode information to Ftq to update
92458dbdfc2SJay    * - redirect if found fault prediction
92558dbdfc2SJay    * - redirect if has false hit last half (last PC is not start + 32 Bytes, but in the midle of an notCFI RVI instruction)
92658dbdfc2SJay    ******************************************************************************
9272a3050c2SJay    */
9280c70648eSEaston Man  val wb_enable         = RegNext(f2_fire && !f2_flush) && !f3_req_is_mmio && !f3_flush
9290c70648eSEaston Man  val wb_valid          = RegNext(wb_enable, init = false.B)
9300c70648eSEaston Man  val wb_ftq_req        = RegEnable(f3_ftq_req, wb_enable)
93158dbdfc2SJay
9320c70648eSEaston Man  val wb_check_result_stage1   = RegEnable(checkerOutStage1, wb_enable)
9335995c9e7SJenius  val wb_check_result_stage2   = checkerOutStage2
9340c70648eSEaston Man  val wb_instr_range    = RegEnable(io.toIbuffer.bits.enqEnable, wb_enable)
935e4d2f6a9Smy-mayfly
936e4d2f6a9Smy-mayfly  val wb_pc_lower_result        = RegEnable(f3_pc_lower_result, wb_enable)
937e4d2f6a9Smy-mayfly  val wb_pc_high                = RegEnable(f3_pc_high, wb_enable)
938e4d2f6a9Smy-mayfly  val wb_pc_high_plus1          = RegEnable(f3_pc_high_plus1, wb_enable)
939e4d2f6a9Smy-mayfly  val wb_pc                     = CatPC(wb_pc_lower_result, wb_pc_high, wb_pc_high_plus1)
940e4d2f6a9Smy-mayfly
941e4d2f6a9Smy-mayfly  //val wb_pc             = RegEnable(f3_pc, wb_enable)
9420c70648eSEaston Man  val wb_pd             = RegEnable(f3_pd, wb_enable)
9430c70648eSEaston Man  val wb_instr_valid    = RegEnable(f3_instr_valid, wb_enable)
9442a3050c2SJay
9452a3050c2SJay  /* false hit lastHalf */
9460c70648eSEaston Man  val wb_lastIdx        = RegEnable(f3_last_validIdx, wb_enable)
9470c70648eSEaston Man  val wb_false_lastHalf = RegEnable(f3_false_lastHalf, wb_enable) && wb_lastIdx =/= (PredictWidth - 1).U
9480c70648eSEaston Man  val wb_false_target   = RegEnable(f3_false_snpc, wb_enable)
9492a3050c2SJay
9502a3050c2SJay  val wb_half_flush = wb_false_lastHalf
9512a3050c2SJay  val wb_half_target = wb_false_target
9522a3050c2SJay
953a1351e5dSJay  /* false oversize */
954a1351e5dSJay  val lastIsRVC = wb_instr_range.asTypeOf(Vec(PredictWidth,Bool())).last  && wb_pd.last.isRVC
955a1351e5dSJay  val lastIsRVI = wb_instr_range.asTypeOf(Vec(PredictWidth,Bool()))(PredictWidth - 2) && !wb_pd(PredictWidth - 2).isRVC
9565995c9e7SJenius  val lastTaken = wb_check_result_stage1.fixedTaken.last
957a1351e5dSJay
9582a3050c2SJay  f3_wb_not_flush := wb_ftq_req.ftqIdx === f3_ftq_req.ftqIdx && f3_valid && wb_valid
9592a3050c2SJay
9603f785aa3SJenius  /** if a req with a last half but miss predicted enters in wb stage, and this cycle f3 stalls,
9613f785aa3SJenius    * we set a flag to notify f3 that the last half flag need not to be set.
9623f785aa3SJenius    */
963804985a5SJenius  //f3_fire is after wb_valid
964076dea5fSJenius  when(wb_valid && RegNext(f3_hasLastHalf,init = false.B)
965251a37e4SJenius        && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && !f3_fire  && !RegNext(f3_fire,init = false.B) && !f3_flush
9663f785aa3SJenius      ){
9673f785aa3SJenius    f3_lastHalf_disable := true.B
968ab6202e2SJenius  }
969ab6202e2SJenius
970804985a5SJenius  //wb_valid and f3_fire are in same cycle
971076dea5fSJenius  when(wb_valid && RegNext(f3_hasLastHalf,init = false.B)
972076dea5fSJenius        && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && f3_fire
973804985a5SJenius      ){
974804985a5SJenius    f3_lastHalf.valid := false.B
975804985a5SJenius  }
976804985a5SJenius
9772a3050c2SJay  val checkFlushWb = Wire(Valid(new PredecodeWritebackBundle))
978b665b650STang Haojin  val checkFlushWbjalTargetIdx = ParallelPriorityEncoder(VecInit(wb_pd.zip(wb_instr_valid).map{case (pd, v) => v && pd.isJal }))
979b665b650STang Haojin  val checkFlushWbTargetIdx = ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
9802a3050c2SJay  checkFlushWb.valid                  := wb_valid
9812a3050c2SJay  checkFlushWb.bits.pc                := wb_pc
9822a3050c2SJay  checkFlushWb.bits.pd                := wb_pd
9832a3050c2SJay  checkFlushWb.bits.pd.zipWithIndex.map{case(instr,i) => instr.valid := wb_instr_valid(i)}
9842a3050c2SJay  checkFlushWb.bits.ftqIdx            := wb_ftq_req.ftqIdx
9852a3050c2SJay  checkFlushWb.bits.ftqOffset         := wb_ftq_req.ftqOffset.bits
9865995c9e7SJenius  checkFlushWb.bits.misOffset.valid   := ParallelOR(wb_check_result_stage2.fixedMissPred) || wb_half_flush
9875995c9e7SJenius  checkFlushWb.bits.misOffset.bits    := Mux(wb_half_flush, wb_lastIdx, ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred))
9885995c9e7SJenius  checkFlushWb.bits.cfiOffset.valid   := ParallelOR(wb_check_result_stage1.fixedTaken)
9895995c9e7SJenius  checkFlushWb.bits.cfiOffset.bits    := ParallelPriorityEncoder(wb_check_result_stage1.fixedTaken)
990b665b650STang Haojin  checkFlushWb.bits.target            := Mux(wb_half_flush, wb_half_target, wb_check_result_stage2.fixedTarget(checkFlushWbTargetIdx))
991d10ddd67SGuokai Chen  checkFlushWb.bits.jalTarget         := wb_check_result_stage2.jalTarget(checkFlushWbjalTargetIdx)
9922a3050c2SJay  checkFlushWb.bits.instrRange        := wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
9932a3050c2SJay
994bccc5520SJenius  toFtq.pdWb := Mux(wb_valid, checkFlushWb,  mmioFlushWb)
9952a3050c2SJay
9962a3050c2SJay  wb_redirect := checkFlushWb.bits.misOffset.valid && wb_valid
99709c6f1ddSLingrui98
9985b3c20f7SJinYue  /*write back flush type*/
9995995c9e7SJenius  val checkFaultType = wb_check_result_stage2.faultType
10005b3c20f7SJinYue  val checkJalFault =  wb_valid && checkFaultType.map(_.isjalFault).reduce(_||_)
10015b3c20f7SJinYue  val checkRetFault =  wb_valid && checkFaultType.map(_.isRetFault).reduce(_||_)
10025b3c20f7SJinYue  val checkTargetFault =  wb_valid && checkFaultType.map(_.istargetFault).reduce(_||_)
10035b3c20f7SJinYue  val checkNotCFIFault =  wb_valid && checkFaultType.map(_.notCFIFault).reduce(_||_)
10045b3c20f7SJinYue  val checkInvalidTaken =  wb_valid && checkFaultType.map(_.invalidTakenFault).reduce(_||_)
10055b3c20f7SJinYue
10065b3c20f7SJinYue
10075b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_jalFault",   checkJalFault )
10085b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_retFault",   checkRetFault )
10095b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_targetFault",   checkTargetFault )
10105b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_notCFIFault",   checkNotCFIFault )
10115b3c20f7SJinYue  XSPerfAccumulate("predecode_flush_incalidTakenFault",   checkInvalidTaken )
10125b3c20f7SJinYue
10135b3c20f7SJinYue  when(checkRetFault){
10145b3c20f7SJinYue    XSDebug("startAddr:%x  nextstartAddr:%x  taken:%d    takenIdx:%d\n",
10155b3c20f7SJinYue        wb_ftq_req.startAddr, wb_ftq_req.nextStartAddr, wb_ftq_req.ftqOffset.valid, wb_ftq_req.ftqOffset.bits)
10165b3c20f7SJinYue  }
10175b3c20f7SJinYue
101851532d8bSGuokai Chen
10191d8f4dcbSJay  /** performance counter */
1020005e809bSJiuyang Liu  val f3_perf_info     = RegEnable(f2_perf_info,  f2_fire)
1021935edac4STang Haojin  val f3_req_0    = io.toIbuffer.fire
1022935edac4STang Haojin  val f3_req_1    = io.toIbuffer.fire && f3_doubleLine
1023935edac4STang Haojin  val f3_hit_0    = io.toIbuffer.fire && f3_perf_info.bank_hit(0)
1024935edac4STang Haojin  val f3_hit_1    = io.toIbuffer.fire && f3_doubleLine & f3_perf_info.bank_hit(1)
10251d8f4dcbSJay  val f3_hit      = f3_perf_info.hit
1026cd365d4cSrvcoresjw  val perfEvents = Seq(
10272a3050c2SJay    ("frontendFlush                ", wb_redirect                                ),
1028935edac4STang Haojin    ("ifu_req                      ", io.toIbuffer.fire                        ),
1029935edac4STang Haojin    ("ifu_miss                     ", io.toIbuffer.fire && !f3_perf_info.hit   ),
1030cd365d4cSrvcoresjw    ("ifu_req_cacheline_0          ", f3_req_0                                   ),
1031cd365d4cSrvcoresjw    ("ifu_req_cacheline_1          ", f3_req_1                                   ),
1032cd365d4cSrvcoresjw    ("ifu_req_cacheline_0_hit      ", f3_hit_1                                   ),
1033cd365d4cSrvcoresjw    ("ifu_req_cacheline_1_hit      ", f3_hit_1                                   ),
1034935edac4STang Haojin    ("only_0_hit                   ", f3_perf_info.only_0_hit       && io.toIbuffer.fire ),
1035935edac4STang Haojin    ("only_0_miss                  ", f3_perf_info.only_0_miss      && io.toIbuffer.fire ),
1036935edac4STang Haojin    ("hit_0_hit_1                  ", f3_perf_info.hit_0_hit_1      && io.toIbuffer.fire ),
1037935edac4STang Haojin    ("hit_0_miss_1                 ", f3_perf_info.hit_0_miss_1     && io.toIbuffer.fire ),
1038935edac4STang Haojin    ("miss_0_hit_1                 ", f3_perf_info.miss_0_hit_1     && io.toIbuffer.fire ),
1039935edac4STang Haojin    ("miss_0_miss_1                ", f3_perf_info.miss_0_miss_1    && io.toIbuffer.fire ),
1040cd365d4cSrvcoresjw  )
10411ca0e4f3SYinan Xu  generatePerfEvent()
104209c6f1ddSLingrui98
1043935edac4STang Haojin  XSPerfAccumulate("ifu_req",   io.toIbuffer.fire )
1044935edac4STang Haojin  XSPerfAccumulate("ifu_miss",  io.toIbuffer.fire && !f3_hit )
1045f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_0", f3_req_0  )
1046f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_1", f3_req_1  )
1047f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_0_hit",   f3_hit_0 )
1048f7c29b0aSJinYue  XSPerfAccumulate("ifu_req_cacheline_1_hit",   f3_hit_1 )
10492a3050c2SJay  XSPerfAccumulate("frontendFlush",  wb_redirect )
1050935edac4STang Haojin  XSPerfAccumulate("only_0_hit",      f3_perf_info.only_0_hit   && io.toIbuffer.fire  )
1051935edac4STang Haojin  XSPerfAccumulate("only_0_miss",     f3_perf_info.only_0_miss  && io.toIbuffer.fire  )
1052935edac4STang Haojin  XSPerfAccumulate("hit_0_hit_1",     f3_perf_info.hit_0_hit_1  && io.toIbuffer.fire  )
1053935edac4STang Haojin  XSPerfAccumulate("hit_0_miss_1",    f3_perf_info.hit_0_miss_1  && io.toIbuffer.fire  )
1054935edac4STang Haojin  XSPerfAccumulate("miss_0_hit_1",    f3_perf_info.miss_0_hit_1   && io.toIbuffer.fire )
1055935edac4STang Haojin  XSPerfAccumulate("miss_0_miss_1",   f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire )
1056935edac4STang Haojin  XSPerfAccumulate("hit_0_except_1",   f3_perf_info.hit_0_except_1 && io.toIbuffer.fire )
1057935edac4STang Haojin  XSPerfAccumulate("miss_0_except_1",   f3_perf_info.miss_0_except_1 && io.toIbuffer.fire )
1058935edac4STang Haojin  XSPerfAccumulate("except_0",   f3_perf_info.except_0 && io.toIbuffer.fire )
1059eb163ef0SHaojin Tang  XSPerfHistogram("ifu2ibuffer_validCnt", PopCount(io.toIbuffer.bits.valid & io.toIbuffer.bits.enqEnable), io.toIbuffer.fire, 0, PredictWidth + 1, 1)
106051532d8bSGuokai Chen
1061c686adcdSYinan Xu  val hartId = p(XSCoreParamsKey).HartId
1062c686adcdSYinan Xu  val isWriteFetchToIBufferTable = Constantin.createRecord(s"isWriteFetchToIBufferTable$hartId")
1063c686adcdSYinan Xu  val isWriteIfuWbToFtqTable = Constantin.createRecord(s"isWriteIfuWbToFtqTable$hartId")
1064c686adcdSYinan Xu  val fetchToIBufferTable = ChiselDB.createTable(s"FetchToIBuffer$hartId", new FetchToIBufferDB)
1065c686adcdSYinan Xu  val ifuWbToFtqTable = ChiselDB.createTable(s"IfuWbToFtq$hartId", new IfuWbToFtqDB)
106651532d8bSGuokai Chen
106751532d8bSGuokai Chen  val fetchIBufferDumpData = Wire(new FetchToIBufferDB)
106851532d8bSGuokai Chen  fetchIBufferDumpData.start_addr := f3_ftq_req.startAddr
106951532d8bSGuokai Chen  fetchIBufferDumpData.instr_count := PopCount(io.toIbuffer.bits.enqEnable)
1070935edac4STang 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)
107151532d8bSGuokai Chen  fetchIBufferDumpData.is_cache_hit := f3_hit
107251532d8bSGuokai Chen
107351532d8bSGuokai Chen  val ifuWbToFtqDumpData = Wire(new IfuWbToFtqDB)
107451532d8bSGuokai Chen  ifuWbToFtqDumpData.start_addr := wb_ftq_req.startAddr
107551532d8bSGuokai Chen  ifuWbToFtqDumpData.is_miss_pred := checkFlushWb.bits.misOffset.valid
107651532d8bSGuokai Chen  ifuWbToFtqDumpData.miss_pred_offset := checkFlushWb.bits.misOffset.bits
107751532d8bSGuokai Chen  ifuWbToFtqDumpData.checkJalFault := checkJalFault
107851532d8bSGuokai Chen  ifuWbToFtqDumpData.checkRetFault := checkRetFault
107951532d8bSGuokai Chen  ifuWbToFtqDumpData.checkTargetFault := checkTargetFault
108051532d8bSGuokai Chen  ifuWbToFtqDumpData.checkNotCFIFault := checkNotCFIFault
108151532d8bSGuokai Chen  ifuWbToFtqDumpData.checkInvalidTaken := checkInvalidTaken
108251532d8bSGuokai Chen
108351532d8bSGuokai Chen  fetchToIBufferTable.log(
108451532d8bSGuokai Chen    data = fetchIBufferDumpData,
1085da3bf434SMaxpicca-Li    en = isWriteFetchToIBufferTable.orR && io.toIbuffer.fire,
108651532d8bSGuokai Chen    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
108751532d8bSGuokai Chen    clock = clock,
108851532d8bSGuokai Chen    reset = reset
108951532d8bSGuokai Chen  )
109051532d8bSGuokai Chen  ifuWbToFtqTable.log(
109151532d8bSGuokai Chen    data = ifuWbToFtqDumpData,
1092da3bf434SMaxpicca-Li    en = isWriteIfuWbToFtqTable.orR && checkFlushWb.valid,
109351532d8bSGuokai Chen    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
109451532d8bSGuokai Chen    clock = clock,
109551532d8bSGuokai Chen    reset = reset
109651532d8bSGuokai Chen  )
109751532d8bSGuokai Chen
109809c6f1ddSLingrui98}
1099