xref: /XiangShan/src/main/scala/xiangshan/mem/pipeline/HybridUnit.scala (revision 04c99ecade0a43f799280ad61b6acbae487d6c91)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.mem
18
19import org.chipsalliance.cde.config.Parameters
20import chisel3._
21import chisel3.util._
22import utils._
23import utility._
24import xiangshan.ExceptionNO._
25import xiangshan._
26import xiangshan.backend.Bundles.{DynInst, MemExuInput, MemExuOutput}
27import xiangshan.backend.fu.PMPRespBundle
28import xiangshan.backend.fu.FuConfig._
29import xiangshan.backend.ctrlblock.{DebugLsInfoBundle, LsTopdownInfo}
30import xiangshan.backend.rob.RobPtr
31import xiangshan.backend.fu._
32import xiangshan.cache._
33import xiangshan.cache.wpu.ReplayCarry
34import xiangshan.cache.mmu.{TlbCmd, TlbReq, TlbRequestIO, TlbResp}
35import xiangshan.mem.mdp._
36
37class HybridUnit(implicit p: Parameters) extends XSModule
38  with HasLoadHelper
39  with HasPerfEvents
40  with HasDCacheParameters
41  with HasCircularQueuePtrHelper
42{
43  val io = IO(new Bundle() {
44    // control
45    val redirect      = Flipped(ValidIO(new Redirect))
46    val csrCtrl       = Flipped(new CustomCSRCtrlIO)
47
48    // flow in
49    val lsin          = Flipped(Decoupled(new MemExuInput))
50
51    // flow out
52    val ldout = DecoupledIO(new MemExuOutput)
53    val stout = DecoupledIO(new MemExuOutput)
54
55    val ldu_io = new Bundle() {
56      // dcache
57      val dcache        = new DCacheLoadIO
58
59      // data path
60      val sbuffer       = new LoadForwardQueryIO
61      val lsq           = new LoadToLsqIO
62      val tl_d_channel  = Input(new DcacheToLduForwardIO)
63      val forward_mshr  = Flipped(new LduToMissqueueForwardIO)
64      val refill        = Flipped(ValidIO(new Refill))
65      val l2_hint       = Input(Valid(new L2ToL1Hint))
66
67      // fast wakeup
68      val fast_uop = ValidIO(new DynInst) // early wakeup signal generated in load_s1, send to RS in load_s2
69
70      // trigger
71      val trigger = Vec(3, new LoadUnitTriggerIO)
72
73      // load to load fast path
74      val l2l_fwd_in    = Input(new LoadToLoadIO)
75      val l2l_fwd_out   = Output(new LoadToLoadIO)
76
77      val ld_fast_match    = Input(Bool())
78      val ld_fast_fuOpType = Input(UInt())
79      val ld_fast_imm      = Input(UInt(12.W))
80
81      // hardware prefetch to l1 cache req
82      val prefetch_req    = Flipped(ValidIO(new L1PrefetchReq))
83
84      // iq cancel
85      val ldCancel = Output(new LoadCancelIO()) // use to cancel the uops waked by this load, and cancel load
86
87      // load ecc error
88      val s3_dly_ld_err = Output(Bool()) // Note that io.s3_dly_ld_err and io.lsq.s3_dly_ld_err is different
89
90      // schedule error query
91      val stld_nuke_query = Flipped(Vec(StorePipelineWidth, Valid(new StoreNukeQueryIO)))
92
93      // queue-based replay
94      val replay       = Flipped(Decoupled(new LsPipelineBundle))
95      val lq_rep_full  = Input(Bool())
96
97      // misc
98      val s2_ptr_chasing = Output(Bool()) // provide right pc for hw prefetch
99
100      // Load fast replay path
101      val fast_rep_in  = Flipped(Decoupled(new LqWriteBundle))
102      val fast_rep_out = Decoupled(new LqWriteBundle)
103
104      // perf
105      val debug_ls         = Output(new DebugLsInfoBundle)
106      val lsTopdownInfo    = Output(new LsTopdownInfo)
107    }
108
109    val stu_io = new Bundle() {
110      val dcache          = new DCacheStoreIO
111      val prefetch_req    = Flipped(DecoupledIO(new StorePrefetchReq))
112      val issue           = Valid(new MemExuInput)
113      val lsq             = ValidIO(new LsPipelineBundle)
114      val lsq_replenish   = Output(new LsPipelineBundle())
115      val stld_nuke_query = Valid(new StoreNukeQueryIO)
116      val st_mask_out     = Valid(new StoreMaskBundle)
117      val debug_ls        = Output(new DebugLsInfoBundle)
118    }
119
120    // prefetch
121    val prefetch_train            = ValidIO(new LdPrefetchTrainBundle()) // provide prefetch info to sms
122    val prefetch_train_l1         = ValidIO(new LdPrefetchTrainBundle()) // provide prefetch info to stream & stride
123    val canAcceptLowConfPrefetch  = Output(Bool())
124    val canAcceptHighConfPrefetch = Output(Bool())
125    val correctMissTrain          = Input(Bool())
126
127    // data path
128    val tlb           = new TlbRequestIO(2)
129    val pmp           = Flipped(new PMPRespBundle()) // arrive same to tlb now
130
131
132    // rs feedback
133    val feedback_fast = ValidIO(new RSFeedback) // stage 2
134    val feedback_slow = ValidIO(new RSFeedback) // stage 3
135  })
136
137  val StorePrefetchL1Enabled = EnableStorePrefetchAtCommit || EnableStorePrefetchAtIssue || EnableStorePrefetchSPB
138  val s1_ready, s2_ready, s3_ready, sx_can_go = WireInit(false.B)
139
140  // Pipeline
141  // --------------------------------------------------------------------------------
142  // stage 0
143  // --------------------------------------------------------------------------------
144  // generate addr, use addr to query DCache and DTLB
145  val s0_valid         = Wire(Bool())
146  val s0_dcache_ready  = Wire(Bool())
147  val s0_kill          = Wire(Bool())
148  val s0_vaddr         = Wire(UInt(VAddrBits.W))
149  val s0_mask          = Wire(UInt((VLEN/8).W))
150  val s0_uop           = Wire(new DynInst)
151  val s0_has_rob_entry = Wire(Bool())
152  val s0_rsIdx         = Wire(UInt(log2Up(MemIQSizeMax).W))
153  val s0_mshrid        = Wire(UInt())
154  val s0_try_l2l       = Wire(Bool())
155  val s0_rep_carry     = Wire(new ReplayCarry(nWays))
156  val s0_isFirstIssue  = Wire(Bool())
157  val s0_fast_rep      = Wire(Bool())
158  val s0_ld_rep        = Wire(Bool())
159  val s0_l2l_fwd       = Wire(Bool())
160  val s0_sched_idx     = Wire(UInt())
161  val s0_can_go        = s1_ready
162  val s0_fire          = s0_valid && s0_dcache_ready && s0_can_go
163  val s0_out           = Wire(new LqWriteBundle)
164
165  // load flow select/gen
166  // src0: super load replayed by LSQ (cache miss replay) (io.ldu_io.replay)
167  // src1: fast load replay (io.ldu_io.fast_rep_in)
168  // src2: load replayed by LSQ (io.ldu_io.replay)
169  // src3: hardware prefetch from prefetchor (high confidence) (io.prefetch)
170  // src4: int read / software prefetch first issue from RS (io.in)
171  // src5: vec read first issue from RS (TODO)
172  // src6: load try pointchaising when no issued or replayed load (io.fastpath)
173  // src7: hardware prefetch from prefetchor (high confidence) (io.prefetch)
174  // priority: high to low
175  val s0_ld_flow             = FuType.isLoad(s0_uop.fuType)
176  val s0_rep_stall           = io.lsin.valid && isAfter(io.ldu_io.replay.bits.uop.robIdx, io.lsin.bits.uop.robIdx)
177  val s0_super_ld_rep_valid  = io.ldu_io.replay.valid && io.ldu_io.replay.bits.forward_tlDchannel
178  val s0_ld_fast_rep_valid   = io.ldu_io.fast_rep_in.valid
179  val s0_ld_rep_valid        = io.ldu_io.replay.valid && !io.ldu_io.replay.bits.forward_tlDchannel && !s0_rep_stall
180  val s0_high_conf_prf_valid = io.ldu_io.prefetch_req.valid && io.ldu_io.prefetch_req.bits.confidence > 0.U
181  val s0_int_iss_valid       = io.lsin.valid // int flow first issue or software prefetch
182  val s0_vec_iss_valid       = WireInit(false.B) // TODO
183  val s0_l2l_fwd_valid       = io.ldu_io.l2l_fwd_in.valid && io.ldu_io.ld_fast_match
184  val s0_low_conf_prf_valid  = io.ldu_io.prefetch_req.valid && io.ldu_io.prefetch_req.bits.confidence === 0.U
185  dontTouch(s0_super_ld_rep_valid)
186  dontTouch(s0_ld_fast_rep_valid)
187  dontTouch(s0_ld_rep_valid)
188  dontTouch(s0_high_conf_prf_valid)
189  dontTouch(s0_int_iss_valid)
190  dontTouch(s0_vec_iss_valid)
191  dontTouch(s0_l2l_fwd_valid)
192  dontTouch(s0_low_conf_prf_valid)
193
194  // load flow source ready
195  val s0_super_ld_rep_ready  = WireInit(true.B)
196  val s0_ld_fast_rep_ready   = !s0_super_ld_rep_valid
197  val s0_ld_rep_ready        = !s0_super_ld_rep_valid &&
198                               !s0_ld_fast_rep_valid
199  val s0_high_conf_prf_ready = !s0_super_ld_rep_valid &&
200                               !s0_ld_fast_rep_valid &&
201                               !s0_ld_rep_valid
202
203  val s0_int_iss_ready       = !s0_super_ld_rep_valid &&
204                               !s0_ld_fast_rep_valid &&
205                               !s0_ld_rep_valid &&
206                               !s0_high_conf_prf_valid
207
208  val s0_vec_iss_ready       = !s0_super_ld_rep_valid &&
209                               !s0_ld_fast_rep_valid &&
210                               !s0_ld_rep_valid &&
211                               !s0_high_conf_prf_valid &&
212                               !s0_int_iss_valid
213
214  val s0_l2l_fwd_ready       = !s0_super_ld_rep_valid &&
215                               !s0_ld_fast_rep_valid &&
216                               !s0_ld_rep_valid &&
217                               !s0_high_conf_prf_valid &&
218                               !s0_int_iss_valid &&
219                               !s0_vec_iss_valid
220
221  val s0_low_conf_prf_ready  = !s0_super_ld_rep_valid &&
222                               !s0_ld_fast_rep_valid &&
223                               !s0_ld_rep_valid &&
224                               !s0_high_conf_prf_valid &&
225                               !s0_int_iss_valid &&
226                               !s0_vec_iss_valid &&
227                               !s0_l2l_fwd_valid
228  dontTouch(s0_super_ld_rep_ready)
229  dontTouch(s0_ld_fast_rep_ready)
230  dontTouch(s0_ld_rep_ready)
231  dontTouch(s0_high_conf_prf_ready)
232  dontTouch(s0_int_iss_ready)
233  dontTouch(s0_vec_iss_ready)
234  dontTouch(s0_l2l_fwd_ready)
235  dontTouch(s0_low_conf_prf_ready)
236
237  // load flow source select (OH)
238  val s0_super_ld_rep_select = s0_super_ld_rep_valid && s0_super_ld_rep_ready
239  val s0_ld_fast_rep_select  = s0_ld_fast_rep_valid && s0_ld_fast_rep_ready
240  val s0_ld_rep_select       = s0_ld_rep_valid && s0_ld_rep_ready
241  val s0_hw_prf_select       = s0_high_conf_prf_ready && s0_high_conf_prf_valid ||
242                               s0_low_conf_prf_ready && s0_low_conf_prf_valid
243  val s0_int_iss_select      = s0_int_iss_ready && s0_int_iss_valid
244  val s0_vec_iss_select      = s0_vec_iss_ready && s0_vec_iss_valid
245  val s0_l2l_fwd_select      = s0_l2l_fwd_ready && s0_l2l_fwd_valid
246  assert(!s0_vec_iss_select) // to be added
247  dontTouch(s0_super_ld_rep_select)
248  dontTouch(s0_ld_fast_rep_select)
249  dontTouch(s0_ld_rep_select)
250  dontTouch(s0_hw_prf_select)
251  dontTouch(s0_int_iss_select)
252  dontTouch(s0_vec_iss_select)
253  dontTouch(s0_l2l_fwd_select)
254
255  s0_valid := (s0_super_ld_rep_valid ||
256               s0_ld_fast_rep_valid ||
257               s0_ld_rep_valid ||
258               s0_high_conf_prf_valid ||
259               s0_int_iss_valid ||
260               s0_vec_iss_valid ||
261               s0_l2l_fwd_valid ||
262               s0_low_conf_prf_valid) && !s0_kill
263
264  // which is S0's out is ready and dcache is ready
265  val s0_try_ptr_chasing      = s0_l2l_fwd_select
266  val s0_do_try_ptr_chasing   = s0_try_ptr_chasing && s0_can_go && io.ldu_io.dcache.req.ready
267  val s0_ptr_chasing_vaddr    = io.ldu_io.l2l_fwd_in.data(5, 0) +& io.ldu_io.ld_fast_imm(5, 0)
268  val s0_ptr_chasing_canceled = WireInit(false.B)
269  s0_kill := s0_ptr_chasing_canceled || (s0_out.uop.robIdx.needFlush(io.redirect) && !s0_try_ptr_chasing)
270
271  // prefetch related ctrl signal
272  val s0_prf    = Wire(Bool())
273  val s0_prf_rd = Wire(Bool())
274  val s0_prf_wr = Wire(Bool())
275  val s0_hw_prf = s0_hw_prf_select
276
277  io.canAcceptLowConfPrefetch  := s0_low_conf_prf_ready
278  io.canAcceptHighConfPrefetch := s0_high_conf_prf_ready
279
280  if (StorePrefetchL1Enabled) {
281    s0_dcache_ready := Mux(s0_ld_flow, io.ldu_io.dcache.req.ready, io.stu_io.dcache.req.ready)
282  } else {
283    s0_dcache_ready := io.ldu_io.dcache.req.ready
284  }
285  // query DTLB
286  io.tlb.req.valid                   := s0_valid && s0_dcache_ready
287  io.tlb.req.bits.cmd                := Mux(s0_prf,
288                                         Mux(s0_prf_wr, TlbCmd.write, TlbCmd.read),
289                                         Mux(s0_ld_flow, TlbCmd.read, TlbCmd.write)
290                                       )
291  io.tlb.req.bits.vaddr              := Mux(s0_hw_prf_select, io.ldu_io.prefetch_req.bits.paddr, s0_vaddr)
292  io.tlb.req.bits.size               := LSUOpType.size(s0_uop.fuOpType)
293  io.tlb.req.bits.kill               := s0_kill
294  io.tlb.req.bits.memidx.is_ld       := s0_ld_flow
295  io.tlb.req.bits.memidx.is_st       := !s0_ld_flow
296  io.tlb.req.bits.memidx.idx         := s0_uop.lqIdx.value
297  io.tlb.req.bits.debug.robIdx       := s0_uop.robIdx
298  io.tlb.req.bits.no_translate       := s0_hw_prf_select  // hw b.reqetch addr does not need to be translated
299  io.tlb.req.bits.debug.pc           := s0_uop.pc
300  io.tlb.req.bits.debug.isFirstIssue := s0_isFirstIssue
301
302  // query DCache
303  // for load
304  io.ldu_io.dcache.req.valid             := s0_valid && s0_dcache_ready && s0_ld_flow
305  io.ldu_io.dcache.req.bits.cmd          :=  Mux(s0_prf_rd, MemoryOpConstants.M_PFR,
306                                              Mux(s0_prf_wr, MemoryOpConstants.M_PFW, MemoryOpConstants.M_XRD))
307  io.ldu_io.dcache.req.bits.vaddr        := s0_vaddr
308  io.ldu_io.dcache.req.bits.mask         := s0_mask
309  io.ldu_io.dcache.req.bits.data         := DontCare
310  io.ldu_io.dcache.req.bits.isFirstIssue := s0_isFirstIssue
311  io.ldu_io.dcache.req.bits.instrtype    := Mux(s0_prf, DCACHE_PREFETCH_SOURCE.U, LOAD_SOURCE.U)
312  io.ldu_io.dcache.req.bits.debug_robIdx := s0_uop.robIdx.value
313  io.ldu_io.dcache.req.bits.replayCarry  := s0_rep_carry
314  io.ldu_io.dcache.req.bits.id           := DontCare // TODO: update cache meta
315  io.ldu_io.dcache.pf_source             := Mux(s0_hw_prf_select, io.ldu_io.prefetch_req.bits.pf_source.value, L1_HW_PREFETCH_NULL)
316
317  // for store
318  io.stu_io.dcache.req.valid             := s0_valid && s0_dcache_ready && !s0_ld_flow && !s0_prf
319  io.stu_io.dcache.req.bits.cmd          := MemoryOpConstants.M_PFW
320  io.stu_io.dcache.req.bits.vaddr        := s0_vaddr
321  io.stu_io.dcache.req.bits.instrtype    := Mux(s0_prf, DCACHE_PREFETCH_SOURCE.U, STORE_SOURCE.U)
322
323  // load flow priority mux
324  def fromNullSource() = {
325    s0_vaddr         := 0.U
326    s0_mask          := 0.U
327    s0_uop           := 0.U.asTypeOf(new DynInst)
328    s0_try_l2l       := false.B
329    s0_has_rob_entry := false.B
330    s0_rsIdx         := 0.U
331    s0_rep_carry     := 0.U.asTypeOf(s0_rep_carry.cloneType)
332    s0_mshrid        := 0.U
333    s0_isFirstIssue  := false.B
334    s0_fast_rep      := false.B
335    s0_ld_rep        := false.B
336    s0_l2l_fwd       := false.B
337    s0_prf           := false.B
338    s0_prf_rd        := false.B
339    s0_prf_wr        := false.B
340    s0_sched_idx     := 0.U
341  }
342
343  def fromFastReplaySource(src: LqWriteBundle) = {
344    s0_vaddr         := src.vaddr
345    s0_mask          := src.mask
346    s0_uop           := src.uop
347    s0_try_l2l       := false.B
348    s0_has_rob_entry := src.hasROBEntry
349    s0_rep_carry     := src.rep_info.rep_carry
350    s0_mshrid        := src.rep_info.mshr_id
351    s0_rsIdx         := src.rsIdx
352    s0_isFirstIssue  := false.B
353    s0_fast_rep      := true.B
354    s0_ld_rep        := src.isLoadReplay
355    s0_l2l_fwd       := false.B
356    s0_prf           := LSUOpType.isPrefetch(src.uop.fuOpType)
357    s0_prf_rd        := src.uop.fuOpType === LSUOpType.prefetch_r
358    s0_prf_wr        := src.uop.fuOpType === LSUOpType.prefetch_w
359    s0_sched_idx     := src.schedIndex
360  }
361
362  def fromNormalReplaySource(src: LsPipelineBundle) = {
363    s0_vaddr         := src.vaddr
364    s0_mask          := genVWmask(src.vaddr, src.uop.fuOpType(1, 0))
365    s0_uop           := src.uop
366    s0_try_l2l       := false.B
367    s0_has_rob_entry := true.B
368    s0_rsIdx         := src.rsIdx
369    s0_rep_carry     := src.replayCarry
370    s0_mshrid        := src.mshrid
371    s0_isFirstIssue  := false.B
372    s0_fast_rep      := false.B
373    s0_ld_rep        := true.B
374    s0_l2l_fwd       := false.B
375    s0_prf           := LSUOpType.isPrefetch(src.uop.fuOpType)
376    s0_prf_rd        := src.uop.fuOpType === LSUOpType.prefetch_r
377    s0_prf_wr        := src.uop.fuOpType === LSUOpType.prefetch_w
378    s0_sched_idx     := src.schedIndex
379  }
380
381  def fromPrefetchSource(src: L1PrefetchReq) = {
382    s0_vaddr         := src.getVaddr()
383    s0_mask          := 0.U
384    s0_uop           := DontCare
385    s0_try_l2l       := false.B
386    s0_has_rob_entry := false.B
387    s0_rsIdx         := 0.U
388    s0_rep_carry     := 0.U.asTypeOf(s0_rep_carry.cloneType)
389    s0_mshrid        := 0.U
390    s0_isFirstIssue  := false.B
391    s0_fast_rep      := false.B
392    s0_ld_rep        := false.B
393    s0_l2l_fwd       := false.B
394    s0_prf           := true.B
395    s0_prf_rd        := !src.is_store
396    s0_prf_wr        := src.is_store
397    s0_sched_idx     := 0.U
398  }
399
400  def fromIntIssueSource(src: MemExuInput) = {
401    s0_vaddr         := src.src(0) + SignExt(src.uop.imm(11, 0), VAddrBits)
402    s0_mask          := genVWmask(s0_vaddr, src.uop.fuOpType(1,0))
403    s0_uop           := src.uop
404    s0_try_l2l       := false.B
405    s0_has_rob_entry := true.B
406    s0_rsIdx         := src.iqIdx
407    s0_rep_carry     := 0.U.asTypeOf(s0_rep_carry.cloneType)
408    s0_mshrid        := 0.U
409    s0_isFirstIssue  := true.B
410    s0_fast_rep      := false.B
411    s0_ld_rep        := false.B
412    s0_l2l_fwd       := false.B
413    s0_prf           := LSUOpType.isPrefetch(src.uop.fuOpType)
414    s0_prf_rd        := src.uop.fuOpType === LSUOpType.prefetch_r
415    s0_prf_wr        := src.uop.fuOpType === LSUOpType.prefetch_w
416    s0_sched_idx     := 0.U
417  }
418
419  def fromVecIssueSource() = {
420    s0_vaddr         := 0.U
421    s0_mask          := 0.U
422    s0_uop           := 0.U.asTypeOf(new DynInst)
423    s0_try_l2l       := false.B
424    s0_has_rob_entry := false.B
425    s0_rsIdx         := 0.U
426    s0_rep_carry     := 0.U.asTypeOf(s0_rep_carry.cloneType)
427    s0_mshrid        := 0.U
428    s0_isFirstIssue  := false.B
429    s0_fast_rep      := false.B
430    s0_ld_rep        := false.B
431    s0_l2l_fwd       := false.B
432    s0_prf           := false.B
433    s0_prf_rd        := false.B
434    s0_prf_wr        := false.B
435    s0_sched_idx     := 0.U
436  }
437
438  def fromLoadToLoadSource(src: LoadToLoadIO) = {
439    s0_vaddr              := Cat(src.data(XLEN-1, 6), s0_ptr_chasing_vaddr(5,0))
440    s0_mask               := genVWmask(s0_vaddr, io.ldu_io.ld_fast_fuOpType(1, 0))
441    // When there's no valid instruction from RS and LSQ, we try the load-to-load forwarding.
442    // Assume the pointer chasing is always ld.
443    s0_uop.fuOpType  := io.ldu_io.ld_fast_fuOpType
444    s0_try_l2l            := true.B
445    // we dont care s0_isFirstIssue and s0_rsIdx and s0_sqIdx in S0 when trying pointchasing
446    // because these signals will be updated in S1
447    s0_has_rob_entry      := false.B
448    s0_rsIdx              := 0.U
449    s0_mshrid             := 0.U
450    s0_rep_carry          := 0.U.asTypeOf(s0_rep_carry.cloneType)
451    s0_isFirstIssue       := true.B
452    s0_fast_rep           := false.B
453    s0_ld_rep             := false.B
454    s0_l2l_fwd            := true.B
455    s0_prf                := false.B
456    s0_prf_rd             := false.B
457    s0_prf_wr             := false.B
458    s0_sched_idx          := 0.U
459  }
460
461  // set default
462  s0_uop := DontCare
463  when (s0_super_ld_rep_select)      { fromNormalReplaySource(io.ldu_io.replay.bits)     }
464  .elsewhen (s0_ld_fast_rep_select)  { fromFastReplaySource(io.ldu_io.fast_rep_in.bits)  }
465  .elsewhen (s0_ld_rep_select)       { fromNormalReplaySource(io.ldu_io.replay.bits)     }
466  .elsewhen (s0_hw_prf_select)       { fromPrefetchSource(io.ldu_io.prefetch_req.bits)   }
467  .elsewhen (s0_int_iss_select)      { fromIntIssueSource(io.lsin.bits)           }
468  .elsewhen (s0_vec_iss_select)      { fromVecIssueSource()                       }
469  .otherwise {
470    if (EnableLoadToLoadForward) {
471      fromLoadToLoadSource(io.ldu_io.l2l_fwd_in)
472    } else {
473      fromNullSource()
474    }
475  }
476
477  // address align check
478  val s0_addr_aligned = LookupTree(s0_uop.fuOpType(1, 0), List(
479    "b00".U   -> true.B,                   //b
480    "b01".U   -> (s0_vaddr(0)    === 0.U), //h
481    "b10".U   -> (s0_vaddr(1, 0) === 0.U), //w
482    "b11".U   -> (s0_vaddr(2, 0) === 0.U)  //d
483  ))
484
485  // accept load flow if dcache ready (tlb is always ready)
486  // TODO: prefetch need writeback to loadQueueFlag
487  s0_out               := DontCare
488  s0_out.rsIdx         := s0_rsIdx
489  s0_out.vaddr         := s0_vaddr
490  s0_out.mask          := s0_mask
491  s0_out.uop           := s0_uop
492  s0_out.isFirstIssue  := s0_isFirstIssue
493  s0_out.hasROBEntry   := s0_has_rob_entry
494  s0_out.isPrefetch    := s0_prf
495  s0_out.isHWPrefetch  := s0_hw_prf
496  s0_out.isFastReplay  := s0_fast_rep
497  s0_out.isLoadReplay  := s0_ld_rep
498  s0_out.isFastPath    := s0_l2l_fwd
499  s0_out.mshrid        := s0_mshrid
500  s0_out.uop.exceptionVec(loadAddrMisaligned)  := !s0_addr_aligned && s0_ld_flow
501  s0_out.uop.exceptionVec(storeAddrMisaligned) := !s0_addr_aligned && !s0_ld_flow
502  s0_out.forward_tlDchannel := s0_super_ld_rep_select
503  when(io.tlb.req.valid && s0_isFirstIssue) {
504    s0_out.uop.debugInfo.tlbFirstReqTime := GTimer()
505  }.otherwise{
506    s0_out.uop.debugInfo.tlbFirstReqTime := s0_uop.debugInfo.tlbFirstReqTime
507  }
508  s0_out.schedIndex     := s0_sched_idx
509
510  // load fast replay
511  io.ldu_io.fast_rep_in.ready := (s0_can_go && io.ldu_io.dcache.req.ready && s0_ld_fast_rep_ready)
512
513  // load flow source ready
514  // cache missed load has highest priority
515  // always accept cache missed load flow from load replay queue
516  io.ldu_io.replay.ready := (s0_can_go && io.ldu_io.dcache.req.ready && (s0_ld_rep_ready && !s0_rep_stall || s0_super_ld_rep_select))
517
518  // accept load flow from rs when:
519  // 1) there is no lsq-replayed load
520  // 2) there is no fast replayed load
521  // 3) there is no high confidence prefetch request
522  if (StorePrefetchL1Enabled) {
523    io.lsin.ready := (s0_can_go && Mux(FuType.isLoad(io.lsin.bits.uop.fuType), io.ldu_io.dcache.req.ready, io.stu_io.dcache.req.ready) && s0_int_iss_ready)
524  } else {
525    io.lsin.ready := (s0_can_go && Mux(FuType.isLoad(io.lsin.bits.uop.fuType), io.ldu_io.dcache.req.ready, true.B) && s0_int_iss_ready)
526  }
527
528  // for hw prefetch load flow feedback, to be added later
529  // io.prefetch_in.ready := s0_hw_prf_select
530
531  // dcache replacement extra info
532  // TODO: should prefetch load update replacement?
533  io.ldu_io.dcache.replacementUpdated := Mux(s0_ld_rep_select || s0_super_ld_rep_select, io.ldu_io.replay.bits.replacementUpdated, false.B)
534
535  io.stu_io.prefetch_req.ready := s1_ready && io.stu_io.dcache.req.ready && !io.lsin.valid
536
537  io.stu_io.st_mask_out.valid       := s0_valid && !s0_ld_flow
538  io.stu_io.st_mask_out.bits.mask   := s0_out.mask
539  io.stu_io.st_mask_out.bits.sqIdx  := s0_out.uop.sqIdx
540
541  // load debug
542  XSDebug(io.ldu_io.dcache.req.fire && s0_ld_flow,
543    p"[DCACHE LOAD REQ] pc ${Hexadecimal(s0_uop.pc)}, vaddr ${Hexadecimal(s0_vaddr)}\n"
544  )
545  XSDebug(s0_valid && s0_ld_flow,
546    p"S0: pc ${Hexadecimal(s0_out.uop.pc)}, lqIdx ${Hexadecimal(s0_out.uop.lqIdx.asUInt)}, " +
547    p"vaddr ${Hexadecimal(s0_out.vaddr)}, mask ${Hexadecimal(s0_out.mask)}\n")
548
549  // store debug
550  XSDebug(io.stu_io.dcache.req.fire && !s0_ld_flow,
551    p"[DCACHE STORE REQ] pc ${Hexadecimal(s0_uop.pc)}, vaddr ${Hexadecimal(s0_vaddr)}\n"
552  )
553  XSDebug(s0_valid && !s0_ld_flow,
554    p"S0: pc ${Hexadecimal(s0_out.uop.pc)}, sqIdx ${Hexadecimal(s0_out.uop.sqIdx.asUInt)}, " +
555    p"vaddr ${Hexadecimal(s0_out.vaddr)}, mask ${Hexadecimal(s0_out.mask)}\n")
556
557
558  // Pipeline
559  // --------------------------------------------------------------------------------
560  // stage 1
561  // --------------------------------------------------------------------------------
562  // TLB resp (send paddr to dcache)
563  val s1_valid      = RegInit(false.B)
564  val s1_in         = Wire(new LqWriteBundle)
565  val s1_out        = Wire(new LqWriteBundle)
566  val s1_kill       = Wire(Bool())
567  val s1_can_go     = s2_ready
568  val s1_fire       = s1_valid && !s1_kill && s1_can_go
569  val s1_ld_flow    = RegNext(s0_ld_flow)
570
571  s1_ready := !s1_valid || s1_kill || s2_ready
572  when (s0_fire) { s1_valid := true.B }
573  .elsewhen (s1_fire) { s1_valid := false.B }
574  .elsewhen (s1_kill) { s1_valid := false.B }
575  s1_in   := RegEnable(s0_out, s0_fire)
576
577  val s1_fast_rep_dly_err = RegNext(io.ldu_io.fast_rep_in.bits.delayedLoadError)
578  val s1_fast_rep_kill    = s1_fast_rep_dly_err && s1_in.isFastReplay
579  val s1_l2l_fwd_dly_err  = RegNext(io.ldu_io.l2l_fwd_in.dly_ld_err)
580  val s1_l2l_fwd_kill     = s1_l2l_fwd_dly_err && s1_in.isFastPath
581  val s1_late_kill        = s1_fast_rep_kill || s1_l2l_fwd_kill
582  val s1_vaddr_hi         = Wire(UInt())
583  val s1_vaddr_lo         = Wire(UInt())
584  val s1_vaddr            = Wire(UInt())
585  val s1_paddr_dup_lsu    = Wire(UInt())
586  val s1_paddr_dup_dcache = Wire(UInt())
587  val s1_ld_exception     = ExceptionNO.selectByFu(s1_out.uop.exceptionVec, LduCfg).asUInt.orR   // af & pf exception were modified below.
588  val s1_st_exception     = ExceptionNO.selectByFu(s1_out.uop.exceptionVec, StaCfg).asUInt.orR   // af & pf exception were modified below.
589  val s1_exception        = (s1_ld_flow && s1_ld_exception) || (!s1_ld_flow && s1_st_exception)
590  val s1_tlb_miss         = io.tlb.resp.bits.miss
591  val s1_prf              = s1_in.isPrefetch
592  val s1_hw_prf           = s1_in.isHWPrefetch
593  val s1_sw_prf           = s1_prf && !s1_hw_prf
594  val s1_tlb_memidx       = io.tlb.resp.bits.memidx
595
596  // mmio cbo decoder
597  val s1_mmio_cbo  = (s1_in.uop.fuOpType === LSUOpType.cbo_clean ||
598                      s1_in.uop.fuOpType === LSUOpType.cbo_flush ||
599                      s1_in.uop.fuOpType === LSUOpType.cbo_inval) && !s1_ld_flow
600  val s1_mmio = s1_mmio_cbo
601
602  s1_vaddr_hi         := s1_in.vaddr(VAddrBits - 1, 6)
603  s1_vaddr_lo         := s1_in.vaddr(5, 0)
604  s1_vaddr            := Cat(s1_vaddr_hi, s1_vaddr_lo)
605  s1_paddr_dup_lsu    := io.tlb.resp.bits.paddr(0)
606  s1_paddr_dup_dcache := io.tlb.resp.bits.paddr(1)
607
608  when (s1_tlb_memidx.is_ld && io.tlb.resp.valid && !s1_tlb_miss &&
609        s1_tlb_memidx.idx === s1_in.uop.lqIdx.value && s1_ld_flow) {
610    // printf("Load idx = %d\n", s1_tlb_memidx.idx)
611    s1_out.uop.debugInfo.tlbRespTime := GTimer()
612  } .elsewhen(s1_tlb_memidx.is_st && io.tlb.resp.valid && !s1_tlb_miss &&
613              s1_tlb_memidx.idx === s1_out.uop.sqIdx.value && !s1_ld_flow) {
614    // printf("Store idx = %d\n", s1_tlb_memidx.idx)
615    s1_out.uop.debugInfo.tlbRespTime := GTimer()
616  }
617
618  io.tlb.req_kill   := s1_kill
619  io.tlb.resp.ready := true.B
620
621  io.ldu_io.dcache.s1_paddr_dup_lsu    <> s1_paddr_dup_lsu
622  io.ldu_io.dcache.s1_paddr_dup_dcache <> s1_paddr_dup_dcache
623  io.ldu_io.dcache.s1_kill             := s1_kill || s1_tlb_miss || s1_exception
624
625  // store to load forwarding
626  io.ldu_io.sbuffer.valid := s1_valid && !(s1_exception || s1_tlb_miss || s1_kill || s1_fast_rep_kill || s1_prf || !s1_ld_flow)
627  io.ldu_io.sbuffer.vaddr := s1_vaddr
628  io.ldu_io.sbuffer.paddr := s1_paddr_dup_lsu
629  io.ldu_io.sbuffer.uop   := s1_in.uop
630  io.ldu_io.sbuffer.sqIdx := s1_in.uop.sqIdx
631  io.ldu_io.sbuffer.mask  := s1_in.mask
632  io.ldu_io.sbuffer.pc    := s1_in.uop.pc // FIXME: remove it
633
634  io.ldu_io.lsq.forward.valid     := s1_valid && !(s1_exception || s1_tlb_miss || s1_kill || s1_fast_rep_kill || s1_prf || !s1_ld_flow)
635  io.ldu_io.lsq.forward.vaddr     := s1_vaddr
636  io.ldu_io.lsq.forward.paddr     := s1_paddr_dup_lsu
637  io.ldu_io.lsq.forward.uop       := s1_in.uop
638  io.ldu_io.lsq.forward.sqIdx     := s1_in.uop.sqIdx
639  io.ldu_io.lsq.forward.sqIdxMask := 0.U
640  io.ldu_io.lsq.forward.mask      := s1_in.mask
641  io.ldu_io.lsq.forward.pc        := s1_in.uop.pc // FIXME: remove it
642
643  // st-ld violation query
644  val s1_nuke = VecInit((0 until StorePipelineWidth).map(w => {
645                       io.ldu_io.stld_nuke_query(w).valid && // query valid
646                       isAfter(s1_in.uop.robIdx, io.ldu_io.stld_nuke_query(w).bits.robIdx) && // older store
647                       // TODO: Fix me when vector instruction
648                       (s1_paddr_dup_lsu(PAddrBits-1, 3) === io.ldu_io.stld_nuke_query(w).bits.paddr(PAddrBits-1, 3)) && // paddr match
649                       (s1_in.mask & io.ldu_io.stld_nuke_query(w).bits.mask).orR // data mask contain
650                      })).asUInt.orR && !s1_tlb_miss && s1_ld_flow
651
652  s1_out                   := s1_in
653  s1_out.vaddr             := s1_vaddr
654  s1_out.paddr             := s1_paddr_dup_lsu
655  s1_out.tlbMiss           := s1_tlb_miss
656  s1_out.ptwBack           := io.tlb.resp.bits.ptwBack
657  s1_out.rsIdx             := s1_in.rsIdx
658  s1_out.rep_info.debug    := s1_in.uop.debugInfo
659  s1_out.rep_info.nuke     := s1_nuke && !s1_sw_prf
660  s1_out.lateKill          := s1_late_kill
661
662  when (s1_ld_flow) {
663    when (!s1_late_kill) {
664      // current ori test will cause the case of ldest == 0, below will be modifeid in the future.
665      // af & pf exception were modified
666      s1_out.uop.exceptionVec(loadPageFault)   := io.tlb.resp.bits.excp(0).pf.ld
667      s1_out.uop.exceptionVec(loadAccessFault) := io.tlb.resp.bits.excp(0).af.ld
668    } .otherwise {
669      s1_out.uop.exceptionVec(loadAddrMisaligned) := false.B
670      s1_out.uop.exceptionVec(loadAccessFault)    := s1_late_kill
671    }
672  } .otherwise {
673    s1_out.uop.exceptionVec(storePageFault)   := io.tlb.resp.bits.excp(0).pf.st
674    s1_out.uop.exceptionVec(storeAccessFault) := io.tlb.resp.bits.excp(0).af.st
675  }
676
677  // pointer chasing
678  val s1_try_ptr_chasing       = RegNext(s0_do_try_ptr_chasing, false.B)
679  val s1_ptr_chasing_vaddr     = RegEnable(s0_ptr_chasing_vaddr, s0_do_try_ptr_chasing)
680  val s1_fu_op_type_not_ld     = WireInit(false.B)
681  val s1_not_fast_match        = WireInit(false.B)
682  val s1_addr_mismatch         = WireInit(false.B)
683  val s1_addr_misaligned       = WireInit(false.B)
684  val s1_ptr_chasing_canceled  = WireInit(false.B)
685  val s1_cancel_ptr_chasing    = WireInit(false.B)
686
687  s1_kill := s1_late_kill ||
688             s1_cancel_ptr_chasing ||
689             s1_in.uop.robIdx.needFlush(io.redirect) ||
690             RegEnable(s0_kill, false.B, io.lsin.valid || io.ldu_io.replay.valid || io.ldu_io.l2l_fwd_in.valid || io.ldu_io.fast_rep_in.valid)
691
692  if (EnableLoadToLoadForward) {
693    // Sometimes, we need to cancel the load-load forwarding.
694    // These can be put at S0 if timing is bad at S1.
695    // Case 0: CACHE_SET(base + offset) != CACHE_SET(base) (lowest 6-bit addition has an overflow)
696    s1_addr_mismatch      := s1_ptr_chasing_vaddr(6) || RegEnable(io.ldu_io.ld_fast_imm(11, 6).orR, s0_do_try_ptr_chasing)
697    // Case 1: the address is misaligned, kill s1
698    s1_addr_misaligned    := LookupTree(s1_in.uop.fuOpType(1, 0), List(
699                             "b00".U   -> false.B,                  //b
700                             "b01".U   -> (s1_vaddr(0)    =/= 0.U), //h
701                             "b10".U   -> (s1_vaddr(1, 0) =/= 0.U), //w
702                             "b11".U   -> (s1_vaddr(2, 0) =/= 0.U)  //d
703                          ))
704    // Case 2: this load-load uop is cancelled
705    s1_ptr_chasing_canceled := !io.lsin.valid
706
707    when (s1_try_ptr_chasing) {
708      s1_cancel_ptr_chasing := s1_addr_mismatch || s1_addr_misaligned || s1_ptr_chasing_canceled
709
710      s1_in.uop           := io.lsin.bits.uop
711      s1_in.rsIdx         := io.lsin.bits.iqIdx
712      s1_in.isFirstIssue  := io.lsin.bits.isFirstIssue
713      s1_vaddr_lo         := s1_ptr_chasing_vaddr(5, 0)
714      s1_paddr_dup_lsu    := Cat(io.tlb.resp.bits.paddr(0)(PAddrBits - 1, 6), s1_vaddr_lo)
715      s1_paddr_dup_dcache := Cat(io.tlb.resp.bits.paddr(0)(PAddrBits - 1, 6), s1_vaddr_lo)
716
717      // recored tlb time when get the data to ensure the correctness of the latency calculation (although it should not record in here, because it does not use tlb)
718      s1_in.uop.debugInfo.tlbFirstReqTime := GTimer()
719      s1_in.uop.debugInfo.tlbRespTime     := GTimer()
720    }
721    when (!s1_cancel_ptr_chasing) {
722      s0_ptr_chasing_canceled := s1_try_ptr_chasing && !io.ldu_io.replay.fire && !io.ldu_io.fast_rep_in.fire
723      when (s1_try_ptr_chasing) {
724        io.lsin.ready := true.B
725      }
726    }
727  }
728
729  // pre-calcuate sqIdx mask in s0, then send it to lsq in s1 for forwarding
730  val s1_sqIdx_mask = RegNext(UIntToMask(s0_out.uop.sqIdx.value, StoreQueueSize))
731  // to enable load-load, sqIdxMask must be calculated based on lsin.uop
732  // If the timing here is not OK, load-load forwarding has to be disabled.
733  // Or we calculate sqIdxMask at RS??
734  io.ldu_io.lsq.forward.sqIdxMask := s1_sqIdx_mask
735  if (EnableLoadToLoadForward) {
736    when (s1_try_ptr_chasing) {
737      io.ldu_io.lsq.forward.sqIdxMask := UIntToMask(io.lsin.bits.uop.sqIdx.value, StoreQueueSize)
738    }
739  }
740
741  io.ldu_io.forward_mshr.valid  := s1_valid && s1_out.forward_tlDchannel && s1_ld_flow
742  io.ldu_io.forward_mshr.mshrid := s1_out.mshrid
743  io.ldu_io.forward_mshr.paddr  := s1_out.paddr
744
745  io.stu_io.dcache.s1_kill := s1_tlb_miss || s1_exception || s1_mmio || s1_in.uop.robIdx.needFlush(io.redirect)
746  io.stu_io.dcache.s1_paddr := s1_paddr_dup_dcache
747
748
749  // load debug
750  XSDebug(s1_valid && s1_ld_flow,
751    p"S1: pc ${Hexadecimal(s1_out.uop.pc)}, lId ${Hexadecimal(s1_out.uop.lqIdx.asUInt)}, tlb_miss ${io.tlb.resp.bits.miss}, " +
752    p"paddr ${Hexadecimal(s1_out.paddr)}, mmio ${s1_out.mmio}\n")
753
754  // store debug
755  XSDebug(s1_valid && !s1_ld_flow,
756    p"S1: pc ${Hexadecimal(s1_out.uop.pc)}, lId ${Hexadecimal(s1_out.uop.sqIdx.asUInt)}, tlb_miss ${io.tlb.resp.bits.miss}, " +
757    p"paddr ${Hexadecimal(s1_out.paddr)}, mmio ${s1_out.mmio}\n")
758
759  // store out
760  io.stu_io.lsq.valid         := s1_valid && !s1_ld_flow
761  io.stu_io.lsq.bits          := s1_out
762  io.stu_io.lsq.bits.miss     := s1_tlb_miss
763
764  io.stu_io.issue.valid       := s1_valid && !s1_tlb_miss && !s1_ld_flow
765  io.stu_io.issue.bits        := RegEnable(io.lsin.bits, io.lsin.fire)
766
767  // st-ld violation dectect request
768  io.stu_io.stld_nuke_query.valid       := s1_valid && !s1_tlb_miss && !s1_ld_flow
769  io.stu_io.stld_nuke_query.bits.robIdx := s1_in.uop.robIdx
770  io.stu_io.stld_nuke_query.bits.paddr  := s1_paddr_dup_lsu
771  io.stu_io.stld_nuke_query.bits.mask   := s1_in.mask
772
773  // Pipeline
774  // --------------------------------------------------------------------------------
775  // stage 2
776  // --------------------------------------------------------------------------------
777  // s2: DCache resp
778  val s2_valid  = RegInit(false.B)
779  val s2_in     = Wire(new LqWriteBundle)
780  val s2_out    = Wire(new LqWriteBundle)
781  val s2_kill   = Wire(Bool())
782  val s2_can_go = s3_ready
783  val s2_fire   = s2_valid && !s2_kill && s2_can_go
784
785  s2_kill := s2_in.uop.robIdx.needFlush(io.redirect)
786  s2_ready := !s2_valid || s2_kill || s3_ready
787  when (s1_fire) { s2_valid := true.B }
788  .elsewhen (s2_fire) { s2_valid := false.B }
789  .elsewhen (s2_kill) { s2_valid := false.B }
790  s2_in := RegEnable(s1_out, s1_fire)
791
792  val s2_pmp = WireInit(io.pmp)
793
794  val s2_prf    = s2_in.isPrefetch
795  val s2_hw_prf = s2_in.isHWPrefetch
796  val s2_ld_flow  = RegEnable(s1_ld_flow, s1_fire)
797
798  // exception that may cause load addr to be invalid / illegal
799  // if such exception happen, that inst and its exception info
800  // will be force writebacked to rob
801  val s2_exception_vec = WireInit(s2_in.uop.exceptionVec)
802  when (s2_ld_flow) {
803    when (!s2_in.lateKill) {
804      s2_exception_vec(loadAccessFault) := s2_in.uop.exceptionVec(loadAccessFault) || s2_pmp.ld
805      // soft prefetch will not trigger any exception (but ecc error interrupt may be triggered)
806      when (s2_prf || s2_in.tlbMiss) {
807        s2_exception_vec := 0.U.asTypeOf(s2_exception_vec.cloneType)
808      }
809    }
810  } .otherwise {
811    s2_exception_vec(storeAccessFault) := s2_in.uop.exceptionVec(storeAccessFault) || s2_pmp.st
812    when (s2_prf || s2_in.tlbMiss) {
813      s2_exception_vec := 0.U.asTypeOf(s2_exception_vec.cloneType)
814    }
815  }
816  val s2_ld_exception = ExceptionNO.selectByFu(s2_exception_vec, LduCfg).asUInt.orR && s2_ld_flow
817  val s2_st_exception = ExceptionNO.selectByFu(s2_exception_vec, StaCfg).asUInt.orR && !s2_ld_flow
818  val s2_exception    = s2_ld_exception || s2_st_exception
819
820  val (s2_fwd_frm_d_chan, s2_fwd_data_frm_d_chan) = io.ldu_io.tl_d_channel.forward(s1_valid && s1_out.forward_tlDchannel, s1_out.mshrid, s1_out.paddr)
821  val (s2_fwd_data_valid, s2_fwd_frm_mshr, s2_fwd_data_frm_mshr) = io.ldu_io.forward_mshr.forward()
822  val s2_fwd_frm_d_chan_or_mshr = s2_fwd_data_valid && (s2_fwd_frm_d_chan || s2_fwd_frm_mshr)
823
824  // writeback access fault caused by ecc error / bus error
825  // * ecc data error is slow to generate, so we will not use it until load stage 3
826  // * in load stage 3, an extra signal io.load_error will be used to
827  val s2_actually_mmio = s2_pmp.mmio
828  val s2_mmio          = !s2_prf &&
829                          s2_actually_mmio &&
830                         !s2_exception &&
831                         !s2_in.tlbMiss
832  val s2_full_fwd      = Wire(Bool())
833  val s2_mem_amb       = s2_in.uop.storeSetHit &&
834                         io.ldu_io.lsq.forward.addrInvalid
835
836  val s2_tlb_miss      = s2_in.tlbMiss
837  val s2_fwd_fail      = io.ldu_io.lsq.forward.dataInvalid
838  val s2_dcache_miss   = io.ldu_io.dcache.resp.bits.miss &&
839                         !s2_fwd_frm_d_chan_or_mshr &&
840                         !s2_full_fwd
841
842  val s2_mq_nack       = io.ldu_io.dcache.s2_mq_nack &&
843                         !s2_fwd_frm_d_chan_or_mshr &&
844                         !s2_full_fwd
845
846  val s2_bank_conflict = io.ldu_io.dcache.s2_bank_conflict &&
847                         !s2_fwd_frm_d_chan_or_mshr &&
848                         !s2_full_fwd
849
850  val s2_wpu_pred_fail = io.ldu_io.dcache.s2_wpu_pred_fail &&
851                        !s2_fwd_frm_d_chan_or_mshr &&
852                        !s2_full_fwd
853
854  val s2_rar_nack      = io.ldu_io.lsq.ldld_nuke_query.req.valid &&
855                         !io.ldu_io.lsq.ldld_nuke_query.req.ready
856
857  val s2_raw_nack      = io.ldu_io.lsq.stld_nuke_query.req.valid &&
858                         !io.ldu_io.lsq.stld_nuke_query.req.ready
859
860  // st-ld violation query
861  //  NeedFastRecovery Valid when
862  //  1. Fast recovery query request Valid.
863  //  2. Load instruction is younger than requestors(store instructions).
864  //  3. Physical address match.
865  //  4. Data contains.
866  val s2_nuke = VecInit((0 until StorePipelineWidth).map(w => {
867                        io.ldu_io.stld_nuke_query(w).valid && // query valid
868                        isAfter(s2_in.uop.robIdx, io.ldu_io.stld_nuke_query(w).bits.robIdx) && // older store
869                        // TODO: Fix me when vector instruction
870                        (s2_in.paddr(PAddrBits-1, 3) === io.ldu_io.stld_nuke_query(w).bits.paddr(PAddrBits-1, 3)) && // paddr match
871                        (s2_in.mask & io.ldu_io.stld_nuke_query(w).bits.mask).orR // data mask contain
872                      })).asUInt.orR && s2_ld_flow || s2_in.rep_info.nuke
873
874  val s2_cache_handled   = io.ldu_io.dcache.resp.bits.handled
875  val s2_cache_tag_error = RegNext(io.csrCtrl.cache_error_enable) &&
876                           io.ldu_io.dcache.resp.bits.tag_error
877
878  val s2_troublem        = !s2_exception &&
879                           !s2_mmio &&
880                           !s2_prf &&
881                           !s2_in.lateKill
882
883  io.ldu_io.dcache.resp.ready := true.B
884  io.stu_io.dcache.resp.ready := true.B
885  val s2_dcache_should_resp = !(s2_in.tlbMiss || s2_exception || s2_mmio || s2_prf || s2_in.lateKill) && s2_ld_flow
886  assert(!(s2_valid && (s2_dcache_should_resp && !io.ldu_io.dcache.resp.valid)), "DCache response got lost")
887
888  // fast replay require
889  val s2_dcache_fast_rep = (s2_mq_nack || !s2_dcache_miss && (s2_bank_conflict || s2_wpu_pred_fail))
890  val s2_nuke_fast_rep   = !s2_mq_nack &&
891                           !s2_dcache_miss &&
892                           !s2_bank_conflict &&
893                           !s2_wpu_pred_fail &&
894                           !s2_rar_nack &&
895                           !s2_raw_nack &&
896                           s2_nuke
897
898  val s2_fast_rep = !s2_mem_amb &&
899                    !s2_tlb_miss &&
900                    !s2_fwd_fail &&
901                    (s2_dcache_fast_rep || s2_nuke_fast_rep) &&
902                    s2_troublem
903
904  // need allocate new entry
905  val s2_can_query = !s2_mem_amb &&
906                     !s2_tlb_miss  &&
907                     !s2_fwd_fail &&
908                     !s2_dcache_fast_rep &&
909                     s2_troublem
910
911  val s2_data_fwded = s2_dcache_miss && (s2_full_fwd || s2_cache_tag_error)
912
913  // ld-ld violation require
914  io.ldu_io.lsq.ldld_nuke_query.req.valid           := s2_valid && s2_can_query
915  io.ldu_io.lsq.ldld_nuke_query.req.bits.uop        := s2_in.uop
916  io.ldu_io.lsq.ldld_nuke_query.req.bits.mask       := s2_in.mask
917  io.ldu_io.lsq.ldld_nuke_query.req.bits.paddr      := s2_in.paddr
918  io.ldu_io.lsq.ldld_nuke_query.req.bits.data_valid := Mux(s2_full_fwd || s2_fwd_data_valid, true.B, !s2_dcache_miss)
919
920  // st-ld violation require
921  io.ldu_io.lsq.stld_nuke_query.req.valid           := s2_valid && s2_can_query
922  io.ldu_io.lsq.stld_nuke_query.req.bits.uop        := s2_in.uop
923  io.ldu_io.lsq.stld_nuke_query.req.bits.mask       := s2_in.mask
924  io.ldu_io.lsq.stld_nuke_query.req.bits.paddr      := s2_in.paddr
925  io.ldu_io.lsq.stld_nuke_query.req.bits.data_valid := Mux(s2_full_fwd || s2_fwd_data_valid, true.B, !s2_dcache_miss)
926
927  // merge forward result
928  // lsq has higher priority than sbuffer
929  val s2_fwd_mask = Wire(Vec((VLEN/8), Bool()))
930  val s2_fwd_data = Wire(Vec((VLEN/8), UInt(8.W)))
931  s2_full_fwd := ((~s2_fwd_mask.asUInt).asUInt & s2_in.mask) === 0.U && !io.ldu_io.lsq.forward.dataInvalid
932  // generate XLEN/8 Muxs
933  for (i <- 0 until VLEN / 8) {
934    s2_fwd_mask(i) := io.ldu_io.lsq.forward.forwardMask(i) || io.ldu_io.sbuffer.forwardMask(i)
935    s2_fwd_data(i) := Mux(io.ldu_io.lsq.forward.forwardMask(i), io.ldu_io.lsq.forward.forwardData(i), io.ldu_io.sbuffer.forwardData(i))
936  }
937
938  XSDebug(s2_fire && s2_ld_flow, "[FWD LOAD RESP] pc %x fwd %x(%b) + %x(%b)\n",
939    s2_in.uop.pc,
940    io.ldu_io.lsq.forward.forwardData.asUInt, io.ldu_io.lsq.forward.forwardMask.asUInt,
941    s2_in.forwardData.asUInt, s2_in.forwardMask.asUInt
942  )
943
944  //
945  s2_out                  := s2_in
946  s2_out.data             := 0.U // data will be generated in load s3
947  s2_out.uop.fpWen        := s2_in.uop.fpWen && !s2_exception && s2_ld_flow
948  s2_out.mmio             := s2_mmio
949  s2_out.atomic           := s2_pmp.atomic && !s2_ld_flow
950  s2_out.uop.flushPipe    := false.B
951  s2_out.uop.exceptionVec := s2_exception_vec
952  s2_out.forwardMask      := s2_fwd_mask
953  s2_out.forwardData      := s2_fwd_data
954  s2_out.handledByMSHR    := s2_cache_handled
955  s2_out.miss             := s2_dcache_miss && s2_troublem
956
957  // Generate replay signal caused by:
958  // * st-ld violation check
959  // * tlb miss
960  // * dcache replay
961  // * forward data invalid
962  // * dcache miss
963  s2_out.rep_info.mem_amb         := s2_mem_amb && s2_troublem
964  s2_out.rep_info.tlb_miss        := s2_tlb_miss && s2_troublem
965  s2_out.rep_info.fwd_fail        := s2_fwd_fail && s2_troublem
966  s2_out.rep_info.dcache_rep      := s2_mq_nack && s2_troublem
967  s2_out.rep_info.dcache_miss     := s2_dcache_miss && s2_troublem
968  s2_out.rep_info.bank_conflict   := s2_bank_conflict && s2_troublem
969  s2_out.rep_info.wpu_fail        := s2_wpu_pred_fail && s2_troublem
970  s2_out.rep_info.rar_nack        := s2_rar_nack && s2_troublem
971  s2_out.rep_info.raw_nack        := s2_raw_nack && s2_troublem
972  s2_out.rep_info.nuke            := s2_nuke && s2_troublem
973  s2_out.rep_info.full_fwd        := s2_data_fwded
974  s2_out.rep_info.data_inv_sq_idx := io.ldu_io.lsq.forward.dataInvalidSqIdx
975  s2_out.rep_info.addr_inv_sq_idx := io.ldu_io.lsq.forward.addrInvalidSqIdx
976  s2_out.rep_info.rep_carry       := io.ldu_io.dcache.resp.bits.replayCarry
977  s2_out.rep_info.mshr_id         := io.ldu_io.dcache.resp.bits.mshr_id
978  s2_out.rep_info.last_beat       := s2_in.paddr(log2Up(refillBytes))
979  s2_out.rep_info.debug           := s2_in.uop.debugInfo
980
981  // if forward fail, replay this inst from fetch
982  val debug_fwd_fail_rep = s2_fwd_fail && !s2_troublem && !s2_in.tlbMiss
983  // if ld-ld violation is detected, replay from this inst from fetch
984  val debug_ldld_nuke_rep = false.B // s2_ldld_violation && !s2_mmio && !s2_is_prefetch && !s2_in.tlbMiss
985  // io.out.bits.uop.replayInst := false.B
986
987  // to be removed
988  val s2_ld_need_fb = !s2_in.isLoadReplay &&      // already feedbacked
989                      io.ldu_io.lq_rep_full &&           // LoadQueueReplay is full
990                      s2_out.rep_info.need_rep && // need replay
991                      !s2_exception &&            // no exception is triggered
992                      !s2_hw_prf                  // not hardware prefetch
993  val s2_st_need_fb = !s2_ld_flow
994  io.feedback_fast.valid                 := s2_valid && (s2_ld_need_fb || s2_st_need_fb)
995  io.feedback_fast.bits.hit              := false.B
996  io.feedback_fast.bits.flushState       := s2_in.ptwBack
997  io.feedback_fast.bits.robIdx           := s2_in.uop.robIdx
998  io.feedback_fast.bits.sourceType       := Mux(s2_ld_flow, RSFeedbackType.lrqFull, RSFeedbackType.tlbMiss)
999  io.feedback_fast.bits.dataInvalidSqIdx := DontCare
1000
1001  io.stu_io.lsq_replenish := s2_out
1002  io.stu_io.lsq_replenish.miss := io.ldu_io.dcache.resp.fire && io.ldu_io.dcache.resp.bits.miss
1003
1004  io.ldu_io.ldCancel.ld1Cancel.valid := s2_valid && (
1005    (s2_out.rep_info.need_rep && s2_out.isFirstIssue) ||                // exe fail and issued from IQ
1006    s2_mmio                                                             // is mmio
1007  ) && s2_ld_flow
1008  io.ldu_io.ldCancel.ld1Cancel.bits := s2_out.deqPortIdx
1009
1010  // fast wakeup
1011  io.ldu_io.fast_uop.valid := RegNext(
1012    !io.ldu_io.dcache.s1_disable_fast_wakeup &&
1013    s1_valid &&
1014    !s1_kill &&
1015    !io.tlb.resp.bits.miss &&
1016    !io.ldu_io.lsq.forward.dataInvalidFast
1017  ) && (s2_valid && !s2_out.rep_info.need_rep && !s2_mmio && s2_ld_flow)
1018  io.ldu_io.fast_uop.bits := RegNext(s1_out.uop)
1019
1020  //
1021  io.ldu_io.s2_ptr_chasing                    := RegEnable(s1_try_ptr_chasing && !s1_cancel_ptr_chasing, false.B, s1_fire)
1022
1023  // prefetch train
1024  io.prefetch_train.valid              := s2_valid && !s2_actually_mmio && !s2_in.tlbMiss
1025  io.prefetch_train.bits.fromLsPipelineBundle(s2_in)
1026  io.prefetch_train.bits.miss          := Mux(s2_ld_flow, io.ldu_io.dcache.resp.bits.miss, io.stu_io.dcache.resp.bits.miss) // TODO: use trace with bank conflict?
1027  io.prefetch_train.bits.meta_prefetch := Mux(s2_ld_flow, io.ldu_io.dcache.resp.bits.meta_prefetch, false.B)
1028  io.prefetch_train.bits.meta_access   := Mux(s2_ld_flow, io.ldu_io.dcache.resp.bits.meta_access, false.B)
1029
1030  io.prefetch_train_l1.valid              := s2_valid && !s2_actually_mmio && s2_ld_flow
1031  io.prefetch_train_l1.bits.fromLsPipelineBundle(s2_in)
1032  io.prefetch_train_l1.bits.miss          := io.ldu_io.dcache.resp.bits.miss
1033  io.prefetch_train_l1.bits.meta_prefetch := io.ldu_io.dcache.resp.bits.meta_prefetch
1034  io.prefetch_train_l1.bits.meta_access   := io.ldu_io.dcache.resp.bits.meta_access
1035  if (env.FPGAPlatform){
1036    io.ldu_io.dcache.s0_pc := DontCare
1037    io.ldu_io.dcache.s1_pc := DontCare
1038    io.ldu_io.dcache.s2_pc := DontCare
1039  }else{
1040    io.ldu_io.dcache.s0_pc := s0_out.uop.pc
1041    io.ldu_io.dcache.s1_pc := s1_out.uop.pc
1042    io.ldu_io.dcache.s2_pc := s2_out.uop.pc
1043  }
1044  io.ldu_io.dcache.s2_kill := s2_pmp.ld  || s2_actually_mmio || s2_kill
1045  io.stu_io.dcache.s2_kill := s2_pmp.st || s2_actually_mmio || s2_kill
1046  io.stu_io.dcache.s2_pc := s2_out.uop.pc
1047
1048  val s1_ld_left_fire = s1_valid && !s1_kill && s2_ready && s1_ld_flow
1049  val s2_ld_valid_dup = RegInit(0.U(6.W))
1050  s2_ld_valid_dup := 0x0.U(6.W)
1051  when (s1_ld_left_fire && !s1_out.isHWPrefetch && s1_ld_flow) { s2_ld_valid_dup := 0x3f.U(6.W) }
1052  when (s1_kill || s1_out.isHWPrefetch || !s1_ld_flow) { s2_ld_valid_dup := 0x0.U(6.W) }
1053  assert(RegNext((s2_valid === s2_ld_valid_dup(0)) || RegNext(s1_out.isHWPrefetch) || RegNext(!s1_ld_flow)))
1054
1055  // Pipeline
1056  // --------------------------------------------------------------------------------
1057  // stage 3
1058  // --------------------------------------------------------------------------------
1059  // writeback and update load queue
1060  val s3_valid        = RegNext(s2_valid && !s2_out.isHWPrefetch && !s2_out.uop.robIdx.needFlush(io.redirect))
1061  val s3_in           = RegEnable(s2_out, s2_fire)
1062  val s3_out          = Wire(Valid(new MemExuOutput))
1063  val s3_dcache_rep   = RegEnable(s2_dcache_fast_rep && s2_troublem, false.B, s2_fire)
1064  val s3_ld_valid_dup = RegEnable(s2_ld_valid_dup, s2_fire)
1065  val s3_fast_rep     = Wire(Bool())
1066  val s3_ld_flow      = RegNext(s2_ld_flow)
1067  val s3_troublem     = RegNext(s2_troublem)
1068  val s3_kill         = s3_in.uop.robIdx.needFlush(io.redirect)
1069  s3_ready := !s3_valid || s3_kill || sx_can_go
1070
1071  // forwrad last beat
1072  val (s3_fwd_frm_d_chan, s3_fwd_data_frm_d_chan) = io.ldu_io.tl_d_channel.forward(s2_valid && s2_out.forward_tlDchannel, s2_out.mshrid, s2_out.paddr)
1073  val s3_fwd_data_valid = RegEnable(s2_fwd_data_valid, false.B, s2_valid)
1074  val s3_fwd_frm_d_chan_valid = (s3_fwd_frm_d_chan && s3_fwd_data_valid) && s3_ld_flow
1075
1076
1077  // s3 load fast replay
1078  io.ldu_io.fast_rep_out.valid := s3_valid &&
1079                                  s3_fast_rep &&
1080                                  !s3_in.uop.robIdx.needFlush(io.redirect) &&
1081                                  s3_ld_flow
1082  io.ldu_io.fast_rep_out.bits := s3_in
1083
1084  io.ldu_io.lsq.ldin.valid := s3_valid &&
1085                              (!s3_fast_rep || !io.ldu_io.fast_rep_out.ready) &&
1086                              !s3_in.feedbacked &&
1087                              !s3_in.lateKill &&
1088                              s3_ld_flow
1089  io.ldu_io.lsq.ldin.bits := s3_in
1090  io.ldu_io.lsq.ldin.bits.miss := s3_in.miss && !s3_fwd_frm_d_chan_valid
1091
1092  /* <------- DANGEROUS: Don't change sequence here ! -------> */
1093  io.ldu_io.lsq.ldin.bits.data_wen_dup := s3_ld_valid_dup.asBools
1094  io.ldu_io.lsq.ldin.bits.replacementUpdated := io.ldu_io.dcache.resp.bits.replacementUpdated
1095  io.ldu_io.lsq.ldin.bits.missDbUpdated := RegNext(s2_fire && s2_in.hasROBEntry && !s2_in.tlbMiss && !s2_in.missDbUpdated)
1096
1097  val s3_dly_ld_err =
1098    if (EnableAccurateLoadError) {
1099      (s3_in.lateKill || io.ldu_io.dcache.resp.bits.error_delayed) && RegNext(io.csrCtrl.cache_error_enable)
1100    } else {
1101      WireInit(false.B)
1102    }
1103  io.ldu_io.s3_dly_ld_err := false.B // s3_dly_ld_err && s3_valid
1104  io.ldu_io.fast_rep_out.bits.delayedLoadError := s3_dly_ld_err
1105  io.ldu_io.lsq.ldin.bits.dcacheRequireReplay  := s3_dcache_rep
1106
1107  val s3_vp_match_fail = RegNext(io.ldu_io.lsq.forward.matchInvalid || io.ldu_io.sbuffer.matchInvalid) && s3_troublem
1108  val s3_ldld_rep_inst =
1109      io.ldu_io.lsq.ldld_nuke_query.resp.valid &&
1110      io.ldu_io.lsq.ldld_nuke_query.resp.bits.rep_frm_fetch &&
1111      RegNext(io.csrCtrl.ldld_vio_check_enable)
1112
1113  val s3_rep_info = WireInit(s3_in.rep_info)
1114  s3_rep_info.dcache_miss   := s3_in.rep_info.dcache_miss && !s3_fwd_frm_d_chan_valid && s3_troublem
1115  val s3_rep_frm_fetch = s3_vp_match_fail || s3_ldld_rep_inst
1116  val s3_sel_rep_cause = PriorityEncoderOH(s3_rep_info.cause.asUInt)
1117  val s3_force_rep     = s3_sel_rep_cause(LoadReplayCauses.C_TM) &&
1118                         !s3_in.uop.exceptionVec(loadAddrMisaligned) &&
1119                         s3_troublem
1120
1121  val s3_ld_exception = ExceptionNO.selectByFu(s3_in.uop.exceptionVec, LduCfg).asUInt.orR && s3_ld_flow
1122  val s3_st_exception = ExceptionNO.selectByFu(s3_in.uop.exceptionVec, StaCfg).asUInt.orR && !s3_ld_flow
1123  val s3_exception    = s3_ld_exception || s3_st_exception
1124  when ((s3_ld_exception || s3_dly_ld_err || s3_rep_frm_fetch) && !s3_force_rep) {
1125    io.ldu_io.lsq.ldin.bits.rep_info.cause := 0.U.asTypeOf(s3_rep_info.cause.cloneType)
1126  } .otherwise {
1127    io.ldu_io.lsq.ldin.bits.rep_info.cause := VecInit(s3_sel_rep_cause.asBools)
1128  }
1129
1130  // Int flow, if hit, will be writebacked at s3
1131  s3_out.valid                := s3_valid &&
1132                                (!s3_ld_flow || !io.ldu_io.lsq.ldin.bits.rep_info.need_rep && !s3_in.mmio)
1133  s3_out.bits.uop             := s3_in.uop
1134  s3_out.bits.uop.exceptionVec(loadAccessFault) := (s3_dly_ld_err  || s3_in.uop.exceptionVec(loadAccessFault)) && s3_ld_flow
1135  s3_out.bits.uop.replayInst := s3_rep_frm_fetch
1136  s3_out.bits.data            := s3_in.data
1137  s3_out.bits.debug.isMMIO    := s3_in.mmio
1138  s3_out.bits.debug.isPerfCnt := false.B
1139  s3_out.bits.debug.paddr     := s3_in.paddr
1140  s3_out.bits.debug.vaddr     := s3_in.vaddr
1141
1142  when (s3_force_rep) {
1143    s3_out.bits.uop.exceptionVec := 0.U.asTypeOf(s3_in.uop.exceptionVec.cloneType)
1144  }
1145
1146  /* <------- DANGEROUS: Don't change sequence here ! -------> */
1147  io.ldu_io.lsq.ldin.bits.uop := s3_out.bits.uop
1148
1149  val s3_revoke = s3_exception || io.ldu_io.lsq.ldin.bits.rep_info.need_rep
1150  io.ldu_io.lsq.ldld_nuke_query.revoke := s3_revoke
1151  io.ldu_io.lsq.stld_nuke_query.revoke := s3_revoke
1152
1153  // feedback slow
1154  s3_fast_rep := RegNext(s2_fast_rep) &&
1155                 !s3_in.feedbacked &&
1156                 !s3_in.lateKill &&
1157                 !s3_rep_frm_fetch &&
1158                 !s3_exception
1159
1160  val s3_fb_no_waiting = !s3_in.isLoadReplay && !(s3_fast_rep && io.ldu_io.fast_rep_out.ready) && !s3_in.feedbacked
1161
1162  //
1163  io.feedback_slow.valid                 := s3_valid && !s3_in.uop.robIdx.needFlush(io.redirect) && s3_fb_no_waiting && s3_ld_flow
1164  io.feedback_slow.bits.hit              := !io.ldu_io.lsq.ldin.bits.rep_info.need_rep || io.ldu_io.lsq.ldin.ready
1165  io.feedback_slow.bits.flushState       := s3_in.ptwBack
1166  io.feedback_slow.bits.robIdx           := s3_in.uop.robIdx
1167  io.feedback_slow.bits.sourceType       := RSFeedbackType.lrqFull
1168  io.feedback_slow.bits.dataInvalidSqIdx := DontCare
1169
1170  io.ldu_io.ldCancel.ld2Cancel.valid := s3_valid && (
1171    (io.ldu_io.lsq.ldin.bits.rep_info.need_rep && s3_in.isFirstIssue) ||
1172    s3_in.mmio
1173  ) && s3_ld_flow
1174  io.ldu_io.ldCancel.ld2Cancel.bits := s3_in.deqPortIdx
1175
1176  // data from dcache hit
1177  val s3_ld_raw_data_frm_cache = Wire(new LoadDataFromDcacheBundle)
1178  s3_ld_raw_data_frm_cache.respDcacheData       := io.ldu_io.dcache.resp.bits.data_delayed
1179  s3_ld_raw_data_frm_cache.forwardMask          := RegEnable(s2_fwd_mask, s2_valid)
1180  s3_ld_raw_data_frm_cache.forwardData          := RegEnable(s2_fwd_data, s2_valid)
1181  s3_ld_raw_data_frm_cache.uop                  := RegEnable(s2_out.uop, s2_valid)
1182  s3_ld_raw_data_frm_cache.addrOffset           := RegEnable(s2_out.paddr(3, 0), s2_valid)
1183  s3_ld_raw_data_frm_cache.forward_D            := RegEnable(s2_fwd_frm_d_chan, false.B, s2_valid) || s3_fwd_frm_d_chan_valid
1184  s3_ld_raw_data_frm_cache.forwardData_D        := Mux(s3_fwd_frm_d_chan_valid, s3_fwd_data_frm_d_chan, RegEnable(s2_fwd_data_frm_d_chan, s2_valid))
1185  s3_ld_raw_data_frm_cache.forward_mshr         := RegEnable(s2_fwd_frm_mshr, false.B, s2_valid)
1186  s3_ld_raw_data_frm_cache.forwardData_mshr     := RegEnable(s2_fwd_data_frm_mshr, s2_valid)
1187  s3_ld_raw_data_frm_cache.forward_result_valid := RegEnable(s2_fwd_data_valid, false.B, s2_valid)
1188
1189  val s3_merged_data_frm_cache = s3_ld_raw_data_frm_cache.mergedData()
1190  val s3_picked_data_frm_cache = LookupTree(s3_ld_raw_data_frm_cache.addrOffset, List(
1191    "b0000".U -> s3_merged_data_frm_cache(63,    0),
1192    "b0001".U -> s3_merged_data_frm_cache(63,    8),
1193    "b0010".U -> s3_merged_data_frm_cache(63,   16),
1194    "b0011".U -> s3_merged_data_frm_cache(63,   24),
1195    "b0100".U -> s3_merged_data_frm_cache(63,   32),
1196    "b0101".U -> s3_merged_data_frm_cache(63,   40),
1197    "b0110".U -> s3_merged_data_frm_cache(63,   48),
1198    "b0111".U -> s3_merged_data_frm_cache(63,   56),
1199    "b1000".U -> s3_merged_data_frm_cache(127,  64),
1200    "b1001".U -> s3_merged_data_frm_cache(127,  72),
1201    "b1010".U -> s3_merged_data_frm_cache(127,  80),
1202    "b1011".U -> s3_merged_data_frm_cache(127,  88),
1203    "b1100".U -> s3_merged_data_frm_cache(127,  96),
1204    "b1101".U -> s3_merged_data_frm_cache(127, 104),
1205    "b1110".U -> s3_merged_data_frm_cache(127, 112),
1206    "b1111".U -> s3_merged_data_frm_cache(127, 120)
1207  ))
1208  val s3_ld_data_frm_cache = rdataHelper(s3_ld_raw_data_frm_cache.uop, s3_picked_data_frm_cache)
1209
1210  // FIXME: add 1 cycle delay ?
1211  io.ldout.bits      := s3_out.bits
1212  io.ldout.bits.data := s3_ld_data_frm_cache
1213  io.ldout.valid     := s3_out.valid && !s3_out.bits.uop.robIdx.needFlush(io.redirect) && s3_ld_flow
1214
1215  // for uncache
1216  io.ldu_io.lsq.uncache.ready := true.B
1217
1218  // fast load to load forward
1219  io.ldu_io.l2l_fwd_out.valid      := s3_out.valid && !s3_in.lateKill && s3_ld_flow
1220  io.ldu_io.l2l_fwd_out.data       := s3_ld_data_frm_cache
1221  io.ldu_io.l2l_fwd_out.dly_ld_err := s3_dly_ld_err // ecc delayed error
1222
1223  // hybrid unit writeback to rob
1224  // delay params
1225  val SelectGroupSize   = RollbackGroupSize
1226  val lgSelectGroupSize = log2Ceil(SelectGroupSize)
1227  val TotalSelectCycles = scala.math.ceil(log2Ceil(LoadQueueRAWSize).toFloat / lgSelectGroupSize).toInt + 1
1228  val TotalDelayCycles  = TotalSelectCycles - 2
1229
1230  // writeback
1231  val sx_valid = Wire(Vec(TotalDelayCycles + 1, Bool()))
1232  val sx_ready = Wire(Vec(TotalDelayCycles + 1, Bool()))
1233  val sx_in    = Wire(Vec(TotalDelayCycles + 1, new MemExuOutput))
1234
1235  sx_can_go := sx_ready.head
1236  for (i <- 0 until TotalDelayCycles + 1) {
1237    if (i == 0) {
1238      sx_valid(i) := s3_valid && !s3_ld_flow
1239      sx_in(i)    := s3_out.bits
1240      sx_ready(i) := !s3_valid(i) || sx_in(i).uop.robIdx.needFlush(io.redirect) || (if (TotalDelayCycles == 0) io.stout.ready else sx_ready(i+1))
1241    } else {
1242      val cur_kill   = sx_in(i).uop.robIdx.needFlush(io.redirect)
1243      val cur_can_go = (if (i == TotalDelayCycles) io.stout.ready else sx_ready(i+1))
1244      val cur_fire   = sx_valid(i) && !cur_kill && cur_can_go
1245      val prev_fire  = sx_valid(i-1) && !sx_in(i-1).uop.robIdx.needFlush(io.redirect) && sx_ready(i)
1246
1247      sx_ready(i) := !sx_valid(i) || cur_kill || (if (i == TotalDelayCycles) io.stout.ready else sx_ready(i+1))
1248      val sx_valid_can_go = prev_fire || cur_fire || cur_kill
1249      sx_valid(i) := RegEnable(Mux(prev_fire, true.B, false.B), sx_valid_can_go)
1250      sx_in(i) := RegEnable(sx_in(i-1), prev_fire)
1251    }
1252  }
1253
1254  val sx_last_valid = sx_valid.takeRight(1).head
1255  val sx_last_ready = sx_ready.takeRight(1).head
1256  val sx_last_in    = sx_in.takeRight(1).head
1257
1258  sx_last_ready  := !sx_last_valid || sx_last_in.uop.robIdx.needFlush(io.redirect) || io.stout.ready
1259  io.stout.valid := sx_last_valid && !sx_last_in.uop.robIdx.needFlush(io.redirect)
1260  io.stout.bits  := sx_last_in
1261
1262   // trigger
1263  val ld_trigger = FuType.isLoad(io.stout.bits.uop.fuType)
1264  val last_valid_data = RegEnable(io.stout.bits.data, io.stout.fire)
1265  val hit_ld_addr_trig_hit_vec = Wire(Vec(3, Bool()))
1266  val lq_ld_addr_trig_hit_vec = RegNext(io.ldu_io.lsq.trigger.lqLoadAddrTriggerHitVec)
1267  (0 until 3).map{i => {
1268    val tdata2    = RegNext(RegNext(io.ldu_io.trigger(i).tdata2))
1269    val matchType = RegNext(RegNext(io.ldu_io.trigger(i).matchType))
1270    val tEnable   = RegNext(RegNext(io.ldu_io.trigger(i).tEnable))
1271
1272    hit_ld_addr_trig_hit_vec(i)        := TriggerCmp(RegNext(s3_in.vaddr), tdata2, matchType, tEnable)
1273    io.ldu_io.trigger(i).addrHit       := Mux(io.stout.valid && ld_trigger, hit_ld_addr_trig_hit_vec(i), lq_ld_addr_trig_hit_vec(i))
1274    io.ldu_io.trigger(i).lastDataHit   := TriggerCmp(last_valid_data, tdata2, matchType, tEnable)
1275  }}
1276  io.ldu_io.lsq.trigger.hitLoadAddrTriggerHitVec := hit_ld_addr_trig_hit_vec
1277
1278  // FIXME: please move this part to LoadQueueReplay
1279  io.ldu_io.debug_ls := DontCare
1280  io.stu_io.debug_ls := DontCare
1281  io.stu_io.debug_ls.s1.isTlbFirstMiss := io.tlb.resp.valid && io.tlb.resp.bits.miss && io.tlb.resp.bits.debug.isFirstIssue && !s1_in.isHWPrefetch && !s1_ld_flow
1282  io.stu_io.debug_ls.s1_robIdx := s1_in.uop.robIdx.value
1283
1284 // Topdown
1285  io.ldu_io.lsTopdownInfo.s1.robIdx          := s1_in.uop.robIdx.value
1286  io.ldu_io.lsTopdownInfo.s1.vaddr_valid     := s1_valid && s1_in.hasROBEntry
1287  io.ldu_io.lsTopdownInfo.s1.vaddr_bits      := s1_vaddr
1288  io.ldu_io.lsTopdownInfo.s2.robIdx          := s2_in.uop.robIdx.value
1289  io.ldu_io.lsTopdownInfo.s2.paddr_valid     := s2_fire && s2_in.hasROBEntry && !s2_in.tlbMiss
1290  io.ldu_io.lsTopdownInfo.s2.paddr_bits      := s2_in.paddr
1291  io.ldu_io.lsTopdownInfo.s2.first_real_miss := io.ldu_io.dcache.resp.bits.real_miss
1292  io.ldu_io.lsTopdownInfo.s2.cache_miss_en   := s2_fire && s2_in.hasROBEntry && !s2_in.tlbMiss && !s2_in.missDbUpdated
1293
1294  // perf cnt
1295  XSPerfAccumulate("s0_in_valid",                  io.lsin.valid)
1296  XSPerfAccumulate("s0_in_block",                  io.lsin.valid && !io.lsin.fire)
1297  XSPerfAccumulate("s0_in_fire_first_issue",       s0_valid && s0_isFirstIssue)
1298  XSPerfAccumulate("s0_lsq_fire_first_issue",      io.ldu_io.replay.fire)
1299  XSPerfAccumulate("s0_ldu_fire_first_issue",      io.lsin.fire && s0_isFirstIssue)
1300  XSPerfAccumulate("s0_fast_replay_issue",         io.ldu_io.fast_rep_in.fire)
1301  XSPerfAccumulate("s0_stall_out",                 s0_valid && !s0_can_go)
1302  XSPerfAccumulate("s0_stall_ld_dcache",           s0_valid && !io.ldu_io.dcache.req.ready)
1303  XSPerfAccumulate("s0_stall_st_dcache",           s0_valid && !io.stu_io.dcache.req.ready)
1304  XSPerfAccumulate("s0_addr_spec_success",         s0_fire && s0_vaddr(VAddrBits-1, 12) === io.lsin.bits.src(0)(VAddrBits-1, 12))
1305  XSPerfAccumulate("s0_addr_spec_failed",          s0_fire && s0_vaddr(VAddrBits-1, 12) =/= io.lsin.bits.src(0)(VAddrBits-1, 12))
1306  XSPerfAccumulate("s0_addr_spec_success_once",    s0_fire && s0_vaddr(VAddrBits-1, 12) === io.lsin.bits.src(0)(VAddrBits-1, 12) && s0_isFirstIssue)
1307  XSPerfAccumulate("s0_addr_spec_failed_once",     s0_fire && s0_vaddr(VAddrBits-1, 12) =/= io.lsin.bits.src(0)(VAddrBits-1, 12) && s0_isFirstIssue)
1308  XSPerfAccumulate("s0_forward_tl_d_channel",      s0_out.forward_tlDchannel)
1309  XSPerfAccumulate("s0_hardware_prefetch_fire",    s0_fire && s0_hw_prf_select)
1310  XSPerfAccumulate("s0_software_prefetch_fire",    s0_fire && s0_prf && s0_int_iss_select)
1311  XSPerfAccumulate("s0_hardware_prefetch_blocked", io.ldu_io.prefetch_req.valid && !s0_hw_prf_select)
1312  XSPerfAccumulate("s0_hardware_prefetch_total",   io.ldu_io.prefetch_req.valid)
1313
1314  XSPerfAccumulate("s1_in_valid",                  s1_valid)
1315  XSPerfAccumulate("s1_in_fire",                   s1_fire)
1316  XSPerfAccumulate("s1_in_fire_first_issue",       s1_fire && s1_in.isFirstIssue)
1317  XSPerfAccumulate("s1_tlb_miss",                  s1_fire && s1_tlb_miss)
1318  XSPerfAccumulate("s1_tlb_miss_first_issue",      s1_fire && s1_tlb_miss && s1_in.isFirstIssue)
1319  XSPerfAccumulate("s1_stall_out",                 s1_valid && !s1_can_go)
1320  XSPerfAccumulate("s1_late_kill",                 s1_valid && s1_fast_rep_kill)
1321
1322  XSPerfAccumulate("s2_in_valid",                  s2_valid)
1323  XSPerfAccumulate("s2_in_fire",                   s2_fire)
1324  XSPerfAccumulate("s2_in_fire_first_issue",       s2_fire && s2_in.isFirstIssue)
1325  XSPerfAccumulate("s2_dcache_miss",               s2_fire && io.ldu_io.dcache.resp.bits.miss)
1326  XSPerfAccumulate("s2_dcache_miss_first_issue",   s2_fire && io.ldu_io.dcache.resp.bits.miss && s2_in.isFirstIssue)
1327  XSPerfAccumulate("s2_dcache_real_miss_first_issue",   s2_fire && io.ldu_io.dcache.resp.bits.miss && s2_in.isFirstIssue)
1328  XSPerfAccumulate("s2_full_forward",              s2_fire && s2_full_fwd)
1329  XSPerfAccumulate("s2_dcache_miss_full_forward",  s2_fire && s2_dcache_miss)
1330  XSPerfAccumulate("s2_fwd_frm_d_can",             s2_valid && s2_fwd_frm_d_chan)
1331  XSPerfAccumulate("s2_fwd_frm_d_chan_or_mshr",    s2_valid && s2_fwd_frm_d_chan_or_mshr)
1332  XSPerfAccumulate("s2_stall_out",                 s2_fire && !s2_can_go)
1333  XSPerfAccumulate("s2_prefetch",                  s2_fire && s2_prf)
1334  XSPerfAccumulate("s2_prefetch_ignored",          s2_fire && s2_prf && s2_mq_nack) // ignore prefetch for mshr full / miss req port conflict
1335  XSPerfAccumulate("s2_prefetch_miss",             s2_fire && s2_prf && io.ldu_io.dcache.resp.bits.miss) // prefetch req miss in l1
1336  XSPerfAccumulate("s2_prefetch_hit",              s2_fire && s2_prf && !io.ldu_io.dcache.resp.bits.miss) // prefetch req hit in l1
1337  XSPerfAccumulate("s2_prefetch_accept",           s2_fire && s2_prf && io.ldu_io.dcache.resp.bits.miss && !s2_mq_nack) // prefetch a missed line in l1, and l1 accepted it
1338  XSPerfAccumulate("s2_forward_req",               s2_fire && s2_in.forward_tlDchannel)
1339  XSPerfAccumulate("s2_successfully_forward_channel_D", s2_fire && s2_fwd_frm_d_chan && s2_fwd_data_valid)
1340  XSPerfAccumulate("s2_successfully_forward_mshr",      s2_fire && s2_fwd_frm_mshr && s2_fwd_data_valid)
1341
1342  XSPerfAccumulate("s3_fwd_frm_d_chan",            s3_valid && s3_fwd_frm_d_chan_valid)
1343
1344  XSPerfAccumulate("load_to_load_forward",                      s1_try_ptr_chasing && !s1_ptr_chasing_canceled)
1345  XSPerfAccumulate("load_to_load_forward_try",                  s1_try_ptr_chasing)
1346  XSPerfAccumulate("load_to_load_forward_fail",                 s1_cancel_ptr_chasing)
1347  XSPerfAccumulate("load_to_load_forward_fail_cancelled",       s1_cancel_ptr_chasing && s1_ptr_chasing_canceled)
1348  XSPerfAccumulate("load_to_load_forward_fail_wakeup_mismatch", s1_cancel_ptr_chasing && !s1_ptr_chasing_canceled && s1_not_fast_match)
1349  XSPerfAccumulate("load_to_load_forward_fail_op_not_ld",       s1_cancel_ptr_chasing && !s1_ptr_chasing_canceled && !s1_not_fast_match && s1_fu_op_type_not_ld)
1350  XSPerfAccumulate("load_to_load_forward_fail_addr_align",      s1_cancel_ptr_chasing && !s1_ptr_chasing_canceled && !s1_not_fast_match && !s1_fu_op_type_not_ld && s1_addr_misaligned)
1351  XSPerfAccumulate("load_to_load_forward_fail_set_mismatch",    s1_cancel_ptr_chasing && !s1_ptr_chasing_canceled && !s1_not_fast_match && !s1_fu_op_type_not_ld && !s1_addr_misaligned && s1_addr_mismatch)
1352
1353  // bug lyq: some signals in perfEvents are no longer suitable for the current MemBlock design
1354  // hardware performance counter
1355  val perfEvents = Seq(
1356    ("load_s0_in_fire         ", s0_fire                                                        ),
1357    ("load_to_load_forward    ", s1_fire && s1_try_ptr_chasing && !s1_ptr_chasing_canceled      ),
1358    ("stall_dcache            ", s0_valid && s0_can_go && !io.ldu_io.dcache.req.ready           ),
1359    ("load_s1_in_fire         ", s0_fire                                                        ),
1360    ("load_s1_tlb_miss        ", s1_fire && io.tlb.resp.bits.miss                               ),
1361    ("load_s2_in_fire         ", s1_fire                                                        ),
1362    ("load_s2_dcache_miss     ", s2_fire && io.ldu_io.dcache.resp.bits.miss                     ),
1363  )
1364  generatePerfEvent()
1365}