xref: /XiangShan/src/main/scala/xiangshan/frontend/IFU.scala (revision b03c55a5df5dc8793cb44b42dd60141566e57e78)
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 org.chipsalliance.cde.config.Parameters
21import chisel3._
22import chisel3.util._
23import freechips.rocketchip.rocket.RVCDecoder
24import xiangshan._
25import xiangshan.cache.mmu._
26import xiangshan.frontend.icache._
27import utils._
28import utility._
29import xiangshan.backend.fu.{PMPReqBundle, PMPRespBundle}
30import utility.ChiselDB
31
32trait HasInstrMMIOConst extends HasXSParameter with HasIFUConst{
33  def mmioBusWidth = 64
34  def mmioBusBytes = mmioBusWidth / 8
35  def maxInstrLen = 32
36}
37
38trait HasIFUConst extends HasXSParameter{
39  def addrAlign(addr: UInt, bytes: Int, highest: Int): UInt = Cat(addr(highest-1, log2Ceil(bytes)), 0.U(log2Ceil(bytes).W))
40  def fetchQueueSize = 2
41
42  def getBasicBlockIdx( pc: UInt, start:  UInt ): UInt = {
43    val byteOffset = pc - start
44    (byteOffset - instBytes.U)(log2Ceil(PredictWidth),instOffsetBits)
45  }
46}
47
48class IfuToFtqIO(implicit p:Parameters) extends XSBundle {
49  val pdWb = Valid(new PredecodeWritebackBundle)
50}
51
52class IfuToBackendIO(implicit p:Parameters) extends XSBundle {
53  // write to backend gpaddr mem
54  val gpaddrMem_wen = Output(Bool())
55  val gpaddrMem_waddr = Output(UInt(log2Ceil(FtqSize).W)) // Ftq Ptr
56  // 2 gpaddrs, correspond to startAddr & nextLineAddr in bundle FtqICacheInfo
57  // TODO: avoid cross page entry in Ftq
58  val gpaddrMem_wdata = Output(UInt(GPAddrBits.W))
59}
60
61class FtqInterface(implicit p: Parameters) extends XSBundle {
62  val fromFtq = Flipped(new FtqToIfuIO)
63  val toFtq   = new IfuToFtqIO
64}
65
66class UncacheInterface(implicit p: Parameters) extends XSBundle {
67  val fromUncache = Flipped(DecoupledIO(new InsUncacheResp))
68  val toUncache   = DecoupledIO( new InsUncacheReq )
69}
70
71class NewIFUIO(implicit p: Parameters) extends XSBundle {
72  val ftqInter         = new FtqInterface
73  val icacheInter      = Flipped(new IFUICacheIO)
74  val icacheStop       = Output(Bool())
75  val icachePerfInfo   = Input(new ICachePerfInfo)
76  val toIbuffer        = Decoupled(new FetchToIBuffer)
77  val toBackend        = new IfuToBackendIO
78  val uncacheInter     = new UncacheInterface
79  val frontendTrigger  = Flipped(new FrontendTdataDistributeIO)
80  val rob_commits      = Flipped(Vec(CommitWidth, Valid(new RobCommitInfo)))
81  val iTLBInter        = new TlbRequestIO
82  val pmp              = new ICachePMPBundle
83  val mmioCommitRead   = new mmioCommitRead
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
100
101class IfuToPredChecker(implicit p: Parameters) extends XSBundle {
102  val ftqOffset     = Valid(UInt(log2Ceil(PredictWidth).W))
103  val jumpOffset    = Vec(PredictWidth, UInt(XLEN.W))
104  val target        = UInt(VAddrBits.W)
105  val instrRange    = Vec(PredictWidth, Bool())
106  val instrValid    = Vec(PredictWidth, Bool())
107  val pds           = Vec(PredictWidth, new PreDecodeInfo)
108  val pc            = Vec(PredictWidth, UInt(VAddrBits.W))
109  val fire_in       = Bool()
110}
111
112class FetchToIBufferDB extends Bundle {
113  val start_addr = UInt(39.W)
114  val instr_count = UInt(32.W)
115  val exception = Bool()
116  val is_cache_hit = Bool()
117}
118
119class IfuWbToFtqDB extends Bundle {
120  val start_addr = UInt(39.W)
121  val is_miss_pred = Bool()
122  val miss_pred_offset = UInt(32.W)
123  val checkJalFault = 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 HasIFUConst
133  with HasPdConst
134  with HasCircularQueuePtrHelper
135  with HasPerfEvents
136  with HasTlbConst
137{
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  }
155  def CatPC(lowVec: Vec[UInt], high: UInt, high1: UInt): Vec[UInt] = VecInit(lowVec.map(CatPC(_, high, high1)))
156  require(numOfStage > 1, "BPU numOfStage must be greater than 1")
157  val topdown_stages = RegInit(VecInit(Seq.fill(numOfStage)(0.U.asTypeOf(new FrontendTopDownBundle))))
158  // bubble events in IFU, only happen in stage 1
159  val icacheMissBubble = Wire(Bool())
160  val itlbMissBubble =Wire(Bool())
161
162  // only driven by clock, not valid-ready
163  topdown_stages(0) := fromFtq.req.bits.topdown_info
164  for (i <- 1 until numOfStage) {
165    topdown_stages(i) := topdown_stages(i - 1)
166  }
167  when (icacheMissBubble) {
168    topdown_stages(1).reasons(TopDownCounters.ICacheMissBubble.id) := true.B
169  }
170  when (itlbMissBubble) {
171    topdown_stages(1).reasons(TopDownCounters.ITLBMissBubble.id) := true.B
172  }
173  io.toIbuffer.bits.topdown_info := topdown_stages(numOfStage - 1)
174  when (fromFtq.topdown_redirect.valid) {
175    // only redirect from backend, IFU redirect itself is handled elsewhere
176    when (fromFtq.topdown_redirect.bits.debugIsCtrl) {
177      /*
178      for (i <- 0 until numOfStage) {
179        topdown_stages(i).reasons(TopDownCounters.ControlRedirectBubble.id) := true.B
180      }
181      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.ControlRedirectBubble.id) := true.B
182      */
183      when (fromFtq.topdown_redirect.bits.ControlBTBMissBubble) {
184        for (i <- 0 until numOfStage) {
185          topdown_stages(i).reasons(TopDownCounters.BTBMissBubble.id) := true.B
186        }
187        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.BTBMissBubble.id) := true.B
188      } .elsewhen (fromFtq.topdown_redirect.bits.TAGEMissBubble) {
189        for (i <- 0 until numOfStage) {
190          topdown_stages(i).reasons(TopDownCounters.TAGEMissBubble.id) := true.B
191        }
192        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.TAGEMissBubble.id) := true.B
193      } .elsewhen (fromFtq.topdown_redirect.bits.SCMissBubble) {
194        for (i <- 0 until numOfStage) {
195          topdown_stages(i).reasons(TopDownCounters.SCMissBubble.id) := true.B
196        }
197        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.SCMissBubble.id) := true.B
198      } .elsewhen (fromFtq.topdown_redirect.bits.ITTAGEMissBubble) {
199        for (i <- 0 until numOfStage) {
200          topdown_stages(i).reasons(TopDownCounters.ITTAGEMissBubble.id) := true.B
201        }
202        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.ITTAGEMissBubble.id) := true.B
203      } .elsewhen (fromFtq.topdown_redirect.bits.RASMissBubble) {
204        for (i <- 0 until numOfStage) {
205          topdown_stages(i).reasons(TopDownCounters.RASMissBubble.id) := true.B
206        }
207        io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.RASMissBubble.id) := true.B
208      }
209    } .elsewhen (fromFtq.topdown_redirect.bits.debugIsMemVio) {
210      for (i <- 0 until numOfStage) {
211        topdown_stages(i).reasons(TopDownCounters.MemVioRedirectBubble.id) := true.B
212      }
213      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.MemVioRedirectBubble.id) := true.B
214    } .otherwise {
215      for (i <- 0 until numOfStage) {
216        topdown_stages(i).reasons(TopDownCounters.OtherRedirectBubble.id) := true.B
217      }
218      io.toIbuffer.bits.topdown_info.reasons(TopDownCounters.OtherRedirectBubble.id) := true.B
219    }
220  }
221
222  class TlbExept(implicit p: Parameters) extends XSBundle{
223    val pageFault = Bool()
224    val accessFault = Bool()
225    val mmio = Bool()
226  }
227
228  val preDecoder       = Module(new PreDecode)
229
230  val predChecker     = Module(new PredChecker)
231  val frontendTrigger = Module(new FrontendTrigger)
232  val (checkerIn, checkerOutStage1, checkerOutStage2)         = (predChecker.io.in, predChecker.io.out.stage1Out,predChecker.io.out.stage2Out)
233
234  io.iTLBInter.req_kill := false.B
235  io.iTLBInter.resp.ready := true.B
236
237  /**
238    ******************************************************************************
239    * IFU Stage 0
240    * - send cacheline fetch request to ICacheMainPipe
241    ******************************************************************************
242    */
243
244  val f0_valid                             = fromFtq.req.valid
245  val f0_ftq_req                           = fromFtq.req.bits
246  val f0_doubleLine                        = fromFtq.req.bits.crossCacheline
247  val f0_vSetIdx                           = VecInit(get_idx((f0_ftq_req.startAddr)), get_idx(f0_ftq_req.nextlineStart))
248  val f0_fire                              = fromFtq.req.fire
249
250  val f0_flush, f1_flush, f2_flush, f3_flush = WireInit(false.B)
251  val from_bpu_f0_flush, from_bpu_f1_flush, from_bpu_f2_flush, from_bpu_f3_flush = WireInit(false.B)
252
253  from_bpu_f0_flush := fromFtq.flushFromBpu.shouldFlushByStage2(f0_ftq_req.ftqIdx) ||
254                       fromFtq.flushFromBpu.shouldFlushByStage3(f0_ftq_req.ftqIdx)
255
256  val wb_redirect , mmio_redirect,  backend_redirect= WireInit(false.B)
257  val f3_wb_not_flush = WireInit(false.B)
258
259  backend_redirect := fromFtq.redirect.valid
260  f3_flush := backend_redirect || (wb_redirect && !f3_wb_not_flush)
261  f2_flush := backend_redirect || mmio_redirect || wb_redirect
262  f1_flush := f2_flush || from_bpu_f1_flush
263  f0_flush := f1_flush || from_bpu_f0_flush
264
265  val f1_ready, f2_ready, f3_ready         = WireInit(false.B)
266
267  fromFtq.req.ready := f1_ready && io.icacheInter.icacheReady
268
269
270  when (wb_redirect) {
271    when (f3_wb_not_flush) {
272      topdown_stages(2).reasons(TopDownCounters.BTBMissBubble.id) := true.B
273    }
274    for (i <- 0 until numOfStage - 1) {
275      topdown_stages(i).reasons(TopDownCounters.BTBMissBubble.id) := true.B
276    }
277  }
278
279  /** <PERF> f0 fetch bubble */
280
281  XSPerfAccumulate("fetch_bubble_ftq_not_valid",   !fromFtq.req.valid && fromFtq.req.ready  )
282  // XSPerfAccumulate("fetch_bubble_pipe_stall",    f0_valid && toICache(0).ready && toICache(1).ready && !f1_ready )
283  // XSPerfAccumulate("fetch_bubble_icache_0_busy",   f0_valid && !toICache(0).ready  )
284  // XSPerfAccumulate("fetch_bubble_icache_1_busy",   f0_valid && !toICache(1).ready  )
285  XSPerfAccumulate("fetch_flush_backend_redirect",   backend_redirect  )
286  XSPerfAccumulate("fetch_flush_wb_redirect",    wb_redirect  )
287  XSPerfAccumulate("fetch_flush_bpu_f1_flush",   from_bpu_f1_flush  )
288  XSPerfAccumulate("fetch_flush_bpu_f0_flush",   from_bpu_f0_flush  )
289
290
291  /**
292    ******************************************************************************
293    * IFU Stage 1
294    * - calculate pc/half_pc/cut_ptr for every instruction
295    ******************************************************************************
296    */
297
298  val f1_valid      = RegInit(false.B)
299  val f1_ftq_req    = RegEnable(f0_ftq_req,    f0_fire)
300  // val f1_situation  = RegEnable(f0_situation,  f0_fire)
301  val f1_doubleLine = RegEnable(f0_doubleLine, f0_fire)
302  val f1_vSetIdx    = RegEnable(f0_vSetIdx,    f0_fire)
303  val f1_fire       = f1_valid && f2_ready
304
305  f1_ready := f1_fire || !f1_valid
306
307  from_bpu_f1_flush := fromFtq.flushFromBpu.shouldFlushByStage3(f1_ftq_req.ftqIdx) && f1_valid
308  // from_bpu_f1_flush := false.B
309
310  when(f1_flush)                  {f1_valid  := false.B}
311  .elsewhen(f0_fire && !f0_flush) {f1_valid  := true.B}
312  .elsewhen(f1_fire)              {f1_valid  := false.B}
313
314  val f1_pc_high            = f1_ftq_req.startAddr(VAddrBits-1, PcCutPoint)
315  val f1_pc_high_plus1      = f1_pc_high + 1.U
316
317  /**
318   * In order to reduce power consumption, avoid calculating the full PC value in the first level.
319   * code of original logic, this code has been deprecated
320   * val f1_pc                 = VecInit(f1_pc_lower_result.map{ i =>
321   *  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)))})
322   *
323   */
324  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
325
326  val f1_pc                 = CatPC(f1_pc_lower_result, f1_pc_high, f1_pc_high_plus1)
327
328  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
329  val f1_half_snpc            = CatPC(f1_half_snpc_lower_result, f1_pc_high, f1_pc_high_plus1)
330
331  if (env.FPGAPlatform){
332    val f1_pc_diff          = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + (i * 2).U))
333    val f1_half_snpc_diff   = VecInit((0 until PredictWidth).map(i => f1_ftq_req.startAddr + ((i+2) * 2).U))
334
335    XSError(f1_pc.zip(f1_pc_diff).map{ case (a,b) => a.asUInt =/= b.asUInt }.reduce(_||_), "f1_half_snpc adder cut fail")
336    XSError(f1_half_snpc.zip(f1_half_snpc_diff).map{ case (a,b) => a.asUInt =/= b.asUInt }.reduce(_||_),  "f1_half_snpc adder cut fail")
337  }
338
339  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 ))
340                                  else           VecInit((0 until PredictWidth).map(i =>     Cat(0.U(2.W), f1_ftq_req.startAddr(blockOffBits-1, 2)) + i.U ))
341
342  /**
343    ******************************************************************************
344    * IFU Stage 2
345    * - icache response data (latched for pipeline stop)
346    * - generate exceprion bits for every instruciton (page fault/access fault/mmio)
347    * - generate predicted instruction range (1 means this instruciton is in this fetch packet)
348    * - cut data from cachlines to packet instruction code
349    * - instruction predecode and RVC expand
350    ******************************************************************************
351    */
352
353  val icacheRespAllValid = WireInit(false.B)
354
355  val f2_valid      = RegInit(false.B)
356  val f2_ftq_req    = RegEnable(f1_ftq_req,    f1_fire)
357  // val f2_situation  = RegEnable(f1_situation,  f1_fire)
358  val f2_doubleLine = RegEnable(f1_doubleLine, f1_fire)
359  val f2_vSetIdx    = RegEnable(f1_vSetIdx,    f1_fire)
360  val f2_fire       = f2_valid && f3_ready && icacheRespAllValid
361
362  f2_ready := f2_fire || !f2_valid
363  //TODO: addr compare may be timing critical
364  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)
365  val f2_icache_all_resp_reg        = RegInit(false.B)
366
367  icacheRespAllValid := f2_icache_all_resp_reg || f2_icache_all_resp_wire
368
369  icacheMissBubble := io.icacheInter.topdownIcacheMiss
370  itlbMissBubble   := io.icacheInter.topdownItlbMiss
371
372  io.icacheStop := !f3_ready
373
374  when(f2_flush)                                              {f2_icache_all_resp_reg := false.B}
375  .elsewhen(f2_valid && f2_icache_all_resp_wire && !f3_ready) {f2_icache_all_resp_reg := true.B}
376  .elsewhen(f2_fire && f2_icache_all_resp_reg)                {f2_icache_all_resp_reg := false.B}
377
378  when(f2_flush)                  {f2_valid := false.B}
379  .elsewhen(f1_fire && !f1_flush) {f2_valid := true.B }
380  .elsewhen(f2_fire)              {f2_valid := false.B}
381
382  val f2_except_pf    = VecInit((0 until PortNumber).map(i => fromICache(i).bits.tlbExcp.pageFault))
383  val f2_except_gpf   = VecInit((0 until PortNumber).map(i => fromICache(i).bits.tlbExcp.guestPageFault))
384  val f2_except_af    = VecInit((0 until PortNumber).map(i => fromICache(i).bits.tlbExcp.accessFault))
385  // paddr and gpaddr of [startAddr, nextLineAddr]
386  val f2_paddrs       = VecInit((0 until PortNumber).map(i => fromICache(i).bits.paddr))
387  val f2_gpaddr       = fromICache(0).bits.gpaddr
388  val f2_mmio         = fromICache(0).bits.tlbExcp.mmio &&
389    !fromICache(0).bits.tlbExcp.accessFault &&
390    !fromICache(0).bits.tlbExcp.pageFault   &&
391    !fromICache(0).bits.tlbExcp.guestPageFault
392
393  /**
394    * reduce the number of registers, origin code
395    * f2_pc = RegEnable(f1_pc, f1_fire)
396    */
397  val f2_pc_lower_result        = RegEnable(f1_pc_lower_result, f1_fire)
398  val f2_pc_high                = RegEnable(f1_pc_high, f1_fire)
399  val f2_pc_high_plus1          = RegEnable(f1_pc_high_plus1, f1_fire)
400  val f2_pc                     = CatPC(f2_pc_lower_result, f2_pc_high, f2_pc_high_plus1)
401
402  val f2_cut_ptr                = RegEnable(f1_cut_ptr, f1_fire)
403  val f2_resend_vaddr           = RegEnable(f1_ftq_req.startAddr + 2.U, f1_fire)
404
405  def isNextLine(pc: UInt, startAddr: UInt) = {
406    startAddr(blockOffBits) ^ pc(blockOffBits)
407  }
408
409  def isLastInLine(pc: UInt) = {
410    pc(blockOffBits - 1, 0) === "b111110".U
411  }
412
413  val f2_foldpc = VecInit(f2_pc.map(i => XORFold(i(VAddrBits-1,1), MemPredPCWidth)))
414  val f2_jump_range = Fill(PredictWidth, !f2_ftq_req.ftqOffset.valid) | Fill(PredictWidth, 1.U(1.W)) >> ~f2_ftq_req.ftqOffset.bits
415  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)
416  val f2_instr_range = f2_jump_range & f2_ftr_range
417  val f2_pf_vec = VecInit((0 until PredictWidth).map(i => (!isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_except_pf(0)   ||  isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_doubleLine &&  f2_except_pf(1))))
418  val f2_af_vec = VecInit((0 until PredictWidth).map(i => (!isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_except_af(0)   ||  isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_doubleLine && f2_except_af(1))))
419  val f2_gpf_vec = VecInit((0 until PredictWidth).map(i => (!isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_except_gpf(0) || isNextLine(f2_pc(i), f2_ftq_req.startAddr) && f2_doubleLine && f2_except_gpf(1))))
420  val f2_perf_info    = io.icachePerfInfo
421
422  def cut(cacheline: UInt, cutPtr: Vec[UInt]) : Vec[UInt] ={
423    require(HasCExtension)
424    // if(HasCExtension){
425      val result   = Wire(Vec(PredictWidth + 1, UInt(16.W)))
426      val dataVec  = cacheline.asTypeOf(Vec(blockBytes, UInt(16.W))) //32 16-bit data vector
427      (0 until PredictWidth + 1).foreach( i =>
428        result(i) := dataVec(cutPtr(i)) //the max ptr is 3*blockBytes/4-1
429      )
430      result
431    // } else {
432    //   val result   = Wire(Vec(PredictWidth, UInt(32.W)) )
433    //   val dataVec  = cacheline.asTypeOf(Vec(blockBytes * 2/ 4, UInt(32.W)))
434    //   (0 until PredictWidth).foreach( i =>
435    //     result(i) := dataVec(cutPtr(i))
436    //   )
437    //   result
438    // }
439  }
440
441  val f2_cache_response_data = fromICache.map(_.bits.data)
442  val f2_data_2_cacheline = Cat(f2_cache_response_data(0), f2_cache_response_data(0))
443
444  val f2_cut_data   = cut(f2_data_2_cacheline, f2_cut_ptr)
445
446  /** predecode (include RVC expander) */
447  // preDecoderRegIn.data := f2_reg_cut_data
448  // preDecoderRegInIn.frontendTrigger := io.frontendTrigger
449  // preDecoderRegInIn.csrTriggerEnable := io.csrTriggerEnable
450  // preDecoderRegIn.pc  := f2_pc
451
452  val preDecoderIn  = preDecoder.io.in
453  preDecoderIn.valid := f2_valid
454  preDecoderIn.bits.data := f2_cut_data
455  preDecoderIn.bits.frontendTrigger := io.frontendTrigger
456  preDecoderIn.bits.pc  := f2_pc
457  val preDecoderOut = preDecoder.io.out
458
459  //val f2_expd_instr     = preDecoderOut.expInstr
460  val f2_instr          = preDecoderOut.instr
461  val f2_pd             = preDecoderOut.pd
462  val f2_jump_offset    = preDecoderOut.jumpOffset
463  val f2_hasHalfValid   =  preDecoderOut.hasHalfValid
464  val f2_crossPageFault = VecInit((0 until PredictWidth).map(i => isLastInLine(f2_pc(i)) && !f2_except_pf(0) && f2_doubleLine &&  f2_except_pf(1) && !f2_pd(i).isRVC ))
465  val f2_crossGuestPageFault = VecInit((0 until PredictWidth).map(i => isLastInLine(f2_pc(i)) && !f2_except_gpf(0) && f2_doubleLine && f2_except_gpf(1) && !f2_pd(i).isRVC ))
466  XSPerfAccumulate("fetch_bubble_icache_not_resp",   f2_valid && !icacheRespAllValid )
467
468
469  /**
470    ******************************************************************************
471    * IFU Stage 3
472    * - handle MMIO instruciton
473    *  -send request to Uncache fetch Unit
474    *  -every packet include 1 MMIO instruction
475    *  -MMIO instructions will stop fetch pipeline until commiting from RoB
476    *  -flush to snpc (send ifu_redirect to Ftq)
477    * - Ibuffer enqueue
478    * - check predict result in Frontend (jalFault/retFault/notCFIFault/invalidTakenFault/targetFault)
479    * - handle last half RVI instruction
480    ******************************************************************************
481    */
482
483  val f3_valid          = RegInit(false.B)
484  val f3_ftq_req        = RegEnable(f2_ftq_req,    f2_fire)
485  // val f3_situation      = RegEnable(f2_situation,  f2_fire)
486  val f3_doubleLine     = RegEnable(f2_doubleLine, f2_fire)
487  val f3_fire           = io.toIbuffer.fire
488
489  val f3_cut_data       = RegEnable(f2_cut_data, f2_fire)
490
491  val f3_except_pf      = RegEnable(f2_except_pf,  f2_fire)
492  val f3_except_af      = RegEnable(f2_except_af,  f2_fire)
493  val f3_except_gpf     = RegEnable(f2_except_gpf,  f2_fire)
494  val f3_mmio           = RegEnable(f2_mmio   ,  f2_fire)
495
496  //val f3_expd_instr     = RegEnable(f2_expd_instr,  f2_fire)
497  val f3_instr          = RegEnable(f2_instr, f2_fire)
498  val f3_expd_instr     = VecInit((0 until PredictWidth).map{ i =>
499    val expander       = Module(new RVCExpander)
500    expander.io.in := f3_instr(i)
501    expander.io.out.bits
502  })
503
504  val f3_pd_wire        = RegEnable(f2_pd,          f2_fire)
505  val f3_pd             = WireInit(f3_pd_wire)
506  val f3_jump_offset    = RegEnable(f2_jump_offset, f2_fire)
507  val f3_af_vec         = RegEnable(f2_af_vec,      f2_fire)
508  val f3_pf_vec         = RegEnable(f2_pf_vec ,     f2_fire)
509  val f3_gpf_vec        = RegEnable(f2_gpf_vec,     f2_fire)
510
511  val f3_pc_lower_result        = RegEnable(f2_pc_lower_result, f2_fire)
512  val f3_pc_high                = RegEnable(f2_pc_high, f2_fire)
513  val f3_pc_high_plus1          = RegEnable(f2_pc_high_plus1, f2_fire)
514  val f3_pc             = CatPC(f3_pc_lower_result, f3_pc_high, f3_pc_high_plus1)
515
516  val f3_pc_last_lower_result_plus2 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 2.U, f2_fire)
517  val f3_pc_last_lower_result_plus4 = RegEnable(f2_pc_lower_result(PredictWidth - 1) + 4.U, f2_fire)
518  //val f3_half_snpc      = RegEnable(f2_half_snpc,   f2_fire)
519
520  /**
521    ***********************************************************************
522    * Half snpc(i) is larger than pc(i) by 4. Using pc to calculate half snpc may be a good choice.
523    ***********************************************************************
524    */
525  val f3_half_snpc      = Wire(Vec(PredictWidth,UInt(VAddrBits.W)))
526  for(i <- 0 until PredictWidth){
527    if(i == (PredictWidth - 2)){
528      f3_half_snpc(i)   := CatPC(f3_pc_last_lower_result_plus2, f3_pc_high, f3_pc_high_plus1)
529    } else if (i == (PredictWidth - 1)){
530      f3_half_snpc(i)   := CatPC(f3_pc_last_lower_result_plus4, f3_pc_high, f3_pc_high_plus1)
531    } else {
532      f3_half_snpc(i)   := f3_pc(i+2)
533    }
534  }
535
536  val f3_instr_range    = RegEnable(f2_instr_range, f2_fire)
537  val f3_foldpc         = RegEnable(f2_foldpc,      f2_fire)
538  val f3_crossPageFault = RegEnable(f2_crossPageFault,           f2_fire)
539  val f3_crossGuestPageFault = RegEnable(f2_crossGuestPageFault, f2_fire)
540  val f3_hasHalfValid   = RegEnable(f2_hasHalfValid,             f2_fire)
541  val f3_except         = VecInit((0 until 2).map{i => f3_except_pf(i) || f3_except_af(i) || f3_except_gpf(i)})
542  val f3_has_except     = f3_valid && (f3_except_af.reduce(_||_) || f3_except_pf.reduce(_||_) || f3_except_gpf.reduce(_||_))
543  val f3_paddrs         = RegEnable(f2_paddrs,  f2_fire)
544  val f3_gpaddr         = RegEnable(f2_gpaddr,  f2_fire)
545  val f3_resend_vaddr   = RegEnable(f2_resend_vaddr,             f2_fire)
546
547  // Expand 1 bit to prevent overflow when assert
548  val f3_ftq_req_startAddr      = Cat(0.U(1.W), f3_ftq_req.startAddr)
549  val f3_ftq_req_nextStartAddr  = Cat(0.U(1.W), f3_ftq_req.nextStartAddr)
550  // brType, isCall and isRet generation is delayed to f3 stage
551  val f3Predecoder = Module(new F3Predecoder)
552
553  f3Predecoder.io.in.instr := f3_instr
554
555  f3_pd.zipWithIndex.map{ case (pd,i) =>
556    pd.brType := f3Predecoder.io.out.pd(i).brType
557    pd.isCall := f3Predecoder.io.out.pd(i).isCall
558    pd.isRet  := f3Predecoder.io.out.pd(i).isRet
559  }
560
561  val f3PdDiff = f3_pd_wire.zip(f3_pd).map{ case (a,b) => a.asUInt =/= b.asUInt }.reduce(_||_)
562  XSError(f3_valid && f3PdDiff, "f3 pd diff")
563
564  when(f3_valid && !f3_ftq_req.ftqOffset.valid){
565    assert(f3_ftq_req_startAddr + (2*PredictWidth).U >= f3_ftq_req_nextStartAddr, s"More tha ${2*PredictWidth} Bytes fetch is not allowed!")
566  }
567
568  /*** MMIO State Machine***/
569  val f3_mmio_data       = Reg(Vec(2, UInt(16.W)))
570  val mmio_is_RVC        = RegInit(false.B)
571  val mmio_resend_addr   = RegInit(0.U(PAddrBits.W))
572  val mmio_resend_af     = RegInit(false.B)
573  val mmio_resend_pf     = RegInit(false.B)
574  val mmio_resend_gpf    = RegInit(false.B)
575  val mmio_resend_gpaddr = RegInit(0.U(GPAddrBits.W))
576
577  //last instuction finish
578  val is_first_instr = RegInit(true.B)
579  /*** Determine whether the MMIO instruction is executable based on the previous prediction block ***/
580  io.mmioCommitRead.mmioFtqPtr := RegNext(f3_ftq_req.ftqIdx - 1.U)
581
582  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)
583  val mmio_state = RegInit(m_idle)
584
585  val f3_req_is_mmio     = f3_mmio && f3_valid
586  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
587  val f3_mmio_req_commit = f3_req_is_mmio && mmio_state === m_commited
588
589  val f3_mmio_to_commit =  f3_req_is_mmio && mmio_state === m_waitCommit
590  val f3_mmio_to_commit_next = RegNext(f3_mmio_to_commit)
591  val f3_mmio_can_go      = f3_mmio_to_commit && !f3_mmio_to_commit_next
592
593  val fromFtqRedirectReg = Wire(fromFtq.redirect.cloneType)
594  fromFtqRedirectReg.bits := RegEnable(fromFtq.redirect.bits, 0.U.asTypeOf(fromFtq.redirect.bits), fromFtq.redirect.valid)
595  fromFtqRedirectReg.valid := RegNext(fromFtq.redirect.valid, init = false.B)
596  val mmioF3Flush           = RegNext(f3_flush,init = false.B)
597  val f3_ftq_flush_self     = fromFtqRedirectReg.valid && RedirectLevel.flushItself(fromFtqRedirectReg.bits.level)
598  val f3_ftq_flush_by_older = fromFtqRedirectReg.valid && isBefore(fromFtqRedirectReg.bits.ftqIdx, f3_ftq_req.ftqIdx)
599
600  val f3_need_not_flush = f3_req_is_mmio && fromFtqRedirectReg.valid && !f3_ftq_flush_self && !f3_ftq_flush_by_older
601
602  /**
603    **********************************************************************************
604    * We want to defer instruction fetching when encountering MMIO instructions to ensure that the MMIO region is not negatively impacted.
605    * This is the exception when the first instruction is an MMIO instruction.
606    **********************************************************************************
607    */
608  when(is_first_instr && f3_fire){
609    is_first_instr := false.B
610  }
611
612  when(f3_flush && !f3_req_is_mmio)                                                 {f3_valid := false.B}
613  .elsewhen(mmioF3Flush && f3_req_is_mmio && !f3_need_not_flush)                    {f3_valid := false.B}
614  .elsewhen(f2_fire && !f2_flush )                                                  {f3_valid := true.B }
615  .elsewhen(io.toIbuffer.fire && !f3_req_is_mmio)                                   {f3_valid := false.B}
616  .elsewhen{f3_req_is_mmio && f3_mmio_req_commit}                                   {f3_valid := false.B}
617
618  val f3_mmio_use_seq_pc = RegInit(false.B)
619
620  val (redirect_ftqIdx, redirect_ftqOffset)  = (fromFtqRedirectReg.bits.ftqIdx,fromFtqRedirectReg.bits.ftqOffset)
621  val redirect_mmio_req = fromFtqRedirectReg.valid && redirect_ftqIdx === f3_ftq_req.ftqIdx && redirect_ftqOffset === 0.U
622
623  when(RegNext(f2_fire && !f2_flush) && f3_req_is_mmio)        { f3_mmio_use_seq_pc := true.B  }
624  .elsewhen(redirect_mmio_req)                                 { f3_mmio_use_seq_pc := false.B }
625
626  f3_ready := (io.toIbuffer.ready && (f3_mmio_req_commit || !f3_req_is_mmio)) || !f3_valid
627
628  // mmio state machine
629  switch(mmio_state){
630    is(m_idle){
631      when(f3_req_is_mmio){
632        mmio_state := m_waitLastCmt
633      }
634    }
635
636    is(m_waitLastCmt){
637      when(is_first_instr){
638        mmio_state := m_sendReq
639      }.otherwise{
640        mmio_state := Mux(io.mmioCommitRead.mmioLastCommit, m_sendReq, m_waitLastCmt)
641      }
642    }
643
644    is(m_sendReq){
645      mmio_state := Mux(toUncache.fire, m_waitResp, m_sendReq)
646    }
647
648    is(m_waitResp){
649      when(fromUncache.fire){
650          val isRVC = fromUncache.bits.data(1,0) =/= 3.U
651          val needResend = !isRVC && f3_paddrs(0)(2,1) === 3.U
652          mmio_state      := Mux(needResend, m_sendTLB, m_waitCommit)
653          mmio_is_RVC     := isRVC
654          f3_mmio_data(0) := fromUncache.bits.data(15,0)
655          f3_mmio_data(1) := fromUncache.bits.data(31,16)
656      }
657    }
658
659    is(m_sendTLB){
660      when( io.iTLBInter.req.valid && !io.iTLBInter.resp.bits.miss ){
661        mmio_state := m_tlbResp
662      }
663    }
664
665    is(m_tlbResp){
666      val tlbExept = io.iTLBInter.resp.bits.excp(0).pf.instr ||
667                     io.iTLBInter.resp.bits.excp(0).af.instr ||
668                     io.iTLBInter.resp.bits.excp(0).gpf.instr
669      mmio_state         := Mux(tlbExept, m_waitCommit, m_sendPMP)
670      mmio_resend_addr   := io.iTLBInter.resp.bits.paddr(0)
671      mmio_resend_af     := mmio_resend_af || io.iTLBInter.resp.bits.excp(0).af.instr
672      mmio_resend_pf     := mmio_resend_pf || io.iTLBInter.resp.bits.excp(0).pf.instr
673      mmio_resend_gpf    := mmio_resend_gpf || io.iTLBInter.resp.bits.excp(0).gpf.instr
674      mmio_resend_gpaddr := io.iTLBInter.resp.bits.gpaddr(0)
675    }
676
677    is(m_sendPMP){
678      val pmpExcpAF = io.pmp.resp.instr || !io.pmp.resp.mmio
679      mmio_state     := Mux(pmpExcpAF, m_waitCommit, m_resendReq)
680      mmio_resend_af := pmpExcpAF
681    }
682
683    is(m_resendReq){
684      mmio_state := Mux(toUncache.fire, m_waitResendResp, m_resendReq)
685    }
686
687    is(m_waitResendResp){
688      when(fromUncache.fire){
689          mmio_state      := m_waitCommit
690          f3_mmio_data(1) := fromUncache.bits.data(15,0)
691      }
692    }
693
694    is(m_waitCommit){
695      when(mmio_commit){
696          mmio_state := m_commited
697      }
698    }
699
700    //normal mmio instruction
701    is(m_commited){
702      mmio_state         := m_idle
703      mmio_is_RVC        := false.B
704      mmio_resend_addr   := 0.U
705      mmio_resend_af     := false.B
706      mmio_resend_pf     := false.B
707      mmio_resend_gpf    := false.B
708      mmio_resend_gpaddr := 0.U
709    }
710  }
711
712  // Exception or flush by older branch prediction
713  // Condition is from RegNext(fromFtq.redirect), 1 cycle after backend rediect
714  when(f3_ftq_flush_self || f3_ftq_flush_by_older)  {
715    mmio_state         := m_idle
716    mmio_is_RVC        := false.B
717    mmio_resend_addr   := 0.U
718    mmio_resend_af     := false.B
719    mmio_resend_pf     := false.B
720    mmio_resend_gpf    := false.B
721    mmio_resend_gpaddr := 0.U
722    f3_mmio_data.map(_ := 0.U)
723  }
724
725  toUncache.valid     :=  ((mmio_state === m_sendReq) || (mmio_state === m_resendReq)) && f3_req_is_mmio
726  toUncache.bits.addr := Mux((mmio_state === m_resendReq), mmio_resend_addr, f3_paddrs(0))
727  fromUncache.ready   := true.B
728
729  io.iTLBInter.req.valid         := (mmio_state === m_sendTLB) && f3_req_is_mmio
730  io.iTLBInter.req.bits.size     := 3.U
731  io.iTLBInter.req.bits.vaddr    := f3_resend_vaddr
732  io.iTLBInter.req.bits.debug.pc := f3_resend_vaddr
733  io.iTLBInter.req.bits.hyperinst:= DontCare
734  io.iTLBInter.req.bits.hlvx     := DontCare
735
736  io.iTLBInter.req.bits.kill                := false.B // IFU use itlb for mmio, doesn't need sync, set it to false
737  io.iTLBInter.req.bits.cmd                 := TlbCmd.exec
738  io.iTLBInter.req.bits.memidx              := DontCare
739  io.iTLBInter.req.bits.debug.robIdx        := DontCare
740  io.iTLBInter.req.bits.no_translate        := false.B
741  io.iTLBInter.req.bits.debug.isFirstIssue  := DontCare
742
743  io.pmp.req.valid := (mmio_state === m_sendPMP) && f3_req_is_mmio
744  io.pmp.req.bits.addr  := mmio_resend_addr
745  io.pmp.req.bits.size  := 3.U
746  io.pmp.req.bits.cmd   := TlbCmd.exec
747
748  val f3_lastHalf       = RegInit(0.U.asTypeOf(new LastHalfInfo))
749
750  val f3_predecode_range = VecInit(preDecoderOut.pd.map(inst => inst.valid)).asUInt
751  val f3_mmio_range      = VecInit((0 until PredictWidth).map(i => if(i ==0) true.B else false.B))
752  val f3_instr_valid     = Wire(Vec(PredictWidth, Bool()))
753
754  /*** prediction result check   ***/
755  checkerIn.ftqOffset   := f3_ftq_req.ftqOffset
756  checkerIn.jumpOffset  := f3_jump_offset
757  checkerIn.target      := f3_ftq_req.nextStartAddr
758  checkerIn.instrRange  := f3_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
759  checkerIn.instrValid  := f3_instr_valid.asTypeOf(Vec(PredictWidth, Bool()))
760  checkerIn.pds         := f3_pd
761  checkerIn.pc          := f3_pc
762  checkerIn.fire_in     := RegNext(f2_fire, init = false.B)
763
764  /*** handle half RVI in the last 2 Bytes  ***/
765
766  def hasLastHalf(idx: UInt) = {
767    //!f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(idx) && !checkerOutStage2.fixedMissPred(idx) && ! f3_req_is_mmio
768    !f3_pd(idx).isRVC && checkerOutStage1.fixedRange(idx) && f3_instr_valid(idx) && !checkerOutStage1.fixedTaken(idx) && ! f3_req_is_mmio
769  }
770
771  val f3_last_validIdx       = ParallelPosteriorityEncoder(checkerOutStage1.fixedRange)
772
773  val f3_hasLastHalf         = hasLastHalf((PredictWidth - 1).U)
774  val f3_false_lastHalf      = hasLastHalf(f3_last_validIdx)
775  val f3_false_snpc          = f3_half_snpc(f3_last_validIdx)
776
777  val f3_lastHalf_mask    = VecInit((0 until PredictWidth).map( i => if(i ==0) false.B else true.B )).asUInt
778  val f3_lastHalf_disable = RegInit(false.B)
779
780  when(f3_flush || (f3_fire && f3_lastHalf_disable)){
781    f3_lastHalf_disable := false.B
782  }
783
784  when (f3_flush) {
785    f3_lastHalf.valid := false.B
786  }.elsewhen (f3_fire) {
787    f3_lastHalf.valid := f3_hasLastHalf && !f3_lastHalf_disable
788    f3_lastHalf.middlePC := f3_ftq_req.nextStartAddr
789  }
790
791  f3_instr_valid := Mux(f3_lastHalf.valid,f3_hasHalfValid ,VecInit(f3_pd.map(inst => inst.valid)))
792
793  /*** frontend Trigger  ***/
794  frontendTrigger.io.pds  := f3_pd
795  frontendTrigger.io.pc   := f3_pc
796  frontendTrigger.io.data   := f3_cut_data
797
798  frontendTrigger.io.frontendTrigger  := io.frontendTrigger
799
800  val f3_triggered = frontendTrigger.io.triggered
801  val f3_toIbuffer_valid = f3_valid && (!f3_req_is_mmio || f3_mmio_can_go) && !f3_flush
802
803  /*** send to Ibuffer  ***/
804  io.toIbuffer.valid            := f3_toIbuffer_valid
805  io.toIbuffer.bits.instrs      := f3_expd_instr
806  io.toIbuffer.bits.valid       := f3_instr_valid.asUInt
807  io.toIbuffer.bits.enqEnable   := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt
808  io.toIbuffer.bits.pd          := f3_pd
809  io.toIbuffer.bits.ftqPtr      := f3_ftq_req.ftqIdx
810  io.toIbuffer.bits.pc          := f3_pc
811  io.toIbuffer.bits.ftqOffset.zipWithIndex.map{case(a, i) => a.bits := i.U; a.valid := checkerOutStage1.fixedTaken(i) && !f3_req_is_mmio}
812  io.toIbuffer.bits.foldpc      := f3_foldpc
813  io.toIbuffer.bits.exceptionType := (0 until PredictWidth).map(i => MuxCase(ExceptionType.none, Seq(
814    (f3_pf_vec(i) || f3_crossPageFault(i)) -> ExceptionType.ipf,
815    (f3_gpf_vec(i) || f3_crossGuestPageFault(i)) -> ExceptionType.igpf,
816    f3_af_vec(i) -> ExceptionType.acf
817  )))
818  io.toIbuffer.bits.crossPageIPFFix := (0 until PredictWidth).map(i => f3_crossPageFault(i) || f3_crossGuestPageFault(i))
819  io.toIbuffer.bits.triggered   := f3_triggered
820
821  when(f3_lastHalf.valid){
822    io.toIbuffer.bits.enqEnable := checkerOutStage1.fixedRange.asUInt & f3_instr_valid.asUInt & f3_lastHalf_mask
823    io.toIbuffer.bits.valid     := f3_lastHalf_mask & f3_instr_valid.asUInt
824  }
825
826  /** to backend */
827  // f3_gpaddr is valid iff gpf is detected
828  io.toBackend.gpaddrMem_wen   := f3_toIbuffer_valid && Mux(
829    f3_req_is_mmio,
830    mmio_resend_gpf,
831    f3_gpf_vec.asUInt.orR || f3_crossGuestPageFault.asUInt.orR
832  )
833  io.toBackend.gpaddrMem_waddr := f3_ftq_req.ftqIdx.value
834  io.toBackend.gpaddrMem_wdata := Mux(f3_req_is_mmio, mmio_resend_gpaddr, f3_gpaddr)
835
836  //Write back to Ftq
837  val f3_cache_fetch = f3_valid && !(f2_fire && !f2_flush)
838  val finishFetchMaskReg = RegNext(f3_cache_fetch)
839
840  val mmioFlushWb = Wire(Valid(new PredecodeWritebackBundle))
841  val f3_mmio_missOffset = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
842  f3_mmio_missOffset.valid := f3_req_is_mmio
843  f3_mmio_missOffset.bits  := 0.U
844
845  // Send mmioFlushWb back to FTQ 1 cycle after uncache fetch return
846  // When backend redirect, mmio_state reset after 1 cycle.
847  // In this case, mask .valid to avoid overriding backend redirect
848  mmioFlushWb.valid           := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire) &&
849    f3_mmio_use_seq_pc && !f3_ftq_flush_self && !f3_ftq_flush_by_older)
850  mmioFlushWb.bits.pc         := f3_pc
851  mmioFlushWb.bits.pd         := f3_pd
852  mmioFlushWb.bits.pd.zipWithIndex.map{case(instr,i) => instr.valid :=  f3_mmio_range(i)}
853  mmioFlushWb.bits.ftqIdx     := f3_ftq_req.ftqIdx
854  mmioFlushWb.bits.ftqOffset  := f3_ftq_req.ftqOffset.bits
855  mmioFlushWb.bits.misOffset  := f3_mmio_missOffset
856  mmioFlushWb.bits.cfiOffset  := DontCare
857  mmioFlushWb.bits.target     := Mux(mmio_is_RVC, f3_ftq_req.startAddr + 2.U , f3_ftq_req.startAddr + 4.U)
858  mmioFlushWb.bits.jalTarget  := DontCare
859  mmioFlushWb.bits.instrRange := f3_mmio_range
860
861  /** external predecode for MMIO instruction */
862  when(f3_req_is_mmio){
863    val inst  = Cat(f3_mmio_data(1), f3_mmio_data(0))
864    val currentIsRVC   = isRVC(inst)
865
866    val brType::isCall::isRet::Nil = brInfo(inst)
867    val jalOffset = jal_offset(inst, currentIsRVC)
868    val brOffset  = br_offset(inst, currentIsRVC)
869
870    io.toIbuffer.bits.instrs(0) := new RVCDecoder(inst, XLEN, fLen, useAddiForMv = true).decode.bits
871
872
873    io.toIbuffer.bits.pd(0).valid   := true.B
874    io.toIbuffer.bits.pd(0).isRVC   := currentIsRVC
875    io.toIbuffer.bits.pd(0).brType  := brType
876    io.toIbuffer.bits.pd(0).isCall  := isCall
877    io.toIbuffer.bits.pd(0).isRet   := isRet
878
879    when (mmio_resend_af) {
880      io.toIbuffer.bits.exceptionType(0) := ExceptionType.acf
881    } .elsewhen (mmio_resend_pf) {
882      io.toIbuffer.bits.exceptionType(0) := ExceptionType.ipf
883    } .elsewhen (mmio_resend_gpf) {
884      io.toIbuffer.bits.exceptionType(0) := ExceptionType.igpf
885    }
886    io.toIbuffer.bits.crossPageIPFFix(0) := mmio_resend_pf
887
888    io.toIbuffer.bits.enqEnable   := f3_mmio_range.asUInt
889
890    mmioFlushWb.bits.pd(0).valid   := true.B
891    mmioFlushWb.bits.pd(0).isRVC   := currentIsRVC
892    mmioFlushWb.bits.pd(0).brType  := brType
893    mmioFlushWb.bits.pd(0).isCall  := isCall
894    mmioFlushWb.bits.pd(0).isRet   := isRet
895  }
896
897  mmio_redirect := (f3_req_is_mmio && mmio_state === m_waitCommit && RegNext(fromUncache.fire)  && f3_mmio_use_seq_pc)
898
899  XSPerfAccumulate("fetch_bubble_ibuffer_not_ready",   io.toIbuffer.valid && !io.toIbuffer.ready )
900
901
902  /**
903    ******************************************************************************
904    * IFU Write Back Stage
905    * - write back predecode information to Ftq to update
906    * - redirect if found fault prediction
907    * - redirect if has false hit last half (last PC is not start + 32 Bytes, but in the midle of an notCFI RVI instruction)
908    ******************************************************************************
909    */
910  val wb_enable         = RegNext(f2_fire && !f2_flush) && !f3_req_is_mmio && !f3_flush
911  val wb_valid          = RegNext(wb_enable, init = false.B)
912  val wb_ftq_req        = RegEnable(f3_ftq_req, wb_enable)
913
914  val wb_check_result_stage1   = RegEnable(checkerOutStage1, wb_enable)
915  val wb_check_result_stage2   = checkerOutStage2
916  val wb_instr_range    = RegEnable(io.toIbuffer.bits.enqEnable, wb_enable)
917
918  val wb_pc_lower_result        = RegEnable(f3_pc_lower_result, wb_enable)
919  val wb_pc_high                = RegEnable(f3_pc_high, wb_enable)
920  val wb_pc_high_plus1          = RegEnable(f3_pc_high_plus1, wb_enable)
921  val wb_pc                     = CatPC(wb_pc_lower_result, wb_pc_high, wb_pc_high_plus1)
922
923  //val wb_pc             = RegEnable(f3_pc, wb_enable)
924  val wb_pd             = RegEnable(f3_pd, wb_enable)
925  val wb_instr_valid    = RegEnable(f3_instr_valid, wb_enable)
926
927  /* false hit lastHalf */
928  val wb_lastIdx        = RegEnable(f3_last_validIdx, wb_enable)
929  val wb_false_lastHalf = RegEnable(f3_false_lastHalf, wb_enable) && wb_lastIdx =/= (PredictWidth - 1).U
930  val wb_false_target   = RegEnable(f3_false_snpc, wb_enable)
931
932  val wb_half_flush = wb_false_lastHalf
933  val wb_half_target = wb_false_target
934
935  /* false oversize */
936  val lastIsRVC = wb_instr_range.asTypeOf(Vec(PredictWidth,Bool())).last  && wb_pd.last.isRVC
937  val lastIsRVI = wb_instr_range.asTypeOf(Vec(PredictWidth,Bool()))(PredictWidth - 2) && !wb_pd(PredictWidth - 2).isRVC
938  val lastTaken = wb_check_result_stage1.fixedTaken.last
939
940  f3_wb_not_flush := wb_ftq_req.ftqIdx === f3_ftq_req.ftqIdx && f3_valid && wb_valid
941
942  /** if a req with a last half but miss predicted enters in wb stage, and this cycle f3 stalls,
943    * we set a flag to notify f3 that the last half flag need not to be set.
944    */
945  //f3_fire is after wb_valid
946  when(wb_valid && RegNext(f3_hasLastHalf,init = false.B)
947        && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && !f3_fire  && !RegNext(f3_fire,init = false.B) && !f3_flush
948      ){
949    f3_lastHalf_disable := true.B
950  }
951
952  //wb_valid and f3_fire are in same cycle
953  when(wb_valid && RegNext(f3_hasLastHalf,init = false.B)
954        && wb_check_result_stage2.fixedMissPred(PredictWidth - 1) && f3_fire
955      ){
956    f3_lastHalf.valid := false.B
957  }
958
959  val checkFlushWb = Wire(Valid(new PredecodeWritebackBundle))
960  val checkFlushWbjalTargetIdx = ParallelPriorityEncoder(VecInit(wb_pd.zip(wb_instr_valid).map{case (pd, v) => v && pd.isJal }))
961  val checkFlushWbTargetIdx = ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred)
962  checkFlushWb.valid                  := wb_valid
963  checkFlushWb.bits.pc                := wb_pc
964  checkFlushWb.bits.pd                := wb_pd
965  checkFlushWb.bits.pd.zipWithIndex.map{case(instr,i) => instr.valid := wb_instr_valid(i)}
966  checkFlushWb.bits.ftqIdx            := wb_ftq_req.ftqIdx
967  checkFlushWb.bits.ftqOffset         := wb_ftq_req.ftqOffset.bits
968  checkFlushWb.bits.misOffset.valid   := ParallelOR(wb_check_result_stage2.fixedMissPred) || wb_half_flush
969  checkFlushWb.bits.misOffset.bits    := Mux(wb_half_flush, wb_lastIdx, ParallelPriorityEncoder(wb_check_result_stage2.fixedMissPred))
970  checkFlushWb.bits.cfiOffset.valid   := ParallelOR(wb_check_result_stage1.fixedTaken)
971  checkFlushWb.bits.cfiOffset.bits    := ParallelPriorityEncoder(wb_check_result_stage1.fixedTaken)
972  checkFlushWb.bits.target            := Mux(wb_half_flush, wb_half_target, wb_check_result_stage2.fixedTarget(checkFlushWbTargetIdx))
973  checkFlushWb.bits.jalTarget         := wb_check_result_stage2.jalTarget(checkFlushWbjalTargetIdx)
974  checkFlushWb.bits.instrRange        := wb_instr_range.asTypeOf(Vec(PredictWidth, Bool()))
975
976  toFtq.pdWb := Mux(wb_valid, checkFlushWb,  mmioFlushWb)
977
978  wb_redirect := checkFlushWb.bits.misOffset.valid && wb_valid
979
980  /*write back flush type*/
981  val checkFaultType = wb_check_result_stage2.faultType
982  val checkJalFault =  wb_valid && checkFaultType.map(_.isjalFault).reduce(_||_)
983  val checkRetFault =  wb_valid && checkFaultType.map(_.isRetFault).reduce(_||_)
984  val checkTargetFault =  wb_valid && checkFaultType.map(_.istargetFault).reduce(_||_)
985  val checkNotCFIFault =  wb_valid && checkFaultType.map(_.notCFIFault).reduce(_||_)
986  val checkInvalidTaken =  wb_valid && checkFaultType.map(_.invalidTakenFault).reduce(_||_)
987
988
989  XSPerfAccumulate("predecode_flush_jalFault",   checkJalFault )
990  XSPerfAccumulate("predecode_flush_retFault",   checkRetFault )
991  XSPerfAccumulate("predecode_flush_targetFault",   checkTargetFault )
992  XSPerfAccumulate("predecode_flush_notCFIFault",   checkNotCFIFault )
993  XSPerfAccumulate("predecode_flush_incalidTakenFault",   checkInvalidTaken )
994
995  when(checkRetFault){
996    XSDebug("startAddr:%x  nextstartAddr:%x  taken:%d    takenIdx:%d\n",
997        wb_ftq_req.startAddr, wb_ftq_req.nextStartAddr, wb_ftq_req.ftqOffset.valid, wb_ftq_req.ftqOffset.bits)
998  }
999
1000
1001  /** performance counter */
1002  val f3_perf_info     = RegEnable(f2_perf_info,  f2_fire)
1003  val f3_req_0    = io.toIbuffer.fire
1004  val f3_req_1    = io.toIbuffer.fire && f3_doubleLine
1005  val f3_hit_0    = io.toIbuffer.fire && f3_perf_info.bank_hit(0)
1006  val f3_hit_1    = io.toIbuffer.fire && f3_doubleLine & f3_perf_info.bank_hit(1)
1007  val f3_hit      = f3_perf_info.hit
1008  val perfEvents = Seq(
1009    ("frontendFlush                ", wb_redirect                                ),
1010    ("ifu_req                      ", io.toIbuffer.fire                        ),
1011    ("ifu_miss                     ", io.toIbuffer.fire && !f3_perf_info.hit   ),
1012    ("ifu_req_cacheline_0          ", f3_req_0                                   ),
1013    ("ifu_req_cacheline_1          ", f3_req_1                                   ),
1014    ("ifu_req_cacheline_0_hit      ", f3_hit_1                                   ),
1015    ("ifu_req_cacheline_1_hit      ", f3_hit_1                                   ),
1016    ("only_0_hit                   ", f3_perf_info.only_0_hit       && io.toIbuffer.fire ),
1017    ("only_0_miss                  ", f3_perf_info.only_0_miss      && io.toIbuffer.fire ),
1018    ("hit_0_hit_1                  ", f3_perf_info.hit_0_hit_1      && io.toIbuffer.fire ),
1019    ("hit_0_miss_1                 ", f3_perf_info.hit_0_miss_1     && io.toIbuffer.fire ),
1020    ("miss_0_hit_1                 ", f3_perf_info.miss_0_hit_1     && io.toIbuffer.fire ),
1021    ("miss_0_miss_1                ", f3_perf_info.miss_0_miss_1    && io.toIbuffer.fire ),
1022  )
1023  generatePerfEvent()
1024
1025  XSPerfAccumulate("ifu_req",   io.toIbuffer.fire )
1026  XSPerfAccumulate("ifu_miss",  io.toIbuffer.fire && !f3_hit )
1027  XSPerfAccumulate("ifu_req_cacheline_0", f3_req_0  )
1028  XSPerfAccumulate("ifu_req_cacheline_1", f3_req_1  )
1029  XSPerfAccumulate("ifu_req_cacheline_0_hit",   f3_hit_0 )
1030  XSPerfAccumulate("ifu_req_cacheline_1_hit",   f3_hit_1 )
1031  XSPerfAccumulate("frontendFlush",  wb_redirect )
1032  XSPerfAccumulate("only_0_hit",      f3_perf_info.only_0_hit   && io.toIbuffer.fire  )
1033  XSPerfAccumulate("only_0_miss",     f3_perf_info.only_0_miss  && io.toIbuffer.fire  )
1034  XSPerfAccumulate("hit_0_hit_1",     f3_perf_info.hit_0_hit_1  && io.toIbuffer.fire  )
1035  XSPerfAccumulate("hit_0_miss_1",    f3_perf_info.hit_0_miss_1  && io.toIbuffer.fire  )
1036  XSPerfAccumulate("miss_0_hit_1",    f3_perf_info.miss_0_hit_1   && io.toIbuffer.fire )
1037  XSPerfAccumulate("miss_0_miss_1",   f3_perf_info.miss_0_miss_1 && io.toIbuffer.fire )
1038  XSPerfAccumulate("hit_0_except_1",   f3_perf_info.hit_0_except_1 && io.toIbuffer.fire )
1039  XSPerfAccumulate("miss_0_except_1",   f3_perf_info.miss_0_except_1 && io.toIbuffer.fire )
1040  XSPerfAccumulate("except_0",   f3_perf_info.except_0 && io.toIbuffer.fire )
1041  XSPerfHistogram("ifu2ibuffer_validCnt", PopCount(io.toIbuffer.bits.valid & io.toIbuffer.bits.enqEnable), io.toIbuffer.fire, 0, PredictWidth + 1, 1)
1042
1043  val hartId = p(XSCoreParamsKey).HartId
1044  val isWriteFetchToIBufferTable = Constantin.createRecord(s"isWriteFetchToIBufferTable$hartId")
1045  val isWriteIfuWbToFtqTable = Constantin.createRecord(s"isWriteIfuWbToFtqTable$hartId")
1046  val fetchToIBufferTable = ChiselDB.createTable(s"FetchToIBuffer$hartId", new FetchToIBufferDB)
1047  val ifuWbToFtqTable = ChiselDB.createTable(s"IfuWbToFtq$hartId", new IfuWbToFtqDB)
1048
1049  val fetchIBufferDumpData = Wire(new FetchToIBufferDB)
1050  fetchIBufferDumpData.start_addr := f3_ftq_req.startAddr
1051  fetchIBufferDumpData.instr_count := PopCount(io.toIbuffer.bits.enqEnable)
1052  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)
1053  fetchIBufferDumpData.is_cache_hit := f3_hit
1054
1055  val ifuWbToFtqDumpData = Wire(new IfuWbToFtqDB)
1056  ifuWbToFtqDumpData.start_addr := wb_ftq_req.startAddr
1057  ifuWbToFtqDumpData.is_miss_pred := checkFlushWb.bits.misOffset.valid
1058  ifuWbToFtqDumpData.miss_pred_offset := checkFlushWb.bits.misOffset.bits
1059  ifuWbToFtqDumpData.checkJalFault := checkJalFault
1060  ifuWbToFtqDumpData.checkRetFault := checkRetFault
1061  ifuWbToFtqDumpData.checkTargetFault := checkTargetFault
1062  ifuWbToFtqDumpData.checkNotCFIFault := checkNotCFIFault
1063  ifuWbToFtqDumpData.checkInvalidTaken := checkInvalidTaken
1064
1065  fetchToIBufferTable.log(
1066    data = fetchIBufferDumpData,
1067    en = isWriteFetchToIBufferTable.orR && io.toIbuffer.fire,
1068    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
1069    clock = clock,
1070    reset = reset
1071  )
1072  ifuWbToFtqTable.log(
1073    data = ifuWbToFtqDumpData,
1074    en = isWriteIfuWbToFtqTable.orR && checkFlushWb.valid,
1075    site = "IFU" + p(XSCoreParamsKey).HartId.toString,
1076    clock = clock,
1077    reset = reset
1078  )
1079
1080}
1081