xref: /XiangShan/src/main/scala/xiangshan/mem/pipeline/LoadUnit.scala (revision 9473e04d5cab97eaf63add958b2392eec3d876a2)
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 chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import utils._
23import utility._
24import xiangshan.ExceptionNO._
25import xiangshan._
26import xiangshan.backend.fu.PMPRespBundle
27import xiangshan.backend.rob.DebugLsInfoBundle
28import xiangshan.cache._
29import xiangshan.cache.dcache.ReplayCarry
30import xiangshan.cache.mmu.{TlbCmd, TlbReq, TlbRequestIO, TlbResp}
31
32class LoadToLsqFastIO(implicit p: Parameters) extends XSBundle {
33  val valid = Output(Bool())
34  val ld_ld_check_ok = Output(Bool())
35  val st_ld_check_ok = Output(Bool())
36  val cache_bank_no_conflict = Output(Bool())
37  val ld_idx = Output(UInt(log2Ceil(LoadQueueSize).W))
38  val debug = Output(new PerfDebugInfo)
39
40  def needreplay: Bool = {
41    !ld_ld_check_ok || !st_ld_check_ok || !cache_bank_no_conflict
42  }
43}
44
45class LoadToLsqSlowIO(implicit p: Parameters) extends XSBundle with HasDCacheParameters {
46  val valid = Output(Bool())
47  val tlb_hited = Output(Bool())
48  val st_ld_check_ok = Output(Bool())
49  val cache_no_replay = Output(Bool())
50  val forward_data_valid = Output(Bool())
51  val cache_hited = Output(Bool())
52  val can_forward_full_data = Output(Bool())
53  val ld_idx = Output(UInt(log2Ceil(LoadQueueSize).W))
54  val data_invalid_sq_idx = Output(UInt(log2Ceil(StoreQueueSize).W))
55  val replayCarry = Output(new ReplayCarry)
56  val miss_mshr_id = Output(UInt(log2Up(cfg.nMissEntries).W))
57  val data_in_last_beat = Output(Bool())
58  val debug = Output(new PerfDebugInfo)
59
60  def needreplay: Bool = {
61    !tlb_hited || !st_ld_check_ok || !cache_no_replay || !forward_data_valid || !cache_hited
62  }
63}
64
65class LoadToLsqIO(implicit p: Parameters) extends XSBundle {
66  val loadIn = ValidIO(new LqWriteBundle)
67  val loadPaddrIn = ValidIO(new LqPaddrWriteBundle)
68  val loadVaddrIn = ValidIO(new LqVaddrWriteBundle)
69  val ldout = Flipped(DecoupledIO(new ExuOutput))
70  val ldRawData = Input(new LoadDataFromLQBundle)
71  val s2_load_data_forwarded = Output(Bool())
72  val s3_delayed_load_error = Output(Bool())
73  val s2_dcache_require_replay = Output(Bool())
74  val s3_replay_from_fetch = Output(Bool()) // update uop.ctrl.replayInst in load queue in s3
75  val forward = new PipeLoadForwardQueryIO
76  val loadViolationQuery = new LoadViolationQueryIO
77  val trigger = Flipped(new LqTriggerIO)
78
79  // for load replay
80  val replayFast = new LoadToLsqFastIO
81  val replaySlow = new LoadToLsqSlowIO
82}
83
84class LoadToLoadIO(implicit p: Parameters) extends XSBundle {
85  // load to load fast path is limited to ld (64 bit) used as vaddr src1 only
86  val data = UInt(XLEN.W)
87  val valid = Bool()
88}
89
90class LoadUnitTriggerIO(implicit p: Parameters) extends XSBundle {
91  val tdata2 = Input(UInt(64.W))
92  val matchType = Input(UInt(2.W))
93  val tEnable = Input(Bool()) // timing is calculated before this
94  val addrHit = Output(Bool())
95  val lastDataHit = Output(Bool())
96}
97
98// Load Pipeline Stage 0
99// Generate addr, use addr to query DCache and DTLB
100class LoadUnit_S0(implicit p: Parameters) extends XSModule with HasDCacheParameters{
101  val io = IO(new Bundle() {
102    val in = Flipped(Decoupled(new ExuInput))
103    val out = Decoupled(new LsPipelineBundle)
104    val prefetch_in = Flipped(ValidIO(new L1PrefetchReq))
105    val dtlbReq = DecoupledIO(new TlbReq)
106    val dcacheReq = DecoupledIO(new DCacheWordReq)
107    val rsIdx = Input(UInt(log2Up(IssQueSize).W))
108    val isFirstIssue = Input(Bool())
109    val fastpath = Input(new LoadToLoadIO)
110    val s0_kill = Input(Bool())
111    // wire from lq to load pipeline
112    val lsqOut = Flipped(Decoupled(new LsPipelineBundle))
113
114    val s0_sqIdx = Output(new SqPtr)
115    // l2l
116    val l2lForward_select = Output(Bool())
117  })
118  require(LoadPipelineWidth == exuParameters.LduCnt)
119
120  val s0_vaddr = Wire(UInt(VAddrBits.W))
121  val s0_mask = Wire(UInt(8.W))
122  val s0_uop = Wire(new MicroOp)
123  val s0_isFirstIssue = Wire(Bool())
124  val s0_rsIdx = Wire(UInt(log2Up(IssQueSize).W))
125  val s0_sqIdx = Wire(new SqPtr)
126  val s0_replayCarry = Wire(new ReplayCarry) // way info for way predict related logic
127  // default value
128  s0_replayCarry.valid := false.B
129  s0_replayCarry.real_way_en := 0.U
130
131  io.s0_sqIdx := s0_sqIdx
132
133  val tryFastpath = WireInit(false.B)
134
135  // load flow select/gen
136  //
137  // src0: load replayed by LSQ (io.lsqOut)
138  // src1: hardware prefetch from prefetchor (high confidence) (io.prefetch)
139  // src2: int read / software prefetch first issue from RS (io.in)
140  // src3: vec read first issue from RS (TODO)
141  // src4: load try pointchaising when no issued or replayed load (io.fastpath)
142  // src5: hardware prefetch from prefetchor (high confidence) (io.prefetch)
143
144  // load flow source valid
145  val lfsrc0_loadReplay_valid = io.lsqOut.valid
146  val lfsrc1_highconfhwPrefetch_valid = io.prefetch_in.valid && io.prefetch_in.bits.confidence > 0.U
147  val lfsrc2_intloadFirstIssue_valid = io.in.valid // int flow first issue or software prefetch
148  val lfsrc3_vecloadFirstIssue_valid = WireInit(false.B) // TODO
149  val lfsrc4_l2lForward_valid = io.fastpath.valid
150  val lfsrc5_lowconfhwPrefetch_valid = io.prefetch_in.valid && io.prefetch_in.bits.confidence === 0.U
151  dontTouch(lfsrc0_loadReplay_valid)
152  dontTouch(lfsrc1_highconfhwPrefetch_valid)
153  dontTouch(lfsrc2_intloadFirstIssue_valid)
154  dontTouch(lfsrc3_vecloadFirstIssue_valid)
155  dontTouch(lfsrc4_l2lForward_valid)
156  dontTouch(lfsrc5_lowconfhwPrefetch_valid)
157
158  // load flow source ready
159  val lfsrc_loadReplay_ready = WireInit(true.B)
160  val lfsrc_highconfhwPrefetch_ready = !lfsrc0_loadReplay_valid
161  val lfsrc_intloadFirstIssue_ready = !lfsrc0_loadReplay_valid &&
162    !lfsrc1_highconfhwPrefetch_valid
163  val lfsrc_vecloadFirstIssue_ready = !lfsrc0_loadReplay_valid &&
164    !lfsrc1_highconfhwPrefetch_valid &&
165    !lfsrc2_intloadFirstIssue_valid
166  val lfsrc_l2lForward_ready = !lfsrc0_loadReplay_valid &&
167    !lfsrc1_highconfhwPrefetch_valid &&
168    !lfsrc2_intloadFirstIssue_valid &&
169    !lfsrc3_vecloadFirstIssue_valid
170  val lfsrc_lowconfhwPrefetch_ready = !lfsrc0_loadReplay_valid &&
171    !lfsrc1_highconfhwPrefetch_valid &&
172    !lfsrc2_intloadFirstIssue_valid &&
173    !lfsrc3_vecloadFirstIssue_valid &&
174    !lfsrc4_l2lForward_valid
175  dontTouch(lfsrc_loadReplay_ready)
176  dontTouch(lfsrc_highconfhwPrefetch_ready)
177  dontTouch(lfsrc_intloadFirstIssue_ready)
178  dontTouch(lfsrc_vecloadFirstIssue_ready)
179  dontTouch(lfsrc_l2lForward_ready)
180  dontTouch(lfsrc_lowconfhwPrefetch_ready)
181
182  // load flow source select (OH)
183  val lfsrc_loadReplay_select = lfsrc0_loadReplay_valid && lfsrc_loadReplay_ready
184  val lfsrc_hwprefetch_select = lfsrc_highconfhwPrefetch_ready && lfsrc1_highconfhwPrefetch_valid ||
185    lfsrc_lowconfhwPrefetch_ready && lfsrc5_lowconfhwPrefetch_valid
186  val lfsrc_intloadFirstIssue_select = lfsrc_intloadFirstIssue_ready && lfsrc2_intloadFirstIssue_valid
187  val lfsrc_vecloadFirstIssue_select = lfsrc_vecloadFirstIssue_ready && lfsrc3_vecloadFirstIssue_valid
188  val lfsrc_l2lForward_select = lfsrc_l2lForward_ready && lfsrc4_l2lForward_valid
189  assert(!lfsrc_vecloadFirstIssue_select) // to be added
190  dontTouch(lfsrc_loadReplay_select)
191  dontTouch(lfsrc_hwprefetch_select)
192  dontTouch(lfsrc_intloadFirstIssue_select)
193  dontTouch(lfsrc_vecloadFirstIssue_select)
194  dontTouch(lfsrc_l2lForward_select)
195
196  io.l2lForward_select := lfsrc_l2lForward_select
197
198  // s0_valid == ture iff there is a valid load flow in load_s0
199  val s0_valid = lfsrc0_loadReplay_valid ||
200    lfsrc1_highconfhwPrefetch_valid ||
201    lfsrc2_intloadFirstIssue_valid ||
202    lfsrc3_vecloadFirstIssue_valid ||
203    lfsrc4_l2lForward_valid ||
204    lfsrc5_lowconfhwPrefetch_valid
205
206  // prefetch related ctrl signal
207  val isPrefetch = WireInit(false.B)
208  val isPrefetchRead = WireInit(s0_uop.ctrl.fuOpType === LSUOpType.prefetch_r)
209  val isPrefetchWrite = WireInit(s0_uop.ctrl.fuOpType === LSUOpType.prefetch_w)
210  val isHWPrefetch = lfsrc_hwprefetch_select
211
212  // query DTLB
213  io.dtlbReq.valid := s0_valid
214  // hw prefetch addr does not need to be translated, give tlb paddr
215  io.dtlbReq.bits.vaddr := Mux(lfsrc_hwprefetch_select, io.prefetch_in.bits.paddr, s0_vaddr)
216  io.dtlbReq.bits.cmd := Mux(isPrefetch,
217    Mux(isPrefetchWrite, TlbCmd.write, TlbCmd.read),
218    TlbCmd.read
219  )
220  io.dtlbReq.bits.size := LSUOpType.size(s0_uop.ctrl.fuOpType)
221  io.dtlbReq.bits.kill := DontCare
222  io.dtlbReq.bits.memidx.is_ld := true.B
223  io.dtlbReq.bits.memidx.is_st := false.B
224  io.dtlbReq.bits.memidx.idx := s0_uop.lqIdx.value
225  io.dtlbReq.bits.debug.robIdx := s0_uop.robIdx
226  // hw prefetch addr does not need to be translated
227  io.dtlbReq.bits.no_translate := lfsrc_hwprefetch_select
228  io.dtlbReq.bits.debug.pc := s0_uop.cf.pc
229  io.dtlbReq.bits.debug.isFirstIssue := s0_isFirstIssue
230
231  // query DCache
232  io.dcacheReq.valid := s0_valid
233  when (isPrefetchRead) {
234    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_PFR
235  }.elsewhen (isPrefetchWrite) {
236    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_PFW
237  }.otherwise {
238    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_XRD
239  }
240  io.dcacheReq.bits.addr := s0_vaddr
241  io.dcacheReq.bits.mask := s0_mask
242  io.dcacheReq.bits.data := DontCare
243  when(isPrefetch) {
244    io.dcacheReq.bits.instrtype := DCACHE_PREFETCH_SOURCE.U
245  }.otherwise {
246    io.dcacheReq.bits.instrtype := LOAD_SOURCE.U
247  }
248  io.dcacheReq.bits.replayCarry := s0_replayCarry
249
250  // TODO: update cache meta
251  io.dcacheReq.bits.id := DontCare
252
253  // assign default value
254  s0_uop := DontCare
255
256  // load flow priority mux
257  when(lfsrc_loadReplay_select) {
258    s0_vaddr := io.lsqOut.bits.vaddr
259    s0_mask := io.lsqOut.bits.mask
260    s0_uop := io.lsqOut.bits.uop
261    s0_isFirstIssue := io.lsqOut.bits.isFirstIssue
262    s0_rsIdx := io.lsqOut.bits.rsIdx
263    s0_sqIdx := io.lsqOut.bits.uop.sqIdx
264    s0_replayCarry := io.lsqOut.bits.replayCarry
265    val replayUopIsPrefetch = WireInit(LSUOpType.isPrefetch(io.lsqOut.bits.uop.ctrl.fuOpType))
266    when (replayUopIsPrefetch) {
267      isPrefetch := true.B
268    }
269  }.elsewhen(lfsrc_hwprefetch_select) {
270    // vaddr based index for dcache
271    s0_vaddr := io.prefetch_in.bits.getVaddr()
272    s0_mask := 0.U
273    s0_uop := DontCare
274    s0_isFirstIssue := false.B
275    s0_rsIdx := DontCare
276    s0_sqIdx := DontCare
277    s0_replayCarry := DontCare
278    // ctrl signal
279    isPrefetch := true.B
280    isPrefetchRead := !io.prefetch_in.bits.is_store
281    isPrefetchWrite := io.prefetch_in.bits.is_store
282  }.elsewhen(lfsrc_intloadFirstIssue_select) {
283    val imm12 = io.in.bits.uop.ctrl.imm(11, 0)
284    s0_vaddr := io.in.bits.src(0) + SignExt(imm12, VAddrBits)
285    s0_mask := genWmask(s0_vaddr, io.in.bits.uop.ctrl.fuOpType(1,0))
286    s0_uop := io.in.bits.uop
287    s0_isFirstIssue := io.isFirstIssue
288    s0_rsIdx := io.rsIdx
289    s0_sqIdx := io.in.bits.uop.sqIdx
290    val issueUopIsPrefetch = WireInit(LSUOpType.isPrefetch(io.in.bits.uop.ctrl.fuOpType))
291    when (issueUopIsPrefetch) {
292      isPrefetch := true.B
293    }
294  }.otherwise {
295    if (EnableLoadToLoadForward) {
296      tryFastpath := lfsrc_l2lForward_select
297      // When there's no valid instruction from RS and LSQ, we try the load-to-load forwarding.
298      s0_vaddr := io.fastpath.data
299      // Assume the pointer chasing is always ld.
300      s0_uop.ctrl.fuOpType := LSUOpType.ld
301      s0_mask := genWmask(0.U, LSUOpType.ld)
302      // we dont care s0_isFirstIssue and s0_rsIdx and s0_sqIdx in S0 when trying pointchasing
303      // because these signals will be updated in S1
304      s0_isFirstIssue := true.B
305      s0_rsIdx := DontCare
306      s0_sqIdx := DontCare
307    }
308  }
309
310  // address align check
311  val addrAligned = LookupTree(s0_uop.ctrl.fuOpType(1, 0), List(
312    "b00".U   -> true.B,                   //b
313    "b01".U   -> (s0_vaddr(0)    === 0.U), //h
314    "b10".U   -> (s0_vaddr(1, 0) === 0.U), //w
315    "b11".U   -> (s0_vaddr(2, 0) === 0.U)  //d
316  ))
317
318  // accept load flow if dcache ready (dtlb is always ready)
319  io.out.valid := s0_valid && io.dcacheReq.ready && !io.s0_kill
320  io.out.bits := DontCare
321  io.out.bits.vaddr := s0_vaddr
322  io.out.bits.mask := s0_mask
323  io.out.bits.uop := s0_uop
324  io.out.bits.uop.cf.exceptionVec(loadAddrMisaligned) := !addrAligned
325  io.out.bits.rsIdx := s0_rsIdx
326  io.out.bits.isFirstIssue := s0_isFirstIssue
327  io.out.bits.isPrefetch := isPrefetch
328  io.out.bits.isHWPrefetch := isHWPrefetch
329  io.out.bits.isLoadReplay := io.lsqOut.valid
330  io.out.bits.mshrid := io.lsqOut.bits.mshrid
331  io.out.bits.forward_tlDchannel := io.lsqOut.valid && io.lsqOut.bits.forward_tlDchannel
332  when(io.dtlbReq.valid && s0_isFirstIssue) {
333    io.out.bits.uop.debugInfo.tlbFirstReqTime := GTimer()
334  }.otherwise{
335    io.out.bits.uop.debugInfo.tlbFirstReqTime := s0_uop.debugInfo.tlbFirstReqTime
336  }
337
338  // load flow source ready
339  // always accept load flow from load replay queue
340  // io.lsqOut has highest priority
341  io.lsqOut.ready := (io.out.ready && io.dcacheReq.ready && lfsrc_loadReplay_ready)
342
343  // accept load flow from rs when:
344  // 1) there is no lsq-replayed load
345  // 2) there is no high confidence prefetch request
346  io.in.ready := (io.out.ready && io.dcacheReq.ready && lfsrc_intloadFirstIssue_select)
347
348  // for hw prefetch load flow feedback, to be added later
349  // io.prefetch_in.ready := lfsrc_hwprefetch_select
350
351  XSDebug(io.dcacheReq.fire,
352    p"[DCACHE LOAD REQ] pc ${Hexadecimal(s0_uop.cf.pc)}, vaddr ${Hexadecimal(s0_vaddr)}\n"
353  )
354  XSPerfAccumulate("in_valid", io.in.valid)
355  XSPerfAccumulate("in_fire", io.in.fire)
356  XSPerfAccumulate("in_fire_first_issue", s0_valid && s0_isFirstIssue)
357  XSPerfAccumulate("lsq_fire_first_issue", io.lsqOut.valid && io.lsqOut.bits.isFirstIssue)
358  XSPerfAccumulate("ldu_fire_first_issue", io.in.valid && io.isFirstIssue)
359  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready && io.dcacheReq.ready)
360  XSPerfAccumulate("stall_dcache", io.out.valid && io.out.ready && !io.dcacheReq.ready)
361  XSPerfAccumulate("addr_spec_success", io.out.fire && s0_vaddr(VAddrBits-1, 12) === io.in.bits.src(0)(VAddrBits-1, 12))
362  XSPerfAccumulate("addr_spec_failed", io.out.fire && s0_vaddr(VAddrBits-1, 12) =/= io.in.bits.src(0)(VAddrBits-1, 12))
363  XSPerfAccumulate("addr_spec_success_once", io.out.fire && s0_vaddr(VAddrBits-1, 12) === io.in.bits.src(0)(VAddrBits-1, 12) && io.isFirstIssue)
364  XSPerfAccumulate("addr_spec_failed_once", io.out.fire && s0_vaddr(VAddrBits-1, 12) =/= io.in.bits.src(0)(VAddrBits-1, 12) && io.isFirstIssue)
365  XSPerfAccumulate("forward_tlDchannel", io.out.bits.forward_tlDchannel)
366  XSPerfAccumulate("hardware_prefetch_fire", io.out.fire && lfsrc_hwprefetch_select)
367  XSPerfAccumulate("software_prefetch_fire", io.out.fire && isPrefetch && lfsrc_intloadFirstIssue_select)
368  XSPerfAccumulate("hardware_prefetch_blocked", io.prefetch_in.valid && !lfsrc_hwprefetch_select)
369  XSPerfAccumulate("hardware_prefetch_total", io.prefetch_in.valid)
370}
371
372
373// Load Pipeline Stage 1
374// TLB resp (send paddr to dcache)
375class LoadUnit_S1(implicit p: Parameters) extends XSModule with HasCircularQueuePtrHelper {
376  val io = IO(new Bundle() {
377    val in = Flipped(Decoupled(new LsPipelineBundle))
378    val s1_kill = Input(Bool())
379    val out = Decoupled(new LsPipelineBundle)
380    val dtlbResp = Flipped(DecoupledIO(new TlbResp(2)))
381    val lsuPAddr = Output(UInt(PAddrBits.W))
382    val dcachePAddr = Output(UInt(PAddrBits.W))
383    val dcacheKill = Output(Bool())
384    val dcacheBankConflict = Input(Bool())
385    val fullForwardFast = Output(Bool())
386    val sbuffer = new LoadForwardQueryIO
387    val lsq = new PipeLoadForwardQueryIO
388    val loadViolationQueryReq = Decoupled(new LoadViolationQueryReq)
389    val reExecuteQuery = Flipped(Vec(StorePipelineWidth, Valid(new LoadReExecuteQueryIO)))
390    val rsFeedback = ValidIO(new RSFeedback)
391    val replayFast = new LoadToLsqFastIO
392    val csrCtrl = Flipped(new CustomCSRCtrlIO)
393    val needLdVioCheckRedo = Output(Bool())
394    val needReExecute = Output(Bool())
395  })
396
397  val s1_uop = io.in.bits.uop
398  val s1_paddr_dup_lsu = io.dtlbResp.bits.paddr(0)
399  val s1_paddr_dup_dcache = io.dtlbResp.bits.paddr(1)
400  // af & pf exception were modified below.
401  val s1_exception = ExceptionNO.selectByFu(io.out.bits.uop.cf.exceptionVec, lduCfg).asUInt.orR
402  val s1_tlb_miss = io.dtlbResp.bits.miss
403  val s1_mask = io.in.bits.mask
404  val s1_is_prefetch = io.in.bits.isPrefetch
405  val s1_is_hw_prefetch = io.in.bits.isHWPrefetch
406  val s1_is_sw_prefetch = s1_is_prefetch && !s1_is_hw_prefetch
407  val s1_bank_conflict = io.dcacheBankConflict
408
409  io.out.bits := io.in.bits // forwardXX field will be updated in s1
410
411  val s1_tlb_memidx = io.dtlbResp.bits.memidx
412  when(s1_tlb_memidx.is_ld && io.dtlbResp.valid && !s1_tlb_miss && s1_tlb_memidx.idx === io.out.bits.uop.lqIdx.value) {
413    // printf("load idx = %d\n", s1_tlb_memidx.idx)
414    io.out.bits.uop.debugInfo.tlbRespTime := GTimer()
415  }
416
417  io.dtlbResp.ready := true.B
418
419  io.lsuPAddr := s1_paddr_dup_lsu
420  io.dcachePAddr := s1_paddr_dup_dcache
421  //io.dcacheKill := s1_tlb_miss || s1_exception || s1_mmio
422  io.dcacheKill := s1_tlb_miss || s1_exception || io.s1_kill
423  // load forward query datapath
424  io.sbuffer.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill || s1_is_prefetch)
425  io.sbuffer.vaddr := io.in.bits.vaddr
426  io.sbuffer.paddr := s1_paddr_dup_lsu
427  io.sbuffer.uop := s1_uop
428  io.sbuffer.sqIdx := s1_uop.sqIdx
429  io.sbuffer.mask := s1_mask
430  io.sbuffer.pc := s1_uop.cf.pc // FIXME: remove it
431
432  io.lsq.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill || s1_is_prefetch)
433  io.lsq.vaddr := io.in.bits.vaddr
434  io.lsq.paddr := s1_paddr_dup_lsu
435  io.lsq.uop := s1_uop
436  io.lsq.sqIdx := s1_uop.sqIdx
437  io.lsq.sqIdxMask := DontCare // will be overwritten by sqIdxMask pre-generated in s0
438  io.lsq.mask := s1_mask
439  io.lsq.pc := s1_uop.cf.pc // FIXME: remove it
440
441  // ld-ld violation query
442  io.loadViolationQueryReq.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill || s1_is_prefetch)
443  io.loadViolationQueryReq.bits.paddr := s1_paddr_dup_lsu
444  io.loadViolationQueryReq.bits.uop := s1_uop
445
446  // st-ld violation query
447  val needReExecuteVec = Wire(Vec(StorePipelineWidth, Bool()))
448  val needReExecute = Wire(Bool())
449
450  for (w <- 0 until StorePipelineWidth) {
451    //  needReExecute valid when
452    //  1. ReExecute query request valid.
453    //  2. Load instruction is younger than requestors(store instructions).
454    //  3. Physical address match.
455    //  4. Data contains.
456
457    needReExecuteVec(w) := io.reExecuteQuery(w).valid &&
458                          isAfter(io.in.bits.uop.robIdx, io.reExecuteQuery(w).bits.robIdx) &&
459                          !s1_tlb_miss &&
460                          (s1_paddr_dup_lsu(PAddrBits-1, 3) === io.reExecuteQuery(w).bits.paddr(PAddrBits-1, 3)) &&
461                          (s1_mask & io.reExecuteQuery(w).bits.mask).orR
462  }
463  needReExecute := needReExecuteVec.asUInt.orR
464  io.needReExecute := needReExecute
465
466  // Generate forwardMaskFast to wake up insts earlier
467  val forwardMaskFast = io.lsq.forwardMaskFast.asUInt | io.sbuffer.forwardMaskFast.asUInt
468  io.fullForwardFast := ((~forwardMaskFast).asUInt & s1_mask) === 0.U
469
470  // Generate feedback signal caused by:
471  // * dcache bank conflict
472  // * need redo ld-ld violation check
473  val needLdVioCheckRedo = io.loadViolationQueryReq.valid &&
474    !io.loadViolationQueryReq.ready &&
475    RegNext(io.csrCtrl.ldld_vio_check_enable)
476  io.needLdVioCheckRedo := needLdVioCheckRedo
477
478  // make nanhu rs feedback port happy
479  // if a load flow comes from rs, always feedback hit (no need to replay from rs)
480  io.rsFeedback.valid := Mux(io.in.bits.isLoadReplay, false.B, io.in.valid && !io.s1_kill && !s1_is_hw_prefetch)
481  io.rsFeedback.bits.hit := true.B // we have found s1_bank_conflict / re do ld-ld violation check
482  io.rsFeedback.bits.rsIdx := io.in.bits.rsIdx
483  io.rsFeedback.bits.flushState := io.in.bits.ptwBack
484  io.rsFeedback.bits.sourceType := Mux(s1_bank_conflict, RSFeedbackType.bankConflict, RSFeedbackType.ldVioCheckRedo)
485  io.rsFeedback.bits.dataInvalidSqIdx := DontCare
486
487  // request replay from load replay queue, fast port
488  io.replayFast.valid := io.in.valid && !io.s1_kill && !s1_is_hw_prefetch
489  io.replayFast.ld_ld_check_ok := !needLdVioCheckRedo || s1_is_sw_prefetch
490  io.replayFast.st_ld_check_ok := !needReExecute || s1_is_sw_prefetch
491  io.replayFast.cache_bank_no_conflict := !s1_bank_conflict || s1_is_sw_prefetch
492  io.replayFast.ld_idx := io.in.bits.uop.lqIdx.value
493  io.replayFast.debug := io.in.bits.uop.debugInfo
494
495  // if replay is detected in load_s1,
496  // load inst will be canceled immediately
497  io.out.valid := io.in.valid && (!needLdVioCheckRedo && !s1_bank_conflict && !needReExecute || s1_is_sw_prefetch) && !io.s1_kill
498  io.out.bits.paddr := s1_paddr_dup_lsu
499  io.out.bits.tlbMiss := s1_tlb_miss
500
501  // current ori test will cause the case of ldest == 0, below will be modifeid in the future.
502  // af & pf exception were modified
503  io.out.bits.uop.cf.exceptionVec(loadPageFault) := io.dtlbResp.bits.excp(0).pf.ld
504  io.out.bits.uop.cf.exceptionVec(loadAccessFault) := io.dtlbResp.bits.excp(0).af.ld
505
506  io.out.bits.ptwBack := io.dtlbResp.bits.ptwBack
507  io.out.bits.rsIdx := io.in.bits.rsIdx
508
509  io.in.ready := !io.in.valid || io.out.ready
510
511  XSPerfAccumulate("in_valid", io.in.valid)
512  XSPerfAccumulate("in_fire", io.in.fire)
513  XSPerfAccumulate("in_fire_first_issue", io.in.fire && io.in.bits.isFirstIssue)
514  XSPerfAccumulate("tlb_miss", io.in.fire && s1_tlb_miss)
515  XSPerfAccumulate("tlb_miss_first_issue", io.in.fire && s1_tlb_miss && io.in.bits.isFirstIssue)
516  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready)
517}
518
519// Load Pipeline Stage 2
520// DCache resp
521class LoadUnit_S2(implicit p: Parameters) extends XSModule with HasLoadHelper with HasCircularQueuePtrHelper with HasDCacheParameters {
522  val io = IO(new Bundle() {
523    val in = Flipped(Decoupled(new LsPipelineBundle))
524    val out = Decoupled(new LsPipelineBundle)
525    val rsFeedback = ValidIO(new RSFeedback)
526    val replaySlow = new LoadToLsqSlowIO
527    val dcacheResp = Flipped(DecoupledIO(new DCacheWordResp))
528    val pmpResp = Flipped(new PMPRespBundle())
529    val lsq = new LoadForwardQueryIO
530    val dataInvalidSqIdx = Input(UInt())
531    val sbuffer = new LoadForwardQueryIO
532    val dataForwarded = Output(Bool())
533    val s2_dcache_require_replay = Output(Bool())
534    val fullForward = Output(Bool())
535    val dcache_kill = Output(Bool())
536    val s3_delayed_load_error = Output(Bool())
537    val loadViolationQueryResp = Flipped(Valid(new LoadViolationQueryResp))
538    val csrCtrl = Flipped(new CustomCSRCtrlIO)
539    val sentFastUop = Input(Bool())
540    val static_pm = Input(Valid(Bool())) // valid for static, bits for mmio
541    val s2_can_replay_from_fetch = Output(Bool()) // dirty code
542    val loadDataFromDcache = Output(new LoadDataFromDcacheBundle)
543    val reExecuteQuery = Flipped(Vec(StorePipelineWidth, Valid(new LoadReExecuteQueryIO)))
544    val needReExecute = Output(Bool())
545    // forward tilelink D channel
546    val forward_D = Input(Bool())
547    val forwardData_D = Input(Vec(8, UInt(8.W)))
548
549    // forward mshr data
550    val forward_mshr = Input(Bool())
551    val forwardData_mshr = Input(Vec(8, UInt(8.W)))
552
553    // indicate whether forward tilelink D channel or mshr data is valid
554    val forward_result_valid = Input(Bool())
555
556    val s2_forward_fail = Output(Bool())
557  })
558
559  val pmp = WireInit(io.pmpResp)
560  when (io.static_pm.valid) {
561    pmp.ld := false.B
562    pmp.st := false.B
563    pmp.instr := false.B
564    pmp.mmio := io.static_pm.bits
565  }
566
567  val s2_is_prefetch = io.in.bits.isPrefetch
568  val s2_is_hw_prefetch = io.in.bits.isHWPrefetch
569
570  val forward_D_or_mshr_valid = io.forward_result_valid && (io.forward_D || io.forward_mshr)
571
572  // assert(!reset && io.forward_D && io.forward_mshr && io.in.valid && io.in.bits.forward_tlDchannel, "forward D and mshr at the same time")
573
574  // exception that may cause load addr to be invalid / illegal
575  //
576  // if such exception happen, that inst and its exception info
577  // will be force writebacked to rob
578  val s2_exception_vec = WireInit(io.in.bits.uop.cf.exceptionVec)
579  s2_exception_vec(loadAccessFault) := io.in.bits.uop.cf.exceptionVec(loadAccessFault) || pmp.ld
580  // soft prefetch will not trigger any exception (but ecc error interrupt may be triggered)
581  when (s2_is_prefetch) {
582    s2_exception_vec := 0.U.asTypeOf(s2_exception_vec.cloneType)
583  }
584  val s2_exception = ExceptionNO.selectByFu(s2_exception_vec, lduCfg).asUInt.orR && !io.in.bits.tlbMiss
585
586  // writeback access fault caused by ecc error / bus error
587  //
588  // * ecc data error is slow to generate, so we will not use it until load stage 3
589  // * in load stage 3, an extra signal io.load_error will be used to
590
591  // now cache ecc error will raise an access fault
592  // at the same time, error info (including error paddr) will be write to
593  // an customized CSR "CACHE_ERROR"
594  if (EnableAccurateLoadError) {
595    io.s3_delayed_load_error := io.dcacheResp.bits.error_delayed &&
596      io.csrCtrl.cache_error_enable &&
597      RegNext(io.out.valid)
598  } else {
599    io.s3_delayed_load_error := false.B
600  }
601
602  val actually_mmio = pmp.mmio
603  val s2_uop = io.in.bits.uop
604  val s2_mask = io.in.bits.mask
605  val s2_paddr = io.in.bits.paddr
606  val s2_tlb_miss = io.in.bits.tlbMiss
607  val s2_mmio = !s2_is_prefetch && actually_mmio && !s2_exception
608  val s2_cache_miss = io.dcacheResp.bits.miss && !forward_D_or_mshr_valid
609  val s2_cache_replay = io.dcacheResp.bits.replay && !forward_D_or_mshr_valid
610  val s2_cache_tag_error = io.dcacheResp.bits.tag_error
611  val s2_forward_fail = io.lsq.matchInvalid || io.sbuffer.matchInvalid
612  val s2_ldld_violation = io.loadViolationQueryResp.valid &&
613    io.loadViolationQueryResp.bits.have_violation &&
614    RegNext(io.csrCtrl.ldld_vio_check_enable)
615  val s2_data_invalid = io.lsq.dataInvalid && !s2_ldld_violation && !s2_exception
616
617  io.s2_forward_fail := s2_forward_fail
618  io.dcache_kill := pmp.ld || pmp.mmio // move pmp resp kill to outside
619  io.dcacheResp.ready := true.B
620  val dcacheShouldResp = !(s2_tlb_miss || s2_exception || s2_mmio || s2_is_prefetch)
621  assert(!(io.in.valid && (dcacheShouldResp && !io.dcacheResp.valid)), "DCache response got lost")
622
623  // merge forward result
624  // lsq has higher priority than sbuffer
625  val forwardMask = Wire(Vec(8, Bool()))
626  val forwardData = Wire(Vec(8, UInt(8.W)))
627
628  val fullForward = ((~forwardMask.asUInt).asUInt & s2_mask) === 0.U && !io.lsq.dataInvalid
629  io.lsq := DontCare
630  io.sbuffer := DontCare
631  io.fullForward := fullForward
632
633  // generate XLEN/8 Muxs
634  for (i <- 0 until XLEN / 8) {
635    forwardMask(i) := io.lsq.forwardMask(i) || io.sbuffer.forwardMask(i)
636    forwardData(i) := Mux(io.lsq.forwardMask(i), io.lsq.forwardData(i), io.sbuffer.forwardData(i))
637  }
638
639  XSDebug(io.out.fire, "[FWD LOAD RESP] pc %x fwd %x(%b) + %x(%b)\n",
640    s2_uop.cf.pc,
641    io.lsq.forwardData.asUInt, io.lsq.forwardMask.asUInt,
642    io.in.bits.forwardData.asUInt, io.in.bits.forwardMask.asUInt
643  )
644
645  // data merge
646  // val rdataVec = VecInit((0 until XLEN / 8).map(j =>
647  //   Mux(forwardMask(j), forwardData(j), io.dcacheResp.bits.data(8*(j+1)-1, 8*j))
648  // )) // s2_rdataVec will be write to load queue
649  // val rdata = rdataVec.asUInt
650  // val rdataSel = LookupTree(s2_paddr(2, 0), List(
651  //   "b000".U -> rdata(63, 0),
652  //   "b001".U -> rdata(63, 8),
653  //   "b010".U -> rdata(63, 16),
654  //   "b011".U -> rdata(63, 24),
655  //   "b100".U -> rdata(63, 32),
656  //   "b101".U -> rdata(63, 40),
657  //   "b110".U -> rdata(63, 48),
658  //   "b111".U -> rdata(63, 56)
659  // ))
660  // val rdataPartialLoad = rdataHelper(s2_uop, rdataSel) // s2_rdataPartialLoad is not used
661
662  io.out.valid := io.in.valid &&
663    !s2_tlb_miss && // always request replay and cancel current flow if tlb miss
664    (!s2_data_invalid && !io.needReExecute || s2_is_prefetch) && // prefetch does not care about ld-st dependency
665    !s2_is_hw_prefetch // hardware prefetch flow should not be writebacked
666  // write_lq_safe is needed by dup logic
667  // io.write_lq_safe := !s2_tlb_miss && !s2_data_invalid
668  // Inst will be canceled in store queue / lsq,
669  // so we do not need to care about flush in load / store unit's out.valid
670  io.out.bits := io.in.bits
671  // io.out.bits.data := rdataPartialLoad
672  io.out.bits.data := 0.U // data will be generated in load_s3
673  // when exception occurs, set it to not miss and let it write back to rob (via int port)
674  if (EnableFastForward) {
675    io.out.bits.miss := s2_cache_miss &&
676      !s2_exception &&
677      !fullForward &&
678      !s2_is_prefetch
679  } else {
680    io.out.bits.miss := s2_cache_miss &&
681      !s2_exception &&
682      !s2_is_prefetch
683  }
684  io.out.bits.uop.ctrl.fpWen := io.in.bits.uop.ctrl.fpWen && !s2_exception
685
686  // val s2_loadDataFromDcache = new LoadDataFromDcacheBundle
687  // s2_loadDataFromDcache.forwardMask := forwardMask
688  // s2_loadDataFromDcache.forwardData := forwardData
689  // s2_loadDataFromDcache.uop := io.out.bits.uop
690  // s2_loadDataFromDcache.addrOffset := s2_paddr(2, 0)
691  // // forward D or mshr
692  // s2_loadDataFromDcache.forward_D := io.forward_D
693  // s2_loadDataFromDcache.forwardData_D := io.forwardData_D
694  // s2_loadDataFromDcache.forward_mshr := io.forward_mshr
695  // s2_loadDataFromDcache.forwardData_mshr := io.forwardData_mshr
696  // s2_loadDataFromDcache.forward_result_valid := io.forward_result_valid
697  // io.loadDataFromDcache := RegEnable(s2_loadDataFromDcache, io.in.valid)
698  io.loadDataFromDcache.respDcacheData := io.dcacheResp.bits.data_delayed
699  io.loadDataFromDcache.forwardMask := RegEnable(forwardMask, io.in.valid)
700  io.loadDataFromDcache.forwardData := RegEnable(forwardData, io.in.valid)
701  io.loadDataFromDcache.uop := RegEnable(io.out.bits.uop, io.in.valid)
702  io.loadDataFromDcache.addrOffset := RegEnable(s2_paddr(2, 0), io.in.valid)
703  // forward D or mshr
704  io.loadDataFromDcache.forward_D := RegEnable(io.forward_D, io.in.valid)
705  io.loadDataFromDcache.forwardData_D := RegEnable(io.forwardData_D, io.in.valid)
706  io.loadDataFromDcache.forward_mshr := RegEnable(io.forward_mshr, io.in.valid)
707  io.loadDataFromDcache.forwardData_mshr := RegEnable(io.forwardData_mshr, io.in.valid)
708  io.loadDataFromDcache.forward_result_valid := RegEnable(io.forward_result_valid, io.in.valid)
709
710  io.s2_can_replay_from_fetch := !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
711  // if forward fail, replay this inst from fetch
712  val debug_forwardFailReplay = s2_forward_fail && !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
713  // if ld-ld violation is detected, replay from this inst from fetch
714  val debug_ldldVioReplay = s2_ldld_violation && !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
715  // io.out.bits.uop.ctrl.replayInst := false.B
716
717  io.out.bits.mmio := s2_mmio
718  io.out.bits.uop.ctrl.flushPipe := s2_mmio && io.sentFastUop
719  io.out.bits.uop.cf.exceptionVec := s2_exception_vec // cache error not included
720
721  // For timing reasons, sometimes we can not let
722  // io.out.bits.miss := s2_cache_miss && !s2_exception && !fullForward
723  // We use io.dataForwarded instead. It means:
724  // 1. Forward logic have prepared all data needed,
725  //    and dcache query is no longer needed.
726  // 2. ... or data cache tag error is detected, this kind of inst
727  //    will not update miss queue. That is to say, if miss, that inst
728  //    may not be refilled
729  // Such inst will be writebacked from load queue.
730  io.dataForwarded := s2_cache_miss && !s2_exception &&
731    (fullForward || io.csrCtrl.cache_error_enable && s2_cache_tag_error)
732  // io.out.bits.forwardX will be send to lq
733  io.out.bits.forwardMask := forwardMask
734  // data from dcache is not included in io.out.bits.forwardData
735  io.out.bits.forwardData := forwardData
736
737  io.in.ready := io.out.ready || !io.in.valid
738
739
740  // st-ld violation query
741  val needReExecuteVec = Wire(Vec(StorePipelineWidth, Bool()))
742  val needReExecute = Wire(Bool())
743
744  for (i <- 0 until StorePipelineWidth) {
745    //  NeedFastRecovery Valid when
746    //  1. Fast recovery query request Valid.
747    //  2. Load instruction is younger than requestors(store instructions).
748    //  3. Physical address match.
749    //  4. Data contains.
750    needReExecuteVec(i) := io.reExecuteQuery(i).valid &&
751                              isAfter(io.in.bits.uop.robIdx, io.reExecuteQuery(i).bits.robIdx) &&
752                              !s2_tlb_miss &&
753                              (s2_paddr(PAddrBits-1,3) === io.reExecuteQuery(i).bits.paddr(PAddrBits-1, 3)) &&
754                              (s2_mask & io.reExecuteQuery(i).bits.mask).orR
755  }
756  needReExecute := needReExecuteVec.asUInt.orR
757  io.needReExecute := needReExecute
758
759  // rs slow feedback port in nanhu is not used for now
760  io.rsFeedback.valid := false.B
761  io.rsFeedback.bits := DontCare
762
763  // request replay from load replay queue, fast port
764  io.replaySlow.valid := io.in.valid && !s2_is_hw_prefetch // hardware prefetch flow should not be reported to load replay queue
765  io.replaySlow.tlb_hited := !s2_tlb_miss
766  io.replaySlow.st_ld_check_ok := !needReExecute || s2_is_prefetch // Note: soft prefetch does not care about ld-st dependency
767  if (EnableFastForward) {
768    io.replaySlow.cache_no_replay := !s2_cache_replay || s2_is_prefetch || s2_mmio || s2_exception || fullForward
769  }else {
770    io.replaySlow.cache_no_replay := !s2_cache_replay || s2_is_prefetch || s2_mmio || s2_exception || io.dataForwarded
771  }
772  io.replaySlow.forward_data_valid := !s2_data_invalid || s2_is_prefetch // Note: soft prefetch does not care about ld-st dependency
773  io.replaySlow.cache_hited := !io.out.bits.miss || io.out.bits.mmio
774  io.replaySlow.can_forward_full_data := io.dataForwarded
775  io.replaySlow.ld_idx := io.in.bits.uop.lqIdx.value
776  io.replaySlow.data_invalid_sq_idx := io.dataInvalidSqIdx
777  io.replaySlow.replayCarry := io.dcacheResp.bits.replayCarry
778  io.replaySlow.miss_mshr_id := io.dcacheResp.bits.mshr_id
779  io.replaySlow.data_in_last_beat := io.in.bits.paddr(log2Up(refillBytes))
780  io.replaySlow.debug := io.in.bits.uop.debugInfo
781
782  // To be removed
783  val s2_need_replay_from_rs = Wire(Bool())
784  if (EnableFastForward) {
785    s2_need_replay_from_rs :=
786      needReExecute ||
787      s2_tlb_miss || // replay if dtlb miss
788      s2_cache_replay && !s2_is_prefetch && !s2_mmio && !s2_exception && !fullForward || // replay if dcache miss queue full / busy
789      s2_data_invalid && !s2_is_prefetch // replay if store to load forward data is not ready
790  } else {
791    // Note that if all parts of data are available in sq / sbuffer, replay required by dcache will not be scheduled
792    s2_need_replay_from_rs :=
793      needReExecute ||
794      s2_tlb_miss || // replay if dtlb miss
795      s2_cache_replay && !s2_is_prefetch && !s2_mmio && !s2_exception && !io.dataForwarded || // replay if dcache miss queue full / busy
796      s2_data_invalid && !s2_is_prefetch // replay if store to load forward data is not ready
797  }
798
799  // s2_cache_replay is quite slow to generate, send it separately to LQ
800  if (EnableFastForward) {
801    io.s2_dcache_require_replay := s2_cache_replay && !fullForward
802  } else {
803    io.s2_dcache_require_replay := s2_cache_replay &&
804      s2_need_replay_from_rs &&
805      !io.dataForwarded &&
806      !s2_is_prefetch &&
807      io.out.bits.miss
808  }
809
810  XSPerfAccumulate("in_valid", io.in.valid)
811  XSPerfAccumulate("in_fire", io.in.fire)
812  XSPerfAccumulate("in_fire_first_issue", io.in.fire && io.in.bits.isFirstIssue)
813  XSPerfAccumulate("dcache_miss", io.in.fire && s2_cache_miss)
814  XSPerfAccumulate("dcache_miss_first_issue", io.in.fire && s2_cache_miss && io.in.bits.isFirstIssue)
815  XSPerfAccumulate("full_forward", io.in.valid && fullForward)
816  XSPerfAccumulate("dcache_miss_full_forward", io.in.valid && s2_cache_miss && fullForward)
817  XSPerfAccumulate("replay",  io.rsFeedback.valid && !io.rsFeedback.bits.hit)
818  XSPerfAccumulate("replay_tlb_miss", io.rsFeedback.valid && !io.rsFeedback.bits.hit && s2_tlb_miss)
819  XSPerfAccumulate("replay_cache", io.rsFeedback.valid && !io.rsFeedback.bits.hit && !s2_tlb_miss && s2_cache_replay)
820  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready)
821  XSPerfAccumulate("replay_from_fetch_forward", io.out.valid && debug_forwardFailReplay)
822  XSPerfAccumulate("replay_from_fetch_load_vio", io.out.valid && debug_ldldVioReplay)
823  XSPerfAccumulate("replay_lq",  io.replaySlow.valid && (!io.replaySlow.tlb_hited || !io.replaySlow.cache_no_replay || !io.replaySlow.forward_data_valid))
824  XSPerfAccumulate("replay_tlb_miss_lq", io.replaySlow.valid && !io.replaySlow.tlb_hited)
825  XSPerfAccumulate("replay_sl_vio", io.replaySlow.valid && io.replaySlow.tlb_hited && !io.replaySlow.st_ld_check_ok)
826  XSPerfAccumulate("replay_cache_lq", io.replaySlow.valid && io.replaySlow.tlb_hited && io.replaySlow.st_ld_check_ok && !io.replaySlow.cache_no_replay)
827  XSPerfAccumulate("replay_cache_miss_lq", io.replaySlow.valid && !io.replaySlow.cache_hited)
828  XSPerfAccumulate("prefetch", io.in.fire && s2_is_prefetch)
829  XSPerfAccumulate("prefetch_ignored", io.in.fire && s2_is_prefetch && s2_cache_replay) // ignore prefetch for mshr full / miss req port conflict
830  XSPerfAccumulate("prefetch_miss", io.in.fire && s2_is_prefetch && s2_cache_miss) // prefetch req miss in l1
831  XSPerfAccumulate("prefetch_hit", io.in.fire && s2_is_prefetch && !s2_cache_miss) // prefetch req hit in l1
832  // prefetch a missed line in l1, and l1 accepted it
833  XSPerfAccumulate("prefetch_accept", io.in.fire && s2_is_prefetch && s2_cache_miss && !s2_cache_replay)
834}
835
836class LoadUnit(implicit p: Parameters) extends XSModule
837  with HasLoadHelper
838  with HasPerfEvents
839  with HasDCacheParameters
840{
841  val io = IO(new Bundle() {
842    val ldin = Flipped(Decoupled(new ExuInput))
843    val ldout = Decoupled(new ExuOutput)
844    val redirect = Flipped(ValidIO(new Redirect))
845    val feedbackSlow = ValidIO(new RSFeedback)
846    val feedbackFast = ValidIO(new RSFeedback)
847    val rsIdx = Input(UInt(log2Up(IssQueSize).W))
848    val isFirstIssue = Input(Bool())
849    val dcache = new DCacheLoadIO
850    val sbuffer = new LoadForwardQueryIO
851    val lsq = new LoadToLsqIO
852    val tlDchannel = Input(new DcacheToLduForwardIO)
853    val forward_mshr = Flipped(new LduToMissqueueForwardIO)
854    val refill = Flipped(ValidIO(new Refill))
855    val fastUop = ValidIO(new MicroOp) // early wakeup signal generated in load_s1, send to RS in load_s2
856    val trigger = Vec(3, new LoadUnitTriggerIO)
857
858    val tlb = new TlbRequestIO(2)
859    val pmp = Flipped(new PMPRespBundle()) // arrive same to tlb now
860
861    // provide prefetch info
862    val prefetch_train = ValidIO(new LdPrefetchTrainBundle())
863
864    // hardware prefetch to l1 cache req
865    val prefetch_req = Flipped(ValidIO(new L1PrefetchReq))
866
867    // load to load fast path
868    val fastpathOut = Output(new LoadToLoadIO)
869    val fastpathIn = Input(new LoadToLoadIO)
870    val loadFastMatch = Input(Bool())
871    val loadFastImm = Input(UInt(12.W))
872
873    // load ecc
874    val s3_delayed_load_error = Output(Bool()) // load ecc error
875    // Note that io.s3_delayed_load_error and io.lsq.s3_delayed_load_error is different
876
877    // load unit ctrl
878    val csrCtrl = Flipped(new CustomCSRCtrlIO)
879
880    val reExecuteQuery = Flipped(Vec(StorePipelineWidth, Valid(new LoadReExecuteQueryIO)))    // load replay
881    val lsqOut = Flipped(Decoupled(new LsPipelineBundle))
882    val debug_ls = Output(new DebugLsInfoBundle)
883    val s2IsPointerChasing = Output(Bool()) // provide right pc for hw prefetch
884  })
885
886  val load_s0 = Module(new LoadUnit_S0)
887  val load_s1 = Module(new LoadUnit_S1)
888  val load_s2 = Module(new LoadUnit_S2)
889
890  load_s0.io.lsqOut <> io.lsqOut
891
892  // load s0
893  load_s0.io.in <> io.ldin
894  load_s0.io.dtlbReq <> io.tlb.req
895  load_s0.io.dcacheReq <> io.dcache.req
896  load_s0.io.rsIdx := io.rsIdx
897  load_s0.io.isFirstIssue := io.isFirstIssue
898  load_s0.io.s0_kill := false.B
899
900  // we try pointerchasing if lfsrc_l2lForward_select condition is satisfied
901  val s0_tryPointerChasing = load_s0.io.l2lForward_select
902  val s0_pointerChasingVAddr = io.fastpathIn.data(5, 0) +& io.loadFastImm(5, 0)
903  load_s0.io.fastpath.valid := io.fastpathIn.valid
904  load_s0.io.fastpath.data := Cat(io.fastpathIn.data(XLEN-1, 6), s0_pointerChasingVAddr(5,0))
905
906  val s1_data = PipelineConnect(load_s0.io.out, load_s1.io.in, true.B,
907    load_s0.io.out.bits.uop.robIdx.needFlush(io.redirect) && !s0_tryPointerChasing).get
908
909  // load s1
910  // update s1_kill when any source has valid request
911  load_s1.io.s1_kill := RegEnable(load_s0.io.s0_kill, false.B, io.ldin.valid || io.lsqOut.valid || io.fastpathIn.valid)
912  io.tlb.req_kill := load_s1.io.s1_kill
913  load_s1.io.dtlbResp <> io.tlb.resp
914  io.dcache.s1_paddr_dup_lsu <> load_s1.io.lsuPAddr
915  io.dcache.s1_paddr_dup_dcache <> load_s1.io.dcachePAddr
916  io.dcache.s1_kill := load_s1.io.dcacheKill
917  load_s1.io.sbuffer <> io.sbuffer
918  load_s1.io.lsq <> io.lsq.forward
919  load_s1.io.loadViolationQueryReq <> io.lsq.loadViolationQuery.req
920  load_s1.io.dcacheBankConflict <> io.dcache.s1_bank_conflict
921  load_s1.io.csrCtrl <> io.csrCtrl
922  load_s1.io.reExecuteQuery := io.reExecuteQuery
923  // provide paddr and vaddr for lq
924  io.lsq.loadPaddrIn.valid := load_s1.io.out.valid && !load_s1.io.out.bits.isHWPrefetch
925  io.lsq.loadPaddrIn.bits.lqIdx := load_s1.io.out.bits.uop.lqIdx
926  io.lsq.loadPaddrIn.bits.paddr := load_s1.io.lsuPAddr
927
928  io.lsq.loadVaddrIn.valid := load_s1.io.in.valid && !load_s1.io.s1_kill && !load_s1.io.out.bits.isHWPrefetch
929  io.lsq.loadVaddrIn.bits.lqIdx := load_s1.io.out.bits.uop.lqIdx
930  io.lsq.loadVaddrIn.bits.vaddr := load_s1.io.out.bits.vaddr
931
932  // when S0 has opportunity to try pointerchasing, make sure it truely goes to S1
933  // which is S0's out is ready and dcache is ready
934  val s0_doTryPointerChasing = s0_tryPointerChasing && load_s0.io.out.ready && load_s0.io.dcacheReq.ready
935  val s1_tryPointerChasing = RegNext(s0_doTryPointerChasing, false.B)
936  val s1_pointerChasingVAddr = RegEnable(s0_pointerChasingVAddr, s0_doTryPointerChasing)
937  val cancelPointerChasing = WireInit(false.B)
938  if (EnableLoadToLoadForward) {
939    // Sometimes, we need to cancel the load-load forwarding.
940    // These can be put at S0 if timing is bad at S1.
941    // Case 0: CACHE_SET(base + offset) != CACHE_SET(base) (lowest 6-bit addition has an overflow)
942    val addressMisMatch = s1_pointerChasingVAddr(6) || RegEnable(io.loadFastImm(11, 6).orR, s0_doTryPointerChasing)
943    // Case 1: the address is not 64-bit aligned or the fuOpType is not LD
944    val addressNotAligned = s1_pointerChasingVAddr(2, 0).orR
945    val fuOpTypeIsNotLd = io.ldin.bits.uop.ctrl.fuOpType =/= LSUOpType.ld
946    // Case 2: this is not a valid load-load pair
947    val notFastMatch = RegEnable(!io.loadFastMatch, s0_tryPointerChasing)
948    // Case 3: this load-load uop is cancelled
949    val isCancelled = !io.ldin.valid
950    when (s1_tryPointerChasing) {
951      cancelPointerChasing := addressMisMatch || addressNotAligned || fuOpTypeIsNotLd || notFastMatch || isCancelled
952      load_s1.io.in.bits.uop := io.ldin.bits.uop
953      val spec_vaddr = s1_data.vaddr
954      val vaddr = Cat(spec_vaddr(VAddrBits - 1, 6), s1_pointerChasingVAddr(5, 3), 0.U(3.W))
955      load_s1.io.in.bits.vaddr := vaddr
956      load_s1.io.in.bits.rsIdx := io.rsIdx
957      load_s1.io.in.bits.isFirstIssue := io.isFirstIssue
958      // We need to replace vaddr(5, 3).
959      val spec_paddr = io.tlb.resp.bits.paddr(0)
960      load_s1.io.dtlbResp.bits.paddr.foreach(_ := Cat(spec_paddr(PAddrBits - 1, 6), s1_pointerChasingVAddr(5, 3), 0.U(3.W)))
961      // 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)
962      load_s1.io.in.bits.uop.debugInfo.tlbFirstReqTime := GTimer()
963      load_s1.io.in.bits.uop.debugInfo.tlbRespTime := GTimer()
964    }
965    when (cancelPointerChasing) {
966      load_s1.io.s1_kill := true.B
967    }.otherwise {
968      load_s0.io.s0_kill := s1_tryPointerChasing && !io.lsqOut.valid
969      when (s1_tryPointerChasing) {
970        io.ldin.ready := true.B
971      }
972    }
973
974    XSPerfAccumulate("load_to_load_forward", s1_tryPointerChasing && !cancelPointerChasing)
975    XSPerfAccumulate("load_to_load_forward_try", s1_tryPointerChasing)
976    XSPerfAccumulate("load_to_load_forward_fail", cancelPointerChasing)
977    XSPerfAccumulate("load_to_load_forward_fail_cancelled", cancelPointerChasing && isCancelled)
978    XSPerfAccumulate("load_to_load_forward_fail_wakeup_mismatch", cancelPointerChasing && !isCancelled && notFastMatch)
979    XSPerfAccumulate("load_to_load_forward_fail_op_not_ld",
980      cancelPointerChasing && !isCancelled && !notFastMatch && fuOpTypeIsNotLd)
981    XSPerfAccumulate("load_to_load_forward_fail_addr_align",
982      cancelPointerChasing && !isCancelled && !notFastMatch && !fuOpTypeIsNotLd && addressNotAligned)
983    XSPerfAccumulate("load_to_load_forward_fail_set_mismatch",
984      cancelPointerChasing && !isCancelled && !notFastMatch && !fuOpTypeIsNotLd && !addressNotAligned && addressMisMatch)
985  }
986  PipelineConnect(load_s1.io.out, load_s2.io.in, true.B,
987    load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect) || cancelPointerChasing)
988
989  val (forward_D, forwardData_D) = io.tlDchannel.forward(load_s1.io.out.valid && load_s1.io.out.bits.forward_tlDchannel, load_s1.io.out.bits.mshrid, load_s1.io.out.bits.paddr)
990
991  io.forward_mshr.valid := load_s1.io.out.valid && load_s1.io.out.bits.forward_tlDchannel
992  io.forward_mshr.mshrid := load_s1.io.out.bits.mshrid
993  io.forward_mshr.paddr := load_s1.io.out.bits.paddr
994  val (forward_result_valid, forward_mshr, forwardData_mshr) = io.forward_mshr.forward()
995
996  XSPerfAccumulate("successfully_forward_channel_D", forward_D && forward_result_valid)
997  XSPerfAccumulate("successfully_forward_mshr", forward_mshr && forward_result_valid)
998  // load s2
999  load_s2.io.forward_D := forward_D
1000  load_s2.io.forwardData_D := forwardData_D
1001  load_s2.io.forward_result_valid := forward_result_valid
1002  load_s2.io.forward_mshr := forward_mshr
1003  load_s2.io.forwardData_mshr := forwardData_mshr
1004  io.s2IsPointerChasing := RegEnable(s1_tryPointerChasing && !cancelPointerChasing, load_s1.io.out.fire)
1005  io.prefetch_train.bits.fromLsPipelineBundle(load_s2.io.in.bits)
1006  // override miss bit
1007  io.prefetch_train.bits.miss := io.dcache.resp.bits.miss
1008  io.prefetch_train.bits.meta_prefetch := io.dcache.resp.bits.meta_prefetch
1009  io.prefetch_train.bits.meta_access := io.dcache.resp.bits.meta_access
1010  io.prefetch_train.valid := load_s2.io.in.fire && !load_s2.io.out.bits.mmio && !load_s2.io.in.bits.tlbMiss
1011  io.dcache.s2_kill := load_s2.io.dcache_kill // to kill mmio resp which are redirected
1012  if (env.FPGAPlatform)
1013    io.dcache.s2_pc := DontCare
1014  else
1015    io.dcache.s2_pc := load_s2.io.out.bits.uop.cf.pc
1016  load_s2.io.dcacheResp <> io.dcache.resp
1017  load_s2.io.pmpResp <> io.pmp
1018  load_s2.io.static_pm := RegNext(io.tlb.resp.bits.static_pm)
1019  load_s2.io.lsq.forwardData <> io.lsq.forward.forwardData
1020  load_s2.io.lsq.forwardMask <> io.lsq.forward.forwardMask
1021  load_s2.io.lsq.forwardMaskFast <> io.lsq.forward.forwardMaskFast // should not be used in load_s2
1022  load_s2.io.lsq.dataInvalid <> io.lsq.forward.dataInvalid
1023  load_s2.io.lsq.matchInvalid <> io.lsq.forward.matchInvalid
1024  load_s2.io.sbuffer.forwardData <> io.sbuffer.forwardData
1025  load_s2.io.sbuffer.forwardMask <> io.sbuffer.forwardMask
1026  load_s2.io.sbuffer.forwardMaskFast <> io.sbuffer.forwardMaskFast // should not be used in load_s2
1027  load_s2.io.sbuffer.dataInvalid <> io.sbuffer.dataInvalid // always false
1028  load_s2.io.sbuffer.matchInvalid <> io.sbuffer.matchInvalid
1029  load_s2.io.dataForwarded <> io.lsq.s2_load_data_forwarded
1030  load_s2.io.dataInvalidSqIdx := io.lsq.forward.dataInvalidSqIdx // provide dataInvalidSqIdx to make wakeup faster
1031  load_s2.io.loadViolationQueryResp <> io.lsq.loadViolationQuery.resp
1032  load_s2.io.csrCtrl <> io.csrCtrl
1033  load_s2.io.sentFastUop := io.fastUop.valid
1034  load_s2.io.reExecuteQuery := io.reExecuteQuery
1035  // feedback bank conflict / ld-vio check struct hazard to rs
1036  io.feedbackFast.bits := RegNext(load_s1.io.rsFeedback.bits)
1037  io.feedbackFast.valid := RegNext(load_s1.io.rsFeedback.valid && !load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect))
1038
1039  // pre-calcuate sqIdx mask in s0, then send it to lsq in s1 for forwarding
1040  val sqIdxMaskReg = RegNext(UIntToMask(load_s0.io.s0_sqIdx.value, StoreQueueSize))
1041  // to enable load-load, sqIdxMask must be calculated based on ldin.uop
1042  // If the timing here is not OK, load-load forwarding has to be disabled.
1043  // Or we calculate sqIdxMask at RS??
1044  io.lsq.forward.sqIdxMask := sqIdxMaskReg
1045  if (EnableLoadToLoadForward) {
1046    when (s1_tryPointerChasing) {
1047      io.lsq.forward.sqIdxMask := UIntToMask(io.ldin.bits.uop.sqIdx.value, StoreQueueSize)
1048    }
1049  }
1050
1051  // // use s2_hit_way to select data received in s1
1052  // load_s2.io.dcacheResp.bits.data := Mux1H(RegNext(io.dcache.s1_hit_way), RegNext(io.dcache.s1_data))
1053  // assert(load_s2.io.dcacheResp.bits.data === io.dcache.resp.bits.data)
1054
1055  // now io.fastUop.valid is sent to RS in load_s2
1056  val forward_D_or_mshr_valid = forward_result_valid && (forward_D || forward_mshr)
1057  val s2_dcache_hit = io.dcache.s2_hit || forward_D_or_mshr_valid // dcache hit dup in lsu side
1058
1059  io.fastUop.valid := RegNext(
1060      !io.dcache.s1_disable_fast_wakeup &&  // load fast wakeup should be disabled when dcache data read is not ready
1061      load_s1.io.in.valid && // valid load request
1062      !load_s1.io.in.bits.isHWPrefetch && // is not hardware prefetch req
1063      !load_s1.io.s1_kill && // killed by load-load forwarding
1064      !load_s1.io.dtlbResp.bits.fast_miss && // not mmio or tlb miss, pf / af not included here
1065      !io.lsq.forward.dataInvalidFast // forward failed
1066    ) &&
1067    !RegNext(load_s1.io.needLdVioCheckRedo) && // load-load violation check: load paddr cam struct hazard
1068    !RegNext(load_s1.io.needReExecute) &&
1069    !RegNext(load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect)) &&
1070    (load_s2.io.in.valid && !load_s2.io.needReExecute && s2_dcache_hit) // dcache hit in lsu side
1071
1072  io.fastUop.bits := RegNext(load_s1.io.out.bits.uop)
1073
1074  XSDebug(load_s0.io.out.valid,
1075    p"S0: pc ${Hexadecimal(load_s0.io.out.bits.uop.cf.pc)}, lId ${Hexadecimal(load_s0.io.out.bits.uop.lqIdx.asUInt)}, " +
1076    p"vaddr ${Hexadecimal(load_s0.io.out.bits.vaddr)}, mask ${Hexadecimal(load_s0.io.out.bits.mask)}\n")
1077  XSDebug(load_s1.io.out.valid,
1078    p"S1: pc ${Hexadecimal(load_s1.io.out.bits.uop.cf.pc)}, lId ${Hexadecimal(load_s1.io.out.bits.uop.lqIdx.asUInt)}, tlb_miss ${io.tlb.resp.bits.miss}, " +
1079    p"paddr ${Hexadecimal(load_s1.io.out.bits.paddr)}, mmio ${load_s1.io.out.bits.mmio}\n")
1080
1081  // writeback to LSQ
1082  // Current dcache use MSHR
1083  // Load queue will be updated at s2 for both hit/miss int/fp load
1084  io.lsq.loadIn.valid := load_s2.io.out.valid && !load_s2.io.out.bits.isHWPrefetch
1085  // generate LqWriteBundle from LsPipelineBundle
1086  io.lsq.loadIn.bits.fromLsPipelineBundle(load_s2.io.out.bits)
1087
1088  io.lsq.replayFast := load_s1.io.replayFast
1089  io.lsq.replaySlow := load_s2.io.replaySlow
1090  io.lsq.replaySlow.valid := load_s2.io.replaySlow.valid && !load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect)
1091
1092  // generate duplicated load queue data wen
1093  val load_s2_valid_vec = RegInit(0.U(6.W))
1094  val load_s2_leftFire = load_s1.io.out.valid && load_s2.io.in.ready
1095  // val write_lq_safe = load_s2.io.write_lq_safe
1096  load_s2_valid_vec := 0x0.U(6.W)
1097  when (load_s2_leftFire && !load_s1.io.out.bits.isHWPrefetch) { load_s2_valid_vec := 0x3f.U(6.W)} // TODO: refactor me
1098  when (load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect)) { load_s2_valid_vec := 0x0.U(6.W) }
1099  assert(RegNext((load_s2.io.in.valid === load_s2_valid_vec(0)) || RegNext(load_s1.io.out.bits.isHWPrefetch)))
1100  io.lsq.loadIn.bits.lq_data_wen_dup := load_s2_valid_vec.asBools()
1101
1102  // s2_dcache_require_replay signal will be RegNexted, then used in s3
1103  io.lsq.s2_dcache_require_replay := load_s2.io.s2_dcache_require_replay
1104
1105  // write to rob and writeback bus
1106  val s2_wb_valid = load_s2.io.out.valid && !load_s2.io.out.bits.miss && !load_s2.io.out.bits.mmio
1107
1108  // Int load, if hit, will be writebacked at s2
1109  val hitLoadOut = Wire(Valid(new ExuOutput))
1110  hitLoadOut.valid := s2_wb_valid
1111  hitLoadOut.bits.uop := load_s2.io.out.bits.uop
1112  hitLoadOut.bits.data := load_s2.io.out.bits.data
1113  hitLoadOut.bits.redirectValid := false.B
1114  hitLoadOut.bits.redirect := DontCare
1115  hitLoadOut.bits.debug.isMMIO := load_s2.io.out.bits.mmio
1116  hitLoadOut.bits.debug.isPerfCnt := false.B
1117  hitLoadOut.bits.debug.paddr := load_s2.io.out.bits.paddr
1118  hitLoadOut.bits.debug.vaddr := load_s2.io.out.bits.vaddr
1119  hitLoadOut.bits.fflags := DontCare
1120
1121  load_s2.io.out.ready := true.B
1122
1123  // load s3
1124  val s3_load_wb_meta_reg = RegNext(Mux(hitLoadOut.valid, hitLoadOut.bits, io.lsq.ldout.bits))
1125
1126  // data from load queue refill
1127  val s3_loadDataFromLQ = RegEnable(io.lsq.ldRawData, io.lsq.ldout.valid)
1128  val s3_rdataLQ = s3_loadDataFromLQ.mergedData()
1129  val s3_rdataSelLQ = LookupTree(s3_loadDataFromLQ.addrOffset, List(
1130    "b000".U -> s3_rdataLQ(63, 0),
1131    "b001".U -> s3_rdataLQ(63, 8),
1132    "b010".U -> s3_rdataLQ(63, 16),
1133    "b011".U -> s3_rdataLQ(63, 24),
1134    "b100".U -> s3_rdataLQ(63, 32),
1135    "b101".U -> s3_rdataLQ(63, 40),
1136    "b110".U -> s3_rdataLQ(63, 48),
1137    "b111".U -> s3_rdataLQ(63, 56)
1138  ))
1139  val s3_rdataPartialLoadLQ = rdataHelper(s3_loadDataFromLQ.uop, s3_rdataSelLQ)
1140
1141  // data from dcache hit
1142  val s3_loadDataFromDcache = load_s2.io.loadDataFromDcache
1143  val s3_rdataDcache = s3_loadDataFromDcache.mergedData()
1144  val s3_rdataSelDcache = LookupTree(s3_loadDataFromDcache.addrOffset, List(
1145    "b000".U -> s3_rdataDcache(63, 0),
1146    "b001".U -> s3_rdataDcache(63, 8),
1147    "b010".U -> s3_rdataDcache(63, 16),
1148    "b011".U -> s3_rdataDcache(63, 24),
1149    "b100".U -> s3_rdataDcache(63, 32),
1150    "b101".U -> s3_rdataDcache(63, 40),
1151    "b110".U -> s3_rdataDcache(63, 48),
1152    "b111".U -> s3_rdataDcache(63, 56)
1153  ))
1154  val s3_rdataPartialLoadDcache = rdataHelper(s3_loadDataFromDcache.uop, s3_rdataSelDcache)
1155
1156  io.ldout.bits := s3_load_wb_meta_reg
1157  io.ldout.bits.data := Mux(RegNext(hitLoadOut.valid), s3_rdataPartialLoadDcache, s3_rdataPartialLoadLQ)
1158  io.ldout.valid := RegNext(hitLoadOut.valid) && !RegNext(load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect)) ||
1159    RegNext(io.lsq.ldout.valid) && !RegNext(io.lsq.ldout.bits.uop.robIdx.needFlush(io.redirect)) && !RegNext(hitLoadOut.valid)
1160
1161  io.ldout.bits.uop.cf.exceptionVec(loadAccessFault) := s3_load_wb_meta_reg.uop.cf.exceptionVec(loadAccessFault) ||
1162    RegNext(hitLoadOut.valid) && load_s2.io.s3_delayed_load_error
1163
1164  // fast load to load forward
1165  io.fastpathOut.valid := RegNext(load_s2.io.out.valid) // for debug only
1166  io.fastpathOut.data := s3_loadDataFromDcache.mergedData() // fastpath is for ld only
1167
1168  // feedback tlb miss / dcache miss queue full
1169  io.feedbackSlow.bits := RegNext(load_s2.io.rsFeedback.bits)
1170  io.feedbackSlow.valid := RegNext(load_s2.io.rsFeedback.valid && !load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect))
1171  // If replay is reported at load_s1, inst will be canceled (will not enter load_s2),
1172  // in that case:
1173  // * replay should not be reported twice
1174  assert(!(RegNext(io.feedbackFast.valid) && io.feedbackSlow.valid))
1175  // * io.fastUop.valid should not be reported
1176  assert(!RegNext(io.feedbackFast.valid && !io.feedbackFast.bits.hit && io.fastUop.valid))
1177
1178  // load forward_fail/ldld_violation check
1179  // check for inst in load pipeline
1180  val s3_forward_fail = RegNext(io.lsq.forward.matchInvalid || io.sbuffer.matchInvalid)
1181  val s3_ldld_violation = RegNext(
1182    io.lsq.loadViolationQuery.resp.valid &&
1183    io.lsq.loadViolationQuery.resp.bits.have_violation &&
1184    RegNext(io.csrCtrl.ldld_vio_check_enable)
1185  )
1186  val s3_need_replay_from_fetch = s3_forward_fail || s3_ldld_violation
1187  val s3_can_replay_from_fetch = RegEnable(load_s2.io.s2_can_replay_from_fetch, load_s2.io.out.valid)
1188  // 1) use load pipe check result generated in load_s3 iff load_hit
1189  when (RegNext(hitLoadOut.valid)) {
1190    io.ldout.bits.uop.ctrl.replayInst := s3_need_replay_from_fetch
1191  }
1192  // 2) otherwise, write check result to load queue
1193  io.lsq.s3_replay_from_fetch := s3_need_replay_from_fetch && s3_can_replay_from_fetch
1194
1195  // s3_delayed_load_error path is not used for now, as we writeback load result in load_s3
1196  // but we keep this path for future use
1197  io.s3_delayed_load_error := false.B
1198  io.lsq.s3_delayed_load_error := false.B //load_s2.io.s3_delayed_load_error
1199
1200  io.lsq.ldout.ready := !hitLoadOut.valid
1201
1202  when(io.feedbackSlow.valid && !io.feedbackSlow.bits.hit){
1203    // when need replay from rs, inst should not be writebacked to rob
1204    assert(RegNext(!hitLoadOut.valid))
1205    assert(RegNext(!io.lsq.loadIn.valid) || RegNext(load_s2.io.s2_dcache_require_replay))
1206  }
1207
1208  // hareware prefetch to l1
1209  io.prefetch_req <> load_s0.io.prefetch_in
1210
1211  // trigger
1212  val lastValidData = RegEnable(io.ldout.bits.data, io.ldout.fire)
1213  val hitLoadAddrTriggerHitVec = Wire(Vec(3, Bool()))
1214  val lqLoadAddrTriggerHitVec = io.lsq.trigger.lqLoadAddrTriggerHitVec
1215  (0 until 3).map{i => {
1216    val tdata2 = io.trigger(i).tdata2
1217    val matchType = io.trigger(i).matchType
1218    val tEnable = io.trigger(i).tEnable
1219
1220    hitLoadAddrTriggerHitVec(i) := TriggerCmp(load_s2.io.out.bits.vaddr, tdata2, matchType, tEnable)
1221    io.trigger(i).addrHit := Mux(hitLoadOut.valid, hitLoadAddrTriggerHitVec(i), lqLoadAddrTriggerHitVec(i))
1222    io.trigger(i).lastDataHit := TriggerCmp(lastValidData, tdata2, matchType, tEnable)
1223  }}
1224  io.lsq.trigger.hitLoadAddrTriggerHitVec := hitLoadAddrTriggerHitVec
1225
1226  // s1
1227  io.debug_ls.s1.isBankConflict := load_s1.io.in.fire && (!load_s1.io.dcacheKill && load_s1.io.dcacheBankConflict)
1228  io.debug_ls.s1.isLoadToLoadForward := load_s1.io.out.valid && s1_tryPointerChasing && !cancelPointerChasing
1229  io.debug_ls.s1.isTlbFirstMiss := io.tlb.resp.valid && io.tlb.resp.bits.miss && io.tlb.resp.bits.debug.isFirstIssue
1230  io.debug_ls.s1.isReplayFast := io.lsq.replayFast.valid && io.lsq.replayFast.needreplay
1231  io.debug_ls.s1_robIdx := load_s1.io.in.bits.uop.robIdx.value
1232  // s2
1233  io.debug_ls.s2.isDcacheFirstMiss := load_s2.io.in.fire && load_s2.io.in.bits.isFirstIssue && load_s2.io.dcacheResp.bits.miss
1234  io.debug_ls.s2.isForwardFail := load_s2.io.in.fire && load_s2.io.s2_forward_fail
1235  io.debug_ls.s2.isReplaySlow := io.lsq.replaySlow.valid && io.lsq.replaySlow.needreplay
1236  io.debug_ls.s2.isLoadReplayTLBMiss := io.lsq.replaySlow.valid && !io.lsq.replaySlow.tlb_hited
1237  io.debug_ls.s2.isLoadReplayCacheMiss := io.lsq.replaySlow.valid && !io.lsq.replaySlow.cache_hited
1238  io.debug_ls.replayCnt := DontCare
1239  io.debug_ls.s2_robIdx := load_s2.io.in.bits.uop.robIdx.value
1240
1241  // bug lyq: some signals in perfEvents are no longer suitable for the current MemBlock design
1242  // hardware performance counter
1243  val perfEvents = Seq(
1244    ("load_s0_in_fire         ", load_s0.io.in.fire                                                                                                              ),
1245    ("load_to_load_forward    ", load_s1.io.out.valid && s1_tryPointerChasing && !cancelPointerChasing                                                           ),
1246    ("stall_dcache            ", load_s0.io.out.valid && load_s0.io.out.ready && !load_s0.io.dcacheReq.ready                                                     ),
1247    ("load_s1_in_fire         ", load_s1.io.in.fire                                                                                                              ),
1248    ("load_s1_tlb_miss        ", load_s1.io.in.fire && load_s1.io.dtlbResp.bits.miss                                                                             ),
1249    ("load_s2_in_fire         ", load_s2.io.in.fire                                                                                                              ),
1250    ("load_s2_dcache_miss     ", load_s2.io.in.fire && load_s2.io.dcacheResp.bits.miss                                                                           ),
1251    ("load_s2_replay          ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit                                                                  ),
1252    ("load_s2_replay_tlb_miss ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit && load_s2.io.in.bits.tlbMiss                                    ),
1253    ("load_s2_replay_cache    ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit && !load_s2.io.in.bits.tlbMiss && load_s2.io.dcacheResp.bits.miss),
1254  )
1255  generatePerfEvent()
1256
1257  when(io.ldout.fire){
1258    XSDebug("ldout %x\n", io.ldout.bits.uop.cf.pc)
1259  }
1260}
1261