xref: /XiangShan/src/main/scala/xiangshan/mem/MemCommon.scala (revision f7063a43ab34da917ba6c670d21871314340c550)
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
19
20import org.chipsalliance.cde.config.Parameters
21import chisel3._
22import chisel3.util._
23import utility._
24import utils._
25import xiangshan._
26import xiangshan.backend.Bundles.{DynInst, MemExuInput}
27import xiangshan.backend.rob.RobPtr
28import xiangshan.cache._
29import xiangshan.backend.fu.FenceToSbuffer
30import xiangshan.cache.wpu.ReplayCarry
31import xiangshan.mem.prefetch.PrefetchReqBundle
32
33object genWmask {
34  def apply(addr: UInt, sizeEncode: UInt): UInt = {
35    (LookupTree(sizeEncode, List(
36      "b00".U -> 0x1.U, //0001 << addr(2:0)
37      "b01".U -> 0x3.U, //0011
38      "b10".U -> 0xf.U, //1111
39      "b11".U -> 0xff.U //11111111
40    )) << addr(2, 0)).asUInt
41  }
42}
43
44object genVWmask {
45  def apply(addr: UInt, sizeEncode: UInt): UInt = {
46    (LookupTree(sizeEncode, List(
47      "b00".U -> 0x1.U, //0001 << addr(2:0)
48      "b01".U -> 0x3.U, //0011
49      "b10".U -> 0xf.U, //1111
50      "b11".U -> 0xff.U //11111111
51    )) << addr(3, 0)).asUInt
52  }
53}
54
55object genWdata {
56  def apply(data: UInt, sizeEncode: UInt): UInt = {
57    LookupTree(sizeEncode, List(
58      "b00".U -> Fill(16, data(7, 0)),
59      "b01".U -> Fill(8, data(15, 0)),
60      "b10".U -> Fill(4, data(31, 0)),
61      "b11".U -> Fill(2, data(63,0))
62    ))
63  }
64}
65
66object shiftDataToLow {
67  def apply(addr: UInt,data : UInt): UInt = {
68    Mux(addr(3), (data >> 64).asUInt,data)
69  }
70}
71object shiftMaskToLow {
72  def apply(addr: UInt,mask: UInt): UInt = {
73    Mux(addr(3),(mask >> 8).asUInt,mask)
74  }
75}
76
77class LsPipelineBundle(implicit p: Parameters) extends XSBundle
78  with HasDCacheParameters
79  with HasVLSUParameters {
80  val uop = new DynInst
81  val vaddr = UInt(VAddrBits.W)
82  val paddr = UInt(PAddrBits.W)
83  val gpaddr = UInt(GPAddrBits.W)
84  // val func = UInt(6.W)
85  val mask = UInt((VLEN/8).W)
86  val data = UInt((VLEN+1).W)
87  val wlineflag = Bool() // store write the whole cache line
88
89  val miss = Bool()
90  val tlbMiss = Bool()
91  val ptwBack = Bool()
92  val mmio = Bool()
93  val atomic = Bool()
94  val rsIdx = UInt(log2Up(MemIQSizeMax).W)
95
96  val forwardMask = Vec(VLEN/8, Bool())
97  val forwardData = Vec(VLEN/8, UInt(8.W))
98
99  // prefetch
100  val isPrefetch = Bool()
101  val isHWPrefetch = Bool()
102  def isSWPrefetch = isPrefetch && !isHWPrefetch
103
104  // vector
105  val isvec = Bool()
106  val isLastElem = Bool()
107  val is128bit = Bool()
108  val uop_unit_stride_fof = Bool()
109  // val rob_idx_valid = Vec(2,Bool())
110  // val inner_idx = Vec(2,UInt(3.W))
111  // val rob_idx = Vec(2,new RobPtr)
112  val reg_offset = UInt(vOffsetBits.W)
113  // val offset = Vec(2,UInt(4.W))
114  val vecActive = Bool() // 1: vector active element or scala mem operation, 0: vector not active element
115  val is_first_ele = Bool()
116  val flowPtr = new VlflowPtr() // VLFlowQueue ptr
117  val sflowPtr = new VsFlowPtr() // VSFlowQueue ptr
118
119  // For debug usage
120  val isFirstIssue = Bool()
121  val hasROBEntry = Bool()
122
123  // For load replay
124  val isLoadReplay = Bool()
125  val isFastPath = Bool()
126  val isFastReplay = Bool()
127  val replayCarry = new ReplayCarry(nWays)
128
129  // For dcache miss load
130  val mshrid = UInt(log2Up(cfg.nMissEntries).W)
131  val handledByMSHR = Bool()
132  val replacementUpdated = Bool()
133  val missDbUpdated = Bool()
134
135  val forward_tlDchannel = Bool()
136  val dcacheRequireReplay = Bool()
137  val delayedLoadError = Bool()
138  val lateKill = Bool()
139  val feedbacked = Bool()
140  val ldCancel = ValidUndirectioned(UInt(log2Ceil(LoadPipelineWidth).W))
141  // loadQueueReplay index.
142  val schedIndex = UInt(log2Up(LoadQueueReplaySize).W)
143}
144
145class LdPrefetchTrainBundle(implicit p: Parameters) extends LsPipelineBundle {
146  val meta_prefetch = UInt(L1PfSourceBits.W)
147  val meta_access = Bool()
148
149  def fromLsPipelineBundle(input: LsPipelineBundle, latch: Boolean = false) = {
150    if (latch) vaddr := RegNext(input.vaddr) else vaddr := input.vaddr
151    if (latch) paddr := RegNext(input.paddr) else paddr := input.paddr
152    if (latch) gpaddr := RegNext(input.gpaddr) else gpaddr := input.gpaddr
153    if (latch) mask := RegNext(input.mask) else mask := input.mask
154    if (latch) data := RegNext(input.data) else data := input.data
155    if (latch) uop := RegNext(input.uop) else uop := input.uop
156    if (latch) wlineflag := RegNext(input.wlineflag) else wlineflag := input.wlineflag
157    if (latch) miss := RegNext(input.miss) else miss := input.miss
158    if (latch) tlbMiss := RegNext(input.tlbMiss) else tlbMiss := input.tlbMiss
159    if (latch) ptwBack := RegNext(input.ptwBack) else ptwBack := input.ptwBack
160    if (latch) mmio := RegNext(input.mmio) else mmio := input.mmio
161    if (latch) rsIdx := RegNext(input.rsIdx) else rsIdx := input.rsIdx
162    if (latch) forwardMask := RegNext(input.forwardMask) else forwardMask := input.forwardMask
163    if (latch) forwardData := RegNext(input.forwardData) else forwardData := input.forwardData
164    if (latch) isPrefetch := RegNext(input.isPrefetch) else isPrefetch := input.isPrefetch
165    if (latch) isHWPrefetch := RegNext(input.isHWPrefetch) else isHWPrefetch := input.isHWPrefetch
166    if (latch) isFirstIssue := RegNext(input.isFirstIssue) else isFirstIssue := input.isFirstIssue
167    if (latch) hasROBEntry := RegNext(input.hasROBEntry) else hasROBEntry := input.hasROBEntry
168    if (latch) dcacheRequireReplay := RegNext(input.dcacheRequireReplay) else dcacheRequireReplay := input.dcacheRequireReplay
169    if (latch) schedIndex := RegNext(input.schedIndex) else schedIndex := input.schedIndex
170    if (latch) isvec               := RegNext(input.isvec)               else isvec               := input.isvec
171    if (latch) isLastElem          := RegNext(input.isLastElem)          else isLastElem          := input.isLastElem
172    if (latch) is128bit            := RegNext(input.is128bit)            else is128bit            := input.is128bit
173    if (latch) vecActive                 := RegNext(input.vecActive)                 else vecActive                 := input.vecActive
174    if (latch) is_first_ele        := RegNext(input.is_first_ele)        else is_first_ele        := input.is_first_ele
175    if (latch) uop_unit_stride_fof := RegNext(input.uop_unit_stride_fof) else uop_unit_stride_fof := input.uop_unit_stride_fof
176    if (latch) reg_offset          := RegNext(input.reg_offset)          else reg_offset          := input.reg_offset
177    if (latch) flowPtr             := RegNext(input.flowPtr)             else flowPtr             := input.flowPtr
178    if (latch) sflowPtr            := RegNext(input.sflowPtr)            else sflowPtr            := input.sflowPtr
179
180    meta_prefetch := DontCare
181    meta_access := DontCare
182    forward_tlDchannel := DontCare
183    mshrid := DontCare
184    replayCarry := DontCare
185    atomic := DontCare
186    isLoadReplay := DontCare
187    isFastPath := DontCare
188    isFastReplay := DontCare
189    handledByMSHR := DontCare
190    replacementUpdated := DontCare
191    missDbUpdated := DontCare
192    delayedLoadError := DontCare
193    lateKill := DontCare
194    feedbacked := DontCare
195    ldCancel := DontCare
196  }
197
198  def asPrefetchReqBundle(): PrefetchReqBundle = {
199    val res = Wire(new PrefetchReqBundle)
200    res.vaddr := this.vaddr
201    res.paddr := this.paddr
202    res.pc    := this.uop.pc
203
204    res
205  }
206}
207
208class StPrefetchTrainBundle(implicit p: Parameters) extends LdPrefetchTrainBundle {}
209
210class LqWriteBundle(implicit p: Parameters) extends LsPipelineBundle {
211  // load inst replay informations
212  val rep_info = new LoadToLsqReplayIO
213  // queue entry data, except flag bits, will be updated if writeQueue is true,
214  // valid bit in LqWriteBundle will be ignored
215  val data_wen_dup = Vec(6, Bool()) // dirty reg dup
216
217
218  def fromLsPipelineBundle(input: LsPipelineBundle, latch: Boolean = false) = {
219    if(latch) vaddr := RegNext(input.vaddr) else vaddr := input.vaddr
220    if(latch) paddr := RegNext(input.paddr) else paddr := input.paddr
221    if(latch) gpaddr := RegNext(input.gpaddr) else gpaddr := input.gpaddr
222    if(latch) mask := RegNext(input.mask) else mask := input.mask
223    if(latch) data := RegNext(input.data) else data := input.data
224    if(latch) uop := RegNext(input.uop) else uop := input.uop
225    if(latch) wlineflag := RegNext(input.wlineflag) else wlineflag := input.wlineflag
226    if(latch) miss := RegNext(input.miss) else miss := input.miss
227    if(latch) tlbMiss := RegNext(input.tlbMiss) else tlbMiss := input.tlbMiss
228    if(latch) ptwBack := RegNext(input.ptwBack) else ptwBack := input.ptwBack
229    if(latch) mmio := RegNext(input.mmio) else mmio := input.mmio
230    if(latch) atomic := RegNext(input.atomic) else atomic := input.atomic
231    if(latch) rsIdx := RegNext(input.rsIdx) else rsIdx := input.rsIdx
232    if(latch) forwardMask := RegNext(input.forwardMask) else forwardMask := input.forwardMask
233    if(latch) forwardData := RegNext(input.forwardData) else forwardData := input.forwardData
234    if(latch) isPrefetch := RegNext(input.isPrefetch) else isPrefetch := input.isPrefetch
235    if(latch) isHWPrefetch := RegNext(input.isHWPrefetch) else isHWPrefetch := input.isHWPrefetch
236    if(latch) isFirstIssue := RegNext(input.isFirstIssue) else isFirstIssue := input.isFirstIssue
237    if(latch) hasROBEntry := RegNext(input.hasROBEntry) else hasROBEntry := input.hasROBEntry
238    if(latch) isLoadReplay := RegNext(input.isLoadReplay) else isLoadReplay := input.isLoadReplay
239    if(latch) isFastPath := RegNext(input.isFastPath) else isFastPath := input.isFastPath
240    if(latch) isFastReplay := RegNext(input.isFastReplay) else isFastReplay := input.isFastReplay
241    if(latch) mshrid := RegNext(input.mshrid) else mshrid := input.mshrid
242    if(latch) forward_tlDchannel := RegNext(input.forward_tlDchannel) else forward_tlDchannel := input.forward_tlDchannel
243    if(latch) replayCarry := RegNext(input.replayCarry) else replayCarry := input.replayCarry
244    if(latch) dcacheRequireReplay := RegNext(input.dcacheRequireReplay) else dcacheRequireReplay := input.dcacheRequireReplay
245    if(latch) schedIndex := RegNext(input.schedIndex) else schedIndex := input.schedIndex
246    if(latch) handledByMSHR := RegNext(input.handledByMSHR) else handledByMSHR := input.handledByMSHR
247    if(latch) replacementUpdated := RegNext(input.replacementUpdated) else replacementUpdated := input.replacementUpdated
248    if(latch) missDbUpdated := RegNext(input.missDbUpdated) else missDbUpdated := input.missDbUpdated
249    if(latch) delayedLoadError := RegNext(input.delayedLoadError) else delayedLoadError := input.delayedLoadError
250    if(latch) lateKill := RegNext(input.lateKill) else lateKill := input.lateKill
251    if(latch) feedbacked := RegNext(input.feedbacked) else feedbacked := input.feedbacked
252    if(latch) isvec               := RegNext(input.isvec)               else isvec               := input.isvec
253    if(latch) is128bit            := RegNext(input.is128bit)            else is128bit            := input.is128bit
254    if(latch) vecActive                 := RegNext(input.vecActive)                 else vecActive                 := input.vecActive
255    if(latch) uop_unit_stride_fof := RegNext(input.uop_unit_stride_fof) else uop_unit_stride_fof := input.uop_unit_stride_fof
256    if(latch) reg_offset          := RegNext(input.reg_offset)          else reg_offset          := input.reg_offset
257
258    rep_info := DontCare
259    data_wen_dup := DontCare
260  }
261}
262
263class LoadForwardQueryIO(implicit p: Parameters) extends XSBundle {
264  val vaddr = Output(UInt(VAddrBits.W))
265  val paddr = Output(UInt(PAddrBits.W))
266  val gpaddr = Output(UInt(GPAddrBits.W))
267  val mask = Output(UInt((VLEN/8).W))
268  val uop = Output(new DynInst) // for replay
269  val pc = Output(UInt(VAddrBits.W)) //for debug
270  val valid = Output(Bool())
271
272  val forwardMaskFast = Input(Vec((VLEN/8), Bool())) // resp to load_s1
273  val forwardMask = Input(Vec((VLEN/8), Bool())) // resp to load_s2
274  val forwardData = Input(Vec((VLEN/8), UInt(8.W))) // resp to load_s2
275
276  // val lqIdx = Output(UInt(LoadQueueIdxWidth.W))
277  val sqIdx = Output(new SqPtr)
278
279  // dataInvalid suggests store to load forward found forward should happen,
280  // but data is not available for now. If dataInvalid, load inst should
281  // be replayed from RS. Feedback type should be RSFeedbackType.dataInvalid
282  val dataInvalid = Input(Bool()) // Addr match, but data is not valid for now
283
284  // matchInvalid suggests in store to load forward logic, paddr cam result does
285  // to equal to vaddr cam result. If matchInvalid, a microarchitectural exception
286  // should be raised to flush SQ and committed sbuffer.
287  val matchInvalid = Input(Bool()) // resp to load_s2
288
289  // addrInvalid suggests store to load forward found forward should happen,
290  // but address (SSID) is not available for now. If addrInvalid, load inst should
291  // be replayed from RS. Feedback type should be RSFeedbackType.addrInvalid
292  val addrInvalid = Input(Bool())
293}
294
295// LoadForwardQueryIO used in load pipeline
296//
297// Difference between PipeLoadForwardQueryIO and LoadForwardQueryIO:
298// PipeIO use predecoded sqIdxMask for better forward timing
299class PipeLoadForwardQueryIO(implicit p: Parameters) extends LoadForwardQueryIO {
300  // val sqIdx = Output(new SqPtr) // for debug, should not be used in pipeline for timing reasons
301  // sqIdxMask is calcuated in earlier stage for better timing
302  val sqIdxMask = Output(UInt(StoreQueueSize.W))
303
304  // dataInvalid: addr match, but data is not valid for now
305  val dataInvalidFast = Input(Bool()) // resp to load_s1
306  // val dataInvalid = Input(Bool()) // resp to load_s2
307  val dataInvalidSqIdx = Input(new SqPtr) // resp to load_s2, sqIdx
308  val addrInvalidSqIdx = Input(new SqPtr) // resp to load_s2, sqIdx
309}
310
311// Query load queue for ld-ld violation
312//
313// Req should be send in load_s1
314// Resp will be generated 1 cycle later
315//
316// Note that query req may be !ready, as dcache is releasing a block
317// If it happens, a replay from rs is needed.
318class LoadNukeQueryReq(implicit p: Parameters) extends XSBundle { // provide lqIdx
319  val uop = new DynInst
320  // mask: load's data mask.
321  val mask = UInt((VLEN/8).W)
322
323  // paddr: load's paddr.
324  val paddr      = UInt(PAddrBits.W)
325  // dataInvalid: load data is invalid.
326  val data_valid = Bool()
327}
328
329class LoadNukeQueryResp(implicit p: Parameters) extends XSBundle {
330  // rep_frm_fetch: ld-ld violation check success, replay from fetch.
331  val rep_frm_fetch = Bool()
332}
333
334class LoadNukeQueryIO(implicit p: Parameters) extends XSBundle {
335  val req    = Decoupled(new LoadNukeQueryReq)
336  val resp   = Flipped(Valid(new LoadNukeQueryResp))
337  val revoke = Output(Bool())
338}
339
340class StoreNukeQueryIO(implicit p: Parameters) extends XSBundle {
341  //  robIdx: Requestor's (a store instruction) rob index for match logic.
342  val robIdx = new RobPtr
343
344  //  paddr: requestor's (a store instruction) physical address for match logic.
345  val paddr  = UInt(PAddrBits.W)
346
347  //  mask: requestor's (a store instruction) data width mask for match logic.
348  val mask = UInt((VLEN/8).W)
349}
350
351// Store byte valid mask write bundle
352//
353// Store byte valid mask write to SQ takes 2 cycles
354class StoreMaskBundle(implicit p: Parameters) extends XSBundle {
355  val sqIdx = new SqPtr
356  val mask = UInt((VLEN/8).W)
357}
358
359class LoadDataFromDcacheBundle(implicit p: Parameters) extends DCacheBundle {
360  // old dcache: optimize data sram read fanout
361  // val bankedDcacheData = Vec(DCacheBanks, UInt(64.W))
362  // val bank_oh = UInt(DCacheBanks.W)
363
364  // new dcache
365  val respDcacheData = UInt(VLEN.W)
366  val forwardMask = Vec(VLEN/8, Bool())
367  val forwardData = Vec(VLEN/8, UInt(8.W))
368  val uop = new DynInst // for data selection, only fwen and fuOpType are used
369  val addrOffset = UInt(4.W) // for data selection
370
371  // forward tilelink D channel
372  val forward_D = Bool()
373  val forwardData_D = Vec(VLEN/8, UInt(8.W))
374
375  // forward mshr data
376  val forward_mshr = Bool()
377  val forwardData_mshr = Vec(VLEN/8, UInt(8.W))
378
379  val forward_result_valid = Bool()
380
381  def dcacheData(): UInt = {
382    // old dcache
383    // val dcache_data = Mux1H(bank_oh, bankedDcacheData)
384    // new dcache
385    val dcache_data = respDcacheData
386    val use_D = forward_D && forward_result_valid
387    val use_mshr = forward_mshr && forward_result_valid
388    Mux(use_D, forwardData_D.asUInt, Mux(use_mshr, forwardData_mshr.asUInt, dcache_data))
389  }
390
391  def mergedData(): UInt = {
392    val rdataVec = VecInit((0 until VLEN / 8).map(j =>
393      Mux(forwardMask(j), forwardData(j), dcacheData()(8*(j+1)-1, 8*j))
394    ))
395    rdataVec.asUInt
396  }
397}
398
399// Load writeback data from load queue (refill)
400class LoadDataFromLQBundle(implicit p: Parameters) extends XSBundle {
401  val lqData = UInt(64.W) // load queue has merged data
402  val uop = new DynInst // for data selection, only fwen and fuOpType are used
403  val addrOffset = UInt(3.W) // for data selection
404
405  def mergedData(): UInt = {
406    lqData
407  }
408}
409
410// Bundle for load / store wait waking up
411class MemWaitUpdateReq(implicit p: Parameters) extends XSBundle {
412  val robIdx = Vec(backendParams.StaExuCnt, ValidIO(new RobPtr))
413  val sqIdx = Vec(backendParams.StdCnt, ValidIO(new SqPtr))
414}
415
416object AddPipelineReg {
417  class PipelineRegModule[T <: Data](gen: T) extends Module {
418    val io = IO(new Bundle() {
419      val in = Flipped(DecoupledIO(gen.cloneType))
420      val out = DecoupledIO(gen.cloneType)
421      val isFlush = Input(Bool())
422    })
423
424    val valid = RegInit(false.B)
425    valid.suggestName("pipeline_reg_valid")
426    when (io.out.fire) { valid := false.B }
427    when (io.in.fire) { valid := true.B }
428    when (io.isFlush) { valid := false.B }
429
430    io.in.ready := !valid || io.out.ready
431    io.out.bits := RegEnable(io.in.bits, io.in.fire)
432    io.out.valid := valid //&& !isFlush
433  }
434
435  def apply[T <: Data]
436  (left: DecoupledIO[T], right: DecoupledIO[T], isFlush: Bool,
437   moduleName: Option[String] = None
438  ){
439    val pipelineReg = Module(new PipelineRegModule[T](left.bits.cloneType))
440    if(moduleName.nonEmpty) pipelineReg.suggestName(moduleName.get)
441    pipelineReg.io.in <> left
442    right <> pipelineReg.io.out
443    pipelineReg.io.isFlush := isFlush
444  }
445}
446