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