xref: /XiangShan/src/main/scala/xiangshan/frontend/IFU.scala (revision 1592abd11eecf7bec0f1453ffe4a7617167f8ba9)
1/***************************************************************************************
2* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC)
3* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences
4* Copyright (c) 2020-2021 Peng Cheng Laboratory
5*
6* XiangShan is licensed under Mulan PSL v2.
7* You can use this software according to the terms and conditions of the Mulan PSL v2.
8* You may obtain a copy of Mulan PSL v2 at:
9*          http://license.coscl.org.cn/MulanPSL2
10*
11* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
12* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
13* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
14*
15* See the Mulan PSL v2 for more details.
16***************************************************************************************/
17
18package xiangshan.frontend
19
20import chisel3._
21import chisel3.util._
22import org.chipsalliance.cde.config.Parameters
23import utility._
24import utility.ChiselDB
25import xiangshan._
26import xiangshan.backend.GPAMemEntry
27import xiangshan.cache.mmu._
28import xiangshan.frontend.icache._
29
30trait HasInstrMMIOConst extends HasXSParameter with HasIFUConst {
31  def mmioBusWidth = 64
32  def mmioBusBytes = mmioBusWidth / 8
33  def maxInstrLen  = 32
34}
35
36trait HasIFUConst extends HasXSParameter {
37  def addrAlign(addr: UInt, bytes: Int, highest: Int): UInt =
38    Cat(addr(highest - 1, log2Ceil(bytes)), 0.U(log2Ceil(bytes).W))
39  def fetchQueueSize = 2
40
41  def getBasicBlockIdx(pc: UInt, start: UInt): UInt = {
42    val byteOffset = pc - start
43    (byteOffset - instBytes.U)(log2Ceil(PredictWidth), instOffsetBits)
44  }
45}
46
47class IfuToFtqIO(implicit p: Parameters) extends XSBundle {
48  val pdWb = Valid(new PredecodeWritebackBundle)
49}
50
51class IfuToBackendIO(implicit p: Parameters) extends XSBundle {
52  // write to backend gpaddr mem
53  val gpaddrMem_wen   = Output(Bool())
54  val gpaddrMem_waddr = Output(UInt(log2Ceil(FtqSize).W)) // Ftq Ptr
55  // 2 gpaddrs, correspond to startAddr & nextLineAddr in bundle FtqICacheInfo
56  // TODO: avoid cross page entry in Ftq
57  val gpaddrMem_wdata = Output(new GPAMemEntry)
58}
59
60class FtqInterface(implicit p: Parameters) extends XSBundle {
61  val fromFtq = Flipped(new FtqToIfuIO)
62  val toFtq   = new IfuToFtqIO
63}
64
65class UncacheInterface(implicit p: Parameters) extends XSBundle {
66  val fromUncache = Flipped(DecoupledIO(new InsUncacheResp))
67  val toUncache   = DecoupledIO(new InsUncacheReq)
68}
69
70class NewIFUIO(implicit p: Parameters) extends XSBundle {
71  val ftqInter        = new FtqInterface
72  val icacheInter     = Flipped(new IFUICacheIO)
73  val icacheStop      = Output(Bool())
74  val icachePerfInfo  = Input(new ICachePerfInfo)
75  val toIbuffer       = Decoupled(new FetchToIBuffer)
76  val toBackend       = new IfuToBackendIO
77  val uncacheInter    = new UncacheInterface
78  val frontendTrigger = Flipped(new FrontendTdataDistributeIO)
79  val rob_commits     = Flipped(Vec(CommitWidth, Valid(new RobCommitInfo)))
80  val iTLBInter       = new TlbRequestIO
81  val pmp             = new ICachePMPBundle
82  val mmioCommitRead  = new mmioCommitRead
83  val csr_fsIsOff     = Input(Bool())
84}
85
86// record the situation in which fallThruAddr falls into
87// the middle of an RVI inst
88class LastHalfInfo(implicit p: Parameters) extends XSBundle {
89  val valid    = Bool()
90  val middlePC = UInt(VAddrBits.W)
91  def matchThisBlock(startAddr: UInt) = valid && middlePC === startAddr
92}
93
94class IfuToPreDecode(implicit p: Parameters) extends XSBundle {
95  val data            = if (HasCExtension) Vec(PredictWidth + 1, UInt(16.W)) else Vec(PredictWidth, UInt(32.W))
96  val frontendTrigger = new FrontendTdataDistributeIO
97  val pc              = Vec(PredictWidth, UInt(VAddrBits.W))
98}
99
100class IfuToPredChecker(implicit p: Parameters) extends XSBundle {
101  val ftqOffset  = Valid(UInt(log2Ceil(PredictWidth).W))
102  val jumpOffset = Vec(PredictWidth, UInt(XLEN.W))
103  val target     = UInt(VAddrBits.W)
104  val instrRange = Vec(PredictWidth, Bool())
105  val instrValid = Vec(PredictWidth, Bool())
106  val pds        = Vec(PredictWidth, new PreDecodeInfo)
107  val pc         = Vec(PredictWidth, UInt(VAddrBits.W))
108  val fire_in    = Bool()
109}
110
111class FetchToIBufferDB extends Bundle {
112  val start_addr   = UInt(39.W)
113  val instr_count  = UInt(32.W)
114  val exception    = Bool()
115  val is_cache_hit = Bool()
116}
117
118class IfuWbToFtqDB extends Bundle {
119  val start_addr        = UInt(39.W)
120  val is_miss_pred      = Bool()
121  val miss_pred_offset  = UInt(32.W)
122  val checkJalFault     = Bool()
123  val checkJalrFault    = Bool()
124  val checkRetFault     = Bool()
125  val checkTargetFault  = Bool()
126  val checkNotCFIFault  = Bool()
127  val checkInvalidTaken = Bool()
128}
129
130class NewIFU(implicit p: Parameters) extends XSModule
131    with HasICacheParameters
132    with HasXSParameter
133    with HasIFUConst
134    with HasPdConst
135    with HasCircularQueuePtrHelper
136    with HasPerfEvents
137    with HasTlbConst {
138  val io                       = IO(new NewIFUIO)
139  val (toFtq, fromFtq)         = (io.ftqInter.toFtq, io.ftqInter.fromFtq)
140  val fromICache               = io.icacheInter.resp
141  val (toUncache, fromUncache) = (io.uncacheInter.toUncache, io.uncacheInter.fromUncache)
142
143  def isCrossLineReq(start: UInt, end: UInt): Bool = start(blockOffBits) ^ end(blockOffBits)
144
145  def numOfStage = 3
146  // equal lower_result overflow bit
147  def PcCutPoint = (VAddrBits / 4) - 1
148  def CatPC(low: UInt, high: UInt, high1: UInt): UInt =
149    Mux(
150      low(PcCutPoint),
151      Cat(high1, low(PcCutPoint - 1, 0)),
152      Cat(high, low(PcCutPoint - 1, 0))
153    )
154  def CatPC(lowVec: Vec[UInt], high: UInt, high1: UInt): Vec[UInt] = VecInit(lowVec.map(CatPC(_, high, high1)))
155  require(numOfStage > 1, "BPU numOfStage must be greater than 1")
156  val topdown_stages = RegInit(VecInit(Seq.fill(numOfStage)(0.U.asTypeOf(new FrontendTopDownBundle))))
157  // bubble events in IFU, only happen in stage 1
158  val icacheMissBubble = Wire(Bool())
159  val itlbMissBubble   = Wire(Bool())
160
161  // only driven by clock, not valid-ready
162  topdown_stages(0) := fromFtq.req.bits.topdown_info
163  for (i <- 1 until numOfStage) {
164    topdown_stages(i) := topdown_stages(i - 1)
165  }
166  when(icacheMissBubble) {
167    topdown_stages(1).reasons(TopDownCounters.ICacheMissBubble.id) := true.B
168  }
169  when(itlbMissBubble) {
170    topdown_stages(1).reasons(TopDownCounters.ITLBMissBubble.id) := true.B
171  }
172  io.toIbuffer.bits.topdown_info := topdown_stages(numOfStage - 1)
173  when(fromFtq.topdown_redirect.valid) {
174    // only redirect from backend, IFU redirect itself is handled elsewhere
175    when(fromFtq.topdown_redirect.bits.debugIsCtrl) {
176      /*
177      for (i <- 0 until numOfStage) {
178        topdown_stages(i).reasons(TopDownCounters.ControlRedirectBubble.id) := true.B
179      }
180      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.ControlRedirectBubble.id) := true.B
181       */
182      when(fromFtq.topdown_redirect.bits.ControlBTBMissBubble) {
183        for (i <- 0 until numOfStage) {
184          topdown_stages(i).reasons(TopDownCounters.BTBMissBubble.id) := true.B
185        }
186        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.BTBMissBubble.id) := true.B
187      }.elsewhen(fromFtq.topdown_redirect.bits.TAGEMissBubble) {
188        for (i <- 0 until numOfStage) {
189          topdown_stages(i).reasons(TopDownCounters.TAGEMissBubble.id) := true.B
190        }
191        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.TAGEMissBubble.id) := true.B
192      }.elsewhen(fromFtq.topdown_redirect.bits.SCMissBubble) {
193        for (i <- 0 until numOfStage) {
194          topdown_stages(i).reasons(TopDownCounters.SCMissBubble.id) := true.B
195        }
196        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.SCMissBubble.id) := true.B
197      }.elsewhen(fromFtq.topdown_redirect.bits.ITTAGEMissBubble) {
198        for (i <- 0 until numOfStage) {
199          topdown_stages(i).reasons(TopDownCounters.ITTAGEMissBubble.id) := true.B
200        }
201        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.ITTAGEMissBubble.id) := true.B
202      }.elsewhen(fromFtq.topdown_redirect.bits.RASMissBubble) {
203        for (i <- 0 until numOfStage) {
204          topdown_stages(i).reasons(TopDownCounters.RASMissBubble.id) := true.B
205        }
206        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.RASMissBubble.id) := true.B
207      }
208    }.elsewhen(fromFtq.topdown_redirect.bits.debugIsMemVio) {
209      for (i <- 0 until numOfStage) {
210        topdown_stages(i).reasons(TopDownCounters.MemVioRedirectBubble.id) := true.B
211      }
212      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.MemVioRedirectBubble.id) := true.B
213    }.otherwise {
214      for (i <- 0 until numOfStage) {
215        topdown_stages(i).reasons(TopDownCounters.OtherRedirectBubble.id) := true.B
216      }
217      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.OtherRedirectBubble.id) := true.B
218    }
219  }
220
221  class TlbExept(implicit p: Parameters) extends XSBundle {
222    val pageFault   = Bool()
223    val accessFault = Bool()
224    val mmio        = Bool()
225  }
226
227  val preDecoder = Module(new PreDecode)
228
229  val predChecker     = Module(new PredChecker)
230  val frontendTrigger = Module(new FrontendTrigger)
231  val (checkerIn, checkerOutStage1, checkerOutStage2) =
232    (predChecker.io.in, predChecker.io.out.stage1Out, predChecker.io.out.stage2Out)
233
234  /**
235    ******************************************************************************
236    * IFU Stage 0
237    * - send cacheline fetch request to ICacheMainPipe
238    ******************************************************************************
239    */
240
241  val f0_valid      = fromFtq.req.valid
242  val f0_ftq_req    = fromFtq.req.bits
243  val f0_doubleLine = fromFtq.req.bits.crossCacheline
244  val f0_vSetIdx    = VecInit(get_idx(f0_ftq_req.startAddr), get_idx(f0_ftq_req.nextlineStart))
245  val f0_fire       = fromFtq.req.fire
246
247  val f0_flush, f1_flush, f2_flush, f3_flush = WireInit(false.B)
248
249  val f0_flush_from_bpu = fromFtq.flushFromBpu.shouldFlushByStage2(f0_ftq_req.ftqIdx) ||
250    fromFtq.flushFromBpu.shouldFlushByStage3(f0_ftq_req.ftqIdx)
251
252  val wb_redirect, mmio_redirect, backend_redirect = WireInit(false.B)
253  val f3_wb_not_flush                              = WireInit(false.B)
254
255  backend_redirect := fromFtq.redirect.valid
256  f3_flush         := backend_redirect || (wb_redirect && !f3_wb_not_flush)
257  f2_flush         := backend_redirect || mmio_redirect || wb_redirect
258  f1_flush         := f2_flush
259  f0_flush         := f1_flush || f0_flush_from_bpu
260
261  val f1_ready, f2_ready, f3_ready = WireInit(false.B)
262
263  fromFtq.req.ready := f1_ready && io.icacheInter.icacheReady
264
265  when(wb_redirect) {
266    when(f3_wb_not_flush) {
267      topdown_stages(2).reasons(TopDownCounters.BTBMissBubble.id) := true.B
268    }
269    for (i <- 0 until numOfStage - 1) {
270      topdown_stages(i).reasons(TopDownCounters.BTBMissBubble.id) := true.B
271    }
272  }
273
274  /** <PERF> f0 fetch bubble */
275
276  XSPerfAccumulate("fetch_bubble_ftq_not_valid", !fromFtq.req.valid && fromFtq.req.ready)
277  // XSPerfAccumulate("fetch_bubble_pipe_stall",    f0_valid && toICache(0).ready && toICache(1).ready && !f1_ready )
278  // XSPerfAccumulate("fetch_bubble_icache_0_busy",   f0_valid && !toICache(0).ready  )
279  // XSPerfAccumulate("fetch_bubble_icache_1_busy",   f0_valid && !toICache(1).ready  )
280  XSPerfAccumulate("fetch_flush_backend_redirect", backend_redirect)
281  XSPerfAccumulate("fetch_flush_wb_redirect", wb_redirect)
282  XSPerfAccumulate("fetch_flush_f0_flush_from_bpu", f0_flush_from_bpu)
283
284  /**
285    ******************************************************************************
286    * IFU Stage 1
287    * - calculate pc/half_pc/cut_ptr for every instruction
288    ******************************************************************************
289    */
290
291  val f1_valid   = RegInit(false.B)
292  val f1_ftq_req = RegEnable(f0_ftq_req, f0_fire)
293  // val f1_situation  = RegEnable(f0_situation,  f0_fire)
294  val f1_doubleLine = RegEnable(f0_doubleLine, f0_fire)
295  val f1_vSetIdx    = RegEnable(f0_vSetIdx, f0_fire)
296  val f1_fire       = f1_valid && f2_ready
297
298  f1_ready := f1_fire || !f1_valid
299
300  assert(!(fromFtq.flushFromBpu.shouldFlushByStage3(f1_ftq_req.ftqIdx) && f1_valid))
301
302  when(f1_flush)(f1_valid := false.B)
303    .elsewhen(f0_fire && !f0_flush)(f1_valid := true.B)
304    .elsewhen(f1_fire)(f1_valid := false.B)
305
306  val f1_pc_high       = f1_ftq_req.startAddr(VAddrBits - 1, PcCutPoint)
307  val f1_pc_high_plus1 = f1_pc_high + 1.U
308
309  /**
310   * In order to reduce power consumption, avoid calculating the full PC value in the first level.
311   * code of original logic, this code has been deprecated
312   * val f1_pc                 = VecInit(f1_pc_lower_result.map{ i =>
313   *  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)))})
314   */
315  val f1_pc_lower_result = VecInit((0 until PredictWidth).map(i =>
316    Cat(0.U(1.W), f1_ftq_req.startAddr(PcCutPoint - 1, 0)) + (i * 2).U
317  )) // cat with overflow bit
318
319  val f1_pc = CatPC(f1_pc_lower_result, f1_pc_high, f1_pc_high_plus1)
320
321  val f1_half_snpc_lower_result = VecInit((0 until PredictWidth).map(i =>
322    Cat(0.U(1.W), f1_ftq_req.startAddr(PcCutPoint - 1, 0)) + ((i + 2) * 2).U
323  )) // cat with overflow bit
324  val f1_half_snpc = CatPC(f1_half_snpc_lower_result, f1_pc_high, f1_pc_high_plus1)
325
326  if (env.FPGAPlatform) {
327    val f1_pc_diff        = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + (i * 2).U))
328    val f1_half_snpc_diff = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + ((i + 2) * 2).U))
329
330    XSError(
331      f1_pc.zip(f1_pc_diff).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _),
332      "f1_half_snpc adder cut fail"
333    )
334    XSError(
335      f1_half_snpc.zip(f1_half_snpc_diff).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _),
336      "f1_half_snpc adder cut fail"
337    )
338  }
339
340  val f1_cut_ptr = if (HasCExtension)
341    VecInit((0 until PredictWidth + 1).map(i => Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits - 1, 1)) + i.U))
342  else VecInit((0 until PredictWidth).map(i => Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits - 1, 2)) + i.U))
343
344  /**
345    ******************************************************************************
346    * IFU Stage 2
347    * - icache response data (latched for pipeline stop)
348    * - generate exceprion bits for every instruciton (page fault/access fault/mmio)
349    * - generate predicted instruction range (1 means this instruciton is in this fetch packet)
350    * - cut data from cachlines to packet instruction code
351    * - instruction predecode and RVC expand
352    ******************************************************************************
353    */
354
355  val icacheRespAllValid = WireInit(false.B)
356
357  val f2_valid   = RegInit(false.B)
358  val f2_ftq_req = RegEnable(f1_ftq_req, f1_fire)
359  // val f2_situation  = RegEnable(f1_situation,  f1_fire)
360  val f2_doubleLine = RegEnable(f1_doubleLine, f1_fire)
361  val f2_vSetIdx    = RegEnable(f1_vSetIdx, f1_fire)
362  val f2_fire       = f2_valid && f3_ready && icacheRespAllValid
363
364  f2_ready := f2_fire || !f2_valid
365  // TODO: addr compare may be timing critical
366  val f2_icache_all_resp_wire =
367    fromICache.valid &&
368      fromICache.bits.vaddr(0) === f2_ftq_req.startAddr &&
369      (fromICache.bits.doubleline && fromICache.bits.vaddr(1) === f2_ftq_req.nextlineStart || !f2_doubleLine)
370  val f2_icache_all_resp_reg = RegInit(false.B)
371
372  icacheRespAllValid := f2_icache_all_resp_reg || f2_icache_all_resp_wire
373
374  icacheMissBubble := io.icacheInter.topdownIcacheMiss
375  itlbMissBubble   := io.icacheInter.topdownItlbMiss
376
377  io.icacheStop := !f3_ready
378
379  when(f2_flush)(f2_icache_all_resp_reg := false.B)
380    .elsewhen(f2_valid && f2_icache_all_resp_wire && !f3_ready)(f2_icache_all_resp_reg := true.B)
381    .elsewhen(f2_fire && f2_icache_all_resp_reg)(f2_icache_all_resp_reg := false.B)
382
383  when(f2_flush)(f2_valid := false.B)
384    .elsewhen(f1_fire && !f1_flush)(f2_valid := true.B)
385    .elsewhen(f2_fire)(f2_valid := false.B)
386
387  val f2_exception_in     = fromICache.bits.exception
388  val f2_backendException = fromICache.bits.backendException
389  // paddr and gpaddr of [startAddr, nextLineAddr]
390  val f2_paddrs            = fromICache.bits.paddr
391  val f2_gpaddr            = fromICache.bits.gpaddr
392  val f2_isForVSnonLeafPTE = fromICache.bits.isForVSnonLeafPTE
393
394  // FIXME: raise af if one fetch block crosses the cacheable-noncacheable boundary, might not correct
395  val f2_mmio_mismatch_exception = VecInit(Seq(
396    ExceptionType.none, // mark the exception only on the second line
397    Mux(
398      // not double-line, skip check
399      !fromICache.bits.doubleline || (
400        // is double-line, ask for consistent pmp_mmio and itlb_pbmt value
401        fromICache.bits.pmp_mmio(0) === fromICache.bits.pmp_mmio(1) &&
402          fromICache.bits.itlb_pbmt(0) === fromICache.bits.itlb_pbmt(1)
403      ),
404      ExceptionType.none,
405      ExceptionType.af
406    )
407  ))
408
409  // merge exceptions
410  val f2_exception = ExceptionType.merge(f2_exception_in, f2_mmio_mismatch_exception)
411
412  // we need only the first port, as the second is asked to be the same
413  val f2_pmp_mmio  = fromICache.bits.pmp_mmio(0)
414  val f2_itlb_pbmt = fromICache.bits.itlb_pbmt(0)
415
416  /**
417    * reduce the number of registers, origin code
418    * f2_pc = RegEnable(f1_pc, f1_fire)
419    */
420  val f2_pc_lower_result = RegEnable(f1_pc_lower_result, f1_fire)
421  val f2_pc_high         = RegEnable(f1_pc_high, f1_fire)
422  val f2_pc_high_plus1   = RegEnable(f1_pc_high_plus1, f1_fire)
423  val f2_pc              = CatPC(f2_pc_lower_result, f2_pc_high, f2_pc_high_plus1)
424
425  val f2_cut_ptr      = RegEnable(f1_cut_ptr, f1_fire)
426  val f2_resend_vaddr = RegEnable(f1_ftq_req.startAddr + 2.U, f1_fire)
427
428  def isNextLine(pc: UInt, startAddr: UInt) =
429    startAddr(blockOffBits) ^ pc(blockOffBits)
430
431  def isLastInLine(pc: UInt) =
432    pc(blockOffBits - 1, 0) === "b111110".U
433
434  val f2_foldpc = VecInit(f2_pc.map(i => XORFold(i(VAddrBits - 1, 1), MemPredPCWidth)))
435  val f2_jump_range =
436    Fill(PredictWidth, !f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~f2_ftq_req.ftqOffset.bits
437  require(
438    isPow2(PredictWidth),
439    "If PredictWidth does not satisfy the power of 2," +
440      "expression: Fill(PredictWidth, 1.U(1.W)) >> ~f2_ftq_req.ftqOffset.bits is not right !!"
441  )
442  val f2_ftr_range = Fill(PredictWidth, f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~getBasicBlockIdx(
443    f2_ftq_req.nextStartAddr,
444    f2_ftq_req.startAddr
445  )
446  val f2_instr_range = f2_jump_range & f2_ftr_range
447  val f2_exception_vec = VecInit((0 until PredictWidth).map(i =>
448    MuxCase(
449      ExceptionType.none,
450      Seq(
451        !isNextLine(f2_pc(i), f2_ftq_req.startAddr)                   -> f2_exception(0),
452        (isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_doubleLine) -> f2_exception(1)
453      )
454    )
455  ))
456  val f2_perf_info = io.icachePerfInfo
457
458  def cut(cacheline: UInt, cutPtr: Vec[UInt]): Vec[UInt] = {
459    require(HasCExtension)
460    // if(HasCExtension){
461    val result  = Wire(Vec(PredictWidth + 1, UInt(16.W)))
462    val dataVec = cacheline.asTypeOf(Vec(blockBytes, UInt(16.W))) // 32 16-bit data vector
463    (0 until PredictWidth + 1).foreach(i =>
464      result(i) := dataVec(cutPtr(i)) // the max ptr is 3*blockBytes/4-1
465    )
466    result
467    // } else {
468    //   val result   = Wire(Vec(PredictWidth, UInt(32.W)) )
469    //   val dataVec  = cacheline.asTypeOf(Vec(blockBytes * 2/ 4, UInt(32.W)))
470    //   (0 until PredictWidth).foreach( i =>
471    //     result(i) := dataVec(cutPtr(i))
472    //   )
473    //   result
474    // }
475  }
476
477  /* NOTE: the following `Cat(_data, _data)` *is* intentional.
478   * Explanation:
479   * In the old design, IFU is responsible for selecting requested data from two adjacent cachelines,
480   *    so IFU has to receive 2*64B (2cacheline * 64B) data from ICache, and do `Cat(_data(1), _data(0))` here.
481   * However, a fetch block is 34B at max, sending 2*64B is quiet a waste of power.
482   * In current design (2024.06~), ICacheDataArray is responsible for selecting data from two adjacent cachelines,
483   *    so IFU only need to receive 40B (5bank * 8B) valid data, and use only one port is enough.
484   * For example, when pc falls on the 6th bank in cacheline0(so this is a doubleline request):
485   *                                MSB                                         LSB
486   *                  cacheline 1 || 1-7 | 1-6 | 1-5 | 1-4 | 1-3 | 1-2 | 1-1 | 1-0 ||
487   *                  cacheline 0 || 0-7 | 0-6 | 0-5 | 0-4 | 0-3 | 0-2 | 0-1 | 0-0 ||
488   *    and ICacheDataArray will respond:
489   *         fromICache.bits.data || 0-7 | 0-6 | xxx | xxx | xxx | 1-2 | 1-1 | 1-0 ||
490   *    therefore simply make a copy of the response and `Cat` together, and obtain the requested data from centre:
491   *          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 ||
492   *                                             requested data: ^-----------------------------^
493   * For another example, pc falls on the 1st bank in cacheline 0, we have:
494   *         fromICache.bits.data || xxx | xxx | 0-5 | 0-4 | 0-3 | 0-2 | 0-1 | xxx ||
495   *          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 ||
496   *                                                                           requested data: ^-----------------------------^
497   * Each "| x-y |" block is a 8B bank from cacheline(x).bank(y)
498   * Please also refer to:
499   * - DataArray selects data:
500   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICache.scala#L355-L381
501   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICache.scala#L149-L161
502   * - ICache respond to IFU:
503   * https://github.com/OpenXiangShan/XiangShan/blob/d4078d6edbfb4611ba58c8b0d1d8236c9115dbfc/src/main/scala/xiangshan/frontend/icache/ICacheMainPipe.scala#L473
504   */
505  val f2_data_2_cacheline = Cat(fromICache.bits.data, fromICache.bits.data)
506
507  val f2_cut_data = cut(f2_data_2_cacheline, f2_cut_ptr)
508
509  /** predecode (include RVC expander) */
510  // preDecoderRegIn.data := f2_reg_cut_data
511  // preDecoderRegInIn.frontendTrigger := io.frontendTrigger
512  // preDecoderRegInIn.csrTriggerEnable := io.csrTriggerEnable
513  // preDecoderRegIn.pc  := f2_pc
514
515  val preDecoderIn = preDecoder.io.in
516  preDecoderIn.valid                := f2_valid
517  preDecoderIn.bits.data            := f2_cut_data
518  preDecoderIn.bits.frontendTrigger := io.frontendTrigger
519  preDecoderIn.bits.pc              := f2_pc
520  val preDecoderOut = preDecoder.io.out
521
522  // val f2_expd_instr     = preDecoderOut.expInstr
523  val f2_instr        = preDecoderOut.instr
524  val f2_pd           = preDecoderOut.pd
525  val f2_jump_offset  = preDecoderOut.jumpOffset
526  val f2_hasHalfValid = preDecoderOut.hasHalfValid
527  /* if there is a cross-page RVI instruction, and the former page has no exception,
528   * whether it has exception is actually depends on the latter page
529   */
530  val f2_crossPage_exception_vec = VecInit((0 until PredictWidth).map { i =>
531    Mux(
532      isLastInLine(f2_pc(i)) && !f2_pd(i).isRVC && f2_doubleLine && !ExceptionType.hasException(f2_exception(0)),
533      f2_exception(1),
534      ExceptionType.none
535    )
536  })
537  XSPerfAccumulate("fetch_bubble_icache_not_resp", f2_valid && !icacheRespAllValid)
538
539  /**
540    ******************************************************************************
541    * IFU Stage 3
542    * - handle MMIO instruciton
543    *  -send request to Uncache fetch Unit
544    *  -every packet include 1 MMIO instruction
545    *  -MMIO instructions will stop fetch pipeline until commiting from RoB
546    *  -flush to snpc (send ifu_redirect to Ftq)
547    * - Ibuffer enqueue
548    * - check predict result in Frontend (jalFault/retFault/notCFIFault/invalidTakenFault/targetFault)
549    * - handle last half RVI instruction
550    ******************************************************************************
551    */
552
553  val expanders = Seq.fill(PredictWidth)(Module(new RVCExpander))
554
555  val f3_valid   = RegInit(false.B)
556  val f3_ftq_req = RegEnable(f2_ftq_req, f2_fire)
557  // val f3_situation      = RegEnable(f2_situation,  f2_fire)
558  val f3_doubleLine = RegEnable(f2_doubleLine, f2_fire)
559  val f3_fire       = io.toIbuffer.fire
560
561  val f3_cut_data = RegEnable(f2_cut_data, f2_fire)
562
563  val f3_exception        = RegEnable(f2_exception, f2_fire)
564  val f3_pmp_mmio         = RegEnable(f2_pmp_mmio, f2_fire)
565  val f3_itlb_pbmt        = RegEnable(f2_itlb_pbmt, f2_fire)
566  val f3_backendException = RegEnable(f2_backendException, f2_fire)
567
568  val f3_instr = RegEnable(f2_instr, f2_fire)
569
570  expanders.zipWithIndex.foreach { case (expander, i) =>
571    expander.io.in      := f3_instr(i)
572    expander.io.fsIsOff := io.csr_fsIsOff
573  }
574  // Use expanded instruction only when input is legal.
575  // Otherwise use origin illegal RVC instruction.
576  val f3_expd_instr = VecInit(expanders.map { expander: RVCExpander =>
577    Mux(expander.io.ill, expander.io.in, expander.io.out.bits)
578  })
579  val f3_ill = VecInit(expanders.map(_.io.ill))
580
581  val f3_pd_wire                 = RegEnable(f2_pd, f2_fire)
582  val f3_pd                      = WireInit(f3_pd_wire)
583  val f3_jump_offset             = RegEnable(f2_jump_offset, f2_fire)
584  val f3_exception_vec           = RegEnable(f2_exception_vec, f2_fire)
585  val f3_crossPage_exception_vec = RegEnable(f2_crossPage_exception_vec, f2_fire)
586
587  val f3_pc_lower_result = RegEnable(f2_pc_lower_result, f2_fire)
588  val f3_pc_high         = RegEnable(f2_pc_high, f2_fire)
589  val f3_pc_high_plus1   = RegEnable(f2_pc_high_plus1, f2_fire)
590  val f3_pc              = CatPC(f3_pc_lower_result, f3_pc_high, f3_pc_high_plus1)
591
592  val f3_pc_last_lower_result_plus2 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 2.U, f2_fire)
593  val f3_pc_last_lower_result_plus4 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 4.U, f2_fire)
594  // val f3_half_snpc      = RegEnable(f2_half_snpc,   f2_fire)
595
596  /**
597    ***********************************************************************
598    * Half snpc(i) is larger than pc(i) by 4. Using pc to calculate half snpc may be a good choice.
599    ***********************************************************************
600    */
601  val f3_half_snpc = Wire(Vec(PredictWidth, UInt(VAddrBits.W)))
602  for (i <- 0 until PredictWidth) {
603    if (i == (PredictWidth - 2)) {
604      f3_half_snpc(i) := CatPC(f3_pc_last_lower_result_plus2, f3_pc_high, f3_pc_high_plus1)
605    } else if (i == (PredictWidth - 1)) {
606      f3_half_snpc(i) := CatPC(f3_pc_last_lower_result_plus4, f3_pc_high, f3_pc_high_plus1)
607    } else {
608      f3_half_snpc(i) := f3_pc(i + 2)
609    }
610  }
611
612  val f3_instr_range       = RegEnable(f2_instr_range, f2_fire)
613  val f3_foldpc            = RegEnable(f2_foldpc, f2_fire)
614  val f3_hasHalfValid      = RegEnable(f2_hasHalfValid, f2_fire)
615  val f3_paddrs            = RegEnable(f2_paddrs, f2_fire)
616  val f3_gpaddr            = RegEnable(f2_gpaddr, f2_fire)
617  val f3_isForVSnonLeafPTE = RegEnable(f2_isForVSnonLeafPTE, f2_fire)
618  val f3_resend_vaddr      = RegEnable(f2_resend_vaddr, f2_fire)
619
620  // Expand 1 bit to prevent overflow when assert
621  val f3_ftq_req_startAddr     = Cat(0.U(1.W), f3_ftq_req.startAddr)
622  val f3_ftq_req_nextStartAddr = Cat(0.U(1.W), f3_ftq_req.nextStartAddr)
623  // brType, isCall and isRet generation is delayed to f3 stage
624  val f3Predecoder = Module(new F3Predecoder)
625
626  f3Predecoder.io.in.instr := f3_instr
627
628  f3_pd.zipWithIndex.map { case (pd, i) =>
629    pd.brType := f3Predecoder.io.out.pd(i).brType
630    pd.isCall := f3Predecoder.io.out.pd(i).isCall
631    pd.isRet  := f3Predecoder.io.out.pd(i).isRet
632  }
633
634  val f3PdDiff = f3_pd_wire.zip(f3_pd).map { case (a, b) => a.asUInt =/= b.asUInt }.reduce(_ || _)
635  XSError(f3_valid && f3PdDiff, "f3 pd diff")
636
637  when(f3_valid && !f3_ftq_req.ftqOffset.valid) {
638    assert(
639      f3_ftq_req_startAddr + (2 * PredictWidth).U >= f3_ftq_req_nextStartAddr,
640      s"More tha ${2 * PredictWidth} Bytes fetch is not allowed!"
641    )
642  }
643
644  /*** MMIO State Machine***/
645  val f3_mmio_data     = Reg(Vec(2, UInt(16.W)))
646  val mmio_exception   = RegInit(0.U(ExceptionType.width.W))
647  val mmio_is_RVC      = RegInit(false.B)
648  val mmio_has_resend  = RegInit(false.B)
649  val mmio_resend_addr = RegInit(0.U(PAddrBits.W))
650  // NOTE: we dont use GPAddrBits here, refer to ICacheMainPipe.scala L43-48 and PR#3795
651  val mmio_resend_gpaddr            = RegInit(0.U(PAddrBitsMax.W))
652  val mmio_resend_isForVSnonLeafPTE = RegInit(false.B)
653
654  // last instuction finish
655  val is_first_instr = RegInit(true.B)
656
657  /*** Determine whether the MMIO instruction is executable based on the previous prediction block ***/
658  io.mmioCommitRead.mmioFtqPtr := RegNext(f3_ftq_req.ftqIdx - 1.U)
659
660  val m_idle :: m_waitLastCmt :: m_sendReq :: m_waitResp :: m_sendTLB :: m_tlbResp :: m_sendPMP :: m_resendReq :: m_waitResendResp :: m_waitCommit :: m_commited :: Nil =
661    Enum(11)
662  val mmio_state = RegInit(m_idle)
663
664  // do mmio fetch only when pmp/pbmt shows it is a uncacheable address and no exception occurs
665  /* FIXME: we do not distinguish pbmt is NC or IO now
666   *        but we actually can do speculative execution if pbmt is NC, maybe fix this later for performance
667   */
668  val f3_req_is_mmio =
669    f3_valid && (f3_pmp_mmio || Pbmt.isUncache(f3_itlb_pbmt)) && !ExceptionType.hasException(f3_exception)
670  val mmio_commit = VecInit(io.rob_commits.map { commit =>
671    commit.valid && commit.bits.ftqIdx === f3_ftq_req.ftqIdx && commit.bits.ftqOffset === 0.U
672  }).asUInt.orR
673  val f3_mmio_req_commit = f3_req_is_mmio && mmio_state === m_commited
674
675  val f3_mmio_to_commit      = f3_req_is_mmio && mmio_state === m_waitCommit
676  val f3_mmio_to_commit_next = RegNext(f3_mmio_to_commit)
677  val f3_mmio_can_go         = f3_mmio_to_commit && !f3_mmio_to_commit_next
678
679  val fromFtqRedirectReg = Wire(fromFtq.redirect.cloneType)
680  fromFtqRedirectReg.bits := RegEnable(
681    fromFtq.redirect.bits,
682    0.U.asTypeOf(fromFtq.redirect.bits),
683    fromFtq.redirect.valid
684  )
685  fromFtqRedirectReg.valid := RegNext(fromFtq.redirect.valid, init = false.B)
686  val mmioF3Flush           = RegNext(f3_flush, init = false.B)
687  val f3_ftq_flush_self     = fromFtqRedirectReg.valid && RedirectLevel.flushItself(fromFtqRedirectReg.bits.level)
688  val f3_ftq_flush_by_older = fromFtqRedirectReg.valid && isBefore(fromFtqRedirectReg.bits.ftqIdx, f3_ftq_req.ftqIdx)
689
690  val f3_need_not_flush = f3_req_is_mmio && fromFtqRedirectReg.valid && !f3_ftq_flush_self && !f3_ftq_flush_by_older
691
692  /**
693    **********************************************************************************
694    * We want to defer instruction fetching when encountering MMIO instructions to ensure that the MMIO region is not negatively impacted.
695    * This is the exception when the first instruction is an MMIO instruction.
696    **********************************************************************************
697    */
698  when(is_first_instr && f3_fire) {
699    is_first_instr := false.B
700  }
701
702  when(f3_flush && !f3_req_is_mmio)(f3_valid := false.B)
703    .elsewhen(mmioF3Flush && f3_req_is_mmio && !f3_need_not_flush)(f3_valid := false.B)
704    .elsewhen(f2_fire && !f2_flush)(f3_valid := true.B)
705    .elsewhen(io.toIbuffer.fire && !f3_req_is_mmio)(f3_valid := false.B)
706    .elsewhen(f3_req_is_mmio && f3_mmio_req_commit)(f3_valid := false.B)
707
708  val f3_mmio_use_seq_pc = RegInit(false.B)
709
710  val (redirect_ftqIdx, redirect_ftqOffset) = (fromFtqRedirectReg.bits.ftqIdx, fromFtqRedirectReg.bits.ftqOffset)
711  val redirect_mmio_req =
712    fromFtqRedirectReg.valid && redirect_ftqIdx === f3_ftq_req.ftqIdx && redirect_ftqOffset === 0.U
713
714  when(RegNext(f2_fire && !f2_flush) && f3_req_is_mmio)(f3_mmio_use_seq_pc := true.B)
715    .elsewhen(redirect_mmio_req)(f3_mmio_use_seq_pc := false.B)
716
717  f3_ready := (io.toIbuffer.ready && (f3_mmio_req_commit || !f3_req_is_mmio)) || !f3_valid
718
719  // mmio state machine
720  switch(mmio_state) {
721    is(m_idle) {
722      when(f3_req_is_mmio) {
723        // in idempotent spaces, we can send request directly (i.e. can do speculative fetch)
724        mmio_state := Mux(f3_itlb_pbmt === Pbmt.nc, m_sendReq, m_waitLastCmt)
725      }
726    }
727
728    is(m_waitLastCmt) {
729      when(is_first_instr) {
730        mmio_state := m_sendReq
731      }.otherwise {
732        mmio_state := Mux(io.mmioCommitRead.mmioLastCommit, m_sendReq, m_waitLastCmt)
733      }
734    }
735
736    is(m_sendReq) {
737      mmio_state := Mux(toUncache.fire, m_waitResp, m_sendReq)
738    }
739
740    is(m_waitResp) {
741      when(fromUncache.fire) {
742        val isRVC      = fromUncache.bits.data(1, 0) =/= 3.U
743        val exception  = ExceptionType.fromTilelink(fromUncache.bits.corrupt)
744        val needResend = !isRVC && f3_paddrs(0)(2, 1) === 3.U && !ExceptionType.hasException(exception)
745        mmio_state      := Mux(needResend, m_sendTLB, m_waitCommit)
746        mmio_exception  := exception
747        mmio_is_RVC     := isRVC
748        mmio_has_resend := needResend
749        f3_mmio_data(0) := fromUncache.bits.data(15, 0)
750        f3_mmio_data(1) := fromUncache.bits.data(31, 16)
751      }
752    }
753
754    is(m_sendTLB) {
755      mmio_state := Mux(io.iTLBInter.req.fire, m_tlbResp, m_sendTLB)
756    }
757
758    is(m_tlbResp) {
759      when(io.iTLBInter.resp.fire) {
760        // we are using a blocked tlb, so resp.fire must have !resp.bits.miss
761        assert(!io.iTLBInter.resp.bits.miss, "blocked mode iTLB miss when resp.fire")
762        val tlb_exception = ExceptionType.fromTlbResp(io.iTLBInter.resp.bits)
763        // if itlb re-check respond pbmt mismatch with previous check, must be access fault
764        val pbmt_mismatch_exception = Mux(
765          io.iTLBInter.resp.bits.pbmt(0) =/= f3_itlb_pbmt,
766          ExceptionType.af,
767          ExceptionType.none
768        )
769        val exception = ExceptionType.merge(tlb_exception, pbmt_mismatch_exception)
770        // if tlb has exception, abort checking pmp, just send instr & exception to ibuffer and wait for commit
771        mmio_state := Mux(ExceptionType.hasException(exception), m_waitCommit, m_sendPMP)
772        // also save itlb response
773        mmio_exception                := exception
774        mmio_resend_addr              := io.iTLBInter.resp.bits.paddr(0)
775        mmio_resend_gpaddr            := io.iTLBInter.resp.bits.gpaddr(0)
776        mmio_resend_isForVSnonLeafPTE := io.iTLBInter.resp.bits.isForVSnonLeafPTE(0)
777      }
778    }
779
780    is(m_sendPMP) {
781      val pmp_exception = ExceptionType.fromPMPResp(io.pmp.resp)
782      // if pmp re-check respond mismatch with previous check, must be access fault
783      val mmio_mismatch_exception = Mux(
784        io.pmp.resp.mmio =/= f3_pmp_mmio,
785        ExceptionType.af,
786        ExceptionType.none
787      )
788      val exception = ExceptionType.merge(pmp_exception, mmio_mismatch_exception)
789      // if pmp has exception, abort sending request, just send instr & exception to ibuffer and wait for commit
790      mmio_state := Mux(ExceptionType.hasException(exception), m_waitCommit, m_resendReq)
791      // also save pmp response
792      mmio_exception := exception
793    }
794
795    is(m_resendReq) {
796      mmio_state := Mux(toUncache.fire, m_waitResendResp, m_resendReq)
797    }
798
799    is(m_waitResendResp) {
800      when(fromUncache.fire) {
801        mmio_state      := m_waitCommit
802        mmio_exception  := ExceptionType.fromTilelink(fromUncache.bits.corrupt)
803        f3_mmio_data(1) := fromUncache.bits.data(15, 0)
804      }
805    }
806
807    is(m_waitCommit) {
808      // in idempotent spaces, we can skip waiting for commit (i.e. can do speculative fetch)
809      // but we do not skip m_waitCommit state, as other signals (e.g. f3_mmio_can_go relies on this)
810      mmio_state := Mux(mmio_commit || f3_itlb_pbmt === Pbmt.nc, m_commited, m_waitCommit)
811    }
812
813    // normal mmio instruction
814    is(m_commited) {
815      mmio_state                    := m_idle
816      mmio_exception                := ExceptionType.none
817      mmio_is_RVC                   := false.B
818      mmio_has_resend               := false.B
819      mmio_resend_addr              := 0.U
820      mmio_resend_gpaddr            := 0.U
821      mmio_resend_isForVSnonLeafPTE := false.B
822    }
823  }
824
825  // Exception or flush by older branch prediction
826  // Condition is from RegNext(fromFtq.redirect), 1 cycle after backend rediect
827  when(f3_ftq_flush_self || f3_ftq_flush_by_older) {
828    mmio_state                    := m_idle
829    mmio_exception                := ExceptionType.none
830    mmio_is_RVC                   := false.B
831    mmio_has_resend               := false.B
832    mmio_resend_addr              := 0.U
833    mmio_resend_gpaddr            := 0.U
834    mmio_resend_isForVSnonLeafPTE := false.B
835    f3_mmio_data.map(_ := 0.U)
836  }
837
838  toUncache.valid     := ((mmio_state === m_sendReq) || (mmio_state === m_resendReq)) && f3_req_is_mmio
839  toUncache.bits.addr := Mux(mmio_state === m_resendReq, mmio_resend_addr, f3_paddrs(0))
840  fromUncache.ready   := true.B
841
842  // send itlb request in m_sendTLB state
843  io.iTLBInter.req.valid                   := (mmio_state === m_sendTLB) && f3_req_is_mmio
844  io.iTLBInter.req.bits.size               := 3.U
845  io.iTLBInter.req.bits.vaddr              := f3_resend_vaddr
846  io.iTLBInter.req.bits.debug.pc           := f3_resend_vaddr
847  io.iTLBInter.req.bits.cmd                := TlbCmd.exec
848  io.iTLBInter.req.bits.isPrefetch         := false.B
849  io.iTLBInter.req.bits.kill               := false.B // IFU use itlb for mmio, doesn't need sync, set it to false
850  io.iTLBInter.req.bits.no_translate       := false.B
851  io.iTLBInter.req.bits.fullva             := 0.U
852  io.iTLBInter.req.bits.checkfullva        := false.B
853  io.iTLBInter.req.bits.hyperinst          := DontCare
854  io.iTLBInter.req.bits.hlvx               := DontCare
855  io.iTLBInter.req.bits.memidx             := DontCare
856  io.iTLBInter.req.bits.debug.robIdx       := DontCare
857  io.iTLBInter.req.bits.debug.isFirstIssue := DontCare
858  io.iTLBInter.req.bits.pmp_addr           := DontCare
859  // whats the difference between req_kill and req.bits.kill?
860  io.iTLBInter.req_kill := false.B
861  // wait for itlb response in m_tlbResp state
862  io.iTLBInter.resp.ready := (mmio_state === m_tlbResp) && f3_req_is_mmio
863
864  io.pmp.req.valid     := (mmio_state === m_sendPMP) && f3_req_is_mmio
865  io.pmp.req.bits.addr := mmio_resend_addr
866  io.pmp.req.bits.size := 3.U
867  io.pmp.req.bits.cmd  := TlbCmd.exec
868
869  val f3_lastHalf = RegInit(0.U.asTypeOf(new LastHalfInfo))
870
871  val f3_predecode_range = VecInit(preDecoderOut.pd.map(inst => inst.valid)).asUInt
872  val f3_mmio_range      = VecInit((0 until PredictWidth).map(i => if (i == 0) true.B else false.B))
873  val f3_instr_valid     = Wire(Vec(PredictWidth, Bool()))
874
875  /*** prediction result check   ***/
876  checkerIn.ftqOffset  := f3_ftq_req.ftqOffset
877  checkerIn.jumpOffset := f3_jump_offset
878  checkerIn.target     := f3_ftq_req.nextStartAddr
879  checkerIn.instrRange := f3_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
880  checkerIn.instrValid := f3_instr_valid.asTypeOf(Vec(PredictWidth, Bool()))
881  checkerIn.pds        := f3_pd
882  checkerIn.pc         := f3_pc
883  checkerIn.fire_in    := RegNext(f2_fire, init = false.B)
884
885  /*** handle half RVI in the last 2 Bytes  ***/
886
887  def hasLastHalf(idx: UInt) =
888    // !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(idx) && !checkerOutStage2.fixedMissPred(idx) && ! f3_req_is_mmio
889    !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(
890      idx
891    ) && !f3_req_is_mmio
892
893  val f3_last_validIdx = ParallelPosteriorityEncoder(checkerOutStage1.fixedRange)
894
895  val f3_hasLastHalf    = hasLastHalf((PredictWidth - 1).U)
896  val f3_false_lastHalf = hasLastHalf(f3_last_validIdx)
897  val f3_false_snpc     = f3_half_snpc(f3_last_validIdx)
898
899  val f3_lastHalf_mask    = VecInit((0 until PredictWidth).map(i => if (i == 0) false.B else true.B)).asUInt
900  val f3_lastHalf_disable = RegInit(false.B)
901
902  when(f3_flush || (f3_fire && f3_lastHalf_disable)) {
903    f3_lastHalf_disable := false.B
904  }
905
906  when(f3_flush) {
907    f3_lastHalf.valid := false.B
908  }.elsewhen(f3_fire) {
909    f3_lastHalf.valid    := f3_hasLastHalf && !f3_lastHalf_disable
910    f3_lastHalf.middlePC := f3_ftq_req.nextStartAddr
911  }
912
913  f3_instr_valid := Mux(f3_lastHalf.valid, f3_hasHalfValid, VecInit(f3_pd.map(inst => inst.valid)))
914
915  /*** frontend Trigger  ***/
916  frontendTrigger.io.pds  := f3_pd
917  frontendTrigger.io.pc   := f3_pc
918  frontendTrigger.io.data := f3_cut_data
919
920  frontendTrigger.io.frontendTrigger := io.frontendTrigger
921
922  val f3_triggered       = frontendTrigger.io.triggered
923  val f3_toIbuffer_valid = f3_valid && (!f3_req_is_mmio || f3_mmio_can_go) && !f3_flush
924
925  /*** send to Ibuffer  ***/
926  io.toIbuffer.valid          := f3_toIbuffer_valid
927  io.toIbuffer.bits.instrs    := f3_expd_instr
928  io.toIbuffer.bits.valid     := f3_instr_valid.asUInt
929  io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt
930  io.toIbuffer.bits.pd        := f3_pd
931  io.toIbuffer.bits.ftqPtr    := f3_ftq_req.ftqIdx
932  io.toIbuffer.bits.pc        := f3_pc
933  // Find last using PriorityMux
934  io.toIbuffer.bits.isLastInFtqEntry := Reverse(PriorityEncoderOH(Reverse(io.toIbuffer.bits.enqEnable))).asBools
935  io.toIbuffer.bits.ftqOffset.zipWithIndex.map { case (a, i) =>
936    a.bits := i.U; a.valid := checkerOutStage1.fixedTaken(i) && !f3_req_is_mmio
937  }
938  io.toIbuffer.bits.foldpc        := f3_foldpc
939  io.toIbuffer.bits.exceptionType := ExceptionType.merge(f3_exception_vec, f3_crossPage_exception_vec)
940  // backendException only needs to be set for the first instruction.
941  // Other instructions in the same block may have pf or af set,
942  // which is a side effect of the first instruction and actually not necessary.
943  io.toIbuffer.bits.backendException := (0 until PredictWidth).map {
944    case 0 => f3_backendException
945    case _ => false.B
946  }
947  io.toIbuffer.bits.crossPageIPFFix := f3_crossPage_exception_vec.map(ExceptionType.hasException)
948  io.toIbuffer.bits.illegalInstr    := f3_ill
949  io.toIbuffer.bits.triggered       := f3_triggered
950
951  when(f3_lastHalf.valid) {
952    io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt & f3_lastHalf_mask
953    io.toIbuffer.bits.valid     := f3_lastHalf_mask & f3_instr_valid.asUInt
954  }
955
956  when(io.toIbuffer.valid && io.toIbuffer.ready) {
957    val enqVec = io.toIbuffer.bits.enqEnable
958    val allocateSeqNum = VecInit((0 until PredictWidth).map { i =>
959      val idx  = PopCount(enqVec.take(i + 1))
960      val pc   = f3_pc(i)
961      val code = io.toIbuffer.bits.instrs(i)
962      PerfCCT.createInstMetaAtFetch(idx, pc, code, enqVec(i), clock, reset)
963    })
964    io.toIbuffer.bits.debug_seqNum.zipWithIndex.foreach { case (a, i) =>
965      a := allocateSeqNum(i)
966    }
967  }.otherwise {
968    io.toIbuffer.bits.debug_seqNum.zipWithIndex.foreach { case (a, i) =>
969      a := 0.U
970    }
971  }
972
973  /** to backend */
974  // f3_gpaddr is valid iff gpf is detected
975  io.toBackend.gpaddrMem_wen := f3_toIbuffer_valid && Mux(
976    f3_req_is_mmio,
977    mmio_exception === ExceptionType.gpf,
978    f3_exception.map(_ === ExceptionType.gpf).reduce(_ || _)
979  )
980  io.toBackend.gpaddrMem_waddr        := f3_ftq_req.ftqIdx.value
981  io.toBackend.gpaddrMem_wdata.gpaddr := Mux(f3_req_is_mmio, mmio_resend_gpaddr, f3_gpaddr)
982  io.toBackend.gpaddrMem_wdata.isForVSnonLeafPTE := Mux(
983    f3_req_is_mmio,
984    mmio_resend_isForVSnonLeafPTE,
985    f3_isForVSnonLeafPTE
986  )
987
988  // Write back to Ftq
989  val f3_cache_fetch     = f3_valid && !(f2_fire && !f2_flush)
990  val finishFetchMaskReg = RegNext(f3_cache_fetch)
991
992  val mmioFlushWb        = Wire(Valid(new PredecodeWritebackBundle))
993  val f3_mmio_missOffset = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
994  f3_mmio_missOffset.valid := f3_req_is_mmio
995  f3_mmio_missOffset.bits  := 0.U
996
997  // Send mmioFlushWb back to FTQ 1 cycle after uncache fetch return
998  // When backend redirect, mmio_state reset after 1 cycle.
999  // In this case, mask .valid to avoid overriding backend redirect
1000  mmioFlushWb.valid := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) &&
1001    f3_mmio_use_seq_pc && !f3_ftq_flush_self && !f3_ftq_flush_by_older)
1002  mmioFlushWb.bits.pc := f3_pc
1003  mmioFlushWb.bits.pd := f3_pd
1004  mmioFlushWb.bits.pd.zipWithIndex.map { case (instr, i) => instr.valid := f3_mmio_range(i) }
1005  mmioFlushWb.bits.ftqIdx     := f3_ftq_req.ftqIdx
1006  mmioFlushWb.bits.ftqOffset  := f3_ftq_req.ftqOffset.bits
1007  mmioFlushWb.bits.misOffset  := f3_mmio_missOffset
1008  mmioFlushWb.bits.cfiOffset  := DontCare
1009  mmioFlushWb.bits.target     := Mux(mmio_is_RVC, f3_ftq_req.startAddr + 2.U, f3_ftq_req.startAddr + 4.U)
1010  mmioFlushWb.bits.jalTarget  := DontCare
1011  mmioFlushWb.bits.instrRange := f3_mmio_range
1012
1013  val mmioRVCExpander = Module(new RVCExpander)
1014  mmioRVCExpander.io.in      := Mux(f3_req_is_mmio, Cat(f3_mmio_data(1), f3_mmio_data(0)), 0.U)
1015  mmioRVCExpander.io.fsIsOff := io.csr_fsIsOff
1016
1017  /** external predecode for MMIO instruction */
1018  when(f3_req_is_mmio) {
1019    val inst = Cat(f3_mmio_data(1), f3_mmio_data(0))
1020
1021    val brType :: isCall :: isRet :: Nil = brInfo(inst)
1022    val jalOffset                        = jal_offset(inst, mmio_is_RVC)
1023    val brOffset                         = br_offset(inst, mmio_is_RVC)
1024
1025    io.toIbuffer.bits.instrs(0) := Mux(mmioRVCExpander.io.ill, mmioRVCExpander.io.in, mmioRVCExpander.io.out.bits)
1026
1027    io.toIbuffer.bits.pd(0).valid  := true.B
1028    io.toIbuffer.bits.pd(0).isRVC  := mmio_is_RVC
1029    io.toIbuffer.bits.pd(0).brType := brType
1030    io.toIbuffer.bits.pd(0).isCall := isCall
1031    io.toIbuffer.bits.pd(0).isRet  := isRet
1032
1033    io.toIbuffer.bits.exceptionType(0) := mmio_exception
1034    // exception can happens in next page only when resend
1035    io.toIbuffer.bits.crossPageIPFFix(0) := mmio_has_resend && ExceptionType.hasException(mmio_exception)
1036    io.toIbuffer.bits.illegalInstr(0)    := mmioRVCExpander.io.ill
1037
1038    io.toIbuffer.bits.enqEnable := f3_mmio_range.asUInt
1039
1040    mmioFlushWb.bits.pd(0).valid  := true.B
1041    mmioFlushWb.bits.pd(0).isRVC  := mmio_is_RVC
1042    mmioFlushWb.bits.pd(0).brType := brType
1043    mmioFlushWb.bits.pd(0).isCall := isCall
1044    mmioFlushWb.bits.pd(0).isRet  := isRet
1045  }
1046
1047  mmio_redirect := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) && f3_mmio_use_seq_pc)
1048
1049  XSPerfAccumulate("fetch_bubble_ibuffer_not_ready", io.toIbuffer.valid && !io.toIbuffer.ready)
1050
1051  /**
1052    ******************************************************************************
1053    * IFU Write Back Stage
1054    * - write back predecode information to Ftq to update
1055    * - redirect if found fault prediction
1056    * - redirect if has false hit last half (last PC is not start + 32 Bytes, but in the midle of an notCFI RVI instruction)
1057    ******************************************************************************
1058    */
1059  val wb_enable  = RegNext(f2_fire && !f2_flush) && !f3_req_is_mmio && !f3_flush
1060  val wb_valid   = RegNext(wb_enable, init = false.B)
1061  val wb_ftq_req = RegEnable(f3_ftq_req, wb_enable)
1062
1063  val wb_check_result_stage1 = RegEnable(checkerOutStage1, wb_enable)
1064  val wb_check_result_stage2 = checkerOutStage2
1065  val wb_instr_range         = RegEnable(io.toIbuffer.bits.enqEnable, wb_enable)
1066
1067  val wb_pc_lower_result = RegEnable(f3_pc_lower_result, wb_enable)
1068  val wb_pc_high         = RegEnable(f3_pc_high, wb_enable)
1069  val wb_pc_high_plus1   = RegEnable(f3_pc_high_plus1, wb_enable)
1070  val wb_pc              = CatPC(wb_pc_lower_result, wb_pc_high, wb_pc_high_plus1)
1071
1072  // val wb_pc             = RegEnable(f3_pc, wb_enable)
1073  val wb_pd          = RegEnable(f3_pd, wb_enable)
1074  val wb_instr_valid = RegEnable(f3_instr_valid, wb_enable)
1075
1076  /* false hit lastHalf */
1077  val wb_lastIdx        = RegEnable(f3_last_validIdx, wb_enable)
1078  val wb_false_lastHalf = RegEnable(f3_false_lastHalf, wb_enable) && wb_lastIdx =/= (PredictWidth - 1).U
1079  val wb_false_target   = RegEnable(f3_false_snpc, wb_enable)
1080
1081  val wb_half_flush  = wb_false_lastHalf
1082  val wb_half_target = wb_false_target
1083
1084  /* false oversize */
1085  val lastIsRVC = wb_instr_range.asTypeOf(Vec(PredictWidth, Bool())).last && wb_pd.last.isRVC
1086  val lastIsRVI = wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))(PredictWidth - 2) && !wb_pd(PredictWidth - 2).isRVC
1087  val lastTaken = wb_check_result_stage1.fixedTaken.last
1088
1089  f3_wb_not_flush := wb_ftq_req.ftqIdx === f3_ftq_req.ftqIdx && f3_valid && wb_valid
1090
1091  /** if a req with a last half but miss predicted enters in wb stage, and this cycle f3 stalls,
1092    * we set a flag to notify f3 that the last half flag need not to be set.
1093    */
1094  // f3_fire is after wb_valid
1095  when(wb_valid && RegNext(f3_hasLastHalf, init = false.B)
1096    && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && !f3_fire && !RegNext(
1097      f3_fire,
1098      init = false.B
1099    ) && !f3_flush) {
1100    f3_lastHalf_disable := true.B
1101  }
1102
1103  // wb_valid and f3_fire are in same cycle
1104  when(wb_valid && RegNext(f3_hasLastHalf, init = false.B)
1105    && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && f3_fire) {
1106    f3_lastHalf.valid := false.B
1107  }
1108
1109  val checkFlushWb = Wire(Valid(new PredecodeWritebackBundle))
1110  val checkFlushWbjalTargetIdx = ParallelPriorityEncoder(VecInit(wb_pd.zip(wb_instr_valid).map { case (pd, v) =>
1111    v && pd.isJal
1112  }))
1113  val checkFlushWbTargetIdx = ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
1114  checkFlushWb.valid   := wb_valid
1115  checkFlushWb.bits.pc := wb_pc
1116  checkFlushWb.bits.pd := wb_pd
1117  checkFlushWb.bits.pd.zipWithIndex.map { case (instr, i) => instr.valid := wb_instr_valid(i) }
1118  checkFlushWb.bits.ftqIdx          := wb_ftq_req.ftqIdx
1119  checkFlushWb.bits.ftqOffset       := wb_ftq_req.ftqOffset.bits
1120  checkFlushWb.bits.misOffset.valid := ParallelOR(wb_check_result_stage2.fixedMissPred) || wb_half_flush
1121  checkFlushWb.bits.misOffset.bits := Mux(
1122    wb_half_flush,
1123    wb_lastIdx,
1124    ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
1125  )
1126  checkFlushWb.bits.cfiOffset.valid := ParallelOR(wb_check_result_stage1.fixedTaken)
1127  checkFlushWb.bits.cfiOffset.bits  := ParallelPriorityEncoder(wb_check_result_stage1.fixedTaken)
1128  checkFlushWb.bits.target := Mux(
1129    wb_half_flush,
1130    wb_half_target,
1131    wb_check_result_stage2.fixedTarget(checkFlushWbTargetIdx)
1132  )
1133  checkFlushWb.bits.jalTarget  := wb_check_result_stage2.jalTarget(checkFlushWbjalTargetIdx)
1134  checkFlushWb.bits.instrRange := wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
1135
1136  toFtq.pdWb := Mux(wb_valid, checkFlushWb, mmioFlushWb)
1137
1138  wb_redirect := checkFlushWb.bits.misOffset.valid && wb_valid
1139
1140  /*write back flush type*/
1141  val checkFaultType    = wb_check_result_stage2.faultType
1142  val checkJalFault     = wb_valid && checkFaultType.map(_.isjalFault).reduce(_ || _)
1143  val checkJalrFault    = wb_valid && checkFaultType.map(_.isjalrFault).reduce(_ || _)
1144  val checkRetFault     = wb_valid && checkFaultType.map(_.isRetFault).reduce(_ || _)
1145  val checkTargetFault  = wb_valid && checkFaultType.map(_.istargetFault).reduce(_ || _)
1146  val checkNotCFIFault  = wb_valid && checkFaultType.map(_.notCFIFault).reduce(_ || _)
1147  val checkInvalidTaken = wb_valid && checkFaultType.map(_.invalidTakenFault).reduce(_ || _)
1148
1149  XSPerfAccumulate("predecode_flush_jalFault", checkJalFault)
1150  XSPerfAccumulate("predecode_flush_jalrFault", checkJalrFault)
1151  XSPerfAccumulate("predecode_flush_retFault", checkRetFault)
1152  XSPerfAccumulate("predecode_flush_targetFault", checkTargetFault)
1153  XSPerfAccumulate("predecode_flush_notCFIFault", checkNotCFIFault)
1154  XSPerfAccumulate("predecode_flush_incalidTakenFault", checkInvalidTaken)
1155
1156  XSDebug(
1157    checkRetFault,
1158    "startAddr:%x  nextstartAddr:%x  taken:%d    takenIdx:%d\n",
1159    wb_ftq_req.startAddr,
1160    wb_ftq_req.nextStartAddr,
1161    wb_ftq_req.ftqOffset.valid,
1162    wb_ftq_req.ftqOffset.bits
1163  )
1164
1165  /** performance counter */
1166  val f3_perf_info = RegEnable(f2_perf_info, f2_fire)
1167  val f3_req_0     = io.toIbuffer.fire
1168  val f3_req_1     = io.toIbuffer.fire && f3_doubleLine
1169  val f3_hit_0     = io.toIbuffer.fire && f3_perf_info.bank_hit(0)
1170  val f3_hit_1     = io.toIbuffer.fire && f3_doubleLine & f3_perf_info.bank_hit(1)
1171  val f3_hit       = f3_perf_info.hit
1172  val perfEvents = Seq(
1173    ("frontendFlush                ", wb_redirect),
1174    ("ifu_req                      ", io.toIbuffer.fire),
1175    ("ifu_miss                     ", io.toIbuffer.fire && !f3_perf_info.hit),
1176    ("ifu_req_cacheline_0          ", f3_req_0),
1177    ("ifu_req_cacheline_1          ", f3_req_1),
1178    ("ifu_req_cacheline_0_hit      ", f3_hit_1),
1179    ("ifu_req_cacheline_1_hit      ", f3_hit_1),
1180    ("only_0_hit                   ", f3_perf_info.only_0_hit && io.toIbuffer.fire),
1181    ("only_0_miss                  ", f3_perf_info.only_0_miss && io.toIbuffer.fire),
1182    ("hit_0_hit_1                  ", f3_perf_info.hit_0_hit_1 && io.toIbuffer.fire),
1183    ("hit_0_miss_1                 ", f3_perf_info.hit_0_miss_1 && io.toIbuffer.fire),
1184    ("miss_0_hit_1                 ", f3_perf_info.miss_0_hit_1 && io.toIbuffer.fire),
1185    ("miss_0_miss_1                ", f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire)
1186  )
1187  generatePerfEvent()
1188
1189  XSPerfAccumulate("ifu_req", io.toIbuffer.fire)
1190  XSPerfAccumulate("ifu_miss", io.toIbuffer.fire && !f3_hit)
1191  XSPerfAccumulate("ifu_req_cacheline_0", f3_req_0)
1192  XSPerfAccumulate("ifu_req_cacheline_1", f3_req_1)
1193  XSPerfAccumulate("ifu_req_cacheline_0_hit", f3_hit_0)
1194  XSPerfAccumulate("ifu_req_cacheline_1_hit", f3_hit_1)
1195  XSPerfAccumulate("frontendFlush", wb_redirect)
1196  XSPerfAccumulate("only_0_hit", f3_perf_info.only_0_hit && io.toIbuffer.fire)
1197  XSPerfAccumulate("only_0_miss", f3_perf_info.only_0_miss && io.toIbuffer.fire)
1198  XSPerfAccumulate("hit_0_hit_1", f3_perf_info.hit_0_hit_1 && io.toIbuffer.fire)
1199  XSPerfAccumulate("hit_0_miss_1", f3_perf_info.hit_0_miss_1 && io.toIbuffer.fire)
1200  XSPerfAccumulate("miss_0_hit_1", f3_perf_info.miss_0_hit_1 && io.toIbuffer.fire)
1201  XSPerfAccumulate("miss_0_miss_1", f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire)
1202  XSPerfAccumulate("hit_0_except_1", f3_perf_info.hit_0_except_1 && io.toIbuffer.fire)
1203  XSPerfAccumulate("miss_0_except_1", f3_perf_info.miss_0_except_1 && io.toIbuffer.fire)
1204  XSPerfAccumulate("except_0", f3_perf_info.except_0 && io.toIbuffer.fire)
1205  XSPerfHistogram(
1206    "ifu2ibuffer_validCnt",
1207    PopCount(io.toIbuffer.bits.valid & io.toIbuffer.bits.enqEnable),
1208    io.toIbuffer.fire,
1209    0,
1210    PredictWidth + 1,
1211    1
1212  )
1213
1214  val hartId                     = p(XSCoreParamsKey).HartId
1215  val isWriteFetchToIBufferTable = Constantin.createRecord(s"isWriteFetchToIBufferTable$hartId")
1216  val isWriteIfuWbToFtqTable     = Constantin.createRecord(s"isWriteIfuWbToFtqTable$hartId")
1217  val fetchToIBufferTable        = ChiselDB.createTable(s"FetchToIBuffer$hartId", new FetchToIBufferDB)
1218  val ifuWbToFtqTable            = ChiselDB.createTable(s"IfuWbToFtq$hartId", new IfuWbToFtqDB)
1219
1220  val fetchIBufferDumpData = Wire(new FetchToIBufferDB)
1221  fetchIBufferDumpData.start_addr  := f3_ftq_req.startAddr
1222  fetchIBufferDumpData.instr_count := PopCount(io.toIbuffer.bits.enqEnable)
1223  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)
1224  fetchIBufferDumpData.is_cache_hit := f3_hit
1225
1226  val ifuWbToFtqDumpData = Wire(new IfuWbToFtqDB)
1227  ifuWbToFtqDumpData.start_addr        := wb_ftq_req.startAddr
1228  ifuWbToFtqDumpData.is_miss_pred      := checkFlushWb.bits.misOffset.valid
1229  ifuWbToFtqDumpData.miss_pred_offset  := checkFlushWb.bits.misOffset.bits
1230  ifuWbToFtqDumpData.checkJalFault     := checkJalFault
1231  ifuWbToFtqDumpData.checkJalrFault    := checkJalrFault
1232  ifuWbToFtqDumpData.checkRetFault     := checkRetFault
1233  ifuWbToFtqDumpData.checkTargetFault  := checkTargetFault
1234  ifuWbToFtqDumpData.checkNotCFIFault  := checkNotCFIFault
1235  ifuWbToFtqDumpData.checkInvalidTaken := checkInvalidTaken
1236
1237  fetchToIBufferTable.log(
1238    data = fetchIBufferDumpData,
1239    en = isWriteFetchToIBufferTable.orR && io.toIbuffer.fire,
1240    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
1241    clock = clock,
1242    reset = reset
1243  )
1244  ifuWbToFtqTable.log(
1245    data = ifuWbToFtqDumpData,
1246    en = isWriteIfuWbToFtqTable.orR && checkFlushWb.valid,
1247    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
1248    clock = clock,
1249    reset = reset
1250  )
1251
1252}
1253