xref: /XiangShan/src/main/scala/xiangshan/mem/pipeline/LoadUnit.scala (revision ebb914e7007fa76b83a869685cc5c3efe1f867e9)
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.ctrlblock.DebugLsInfoBundle
32import xiangshan.backend.fu.util.SdtrigExt
33
34import xiangshan.cache._
35import xiangshan.cache.wpu.ReplayCarry
36import xiangshan.cache.mmu._
37import xiangshan.mem.mdp._
38
39class LoadToLsqReplayIO(implicit p: Parameters) extends XSBundle
40  with HasDCacheParameters
41  with HasTlbConst
42{
43  // mshr refill index
44  val mshr_id         = UInt(log2Up(cfg.nMissEntries).W)
45  // get full data from store queue and sbuffer
46  val full_fwd        = Bool()
47  // wait for data from store inst's store queue index
48  val data_inv_sq_idx = new SqPtr
49  // wait for address from store queue index
50  val addr_inv_sq_idx = new SqPtr
51  // replay carry
52  val rep_carry       = new ReplayCarry(nWays)
53  // data in last beat
54  val last_beat       = Bool()
55  // replay cause
56  val cause           = Vec(LoadReplayCauses.allCauses, Bool())
57  // performance debug information
58  val debug           = new PerfDebugInfo
59  // tlb hint
60  val tlb_id          = UInt(log2Up(loadfiltersize).W)
61  val tlb_full        = Bool()
62
63  // alias
64  def mem_amb       = cause(LoadReplayCauses.C_MA)
65  def tlb_miss      = cause(LoadReplayCauses.C_TM)
66  def fwd_fail      = cause(LoadReplayCauses.C_FF)
67  def dcache_rep    = cause(LoadReplayCauses.C_DR)
68  def dcache_miss   = cause(LoadReplayCauses.C_DM)
69  def wpu_fail      = cause(LoadReplayCauses.C_WF)
70  def bank_conflict = cause(LoadReplayCauses.C_BC)
71  def rar_nack      = cause(LoadReplayCauses.C_RAR)
72  def raw_nack      = cause(LoadReplayCauses.C_RAW)
73  def nuke          = cause(LoadReplayCauses.C_NK)
74  def need_rep      = cause.asUInt.orR
75}
76
77
78class LoadToLsqIO(implicit p: Parameters) extends XSBundle {
79  val ldin            = DecoupledIO(new LqWriteBundle)
80  val uncache         = Flipped(DecoupledIO(new MemExuOutput))
81  val ld_raw_data     = Input(new LoadDataFromLQBundle)
82  val forward         = new PipeLoadForwardQueryIO
83  val stld_nuke_query = new LoadNukeQueryIO
84  val ldld_nuke_query = new LoadNukeQueryIO
85  val trigger         = Flipped(new LqTriggerIO)
86}
87
88class LoadToLoadIO(implicit p: Parameters) extends XSBundle {
89  val valid      = Bool()
90  val data       = UInt(XLEN.W) // load to load fast path is limited to ld (64 bit) used as vaddr src1 only
91  val dly_ld_err = Bool()
92}
93
94class LoadUnitTriggerIO(implicit p: Parameters) extends XSBundle {
95  val tdata2      = Input(UInt(64.W))
96  val matchType   = Input(UInt(2.W))
97  val tEnable     = Input(Bool()) // timing is calculated before this
98  val addrHit     = Output(Bool())
99}
100
101class LoadUnit(implicit p: Parameters) extends XSModule
102  with HasLoadHelper
103  with HasPerfEvents
104  with HasDCacheParameters
105  with HasCircularQueuePtrHelper
106  with HasVLSUParameters
107  with SdtrigExt
108{
109  val io = IO(new Bundle() {
110    // control
111    val redirect      = Flipped(ValidIO(new Redirect))
112    val csrCtrl       = Flipped(new CustomCSRCtrlIO)
113
114    // int issue path
115    val ldin          = Flipped(Decoupled(new MemExuInput))
116    val ldout         = Decoupled(new MemExuOutput)
117
118    // vec issue path
119    val vecldin = Flipped(Decoupled(new VecPipeBundle))
120    val vecldout = Decoupled(new VecPipelineFeedbackIO(isVStore = false))
121
122    // data path
123    val tlb           = new TlbRequestIO(2)
124    val pmp           = Flipped(new PMPRespBundle()) // arrive same to tlb now
125    val dcache        = new DCacheLoadIO
126    val sbuffer       = new LoadForwardQueryIO
127    val lsq           = new LoadToLsqIO
128    val tl_d_channel  = Input(new DcacheToLduForwardIO)
129    val forward_mshr  = Flipped(new LduToMissqueueForwardIO)
130    val refill        = Flipped(ValidIO(new Refill))
131    val l2_hint       = Input(Valid(new L2ToL1Hint))
132    val tlb_hint      = Flipped(new TlbHintReq)
133    // fast wakeup
134    // TODO: implement vector fast wakeup
135    val fast_uop = ValidIO(new DynInst) // early wakeup signal generated in load_s1, send to RS in load_s2
136
137    // trigger
138    val trigger = Vec(TriggerNum, new LoadUnitTriggerIO)
139
140    // prefetch
141    val prefetch_train            = ValidIO(new LdPrefetchTrainBundle()) // provide prefetch info to sms
142    val prefetch_train_l1         = ValidIO(new LdPrefetchTrainBundle()) // provide prefetch info to stream & stride
143    val prefetch_req              = Flipped(ValidIO(new L1PrefetchReq)) // hardware prefetch to l1 cache req
144    val canAcceptLowConfPrefetch  = Output(Bool())
145    val canAcceptHighConfPrefetch = Output(Bool())
146
147    // load to load fast path
148    val l2l_fwd_in    = Input(new LoadToLoadIO)
149    val l2l_fwd_out   = Output(new LoadToLoadIO)
150
151    val ld_fast_match    = Input(Bool())
152    val ld_fast_fuOpType = Input(UInt())
153    val ld_fast_imm      = Input(UInt(12.W))
154
155    // rs feedback
156    val wakeup = ValidIO(new DynInst)
157    val feedback_fast = ValidIO(new RSFeedback) // stage 2
158    val feedback_slow = ValidIO(new RSFeedback) // stage 3
159    val ldCancel = Output(new LoadCancelIO()) // use to cancel the uops waked by this load, and cancel load
160
161    // load ecc error
162    val s3_dly_ld_err = Output(Bool()) // Note that io.s3_dly_ld_err and io.lsq.s3_dly_ld_err is different
163
164    // schedule error query
165    val stld_nuke_query = Flipped(Vec(StorePipelineWidth, Valid(new StoreNukeQueryIO)))
166
167    // queue-based replay
168    val replay       = Flipped(Decoupled(new LsPipelineBundle))
169    val lq_rep_full  = Input(Bool())
170
171    // misc
172    val s2_ptr_chasing = Output(Bool()) // provide right pc for hw prefetch
173
174    // Load fast replay path
175    val fast_rep_in  = Flipped(Decoupled(new LqWriteBundle))
176    val fast_rep_out = Decoupled(new LqWriteBundle)
177
178    // Load RAR rollback
179    val rollback = Valid(new Redirect)
180
181    // perf
182    val debug_ls         = Output(new DebugLsInfoBundle)
183    val lsTopdownInfo    = Output(new LsTopdownInfo)
184    val correctMissTrain = Input(Bool())
185  })
186
187  val s1_ready, s2_ready, s3_ready = WireInit(false.B)
188
189  // Pipeline
190  // --------------------------------------------------------------------------------
191  // stage 0
192  // --------------------------------------------------------------------------------
193  // generate addr, use addr to query DCache and DTLB
194  val s0_valid         = Wire(Bool())
195  val s0_mmio_select   = Wire(Bool())
196  val s0_kill          = Wire(Bool())
197  val s0_can_go        = s1_ready
198  val s0_fire          = s0_valid && s0_can_go
199  val s0_mmio_fire     = s0_mmio_select && s0_can_go
200  val s0_out           = Wire(new LqWriteBundle)
201
202  // flow source bundle
203  class FlowSource extends Bundle {
204    val vaddr         = UInt(VAddrBits.W)
205    val mask          = UInt((VLEN/8).W)
206    val uop           = new DynInst
207    val try_l2l       = Bool()
208    val has_rob_entry = Bool()
209    val rsIdx         = UInt(log2Up(MemIQSizeMax).W)
210    val rep_carry     = new ReplayCarry(nWays)
211    val mshrid        = UInt(log2Up(cfg.nMissEntries).W)
212    val isFirstIssue  = Bool()
213    val fast_rep      = Bool()
214    val ld_rep        = Bool()
215    val l2l_fwd       = Bool()
216    val prf           = Bool()
217    val prf_rd        = Bool()
218    val prf_wr        = Bool()
219    val sched_idx     = UInt(log2Up(LoadQueueReplaySize+1).W)
220    // Record the issue port idx of load issue queue. This signal is used by load cancel.
221    val deqPortIdx    = UInt(log2Ceil(LoadPipelineWidth).W)
222    // vec only
223    val isvec         = Bool()
224    val is128bit      = Bool()
225    val uop_unit_stride_fof = Bool()
226    val reg_offset    = UInt(vOffsetBits.W)
227    val vecActive     = Bool() // 1: vector active element or scala mem operation, 0: vector not active element
228    val is_first_ele  = Bool()
229    // val flowPtr       = new VlflowPtr
230    val usSecondInv   = Bool()
231    val mbIndex       = UInt(vlmBindexBits.W)
232    val elemIdx       = UInt(elemIdxBits.W)
233    val alignedType   = UInt(alignTypeBits.W)
234  }
235  val s0_sel_src = Wire(new FlowSource)
236
237  // load flow select/gen
238  // src0: super load replayed by LSQ (cache miss replay) (io.replay)
239  // src1: fast load replay (io.fast_rep_in)
240  // src2: mmio (io.lsq.uncache)
241  // src3: load replayed by LSQ (io.replay)
242  // src4: hardware prefetch from prefetchor (high confidence) (io.prefetch)
243  // NOTE: Now vec/int loads are sent from same RS
244  //       A vec load will be splited into multiple uops,
245  //       so as long as one uop is issued,
246  //       the other uops should have higher priority
247  // src5: vec read from RS (io.vecldin)
248  // src6: int read / software prefetch first issue from RS (io.in)
249  // src7: load try pointchaising when no issued or replayed load (io.fastpath)
250  // src8: hardware prefetch from prefetchor (high confidence) (io.prefetch)
251  // priority: high to low
252  val s0_rep_stall           = io.ldin.valid && isAfter(io.replay.bits.uop.robIdx, io.ldin.bits.uop.robIdx)
253  val s0_super_ld_rep_valid  = io.replay.valid && io.replay.bits.forward_tlDchannel
254  val s0_ld_fast_rep_valid   = io.fast_rep_in.valid
255  val s0_ld_mmio_valid       = io.lsq.uncache.valid
256  val s0_ld_rep_valid        = io.replay.valid && !io.replay.bits.forward_tlDchannel && !s0_rep_stall
257  val s0_high_conf_prf_valid = io.prefetch_req.valid && io.prefetch_req.bits.confidence > 0.U
258  val s0_vec_iss_valid       = io.vecldin.valid
259  val s0_int_iss_valid       = io.ldin.valid // int flow first issue or software prefetch
260  val s0_l2l_fwd_valid       = io.l2l_fwd_in.valid
261  val s0_low_conf_prf_valid  = io.prefetch_req.valid && io.prefetch_req.bits.confidence === 0.U
262  val s0_is128bit            = is128Bit(io.vecldin.bits.alignedType) && io.vecldin.valid
263  dontTouch(s0_super_ld_rep_valid)
264  dontTouch(s0_ld_fast_rep_valid)
265  dontTouch(s0_ld_mmio_valid)
266  dontTouch(s0_ld_rep_valid)
267  dontTouch(s0_high_conf_prf_valid)
268  dontTouch(s0_vec_iss_valid)
269  dontTouch(s0_int_iss_valid)
270  dontTouch(s0_l2l_fwd_valid)
271  dontTouch(s0_low_conf_prf_valid)
272
273  // load flow source ready
274  val s0_super_ld_rep_ready  = WireInit(true.B)
275  val s0_ld_fast_rep_ready   = !s0_super_ld_rep_valid
276  val s0_ld_mmio_ready       = !s0_super_ld_rep_valid &&
277                               !s0_ld_fast_rep_valid
278  val s0_ld_rep_ready        = !s0_super_ld_rep_valid &&
279                               !s0_ld_fast_rep_valid &&
280                               !s0_ld_mmio_valid
281  val s0_high_conf_prf_ready = !s0_super_ld_rep_valid &&
282                               !s0_ld_fast_rep_valid &&
283                               !s0_ld_mmio_valid &&
284                               !s0_ld_rep_valid
285
286  val s0_vec_iss_ready       = !s0_super_ld_rep_valid &&
287                               !s0_ld_fast_rep_valid &&
288                               !s0_ld_mmio_valid &&
289                               !s0_ld_rep_valid &&
290                               !s0_high_conf_prf_valid
291
292  val s0_int_iss_ready       = !s0_super_ld_rep_valid &&
293                               !s0_ld_fast_rep_valid &&
294                               !s0_ld_mmio_valid &&
295                               !s0_ld_rep_valid &&
296                               !s0_high_conf_prf_valid &&
297                               !s0_vec_iss_valid
298
299  val s0_l2l_fwd_ready       = !s0_super_ld_rep_valid &&
300                               !s0_ld_fast_rep_valid &&
301                               !s0_ld_mmio_valid &&
302                               !s0_ld_rep_valid &&
303                               !s0_high_conf_prf_valid &&
304                               !s0_int_iss_valid &&
305                               !s0_vec_iss_valid
306
307  val s0_low_conf_prf_ready  = !s0_super_ld_rep_valid &&
308                               !s0_ld_fast_rep_valid &&
309                               !s0_ld_mmio_valid &&
310                               !s0_ld_rep_valid &&
311                               !s0_high_conf_prf_valid &&
312                               !s0_int_iss_valid &&
313                               !s0_vec_iss_valid &&
314                               !s0_l2l_fwd_valid
315  dontTouch(s0_super_ld_rep_ready)
316  dontTouch(s0_ld_fast_rep_ready)
317  dontTouch(s0_ld_mmio_ready)
318  dontTouch(s0_ld_rep_ready)
319  dontTouch(s0_high_conf_prf_ready)
320  dontTouch(s0_vec_iss_ready)
321  dontTouch(s0_int_iss_ready)
322  dontTouch(s0_l2l_fwd_ready)
323  dontTouch(s0_low_conf_prf_ready)
324
325  // load flow source select (OH)
326  val s0_super_ld_rep_select = s0_super_ld_rep_valid && s0_super_ld_rep_ready
327  val s0_ld_fast_rep_select  = s0_ld_fast_rep_valid && s0_ld_fast_rep_ready
328  val s0_ld_mmio_select      = s0_ld_mmio_valid && s0_ld_mmio_ready
329  val s0_ld_rep_select       = s0_ld_rep_valid && s0_ld_rep_ready
330  val s0_hw_prf_select       = s0_high_conf_prf_ready && s0_high_conf_prf_valid ||
331                               s0_low_conf_prf_ready && s0_low_conf_prf_valid
332  val s0_vec_iss_select      = s0_vec_iss_ready && s0_vec_iss_valid
333  val s0_int_iss_select      = s0_int_iss_ready && s0_int_iss_valid
334  val s0_l2l_fwd_select      = s0_l2l_fwd_ready && s0_l2l_fwd_valid
335  dontTouch(s0_super_ld_rep_select)
336  dontTouch(s0_ld_fast_rep_select)
337  dontTouch(s0_ld_mmio_select)
338  dontTouch(s0_ld_rep_select)
339  dontTouch(s0_hw_prf_select)
340  dontTouch(s0_vec_iss_select)
341  dontTouch(s0_int_iss_select)
342  dontTouch(s0_l2l_fwd_select)
343
344  s0_valid := (s0_super_ld_rep_valid ||
345               s0_ld_fast_rep_valid ||
346               s0_ld_rep_valid ||
347               s0_high_conf_prf_valid ||
348               s0_vec_iss_valid ||
349               s0_int_iss_valid ||
350               s0_l2l_fwd_valid ||
351               s0_low_conf_prf_valid) && !s0_ld_mmio_select && io.dcache.req.ready && !s0_kill
352
353  s0_mmio_select := s0_ld_mmio_select && !s0_kill
354
355  // which is S0's out is ready and dcache is ready
356  val s0_try_ptr_chasing      = s0_l2l_fwd_select
357  val s0_do_try_ptr_chasing   = s0_try_ptr_chasing && s0_can_go && io.dcache.req.ready
358  val s0_ptr_chasing_vaddr    = io.l2l_fwd_in.data(5, 0) +& io.ld_fast_imm(5, 0)
359  val s0_ptr_chasing_canceled = WireInit(false.B)
360  s0_kill := s0_ptr_chasing_canceled
361
362  // prefetch related ctrl signal
363  io.canAcceptLowConfPrefetch  := s0_low_conf_prf_ready
364  io.canAcceptHighConfPrefetch := s0_high_conf_prf_ready
365
366  // query DTLB
367  io.tlb.req.valid                   := s0_valid
368  io.tlb.req.bits.cmd                := Mux(s0_sel_src.prf,
369                                         Mux(s0_sel_src.prf_wr, TlbCmd.write, TlbCmd.read),
370                                         TlbCmd.read
371                                       )
372  io.tlb.req.bits.vaddr              := Mux(s0_hw_prf_select, io.prefetch_req.bits.paddr, s0_sel_src.vaddr)
373  io.tlb.req.bits.size               := Mux(s0_sel_src.isvec, io.vecldin.bits.alignedType(2,0), LSUOpType.size(s0_sel_src.uop.fuOpType)) // FIXME : currently not use, 128 bit load will error if use it
374  io.tlb.req.bits.kill               := s0_kill
375  io.tlb.req.bits.memidx.is_ld       := true.B
376  io.tlb.req.bits.memidx.is_st       := false.B
377  io.tlb.req.bits.memidx.idx         := s0_sel_src.uop.lqIdx.value
378  io.tlb.req.bits.debug.robIdx       := s0_sel_src.uop.robIdx
379  io.tlb.req.bits.no_translate       := s0_hw_prf_select  // hw b.reqetch addr does not need to be translated
380  io.tlb.req.bits.debug.pc           := s0_sel_src.uop.pc
381  io.tlb.req.bits.debug.isFirstIssue := s0_sel_src.isFirstIssue
382
383  // query DCache
384  io.dcache.req.valid             := s0_valid
385  io.dcache.req.bits.cmd          := Mux(s0_sel_src.prf_rd,
386                                      MemoryOpConstants.M_PFR,
387                                      Mux(s0_sel_src.prf_wr, MemoryOpConstants.M_PFW, MemoryOpConstants.M_XRD)
388                                    )
389  io.dcache.req.bits.vaddr        := s0_sel_src.vaddr
390  io.dcache.req.bits.mask         := s0_sel_src.mask
391  io.dcache.req.bits.data         := DontCare
392  io.dcache.req.bits.isFirstIssue := s0_sel_src.isFirstIssue
393  io.dcache.req.bits.instrtype    := Mux(s0_sel_src.prf, DCACHE_PREFETCH_SOURCE.U, LOAD_SOURCE.U)
394  io.dcache.req.bits.debug_robIdx := s0_sel_src.uop.robIdx.value
395  io.dcache.req.bits.replayCarry  := s0_sel_src.rep_carry
396  io.dcache.req.bits.id           := DontCare // TODO: update cache meta
397  io.dcache.pf_source             := Mux(s0_hw_prf_select, io.prefetch_req.bits.pf_source.value, L1_HW_PREFETCH_NULL)
398  io.dcache.is128Req              := s0_is128bit && s0_vec_iss_select
399
400  // load flow priority mux
401  def fromNullSource(): FlowSource = {
402    val out = WireInit(0.U.asTypeOf(new FlowSource))
403    out
404  }
405
406  def fromFastReplaySource(src: LqWriteBundle): FlowSource = {
407    val out = WireInit(0.U.asTypeOf(new FlowSource))
408    out.vaddr         := src.vaddr
409    out.mask          := src.mask
410    out.uop           := src.uop
411    out.try_l2l       := false.B
412    out.has_rob_entry := src.hasROBEntry
413    out.rep_carry     := src.rep_info.rep_carry
414    out.mshrid        := src.rep_info.mshr_id
415    out.rsIdx         := src.rsIdx
416    out.isFirstIssue  := false.B
417    out.fast_rep      := true.B
418    out.ld_rep        := src.isLoadReplay
419    out.l2l_fwd       := false.B
420    out.prf           := LSUOpType.isPrefetch(src.uop.fuOpType)
421    out.prf_rd        := src.uop.fuOpType === LSUOpType.prefetch_r
422    out.prf_wr        := src.uop.fuOpType === LSUOpType.prefetch_w
423    out.sched_idx     := src.schedIndex
424    out.isvec         := src.isvec
425    out.is128bit      := src.is128bit
426    out.uop_unit_stride_fof := src.uop_unit_stride_fof
427    out.reg_offset    := src.reg_offset
428    out.vecActive     := src.vecActive
429    out.is_first_ele  := src.is_first_ele
430    out.usSecondInv   := src.usSecondInv
431    out.mbIndex       := src.mbIndex
432    out.elemIdx       := src.elemIdx
433    out.alignedType   := src.alignedType
434    out
435  }
436
437  // TODO: implement vector mmio
438  def fromMmioSource(src: MemExuOutput) = {
439    val out = WireInit(0.U.asTypeOf(new FlowSource))
440    out.vaddr        := 0.U
441    out.mask          := 0.U
442    out.uop           := src.uop
443    out.try_l2l       := false.B
444    out.has_rob_entry := false.B
445    out.rsIdx         := 0.U
446    out.rep_carry     := 0.U.asTypeOf(out.rep_carry)
447    out.mshrid        := 0.U
448    out.isFirstIssue  := false.B
449    out.fast_rep      := false.B
450    out.ld_rep        := false.B
451    out.l2l_fwd       := false.B
452    out.prf           := false.B
453    out.prf_rd        := false.B
454    out.prf_wr        := false.B
455    out.sched_idx     := 0.U
456    out.vecActive     := true.B
457    out
458  }
459
460  def fromNormalReplaySource(src: LsPipelineBundle): FlowSource = {
461    val out = WireInit(0.U.asTypeOf(new FlowSource))
462    out.vaddr         := src.vaddr
463    out.mask          := Mux(src.isvec, src.mask, genVWmask(src.vaddr, src.uop.fuOpType(1, 0)))
464    out.uop           := src.uop
465    out.try_l2l       := false.B
466    out.has_rob_entry := true.B
467    out.rsIdx         := src.rsIdx
468    out.rep_carry     := src.replayCarry
469    out.mshrid        := src.mshrid
470    out.isFirstIssue  := false.B
471    out.fast_rep      := false.B
472    out.ld_rep        := true.B
473    out.l2l_fwd       := false.B
474    out.prf           := LSUOpType.isPrefetch(src.uop.fuOpType)
475    out.prf_rd        := src.uop.fuOpType === LSUOpType.prefetch_r
476    out.prf_wr        := src.uop.fuOpType === LSUOpType.prefetch_w
477    out.sched_idx     := src.schedIndex
478    out.isvec         := src.isvec
479    out.is128bit      := src.is128bit
480    out.uop_unit_stride_fof := src.uop_unit_stride_fof
481    out.reg_offset    := src.reg_offset
482    out.vecActive     := src.vecActive
483    out.is_first_ele  := src.is_first_ele
484    out.usSecondInv   := src.usSecondInv
485    out.mbIndex       := src.mbIndex
486    out.elemIdx       := src.elemIdx
487    out.alignedType   := src.alignedType
488    out
489  }
490
491  // TODO: implement vector prefetch
492  def fromPrefetchSource(src: L1PrefetchReq): FlowSource = {
493    val out = WireInit(0.U.asTypeOf(new FlowSource))
494    out.vaddr         := src.getVaddr()
495    out.mask          := 0.U
496    out.uop           := DontCare
497    out.try_l2l       := false.B
498    out.has_rob_entry := false.B
499    out.rsIdx         := 0.U
500    out.rep_carry     := 0.U.asTypeOf(out.rep_carry)
501    out.mshrid        := 0.U
502    out.isFirstIssue  := false.B
503    out.fast_rep      := false.B
504    out.ld_rep        := false.B
505    out.l2l_fwd       := false.B
506    out.prf           := true.B
507    out.prf_rd        := !src.is_store
508    out.prf_wr        := src.is_store
509    out.sched_idx     := 0.U
510    out
511  }
512
513  def fromVecIssueSource(src: VecPipeBundle): FlowSource = {
514    val out = WireInit(0.U.asTypeOf(new FlowSource))
515    out.vaddr         := src.vaddr
516    out.mask          := src.mask
517    out.uop           := src.uop
518    out.try_l2l       := false.B
519    out.has_rob_entry := true.B
520    // TODO: VLSU, implement vector feedback
521    out.rsIdx         := 0.U
522    // TODO: VLSU, implement replay carry
523    out.rep_carry     := 0.U.asTypeOf(out.rep_carry)
524    out.mshrid        := 0.U
525    // TODO: VLSU, implement first issue
526//    out.isFirstIssue  := src.isFirstIssue
527    out.fast_rep      := false.B
528    out.ld_rep        := false.B
529    out.l2l_fwd       := false.B
530    out.prf           := false.B
531    out.prf_rd        := false.B
532    out.prf_wr        := false.B
533    out.sched_idx     := 0.U
534    // Vector load interface
535    out.isvec               := true.B
536    // vector loads only access a single element at a time, so 128-bit path is not used for now
537    out.is128bit            := is128Bit(src.alignedType)
538    out.uop_unit_stride_fof := src.uop_unit_stride_fof
539    // out.rob_idx_valid       := src.rob_idx_valid
540    // out.inner_idx           := src.inner_idx
541    // out.rob_idx             := src.rob_idx
542    out.reg_offset          := src.reg_offset
543    // out.offset              := src.offset
544    out.vecActive           := src.vecActive
545    out.is_first_ele        := src.is_first_ele
546    // out.flowPtr             := src.flowPtr
547    out.usSecondInv         := src.usSecondInv
548    out.mbIndex             := src.mBIndex
549    out.elemIdx             := src.elemIdx
550    out.alignedType         := src.alignedType
551    out
552  }
553
554  def fromIntIssueSource(src: MemExuInput): FlowSource = {
555    val out = WireInit(0.U.asTypeOf(new FlowSource))
556    out.vaddr         := src.src(0) + SignExt(src.uop.imm(11, 0), VAddrBits)
557    out.mask          := genVWmask(out.vaddr, src.uop.fuOpType(1,0))
558    out.uop           := src.uop
559    out.try_l2l       := false.B
560    out.has_rob_entry := true.B
561    out.rsIdx         := src.iqIdx
562    out.rep_carry     := 0.U.asTypeOf(out.rep_carry)
563    out.mshrid        := 0.U
564    out.isFirstIssue  := true.B
565    out.fast_rep      := false.B
566    out.ld_rep        := false.B
567    out.l2l_fwd       := false.B
568    out.prf           := LSUOpType.isPrefetch(src.uop.fuOpType)
569    out.prf_rd        := src.uop.fuOpType === LSUOpType.prefetch_r
570    out.prf_wr        := src.uop.fuOpType === LSUOpType.prefetch_w
571    out.sched_idx     := 0.U
572    out.vecActive     := true.B // true for scala load
573    out
574  }
575
576  // TODO: implement vector l2l
577  def fromLoadToLoadSource(src: LoadToLoadIO): FlowSource = {
578    val out = WireInit(0.U.asTypeOf(new FlowSource))
579    out.vaddr              := Cat(src.data(XLEN-1, 6), s0_ptr_chasing_vaddr(5,0))
580    out.mask               := genVWmask(0.U, LSUOpType.ld)
581    // When there's no valid instruction from RS and LSQ, we try the load-to-load forwarding.
582    // Assume the pointer chasing is always ld.
583    out.uop.fuOpType       := LSUOpType.ld
584    out.try_l2l            := true.B
585    // we dont care out.isFirstIssue and out.rsIdx and s0_sqIdx in S0 when trying pointchasing
586    // because these signals will be updated in S1
587    out.has_rob_entry      := false.B
588    out.rsIdx              := 0.U
589    out.mshrid             := 0.U
590    out.rep_carry          := 0.U.asTypeOf(out.rep_carry)
591    out.isFirstIssue       := true.B
592    out.fast_rep           := false.B
593    out.ld_rep             := false.B
594    out.l2l_fwd            := true.B
595    out.prf                := false.B
596    out.prf_rd             := false.B
597    out.prf_wr             := false.B
598    out.sched_idx          := 0.U
599    out
600  }
601
602  // set default
603  val s0_src_selector = Seq(
604    s0_super_ld_rep_select,
605    s0_ld_fast_rep_select,
606    s0_ld_mmio_select,
607    s0_ld_rep_select,
608    s0_hw_prf_select,
609    s0_vec_iss_select,
610    s0_int_iss_select,
611    (if (EnableLoadToLoadForward) s0_l2l_fwd_select else true.B)
612  )
613  val s0_src_format = Seq(
614    fromNormalReplaySource(io.replay.bits),
615    fromFastReplaySource(io.fast_rep_in.bits),
616    fromMmioSource(io.lsq.uncache.bits),
617    fromNormalReplaySource(io.replay.bits),
618    fromPrefetchSource(io.prefetch_req.bits),
619    fromVecIssueSource(io.vecldin.bits),
620    fromIntIssueSource(io.ldin.bits),
621    (if (EnableLoadToLoadForward) fromLoadToLoadSource(io.l2l_fwd_in) else fromNullSource())
622  )
623  s0_sel_src := ParallelPriorityMux(s0_src_selector, s0_src_format)
624
625  // address align check
626  val s0_addr_aligned = LookupTree(Mux(s0_sel_src.isvec, io.vecldin.bits.alignedType(1,0), s0_sel_src.uop.fuOpType(1, 0)), List(
627    "b00".U   -> true.B,                   //b
628    "b01".U   -> (s0_sel_src.vaddr(0)    === 0.U), //h
629    "b10".U   -> (s0_sel_src.vaddr(1, 0) === 0.U), //w
630    "b11".U   -> (s0_sel_src.vaddr(2, 0) === 0.U)  //d
631  ))
632  XSError(s0_sel_src.isvec && s0_sel_src.vaddr(3, 0) =/= 0.U && io.vecldin.bits.alignedType(2), "unit-stride 128 bit element is not aligned!")
633
634  // accept load flow if dcache ready (tlb is always ready)
635  // TODO: prefetch need writeback to loadQueueFlag
636  s0_out               := DontCare
637  s0_out.rsIdx         := s0_sel_src.rsIdx
638  s0_out.vaddr         := s0_sel_src.vaddr
639  s0_out.mask          := s0_sel_src.mask
640  s0_out.uop           := s0_sel_src.uop
641  s0_out.isFirstIssue  := s0_sel_src.isFirstIssue
642  s0_out.hasROBEntry   := s0_sel_src.has_rob_entry
643  s0_out.isPrefetch    := s0_sel_src.prf
644  s0_out.isHWPrefetch  := s0_hw_prf_select
645  s0_out.isFastReplay  := s0_sel_src.fast_rep
646  s0_out.isLoadReplay  := s0_sel_src.ld_rep
647  s0_out.isFastPath    := s0_sel_src.l2l_fwd
648  s0_out.mshrid        := s0_sel_src.mshrid
649  s0_out.isvec           := s0_sel_src.isvec
650  s0_out.is128bit        := s0_sel_src.is128bit
651  s0_out.uop_unit_stride_fof := s0_sel_src.uop_unit_stride_fof
652  // s0_out.rob_idx_valid   := s0_rob_idx_valid
653  // s0_out.inner_idx       := s0_inner_idx
654  // s0_out.rob_idx         := s0_rob_idx
655  s0_out.reg_offset      := s0_sel_src.reg_offset
656  // s0_out.offset          := s0_offset
657  s0_out.vecActive             := s0_sel_src.vecActive
658  s0_out.usSecondInv    := s0_sel_src.usSecondInv
659  s0_out.is_first_ele   := s0_sel_src.is_first_ele
660  s0_out.elemIdx        := s0_sel_src.elemIdx
661  s0_out.alignedType    := s0_sel_src.alignedType
662  s0_out.mbIndex        := s0_sel_src.mbIndex
663  // s0_out.flowPtr         := s0_sel_src.flowPtr
664  s0_out.uop.exceptionVec(loadAddrMisaligned) := !s0_addr_aligned && s0_sel_src.vecActive
665  s0_out.forward_tlDchannel := s0_super_ld_rep_select
666  when(io.tlb.req.valid && s0_sel_src.isFirstIssue) {
667    s0_out.uop.debugInfo.tlbFirstReqTime := GTimer()
668  }.otherwise{
669    s0_out.uop.debugInfo.tlbFirstReqTime := s0_sel_src.uop.debugInfo.tlbFirstReqTime
670  }
671  s0_out.schedIndex     := s0_sel_src.sched_idx
672
673  // load fast replay
674  io.fast_rep_in.ready := (s0_can_go && io.dcache.req.ready && s0_ld_fast_rep_ready)
675
676  // mmio
677  io.lsq.uncache.ready := s0_mmio_fire
678
679  // load flow source ready
680  // cache missed load has highest priority
681  // always accept cache missed load flow from load replay queue
682  io.replay.ready := (s0_can_go && io.dcache.req.ready && (s0_ld_rep_ready && !s0_rep_stall || s0_super_ld_rep_select))
683
684  // accept load flow from rs when:
685  // 1) there is no lsq-replayed load
686  // 2) there is no fast replayed load
687  // 3) there is no high confidence prefetch request
688  io.vecldin.ready := s0_can_go && io.dcache.req.ready && s0_vec_iss_ready
689  io.ldin.ready := s0_can_go && io.dcache.req.ready && s0_int_iss_ready
690
691  // for hw prefetch load flow feedback, to be added later
692  // io.prefetch_in.ready := s0_hw_prf_select
693
694  // dcache replacement extra info
695  // TODO: should prefetch load update replacement?
696  io.dcache.replacementUpdated := Mux(s0_ld_rep_select || s0_super_ld_rep_select, io.replay.bits.replacementUpdated, false.B)
697
698  // load wakeup
699  // TODO: vector load wakeup?
700  io.wakeup.valid := s0_fire && (s0_super_ld_rep_select || s0_ld_fast_rep_select || s0_ld_rep_select || s0_int_iss_select) || s0_mmio_fire
701  io.wakeup.bits := s0_out.uop
702
703  XSDebug(io.dcache.req.fire,
704    p"[DCACHE LOAD REQ] pc ${Hexadecimal(s0_sel_src.uop.pc)}, vaddr ${Hexadecimal(s0_sel_src.vaddr)}\n"
705  )
706  XSDebug(s0_valid,
707    p"S0: pc ${Hexadecimal(s0_out.uop.pc)}, lId ${Hexadecimal(s0_out.uop.lqIdx.asUInt)}, " +
708    p"vaddr ${Hexadecimal(s0_out.vaddr)}, mask ${Hexadecimal(s0_out.mask)}\n")
709
710  // Pipeline
711  // --------------------------------------------------------------------------------
712  // stage 1
713  // --------------------------------------------------------------------------------
714  // TLB resp (send paddr to dcache)
715  val s1_valid      = RegInit(false.B)
716  val s1_in         = Wire(new LqWriteBundle)
717  val s1_out        = Wire(new LqWriteBundle)
718  val s1_kill       = Wire(Bool())
719  val s1_can_go     = s2_ready
720  val s1_fire       = s1_valid && !s1_kill && s1_can_go
721  val s1_vecActive        = RegEnable(s0_out.vecActive, true.B, s0_fire)
722
723  s1_ready := !s1_valid || s1_kill || s2_ready
724  when (s0_fire) { s1_valid := true.B }
725  .elsewhen (s1_fire) { s1_valid := false.B }
726  .elsewhen (s1_kill) { s1_valid := false.B }
727  s1_in   := RegEnable(s0_out, s0_fire)
728
729  val s1_fast_rep_dly_kill = RegNext(io.fast_rep_in.bits.lateKill) && s1_in.isFastReplay
730  val s1_fast_rep_dly_err =  RegNext(io.fast_rep_in.bits.delayedLoadError) && s1_in.isFastReplay
731  val s1_l2l_fwd_dly_err  = RegNext(io.l2l_fwd_in.dly_ld_err) && s1_in.isFastPath
732  val s1_dly_err          = s1_fast_rep_dly_err || s1_l2l_fwd_dly_err
733  val s1_vaddr_hi         = Wire(UInt())
734  val s1_vaddr_lo         = Wire(UInt())
735  val s1_vaddr            = Wire(UInt())
736  val s1_paddr_dup_lsu    = Wire(UInt())
737  val s1_paddr_dup_dcache = Wire(UInt())
738  val s1_exception        = ExceptionNO.selectByFu(s1_out.uop.exceptionVec, LduCfg).asUInt.orR   // af & pf exception were modified below.
739  val s1_tlb_miss         = io.tlb.resp.bits.miss
740  val s1_prf              = s1_in.isPrefetch
741  val s1_hw_prf           = s1_in.isHWPrefetch
742  val s1_sw_prf           = s1_prf && !s1_hw_prf
743  val s1_tlb_memidx       = io.tlb.resp.bits.memidx
744
745  s1_vaddr_hi         := s1_in.vaddr(VAddrBits - 1, 6)
746  s1_vaddr_lo         := s1_in.vaddr(5, 0)
747  s1_vaddr            := Cat(s1_vaddr_hi, s1_vaddr_lo)
748  s1_paddr_dup_lsu    := io.tlb.resp.bits.paddr(0)
749  s1_paddr_dup_dcache := io.tlb.resp.bits.paddr(1)
750
751  when (s1_tlb_memidx.is_ld && io.tlb.resp.valid && !s1_tlb_miss && s1_tlb_memidx.idx === s1_in.uop.lqIdx.value) {
752    // printf("load idx = %d\n", s1_tlb_memidx.idx)
753    s1_out.uop.debugInfo.tlbRespTime := GTimer()
754  }
755
756  io.tlb.req_kill   := s1_kill || s1_dly_err
757  io.tlb.resp.ready := true.B
758
759  io.dcache.s1_paddr_dup_lsu    <> s1_paddr_dup_lsu
760  io.dcache.s1_paddr_dup_dcache <> s1_paddr_dup_dcache
761  io.dcache.s1_kill             := s1_kill || s1_dly_err || s1_tlb_miss || s1_exception
762
763  // store to load forwarding
764  io.sbuffer.valid := s1_valid && !(s1_exception || s1_tlb_miss || s1_kill || s1_dly_err || s1_prf)
765  io.sbuffer.vaddr := s1_vaddr
766  io.sbuffer.paddr := s1_paddr_dup_lsu
767  io.sbuffer.uop   := s1_in.uop
768  io.sbuffer.sqIdx := s1_in.uop.sqIdx
769  io.sbuffer.mask  := s1_in.mask
770  io.sbuffer.pc    := s1_in.uop.pc // FIXME: remove it
771
772  io.lsq.forward.valid     := s1_valid && !(s1_exception || s1_tlb_miss || s1_kill || s1_dly_err || s1_prf)
773  io.lsq.forward.vaddr     := s1_vaddr
774  io.lsq.forward.paddr     := s1_paddr_dup_lsu
775  io.lsq.forward.uop       := s1_in.uop
776  io.lsq.forward.sqIdx     := s1_in.uop.sqIdx
777  io.lsq.forward.sqIdxMask := 0.U
778  io.lsq.forward.mask      := s1_in.mask
779  io.lsq.forward.pc        := s1_in.uop.pc // FIXME: remove it
780
781  // st-ld violation query
782  val s1_nuke_paddr_match = VecInit((0 until StorePipelineWidth).map(w => {Mux(s1_in.isvec && s1_in.is128bit,
783    s1_paddr_dup_lsu(PAddrBits-1, 4) === io.stld_nuke_query(w).bits.paddr(PAddrBits-1, 4),
784    s1_paddr_dup_lsu(PAddrBits-1, 3) === io.stld_nuke_query(w).bits.paddr(PAddrBits-1, 3))}))
785  val s1_nuke = VecInit((0 until StorePipelineWidth).map(w => {
786                       io.stld_nuke_query(w).valid && // query valid
787                       isAfter(s1_in.uop.robIdx, io.stld_nuke_query(w).bits.robIdx) && // older store
788                       s1_nuke_paddr_match(w) && // paddr match
789                       (s1_in.mask & io.stld_nuke_query(w).bits.mask).orR // data mask contain
790                      })).asUInt.orR && !s1_tlb_miss
791
792  s1_out                   := s1_in
793  s1_out.vaddr             := s1_vaddr
794  s1_out.paddr             := s1_paddr_dup_lsu
795  s1_out.tlbMiss           := s1_tlb_miss
796  s1_out.ptwBack           := io.tlb.resp.bits.ptwBack
797  s1_out.rsIdx             := s1_in.rsIdx
798  s1_out.rep_info.debug    := s1_in.uop.debugInfo
799  s1_out.rep_info.nuke     := s1_nuke && !s1_sw_prf
800  s1_out.delayedLoadError  := s1_dly_err
801
802  when (!s1_dly_err) {
803    // current ori test will cause the case of ldest == 0, below will be modifeid in the future.
804    // af & pf exception were modified
805    s1_out.uop.exceptionVec(loadPageFault)   := io.tlb.resp.bits.excp(0).pf.ld && s1_vecActive && !s1_tlb_miss
806    s1_out.uop.exceptionVec(loadAccessFault) := io.tlb.resp.bits.excp(0).af.ld && s1_vecActive && !s1_tlb_miss
807  } .otherwise {
808    s1_out.uop.exceptionVec(loadPageFault)      := false.B
809    s1_out.uop.exceptionVec(loadAddrMisaligned) := false.B
810    s1_out.uop.exceptionVec(loadAccessFault)    := s1_dly_err && s1_vecActive
811  }
812
813  // pointer chasing
814  val s1_try_ptr_chasing       = RegNext(s0_do_try_ptr_chasing, false.B)
815  val s1_ptr_chasing_vaddr     = RegEnable(s0_ptr_chasing_vaddr, s0_do_try_ptr_chasing)
816  val s1_fu_op_type_not_ld     = WireInit(false.B)
817  val s1_not_fast_match        = WireInit(false.B)
818  val s1_addr_mismatch         = WireInit(false.B)
819  val s1_addr_misaligned       = WireInit(false.B)
820  val s1_fast_mismatch         = WireInit(false.B)
821  val s1_ptr_chasing_canceled  = WireInit(false.B)
822  val s1_cancel_ptr_chasing    = WireInit(false.B)
823
824  s1_kill := s1_fast_rep_dly_kill ||
825             s1_cancel_ptr_chasing ||
826             s1_in.uop.robIdx.needFlush(io.redirect) ||
827            (s1_in.uop.robIdx.needFlush(RegNext(io.redirect)) && !RegNext(s0_try_ptr_chasing)) ||
828             RegEnable(s0_kill, false.B, io.ldin.valid || io.vecldin.valid || io.replay.valid || io.l2l_fwd_in.valid || io.fast_rep_in.valid)
829
830  if (EnableLoadToLoadForward) {
831    // Sometimes, we need to cancel the load-load forwarding.
832    // These can be put at S0 if timing is bad at S1.
833    // Case 0: CACHE_SET(base + offset) != CACHE_SET(base) (lowest 6-bit addition has an overflow)
834    s1_addr_mismatch     := s1_ptr_chasing_vaddr(6) ||
835                             RegEnable(io.ld_fast_imm(11, 6).orR, s0_do_try_ptr_chasing)
836    // Case 1: the address is not 64-bit aligned or the fuOpType is not LD
837    s1_addr_misaligned := s1_ptr_chasing_vaddr(2, 0).orR
838    s1_fu_op_type_not_ld := io.ldin.bits.uop.fuOpType =/= LSUOpType.ld
839    // Case 2: this load-load uop is cancelled
840    s1_ptr_chasing_canceled := !io.ldin.valid
841    // Case 3: fast mismatch
842    s1_fast_mismatch := RegEnable(!io.ld_fast_match, s0_do_try_ptr_chasing)
843
844    when (s1_try_ptr_chasing) {
845      s1_cancel_ptr_chasing := s1_addr_mismatch ||
846                               s1_addr_misaligned ||
847                               s1_fu_op_type_not_ld ||
848                               s1_ptr_chasing_canceled ||
849                               s1_fast_mismatch
850
851      s1_in.uop           := io.ldin.bits.uop
852      s1_in.rsIdx         := io.ldin.bits.iqIdx
853      s1_in.isFirstIssue  := io.ldin.bits.isFirstIssue
854      s1_vaddr_lo         := s1_ptr_chasing_vaddr(5, 0)
855      s1_paddr_dup_lsu    := Cat(io.tlb.resp.bits.paddr(0)(PAddrBits - 1, 6), s1_vaddr_lo)
856      s1_paddr_dup_dcache := Cat(io.tlb.resp.bits.paddr(0)(PAddrBits - 1, 6), s1_vaddr_lo)
857
858      // 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)
859      s1_in.uop.debugInfo.tlbFirstReqTime := GTimer()
860      s1_in.uop.debugInfo.tlbRespTime     := GTimer()
861    }
862    when (!s1_cancel_ptr_chasing) {
863      s0_ptr_chasing_canceled := s1_try_ptr_chasing && !io.replay.fire && !io.fast_rep_in.fire
864      when (s1_try_ptr_chasing) {
865        io.ldin.ready := true.B
866      }
867    }
868  }
869
870  // pre-calcuate sqIdx mask in s0, then send it to lsq in s1 for forwarding
871  val s1_sqIdx_mask = RegNext(UIntToMask(s0_out.uop.sqIdx.value, StoreQueueSize))
872  // to enable load-load, sqIdxMask must be calculated based on ldin.uop
873  // If the timing here is not OK, load-load forwarding has to be disabled.
874  // Or we calculate sqIdxMask at RS??
875  io.lsq.forward.sqIdxMask := s1_sqIdx_mask
876  if (EnableLoadToLoadForward) {
877    when (s1_try_ptr_chasing) {
878      io.lsq.forward.sqIdxMask := UIntToMask(io.ldin.bits.uop.sqIdx.value, StoreQueueSize)
879    }
880  }
881
882  io.forward_mshr.valid  := s1_valid && s1_out.forward_tlDchannel
883  io.forward_mshr.mshrid := s1_out.mshrid
884  io.forward_mshr.paddr  := s1_out.paddr
885
886  XSDebug(s1_valid,
887    p"S1: pc ${Hexadecimal(s1_out.uop.pc)}, lId ${Hexadecimal(s1_out.uop.lqIdx.asUInt)}, tlb_miss ${io.tlb.resp.bits.miss}, " +
888    p"paddr ${Hexadecimal(s1_out.paddr)}, mmio ${s1_out.mmio}\n")
889
890  // Pipeline
891  // --------------------------------------------------------------------------------
892  // stage 2
893  // --------------------------------------------------------------------------------
894  // s2: DCache resp
895  val s2_valid  = RegInit(false.B)
896  val s2_in     = Wire(new LqWriteBundle)
897  val s2_out    = Wire(new LqWriteBundle)
898  val s2_kill   = Wire(Bool())
899  val s2_can_go = s3_ready
900  val s2_fire   = s2_valid && !s2_kill && s2_can_go
901  val s2_vecActive = RegEnable(s1_out.vecActive, true.B, s1_fire)
902  val s2_isvec  = RegEnable(s1_out.isvec, false.B, s1_fire)
903
904  s2_kill := s2_in.uop.robIdx.needFlush(io.redirect)
905  s2_ready := !s2_valid || s2_kill || s3_ready
906  when (s1_fire) { s2_valid := true.B }
907  .elsewhen (s2_fire) { s2_valid := false.B }
908  .elsewhen (s2_kill) { s2_valid := false.B }
909  s2_in := RegEnable(s1_out, s1_fire)
910
911  val s2_pmp = WireInit(io.pmp)
912
913  val s2_prf    = s2_in.isPrefetch
914  val s2_hw_prf = s2_in.isHWPrefetch
915
916  // exception that may cause load addr to be invalid / illegal
917  // if such exception happen, that inst and its exception info
918  // will be force writebacked to rob
919  val s2_exception_vec = WireInit(s2_in.uop.exceptionVec)
920  when (!s2_in.delayedLoadError) {
921    s2_exception_vec(loadAccessFault) := (s2_in.uop.exceptionVec(loadAccessFault) || s2_pmp.ld ||
922                                       (io.dcache.resp.bits.tag_error && RegNext(io.csrCtrl.cache_error_enable))) && s2_vecActive
923  }
924
925  // soft prefetch will not trigger any exception (but ecc error interrupt may
926  // be triggered)
927  when (!s2_in.delayedLoadError && (s2_prf || s2_in.tlbMiss)) {
928    s2_exception_vec := 0.U.asTypeOf(s2_exception_vec.cloneType)
929  }
930  val s2_exception = ExceptionNO.selectByFu(s2_exception_vec, LduCfg).asUInt.orR && s2_vecActive
931
932  val (s2_fwd_frm_d_chan, s2_fwd_data_frm_d_chan) = io.tl_d_channel.forward(s1_valid && s1_out.forward_tlDchannel, s1_out.mshrid, s1_out.paddr)
933  val (s2_fwd_data_valid, s2_fwd_frm_mshr, s2_fwd_data_frm_mshr) = io.forward_mshr.forward()
934  val s2_fwd_frm_d_chan_or_mshr = s2_fwd_data_valid && (s2_fwd_frm_d_chan || s2_fwd_frm_mshr)
935
936  // writeback access fault caused by ecc error / bus error
937  // * ecc data error is slow to generate, so we will not use it until load stage 3
938  // * in load stage 3, an extra signal io.load_error will be used to
939  val s2_actually_mmio = s2_pmp.mmio
940  val s2_mmio          = !s2_prf &&
941                          s2_actually_mmio &&
942                         !s2_exception &&
943                         !s2_in.tlbMiss
944
945  val s2_full_fwd      = Wire(Bool())
946  val s2_mem_amb       = s2_in.uop.storeSetHit &&
947                         io.lsq.forward.addrInvalid
948
949  val s2_tlb_miss      = s2_in.tlbMiss
950  val s2_fwd_fail      = io.lsq.forward.dataInvalid
951  val s2_dcache_miss   = io.dcache.resp.bits.miss &&
952                         !s2_fwd_frm_d_chan_or_mshr &&
953                         !s2_full_fwd
954
955  val s2_mq_nack       = io.dcache.s2_mq_nack &&
956                         !s2_fwd_frm_d_chan_or_mshr &&
957                         !s2_full_fwd
958
959  val s2_bank_conflict = io.dcache.s2_bank_conflict &&
960                         !s2_fwd_frm_d_chan_or_mshr &&
961                         !s2_full_fwd
962
963  val s2_wpu_pred_fail = io.dcache.s2_wpu_pred_fail &&
964                        !s2_fwd_frm_d_chan_or_mshr &&
965                        !s2_full_fwd
966
967  val s2_rar_nack      = io.lsq.ldld_nuke_query.req.valid &&
968                         !io.lsq.ldld_nuke_query.req.ready
969
970  val s2_raw_nack      = io.lsq.stld_nuke_query.req.valid &&
971                         !io.lsq.stld_nuke_query.req.ready
972  // st-ld violation query
973  //  NeedFastRecovery Valid when
974  //  1. Fast recovery query request Valid.
975  //  2. Load instruction is younger than requestors(store instructions).
976  //  3. Physical address match.
977  //  4. Data contains.
978  val s2_nuke_paddr_match = VecInit((0 until StorePipelineWidth).map(w => {Mux(s2_in.isvec && s2_in.is128bit,
979    s2_in.paddr(PAddrBits-1, 4) === io.stld_nuke_query(w).bits.paddr(PAddrBits-1, 4),
980    s2_in.paddr(PAddrBits-1, 3) === io.stld_nuke_query(w).bits.paddr(PAddrBits-1, 3))}))
981  val s2_nuke          = VecInit((0 until StorePipelineWidth).map(w => {
982                          io.stld_nuke_query(w).valid && // query valid
983                          isAfter(s2_in.uop.robIdx, io.stld_nuke_query(w).bits.robIdx) && // older store
984                          s2_nuke_paddr_match(w) && // paddr match
985                          (s2_in.mask & io.stld_nuke_query(w).bits.mask).orR // data mask contain
986                        })).asUInt.orR && !s2_tlb_miss || s2_in.rep_info.nuke
987
988  val s2_cache_handled   = io.dcache.resp.bits.handled
989  val s2_cache_tag_error = RegNext(io.csrCtrl.cache_error_enable) &&
990                           io.dcache.resp.bits.tag_error
991
992  val s2_troublem        = !s2_exception &&
993                           !s2_mmio &&
994                           !s2_prf &&
995                           !s2_in.delayedLoadError
996
997  io.dcache.resp.ready  := true.B
998  val s2_dcache_should_resp = !(s2_in.tlbMiss || s2_exception || s2_in.delayedLoadError || s2_mmio || s2_prf)
999  assert(!(s2_valid && (s2_dcache_should_resp && !io.dcache.resp.valid)), "DCache response got lost")
1000
1001  // fast replay require
1002  val s2_dcache_fast_rep = (s2_mq_nack || !s2_dcache_miss && (s2_bank_conflict || s2_wpu_pred_fail))
1003  val s2_nuke_fast_rep   = !s2_mq_nack &&
1004                           !s2_dcache_miss &&
1005                           !s2_bank_conflict &&
1006                           !s2_wpu_pred_fail &&
1007                           !s2_rar_nack &&
1008                           !s2_raw_nack &&
1009                           s2_nuke
1010
1011  val s2_fast_rep = !s2_mem_amb &&
1012                    !s2_tlb_miss &&
1013                    !s2_fwd_fail &&
1014                    (s2_dcache_fast_rep || s2_nuke_fast_rep) &&
1015                    s2_troublem
1016
1017  // need allocate new entry
1018  val s2_can_query = !s2_mem_amb &&
1019                     !s2_tlb_miss &&
1020                     !s2_fwd_fail &&
1021                     s2_troublem
1022
1023  val s2_data_fwded = s2_dcache_miss && (s2_full_fwd || s2_cache_tag_error)
1024
1025  // ld-ld violation require
1026  io.lsq.ldld_nuke_query.req.valid           := s2_valid && s2_can_query
1027  io.lsq.ldld_nuke_query.req.bits.uop        := s2_in.uop
1028  io.lsq.ldld_nuke_query.req.bits.mask       := s2_in.mask
1029  io.lsq.ldld_nuke_query.req.bits.paddr      := s2_in.paddr
1030  io.lsq.ldld_nuke_query.req.bits.data_valid := Mux(s2_full_fwd || s2_fwd_data_valid, true.B, !s2_dcache_miss)
1031
1032  // st-ld violation require
1033  io.lsq.stld_nuke_query.req.valid           := s2_valid && s2_can_query
1034  io.lsq.stld_nuke_query.req.bits.uop        := s2_in.uop
1035  io.lsq.stld_nuke_query.req.bits.mask       := s2_in.mask
1036  io.lsq.stld_nuke_query.req.bits.paddr      := s2_in.paddr
1037  io.lsq.stld_nuke_query.req.bits.data_valid := Mux(s2_full_fwd || s2_fwd_data_valid, true.B, !s2_dcache_miss)
1038
1039  // merge forward result
1040  // lsq has higher priority than sbuffer
1041  val s2_fwd_mask = Wire(Vec((VLEN/8), Bool()))
1042  val s2_fwd_data = Wire(Vec((VLEN/8), UInt(8.W)))
1043  s2_full_fwd := ((~s2_fwd_mask.asUInt).asUInt & s2_in.mask) === 0.U && !io.lsq.forward.dataInvalid
1044  // generate XLEN/8 Muxs
1045  for (i <- 0 until VLEN / 8) {
1046    s2_fwd_mask(i) := io.lsq.forward.forwardMask(i) || io.sbuffer.forwardMask(i)
1047    s2_fwd_data(i) := Mux(io.lsq.forward.forwardMask(i), io.lsq.forward.forwardData(i), io.sbuffer.forwardData(i))
1048  }
1049
1050  XSDebug(s2_fire, "[FWD LOAD RESP] pc %x fwd %x(%b) + %x(%b)\n",
1051    s2_in.uop.pc,
1052    io.lsq.forward.forwardData.asUInt, io.lsq.forward.forwardMask.asUInt,
1053    s2_in.forwardData.asUInt, s2_in.forwardMask.asUInt
1054  )
1055
1056  //
1057  s2_out                     := s2_in
1058  s2_out.data                := 0.U // data will be generated in load s3
1059  s2_out.uop.fpWen           := s2_in.uop.fpWen && !s2_exception
1060  s2_out.mmio                := s2_mmio
1061  s2_out.uop.flushPipe       := false.B
1062  s2_out.uop.exceptionVec    := s2_exception_vec
1063  s2_out.forwardMask         := s2_fwd_mask
1064  s2_out.forwardData         := s2_fwd_data
1065  s2_out.handledByMSHR       := s2_cache_handled
1066  s2_out.miss                := s2_dcache_miss && s2_troublem
1067  s2_out.feedbacked          := io.feedback_fast.valid
1068
1069  // Generate replay signal caused by:
1070  // * st-ld violation check
1071  // * tlb miss
1072  // * dcache replay
1073  // * forward data invalid
1074  // * dcache miss
1075  s2_out.rep_info.mem_amb         := s2_mem_amb && s2_troublem
1076  s2_out.rep_info.tlb_miss        := s2_tlb_miss && s2_troublem
1077  s2_out.rep_info.fwd_fail        := s2_fwd_fail && s2_troublem
1078  s2_out.rep_info.dcache_rep      := s2_mq_nack && s2_troublem
1079  s2_out.rep_info.dcache_miss     := s2_dcache_miss && s2_troublem
1080  s2_out.rep_info.bank_conflict   := s2_bank_conflict && s2_troublem
1081  s2_out.rep_info.wpu_fail        := s2_wpu_pred_fail && s2_troublem
1082  s2_out.rep_info.rar_nack        := s2_rar_nack && s2_troublem
1083  s2_out.rep_info.raw_nack        := s2_raw_nack && s2_troublem
1084  s2_out.rep_info.nuke            := s2_nuke && s2_troublem
1085  s2_out.rep_info.full_fwd        := s2_data_fwded
1086  s2_out.rep_info.data_inv_sq_idx := io.lsq.forward.dataInvalidSqIdx
1087  s2_out.rep_info.addr_inv_sq_idx := io.lsq.forward.addrInvalidSqIdx
1088  s2_out.rep_info.rep_carry       := io.dcache.resp.bits.replayCarry
1089  s2_out.rep_info.mshr_id         := io.dcache.resp.bits.mshr_id
1090  s2_out.rep_info.last_beat       := s2_in.paddr(log2Up(refillBytes))
1091  s2_out.rep_info.debug           := s2_in.uop.debugInfo
1092  s2_out.rep_info.tlb_id          := io.tlb_hint.id
1093  s2_out.rep_info.tlb_full        := io.tlb_hint.full
1094
1095  // if forward fail, replay this inst from fetch
1096  val debug_fwd_fail_rep = s2_fwd_fail && !s2_troublem && !s2_in.tlbMiss
1097  // if ld-ld violation is detected, replay from this inst from fetch
1098  val debug_ldld_nuke_rep = false.B // s2_ldld_violation && !s2_mmio && !s2_is_prefetch && !s2_in.tlbMiss
1099
1100  // to be removed
1101  io.feedback_fast.valid                 := false.B
1102  io.feedback_fast.bits.hit              := false.B
1103  io.feedback_fast.bits.flushState       := s2_in.ptwBack
1104  io.feedback_fast.bits.robIdx           := s2_in.uop.robIdx
1105  io.feedback_fast.bits.sourceType       := RSFeedbackType.lrqFull
1106  io.feedback_fast.bits.dataInvalidSqIdx := DontCare
1107
1108  io.ldCancel.ld1Cancel := false.B
1109
1110  // fast wakeup
1111  io.fast_uop.valid := RegNext(
1112    !io.dcache.s1_disable_fast_wakeup &&
1113    s1_valid &&
1114    !s1_kill &&
1115    !io.tlb.resp.bits.miss &&
1116    !io.lsq.forward.dataInvalidFast
1117  ) && (s2_valid && !s2_out.rep_info.need_rep && !s2_mmio) && !s2_isvec
1118  io.fast_uop.bits := RegNext(s1_out.uop)
1119
1120  //
1121  io.s2_ptr_chasing                    := RegEnable(s1_try_ptr_chasing && !s1_cancel_ptr_chasing, false.B, s1_fire)
1122
1123  // RegNext prefetch train for better timing
1124  // ** Now, prefetch train is valid at load s3 **
1125  io.prefetch_train.valid              := RegNext(s2_valid && !s2_actually_mmio && !s2_in.tlbMiss)
1126  io.prefetch_train.bits.fromLsPipelineBundle(s2_in, latch = true)
1127  io.prefetch_train.bits.miss          := RegNext(io.dcache.resp.bits.miss) // TODO: use trace with bank conflict?
1128  io.prefetch_train.bits.meta_prefetch := RegNext(io.dcache.resp.bits.meta_prefetch)
1129  io.prefetch_train.bits.meta_access   := RegNext(io.dcache.resp.bits.meta_access)
1130
1131  io.prefetch_train_l1.valid              := RegNext(s2_valid && !s2_actually_mmio)
1132  io.prefetch_train_l1.bits.fromLsPipelineBundle(s2_in, latch = true)
1133  io.prefetch_train_l1.bits.miss          := RegNext(io.dcache.resp.bits.miss)
1134  io.prefetch_train_l1.bits.meta_prefetch := RegNext(io.dcache.resp.bits.meta_prefetch)
1135  io.prefetch_train_l1.bits.meta_access   := RegNext(io.dcache.resp.bits.meta_access)
1136  if (env.FPGAPlatform){
1137    io.dcache.s0_pc := DontCare
1138    io.dcache.s1_pc := DontCare
1139    io.dcache.s2_pc := DontCare
1140  }else{
1141    io.dcache.s0_pc := s0_out.uop.pc
1142    io.dcache.s1_pc := s1_out.uop.pc
1143    io.dcache.s2_pc := s2_out.uop.pc
1144  }
1145  io.dcache.s2_kill := s2_pmp.ld || s2_actually_mmio || s2_kill
1146
1147  val s1_ld_left_fire = s1_valid && !s1_kill && s2_ready
1148  val s2_ld_valid_dup = RegInit(0.U(6.W))
1149  s2_ld_valid_dup := 0x0.U(6.W)
1150  when (s1_ld_left_fire && !s1_out.isHWPrefetch) { s2_ld_valid_dup := 0x3f.U(6.W) }
1151  when (s1_kill || s1_out.isHWPrefetch) { s2_ld_valid_dup := 0x0.U(6.W) }
1152  assert(RegNext((s2_valid === s2_ld_valid_dup(0)) || RegNext(s1_out.isHWPrefetch)))
1153
1154  // Pipeline
1155  // --------------------------------------------------------------------------------
1156  // stage 3
1157  // --------------------------------------------------------------------------------
1158  // writeback and update load queue
1159  val s3_valid        = RegNext(s2_valid && !s2_out.isHWPrefetch && !s2_out.uop.robIdx.needFlush(io.redirect))
1160  val s3_in           = RegEnable(s2_out, s2_fire)
1161  val s3_out          = Wire(Valid(new MemExuOutput))
1162  val s3_dcache_rep   = RegEnable(s2_dcache_fast_rep && s2_troublem, false.B, s2_fire)
1163  val s3_ld_valid_dup = RegEnable(s2_ld_valid_dup, s2_fire)
1164  val s3_fast_rep     = Wire(Bool())
1165  val s3_troublem     = RegNext(s2_troublem)
1166  val s3_kill         = s3_in.uop.robIdx.needFlush(io.redirect)
1167  val s3_vecout       = Wire(new OnlyVecExuOutput)
1168  val s3_vecActive    = RegEnable(s2_out.vecActive, true.B, s2_fire)
1169  val s3_isvec        = RegEnable(s2_out.isvec, false.B, s2_fire)
1170  val s3_vec_alignedType = RegEnable(s2_out.alignedType, s2_fire)
1171  val s3_vec_mBIndex     = RegEnable(s2_out.mbIndex, s2_fire)
1172  val s3_mmio         = Wire(chiselTypeOf(io.lsq.uncache))
1173  dontTouch(s2_out)
1174  dontTouch(s1_out)
1175  // TODO: Fix vector load merge buffer nack
1176  val s3_vec_mb_nack  = Wire(Bool())
1177  s3_vec_mb_nack     := false.B
1178  XSError(s3_valid && s3_vec_mb_nack, "Merge buffer should always accept vector loads!")
1179
1180  s3_ready := !s3_valid || s3_kill || io.ldout.ready
1181  s3_mmio.valid := RegNextN(io.lsq.uncache.valid, 3, Some(false.B))
1182  s3_mmio.ready := RegNextN(io.lsq.uncache.ready, 3, Some(false.B))
1183  s3_mmio.bits  := RegNextN(io.lsq.uncache.bits, 3)
1184
1185  // forwrad last beat
1186  val (s3_fwd_frm_d_chan, s3_fwd_data_frm_d_chan) = io.tl_d_channel.forward(s2_valid && s2_out.forward_tlDchannel, s2_out.mshrid, s2_out.paddr)
1187  val s3_fwd_data_valid = RegEnable(s2_fwd_data_valid, false.B, s2_valid)
1188  val s3_fwd_frm_d_chan_valid = (s3_fwd_frm_d_chan && s3_fwd_data_valid && s3_in.handledByMSHR)
1189  val s3_fast_rep_canceled = io.replay.valid && io.replay.bits.forward_tlDchannel || !io.dcache.req.ready
1190
1191  // s3 load fast replay
1192  io.fast_rep_out.valid := s3_valid && s3_fast_rep && !s3_in.uop.robIdx.needFlush(io.redirect)
1193  io.fast_rep_out.bits := s3_in
1194
1195  io.lsq.ldin.valid := s3_valid && (!s3_fast_rep || s3_fast_rep_canceled) && !s3_in.feedbacked
1196  // TODO: check this --by hx
1197  // io.lsq.ldin.valid := s3_valid && (!s3_fast_rep || !io.fast_rep_out.ready) && !s3_in.feedbacked && !s3_in.lateKill
1198  io.lsq.ldin.bits := s3_in
1199  io.lsq.ldin.bits.miss := s3_in.miss && !s3_fwd_frm_d_chan_valid
1200
1201  /* <------- DANGEROUS: Don't change sequence here ! -------> */
1202  io.lsq.ldin.bits.data_wen_dup := s3_ld_valid_dup.asBools
1203  io.lsq.ldin.bits.replacementUpdated := io.dcache.resp.bits.replacementUpdated
1204  io.lsq.ldin.bits.missDbUpdated := RegNext(s2_fire && s2_in.hasROBEntry && !s2_in.tlbMiss && !s2_in.missDbUpdated)
1205
1206  val s3_dly_ld_err =
1207    if (EnableAccurateLoadError) {
1208      io.dcache.resp.bits.error_delayed && RegNext(io.csrCtrl.cache_error_enable) && s3_troublem
1209    } else {
1210      WireInit(false.B)
1211    }
1212  io.s3_dly_ld_err := false.B // s3_dly_ld_err && s3_valid
1213  io.lsq.ldin.bits.dcacheRequireReplay  := s3_dcache_rep
1214  io.fast_rep_out.bits.delayedLoadError := s3_dly_ld_err
1215
1216  val s3_vp_match_fail = RegNext(io.lsq.forward.matchInvalid || io.sbuffer.matchInvalid) && s3_troublem
1217  val s3_rep_frm_fetch = s3_vp_match_fail
1218  val s3_ldld_rep_inst =
1219      io.lsq.ldld_nuke_query.resp.valid &&
1220      io.lsq.ldld_nuke_query.resp.bits.rep_frm_fetch &&
1221      RegNext(io.csrCtrl.ldld_vio_check_enable)
1222  val s3_flushPipe = s3_ldld_rep_inst
1223
1224  val s3_rep_info = WireInit(s3_in.rep_info)
1225  s3_rep_info.dcache_miss   := s3_in.rep_info.dcache_miss && !s3_fwd_frm_d_chan_valid
1226  val s3_sel_rep_cause = PriorityEncoderOH(s3_rep_info.cause.asUInt)
1227
1228  val s3_exception = ExceptionNO.selectByFu(s3_in.uop.exceptionVec, LduCfg).asUInt.orR && s3_vecActive
1229  when (s3_exception || s3_dly_ld_err || s3_rep_frm_fetch) {
1230    io.lsq.ldin.bits.rep_info.cause := 0.U.asTypeOf(s3_rep_info.cause.cloneType)
1231  } .otherwise {
1232    io.lsq.ldin.bits.rep_info.cause := VecInit(s3_sel_rep_cause.asBools)
1233  }
1234
1235  // Int load, if hit, will be writebacked at s3
1236  s3_out.valid                := s3_valid && !io.lsq.ldin.bits.rep_info.need_rep && !s3_in.mmio
1237  s3_out.bits.uop             := s3_in.uop
1238  s3_out.bits.uop.exceptionVec(loadAccessFault) := (s3_dly_ld_err || s3_in.uop.exceptionVec(loadAccessFault)) && s3_vecActive
1239  s3_out.bits.uop.flushPipe   := false.B
1240  s3_out.bits.uop.replayInst  := s3_rep_frm_fetch || s3_flushPipe
1241  s3_out.bits.data            := s3_in.data
1242  s3_out.bits.debug.isMMIO    := s3_in.mmio
1243  s3_out.bits.debug.isPerfCnt := false.B
1244  s3_out.bits.debug.paddr     := s3_in.paddr
1245  s3_out.bits.debug.vaddr     := s3_in.vaddr
1246
1247  // Vector load, writeback to merge buffer
1248  // TODO: Add assertion in merge buffer, merge buffer must accept vec load writeback
1249  s3_vecout.isvec             := s3_isvec
1250  s3_vecout.vecdata           := 0.U // Data will be assigned later
1251  s3_vecout.mask              := s3_in.mask
1252  // s3_vecout.rob_idx_valid     := s3_in.rob_idx_valid
1253  // s3_vecout.inner_idx         := s3_in.inner_idx
1254  // s3_vecout.rob_idx           := s3_in.rob_idx
1255  // s3_vecout.offset            := s3_in.offset
1256  s3_vecout.reg_offset        := s3_in.reg_offset
1257  s3_vecout.vecActive         := s3_vecActive
1258  s3_vecout.is_first_ele      := s3_in.is_first_ele
1259  // s3_vecout.uopQueuePtr       := DontCare // uopQueuePtr is already saved in flow queue
1260  // s3_vecout.flowPtr           := s3_in.flowPtr
1261  s3_vecout.elemIdx           := s3_in.elemIdx // elemIdx is already saved in flow queue // TODO:
1262  s3_vecout.elemIdxInsideVd   := DontCare
1263  val s3_usSecondInv          = s3_in.usSecondInv
1264
1265  io.rollback.valid := s3_valid && (s3_rep_frm_fetch || s3_flushPipe) && !s3_exception
1266  io.rollback.bits             := DontCare
1267  io.rollback.bits.isRVC       := s3_out.bits.uop.preDecodeInfo.isRVC
1268  io.rollback.bits.robIdx      := s3_out.bits.uop.robIdx
1269  io.rollback.bits.ftqIdx      := s3_out.bits.uop.ftqPtr
1270  io.rollback.bits.ftqOffset   := s3_out.bits.uop.ftqOffset
1271  io.rollback.bits.level       := Mux(s3_rep_frm_fetch, RedirectLevel.flush, RedirectLevel.flushAfter)
1272  io.rollback.bits.cfiUpdate.target := s3_out.bits.uop.pc
1273  io.rollback.bits.debug_runahead_checkpoint_id := s3_out.bits.uop.debugInfo.runahead_checkpoint_id
1274  /* <------- DANGEROUS: Don't change sequence here ! -------> */
1275
1276  io.lsq.ldin.bits.uop := s3_out.bits.uop
1277
1278  val s3_revoke = s3_exception || io.lsq.ldin.bits.rep_info.need_rep
1279  io.lsq.ldld_nuke_query.revoke := s3_revoke
1280  io.lsq.stld_nuke_query.revoke := s3_revoke
1281
1282  // feedback slow
1283  s3_fast_rep := RegNext(s2_fast_rep)
1284
1285  val s3_fb_no_waiting = !s3_in.isLoadReplay &&
1286                        (!(s3_fast_rep && !s3_fast_rep_canceled)) &&
1287                        !s3_in.feedbacked
1288
1289  // feedback: scalar load will send feedback to RS
1290  //           vector load will send signal to VL Merge Buffer, then send feedback at granularity of uops
1291  io.feedback_slow.valid                 := s3_valid && s3_fb_no_waiting && !s3_isvec
1292  io.feedback_slow.bits.hit              := !s3_rep_info.need_rep || io.lsq.ldin.ready
1293  io.feedback_slow.bits.flushState       := s3_in.ptwBack
1294  io.feedback_slow.bits.robIdx           := s3_in.uop.robIdx
1295  io.feedback_slow.bits.sourceType       := RSFeedbackType.lrqFull
1296  io.feedback_slow.bits.dataInvalidSqIdx := DontCare
1297
1298  io.ldCancel.ld2Cancel := s3_valid && (
1299    io.lsq.ldin.bits.rep_info.need_rep ||                       // exe fail or
1300    s3_in.mmio                                                  // is mmio
1301  )
1302
1303  val s3_ld_wb_meta = Mux(s3_valid, s3_out.bits, s3_mmio.bits)
1304
1305  // data from load queue refill
1306  val s3_ld_raw_data_frm_uncache = RegNextN(io.lsq.ld_raw_data, 3)
1307  val s3_merged_data_frm_uncache = s3_ld_raw_data_frm_uncache.mergedData()
1308  val s3_picked_data_frm_uncache = LookupTree(s3_ld_raw_data_frm_uncache.addrOffset, List(
1309    "b000".U -> s3_merged_data_frm_uncache(63,  0),
1310    "b001".U -> s3_merged_data_frm_uncache(63,  8),
1311    "b010".U -> s3_merged_data_frm_uncache(63, 16),
1312    "b011".U -> s3_merged_data_frm_uncache(63, 24),
1313    "b100".U -> s3_merged_data_frm_uncache(63, 32),
1314    "b101".U -> s3_merged_data_frm_uncache(63, 40),
1315    "b110".U -> s3_merged_data_frm_uncache(63, 48),
1316    "b111".U -> s3_merged_data_frm_uncache(63, 56)
1317  ))
1318  val s3_ld_data_frm_uncache = rdataHelper(s3_ld_raw_data_frm_uncache.uop, s3_picked_data_frm_uncache)
1319
1320  // data from dcache hit
1321  val s3_ld_raw_data_frm_cache = Wire(new LoadDataFromDcacheBundle)
1322  s3_ld_raw_data_frm_cache.respDcacheData       := io.dcache.resp.bits.data_delayed
1323  s3_ld_raw_data_frm_cache.forwardMask          := RegEnable(s2_fwd_mask, s2_valid)
1324  s3_ld_raw_data_frm_cache.forwardData          := RegEnable(s2_fwd_data, s2_valid)
1325  s3_ld_raw_data_frm_cache.uop                  := RegEnable(s2_out.uop, s2_valid)
1326  s3_ld_raw_data_frm_cache.addrOffset           := RegEnable(s2_out.paddr(3, 0), s2_valid)
1327  s3_ld_raw_data_frm_cache.forward_D            := RegEnable(s2_fwd_frm_d_chan, false.B, s2_valid) || s3_fwd_frm_d_chan_valid
1328  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))
1329  s3_ld_raw_data_frm_cache.forward_mshr         := RegEnable(s2_fwd_frm_mshr, false.B, s2_valid)
1330  s3_ld_raw_data_frm_cache.forwardData_mshr     := RegEnable(s2_fwd_data_frm_mshr, s2_valid)
1331  s3_ld_raw_data_frm_cache.forward_result_valid := RegEnable(s2_fwd_data_valid, false.B, s2_valid)
1332
1333  val s3_merged_data_frm_cache = s3_ld_raw_data_frm_cache.mergedData()
1334  val s3_picked_data_frm_cache = LookupTree(s3_ld_raw_data_frm_cache.addrOffset, List(
1335    "b0000".U -> s3_merged_data_frm_cache(63,    0),
1336    "b0001".U -> s3_merged_data_frm_cache(63,    8),
1337    "b0010".U -> s3_merged_data_frm_cache(63,   16),
1338    "b0011".U -> s3_merged_data_frm_cache(63,   24),
1339    "b0100".U -> s3_merged_data_frm_cache(63,   32),
1340    "b0101".U -> s3_merged_data_frm_cache(63,   40),
1341    "b0110".U -> s3_merged_data_frm_cache(63,   48),
1342    "b0111".U -> s3_merged_data_frm_cache(63,   56),
1343    "b1000".U -> s3_merged_data_frm_cache(127,  64),
1344    "b1001".U -> s3_merged_data_frm_cache(127,  72),
1345    "b1010".U -> s3_merged_data_frm_cache(127,  80),
1346    "b1011".U -> s3_merged_data_frm_cache(127,  88),
1347    "b1100".U -> s3_merged_data_frm_cache(127,  96),
1348    "b1101".U -> s3_merged_data_frm_cache(127, 104),
1349    "b1110".U -> s3_merged_data_frm_cache(127, 112),
1350    "b1111".U -> s3_merged_data_frm_cache(127, 120)
1351  ))
1352  val s3_ld_data_frm_cache = rdataHelper(s3_ld_raw_data_frm_cache.uop, s3_picked_data_frm_cache)
1353
1354  // FIXME: add 1 cycle delay ?
1355  // io.lsq.uncache.ready := !s3_valid
1356  io.ldout.bits        := s3_ld_wb_meta
1357  io.ldout.bits.data   := Mux(s3_valid, s3_ld_data_frm_cache, s3_ld_data_frm_uncache)
1358  io.ldout.valid       := (s3_out.valid || (s3_mmio.valid && !s3_valid)) && !s3_vecout.isvec
1359
1360  // TODO: check this --hx
1361  // io.ldout.valid       := s3_out.valid && !s3_out.bits.uop.robIdx.needFlush(io.redirect) && !s3_vecout.isvec ||
1362  //   io.lsq.uncache.valid && !io.lsq.uncache.bits.uop.robIdx.needFlush(io.redirect) && !s3_out.valid && !io.lsq.uncache.bits.isVls
1363  //  io.ldout.bits.data   := Mux(s3_out.valid, s3_ld_data_frm_cache, s3_ld_data_frm_uncache)
1364  //  io.ldout.valid       := s3_out.valid && !s3_out.bits.uop.robIdx.needFlush(io.redirect) ||
1365  //                         s3_mmio.valid && !s3_mmio.bits.uop.robIdx.needFlush(io.redirect) && !s3_out.valid
1366
1367  // s3 load fast replay
1368  io.fast_rep_out.valid := s3_valid && s3_fast_rep
1369  io.fast_rep_out.bits := s3_in
1370  io.fast_rep_out.bits.lateKill := s3_rep_frm_fetch
1371
1372  val vecFeedback = s3_valid && s3_fb_no_waiting && s3_rep_info.need_rep && !io.lsq.ldin.ready && s3_isvec
1373
1374  // vector output
1375  io.vecldout.bits.alignedType.get := s3_vec_alignedType
1376  // vec feedback
1377  io.vecldout.bits.vecFeedback := vecFeedback
1378  // TODO: VLSU, uncache data logic
1379  val vecdata = rdataVecHelper(s3_vec_alignedType(1,0), s3_picked_data_frm_cache)
1380  io.vecldout.bits.vecdata.get := Mux(s3_in.is128bit, s3_merged_data_frm_cache, vecdata)
1381  // io.vecldout.bits.hit :=
1382  io.vecldout.bits.isvec := s3_vecout.isvec
1383  io.vecldout.bits.elemIdx.get := s3_vecout.elemIdx
1384  io.vecldout.bits.elemIdxInsideVd.get := s3_vecout.elemIdxInsideVd
1385  io.vecldout.bits.mask.get := s3_vecout.mask
1386  io.vecldout.bits.reg_offset.get := s3_vecout.reg_offset
1387  io.vecldout.bits.usSecondInv := s3_usSecondInv
1388  io.vecldout.bits.mBIndex := s3_vec_mBIndex
1389  io.vecldout.bits.hit := !s3_rep_info.need_rep || io.lsq.ldin.ready
1390  io.vecldout.bits.sourceType := RSFeedbackType.lrqFull
1391  io.vecldout.bits.flushState := DontCare
1392  io.vecldout.bits.exceptionVec := s3_out.bits.uop.exceptionVec
1393  io.vecldout.bits.mmio := DontCare
1394
1395  io.vecldout.valid := s3_out.valid && !s3_out.bits.uop.robIdx.needFlush(io.redirect) && s3_vecout.isvec ||
1396  // TODO: check this, why !io.lsq.uncache.bits.isVls before?
1397    io.lsq.uncache.valid && !io.lsq.uncache.bits.uop.robIdx.needFlush(io.redirect) && !s3_out.valid && io.lsq.uncache.bits.isVls
1398    //io.lsq.uncache.valid && !io.lsq.uncache.bits.uop.robIdx.needFlush(io.redirect) && !s3_out.valid && !io.lsq.uncache.bits.isVls
1399
1400  // fast load to load forward
1401  if (EnableLoadToLoadForward) {
1402    io.l2l_fwd_out.valid      := s3_valid && !s3_in.mmio && !s3_rep_info.need_rep
1403    io.l2l_fwd_out.data       := Mux(s3_in.vaddr(3), s3_merged_data_frm_cache(127, 64), s3_merged_data_frm_cache(63, 0))
1404    io.l2l_fwd_out.dly_ld_err := s3_dly_ld_err || // ecc delayed error
1405                                 s3_ldld_rep_inst ||
1406                                 s3_rep_frm_fetch
1407  } else {
1408    io.l2l_fwd_out.valid := false.B
1409    io.l2l_fwd_out.data := DontCare
1410    io.l2l_fwd_out.dly_ld_err := DontCare
1411  }
1412
1413   // trigger
1414  val last_valid_data = RegNext(RegEnable(io.ldout.bits.data, io.ldout.fire))
1415  val hit_ld_addr_trig_hit_vec = Wire(Vec(TriggerNum, Bool()))
1416  val lq_ld_addr_trig_hit_vec = io.lsq.trigger.lqLoadAddrTriggerHitVec
1417  (0 until TriggerNum).map{i => {
1418    val tdata2    = RegNext(io.trigger(i).tdata2)
1419    val matchType = RegNext(io.trigger(i).matchType)
1420    val tEnable   = RegNext(io.trigger(i).tEnable)
1421
1422    hit_ld_addr_trig_hit_vec(i) := TriggerCmp(RegNext(s2_out.vaddr), tdata2, matchType, tEnable)
1423    io.trigger(i).addrHit       := Mux(s3_out.valid, hit_ld_addr_trig_hit_vec(i), lq_ld_addr_trig_hit_vec(i))
1424  }}
1425  io.lsq.trigger.hitLoadAddrTriggerHitVec := hit_ld_addr_trig_hit_vec
1426
1427  // FIXME: please move this part to LoadQueueReplay
1428  io.debug_ls := DontCare
1429
1430  // Topdown
1431  io.lsTopdownInfo.s1.robIdx          := s1_in.uop.robIdx.value
1432  io.lsTopdownInfo.s1.vaddr_valid     := s1_valid && s1_in.hasROBEntry
1433  io.lsTopdownInfo.s1.vaddr_bits      := s1_vaddr
1434  io.lsTopdownInfo.s2.robIdx          := s2_in.uop.robIdx.value
1435  io.lsTopdownInfo.s2.paddr_valid     := s2_fire && s2_in.hasROBEntry && !s2_in.tlbMiss
1436  io.lsTopdownInfo.s2.paddr_bits      := s2_in.paddr
1437  io.lsTopdownInfo.s2.first_real_miss := io.dcache.resp.bits.real_miss
1438  io.lsTopdownInfo.s2.cache_miss_en   := s2_fire && s2_in.hasROBEntry && !s2_in.tlbMiss && !s2_in.missDbUpdated
1439
1440  // perf cnt
1441  XSPerfAccumulate("s0_in_valid",                  io.ldin.valid)
1442  XSPerfAccumulate("s0_in_block",                  io.ldin.valid && !io.ldin.fire)
1443  XSPerfAccumulate("s0_in_fire_first_issue",       s0_valid && s0_sel_src.isFirstIssue)
1444  XSPerfAccumulate("s0_lsq_fire_first_issue",      io.replay.fire)
1445  XSPerfAccumulate("s0_ldu_fire_first_issue",      io.ldin.fire && s0_sel_src.isFirstIssue)
1446  XSPerfAccumulate("s0_fast_replay_issue",         io.fast_rep_in.fire)
1447  XSPerfAccumulate("s0_stall_out",                 s0_valid && !s0_can_go)
1448  XSPerfAccumulate("s0_stall_dcache",              s0_valid && !io.dcache.req.ready)
1449  XSPerfAccumulate("s0_addr_spec_success",         s0_fire && s0_sel_src.vaddr(VAddrBits-1, 12) === io.ldin.bits.src(0)(VAddrBits-1, 12))
1450  XSPerfAccumulate("s0_addr_spec_failed",          s0_fire && s0_sel_src.vaddr(VAddrBits-1, 12) =/= io.ldin.bits.src(0)(VAddrBits-1, 12))
1451  XSPerfAccumulate("s0_addr_spec_success_once",    s0_fire && s0_sel_src.vaddr(VAddrBits-1, 12) === io.ldin.bits.src(0)(VAddrBits-1, 12) && s0_sel_src.isFirstIssue)
1452  XSPerfAccumulate("s0_addr_spec_failed_once",     s0_fire && s0_sel_src.vaddr(VAddrBits-1, 12) =/= io.ldin.bits.src(0)(VAddrBits-1, 12) && s0_sel_src.isFirstIssue)
1453  XSPerfAccumulate("s0_forward_tl_d_channel",      s0_out.forward_tlDchannel)
1454  XSPerfAccumulate("s0_hardware_prefetch_fire",    s0_fire && s0_hw_prf_select)
1455  XSPerfAccumulate("s0_software_prefetch_fire",    s0_fire && s0_sel_src.prf && s0_int_iss_select)
1456  XSPerfAccumulate("s0_hardware_prefetch_blocked", io.prefetch_req.valid && !s0_hw_prf_select)
1457  XSPerfAccumulate("s0_hardware_prefetch_total",   io.prefetch_req.valid)
1458
1459  XSPerfAccumulate("s1_in_valid",                  s1_valid)
1460  XSPerfAccumulate("s1_in_fire",                   s1_fire)
1461  XSPerfAccumulate("s1_in_fire_first_issue",       s1_fire && s1_in.isFirstIssue)
1462  XSPerfAccumulate("s1_tlb_miss",                  s1_fire && s1_tlb_miss)
1463  XSPerfAccumulate("s1_tlb_miss_first_issue",      s1_fire && s1_tlb_miss && s1_in.isFirstIssue)
1464  XSPerfAccumulate("s1_stall_out",                 s1_valid && !s1_can_go)
1465  XSPerfAccumulate("s1_dly_err",                   s1_valid && s1_fast_rep_dly_err)
1466
1467  XSPerfAccumulate("s2_in_valid",                  s2_valid)
1468  XSPerfAccumulate("s2_in_fire",                   s2_fire)
1469  XSPerfAccumulate("s2_in_fire_first_issue",       s2_fire && s2_in.isFirstIssue)
1470  XSPerfAccumulate("s2_dcache_miss",               s2_fire && io.dcache.resp.bits.miss)
1471  XSPerfAccumulate("s2_dcache_miss_first_issue",   s2_fire && io.dcache.resp.bits.miss && s2_in.isFirstIssue)
1472  XSPerfAccumulate("s2_dcache_real_miss_first_issue",   s2_fire && io.dcache.resp.bits.miss && s2_in.isFirstIssue)
1473  XSPerfAccumulate("s2_full_forward",              s2_fire && s2_full_fwd)
1474  XSPerfAccumulate("s2_dcache_miss_full_forward",  s2_fire && s2_dcache_miss)
1475  XSPerfAccumulate("s2_fwd_frm_d_can",             s2_valid && s2_fwd_frm_d_chan)
1476  XSPerfAccumulate("s2_fwd_frm_d_chan_or_mshr",    s2_valid && s2_fwd_frm_d_chan_or_mshr)
1477  XSPerfAccumulate("s2_stall_out",                 s2_fire && !s2_can_go)
1478  XSPerfAccumulate("s2_prefetch",                  s2_fire && s2_prf)
1479  XSPerfAccumulate("s2_prefetch_ignored",          s2_fire && s2_prf && s2_mq_nack) // ignore prefetch for mshr full / miss req port conflict
1480  XSPerfAccumulate("s2_prefetch_miss",             s2_fire && s2_prf && io.dcache.resp.bits.miss) // prefetch req miss in l1
1481  XSPerfAccumulate("s2_prefetch_hit",              s2_fire && s2_prf && !io.dcache.resp.bits.miss) // prefetch req hit in l1
1482  XSPerfAccumulate("s2_prefetch_accept",           s2_fire && s2_prf && io.dcache.resp.bits.miss && !s2_mq_nack) // prefetch a missed line in l1, and l1 accepted it
1483  XSPerfAccumulate("s2_forward_req",               s2_fire && s2_in.forward_tlDchannel)
1484  XSPerfAccumulate("s2_successfully_forward_channel_D", s2_fire && s2_fwd_frm_d_chan && s2_fwd_data_valid)
1485  XSPerfAccumulate("s2_successfully_forward_mshr",      s2_fire && s2_fwd_frm_mshr && s2_fwd_data_valid)
1486
1487  XSPerfAccumulate("s3_fwd_frm_d_chan",            s3_valid && s3_fwd_frm_d_chan_valid)
1488
1489  XSPerfAccumulate("load_to_load_forward",                      s1_try_ptr_chasing && !s1_ptr_chasing_canceled)
1490  XSPerfAccumulate("load_to_load_forward_try",                  s1_try_ptr_chasing)
1491  XSPerfAccumulate("load_to_load_forward_fail",                 s1_cancel_ptr_chasing)
1492  XSPerfAccumulate("load_to_load_forward_fail_cancelled",       s1_cancel_ptr_chasing && s1_ptr_chasing_canceled)
1493  XSPerfAccumulate("load_to_load_forward_fail_wakeup_mismatch", s1_cancel_ptr_chasing && !s1_ptr_chasing_canceled && s1_not_fast_match)
1494  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)
1495  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)
1496  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)
1497
1498  // bug lyq: some signals in perfEvents are no longer suitable for the current MemBlock design
1499  // hardware performance counter
1500  val perfEvents = Seq(
1501    ("load_s0_in_fire         ", s0_fire                                                        ),
1502    ("load_to_load_forward    ", s1_fire && s1_try_ptr_chasing && !s1_ptr_chasing_canceled      ),
1503    ("stall_dcache            ", s0_valid && s0_can_go && !io.dcache.req.ready                  ),
1504    ("load_s1_in_fire         ", s0_fire                                                        ),
1505    ("load_s1_tlb_miss        ", s1_fire && io.tlb.resp.bits.miss                               ),
1506    ("load_s2_in_fire         ", s1_fire                                                        ),
1507    ("load_s2_dcache_miss     ", s2_fire && io.dcache.resp.bits.miss                            ),
1508  )
1509  generatePerfEvent()
1510
1511  when(io.ldout.fire){
1512    XSDebug("ldout %x\n", io.ldout.bits.uop.pc)
1513  }
1514  // end
1515}