xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/LoadQueueRAW.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
19import chisel3._
20import chisel3.util._
21import org.chipsalliance.cde.config._
22import xiangshan._
23import xiangshan.backend.rob.RobPtr
24import xiangshan.cache._
25import xiangshan.frontend.FtqPtr
26import xiangshan.mem.mdp._
27import utils._
28import utility._
29import xiangshan.backend.Bundles.DynInst
30
31class LoadQueueRAW(implicit p: Parameters) extends XSModule
32  with HasDCacheParameters
33  with HasCircularQueuePtrHelper
34  with HasLoadHelper
35  with HasPerfEvents
36{
37  val io = IO(new Bundle() {
38    // control
39    val redirect = Flipped(ValidIO(new Redirect))
40
41    // violation query
42    val query = Vec(LoadPipelineWidth, Flipped(new LoadNukeQueryIO))
43
44    // from store unit s1
45    val storeIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle)))
46    val vecStoreIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle)))
47
48    // global rollback flush
49    val rollback = Output(Valid(new Redirect))
50
51    // to LoadQueueReplay
52    val stAddrReadySqPtr = Input(new SqPtr)
53    val stIssuePtr       = Input(new SqPtr)
54    val lqFull           = Output(Bool())
55  })
56
57  println("LoadQueueRAW: size " + LoadQueueRAWSize)
58  //  LoadQueueRAW field
59  //  +-------+--------+-------+-------+-----------+
60  //  | Valid |  uop   |PAddr  | Mask  | Datavalid |
61  //  +-------+--------+-------+-------+-----------+
62  //
63  //  Field descriptions:
64  //  Allocated   : entry has been allocated already
65  //  MicroOp     : inst's microOp
66  //  PAddr       : physical address.
67  //  Mask        : data mask
68  //  Datavalid   : data valid
69  //
70  val allocated = RegInit(VecInit(List.fill(LoadQueueRAWSize)(false.B))) // The control signals need to explicitly indicate the initial value
71  val uop = Reg(Vec(LoadQueueRAWSize, new DynInst))
72  val paddrModule = Module(new LqPAddrModule(
73    gen = UInt(PAddrBits.W),
74    numEntries = LoadQueueRAWSize,
75    numRead = LoadPipelineWidth,
76    numWrite = LoadPipelineWidth,
77    numWBank = LoadQueueNWriteBanks,
78    numWDelay = 2,
79    numCamPort = StorePipelineWidth
80  ))
81  paddrModule.io := DontCare
82  val maskModule = Module(new LqMaskModule(
83    gen = UInt((VLEN/8).W),
84    numEntries = LoadQueueRAWSize,
85    numRead = LoadPipelineWidth,
86    numWrite = LoadPipelineWidth,
87    numWBank = LoadQueueNWriteBanks,
88    numWDelay = 2,
89    numCamPort = StorePipelineWidth
90  ))
91  maskModule.io := DontCare
92  val datavalid = RegInit(VecInit(List.fill(LoadQueueRAWSize)(false.B)))
93
94  // freeliset: store valid entries index.
95  // +---+---+--------------+-----+-----+
96  // | 0 | 1 |      ......  | n-2 | n-1 |
97  // +---+---+--------------+-----+-----+
98  val freeList = Module(new FreeList(
99    size = LoadQueueRAWSize,
100    allocWidth = LoadPipelineWidth,
101    freeWidth = 4,
102    enablePreAlloc = true,
103    moduleName = "LoadQueueRAW freelist"
104  ))
105  freeList.io := DontCare
106
107  //  LoadQueueRAW enqueue
108  val canEnqueue = io.query.map(_.req.valid)
109  val cancelEnqueue = io.query.map(_.req.bits.uop.robIdx.needFlush(io.redirect))
110  val allAddrCheck = io.stIssuePtr === io.stAddrReadySqPtr
111  val hasAddrInvalidStore = io.query.map(_.req.bits.uop.sqIdx).map(sqIdx => {
112    Mux(!allAddrCheck, isBefore(io.stAddrReadySqPtr, sqIdx), false.B)
113  })
114  val needEnqueue = canEnqueue.zip(hasAddrInvalidStore).zip(cancelEnqueue).map { case ((v, r), c) => v && r && !c }
115
116  // Allocate logic
117  val acceptedVec = Wire(Vec(LoadPipelineWidth, Bool()))
118  val enqIndexVec = Wire(Vec(LoadPipelineWidth, UInt()))
119
120  // Enqueue
121  for ((enq, w) <- io.query.map(_.req).zipWithIndex) {
122    acceptedVec(w) := false.B
123    paddrModule.io.wen(w) := false.B
124    maskModule.io.wen(w) := false.B
125    freeList.io.doAllocate(w) := false.B
126
127    freeList.io.allocateReq(w) := true.B
128
129    //  Allocate ready
130    val offset = PopCount(needEnqueue.take(w))
131    val canAccept = freeList.io.canAllocate(offset)
132    val enqIndex = freeList.io.allocateSlot(offset)
133    enq.ready := Mux(needEnqueue(w), canAccept, true.B)
134
135    enqIndexVec(w) := enqIndex
136    when (needEnqueue(w) && enq.ready) {
137      acceptedVec(w) := true.B
138
139      val debug_robIdx = enq.bits.uop.robIdx.asUInt
140      XSError(allocated(enqIndex), p"LoadQueueRAW: You can not write an valid entry! check: ldu $w, robIdx $debug_robIdx")
141
142      freeList.io.doAllocate(w) := true.B
143
144      //  Allocate new entry
145      allocated(enqIndex) := true.B
146
147      //  Write paddr
148      paddrModule.io.wen(w) := true.B
149      paddrModule.io.waddr(w) := enqIndex
150      paddrModule.io.wdata(w) := enq.bits.paddr
151
152      //  Write mask
153      maskModule.io.wen(w) := true.B
154      maskModule.io.waddr(w) := enqIndex
155      maskModule.io.wdata(w) := enq.bits.mask
156
157      //  Fill info
158      uop(enqIndex) := enq.bits.uop
159      datavalid(enqIndex) := enq.bits.data_valid
160    }
161  }
162
163  for ((query, w) <- io.query.map(_.resp).zipWithIndex) {
164    query.valid := RegNext(io.query(w).req.valid)
165    query.bits.rep_frm_fetch := RegNext(false.B)
166  }
167
168  //  LoadQueueRAW deallocate
169  val freeMaskVec = Wire(Vec(LoadQueueRAWSize, Bool()))
170
171  // init
172  freeMaskVec.map(e => e := false.B)
173
174  // when the stores that "older than" current load address were ready.
175  // current load will be released.
176  for (i <- 0 until LoadQueueRAWSize) {
177    val deqNotBlock = Mux(!allAddrCheck, !isBefore(io.stAddrReadySqPtr, uop(i).sqIdx), true.B)
178    val needCancel = uop(i).robIdx.needFlush(io.redirect)
179
180    when (allocated(i) && (deqNotBlock || needCancel)) {
181      allocated(i) := false.B
182      freeMaskVec(i) := true.B
183    }
184  }
185
186  // if need replay deallocate entry
187  val lastCanAccept = RegNext(acceptedVec)
188  val lastAllocIndex = RegNext(enqIndexVec)
189
190  for ((revoke, w) <- io.query.map(_.revoke).zipWithIndex) {
191    val revokeValid = revoke && lastCanAccept(w)
192    val revokeIndex = lastAllocIndex(w)
193
194    when (allocated(revokeIndex) && revokeValid) {
195      allocated(revokeIndex) := false.B
196      freeMaskVec(revokeIndex) := true.B
197    }
198  }
199  freeList.io.free := freeMaskVec.asUInt
200
201  io.lqFull := freeList.io.empty
202
203  /**
204    * Store-Load Memory violation detection
205    * Scheme 1(Current scheme): flush the pipeline then re-fetch from the load instruction (like old load queue).
206    * Scheme 2                : re-fetch instructions from the first instruction after the store instruction.
207    *
208    * When store writes back, it searches LoadQueue for younger load instructions
209    * with the same load physical address. They loaded wrong data and need re-execution.
210    *
211    * Cycle 0: Store Writeback
212    *   Generate match vector for store address with rangeMask(stPtr, enqPtr).
213    * Cycle 1: Select oldest load from select group.
214    * Cycle x: Redirect Fire
215    *   Choose the oldest load from LoadPipelineWidth oldest loads.
216    *   Prepare redirect request according to the detected violation.
217    *   Fire redirect request (if valid)
218    */
219  //              SelectGroup 0         SelectGroup 1          SelectGroup y
220  // stage 0:       lq  lq  lq  ......    lq  lq  lq  .......    lq  lq  lq
221  //                |   |   |             |   |   |              |   |   |
222  // stage 1:       lq  lq  lq  ......    lq  lq  lq  .......    lq  lq  lq
223  //                 \  |  /    ......     \  |  /    .......     \  |  /
224  // stage 2:           lq                    lq                     lq
225  //                     \  |  /  .......  \  |  /   ........  \  |  /
226  // stage 3:               lq                lq                  lq
227  //                                          ...
228  //                                          ...
229  //                                           |
230  // stage x:                                  lq
231  //                                           |
232  //                                       rollback req
233
234  // select logic
235  val SelectGroupSize = RollbackGroupSize
236  val lgSelectGroupSize = log2Ceil(SelectGroupSize)
237  val TotalSelectCycles = scala.math.ceil(log2Ceil(LoadQueueRAWSize).toFloat / lgSelectGroupSize).toInt + 1
238
239  def selectPartialOldest[T <: XSBundleWithMicroOp](valid: Seq[Bool], bits: Seq[T]): (Seq[Bool], Seq[T]) = {
240    assert(valid.length == bits.length)
241    if (valid.length == 0 || valid.length == 1) {
242      (valid, bits)
243    } else if (valid.length == 2) {
244      val res = Seq.fill(2)(Wire(ValidIO(chiselTypeOf(bits(0)))))
245      for (i <- res.indices) {
246        res(i).valid := valid(i)
247        res(i).bits := bits(i)
248      }
249      val oldest = Mux(valid(0) && valid(1), Mux(isAfter(bits(0).uop.robIdx, bits(1).uop.robIdx), res(1), res(0)), Mux(valid(0) && !valid(1), res(0), res(1)))
250      (Seq(oldest.valid), Seq(oldest.bits))
251    } else {
252      val left = selectPartialOldest(valid.take(valid.length / 2), bits.take(bits.length / 2))
253      val right = selectPartialOldest(valid.takeRight(valid.length - (valid.length / 2)), bits.takeRight(bits.length - (bits.length / 2)))
254      selectPartialOldest(left._1 ++ right._1, left._2 ++ right._2)
255    }
256  }
257
258  def selectOldest[T <: XSBundleWithMicroOp](valid: Seq[Bool], bits: Seq[T]): (Seq[Bool], Seq[T]) = {
259    assert(valid.length == bits.length)
260    val numSelectGroups = scala.math.ceil(valid.length.toFloat / SelectGroupSize).toInt
261
262    // group info
263    val selectValidGroups =
264      if (valid.length <= SelectGroupSize) {
265        Seq(valid)
266      } else {
267        (0 until numSelectGroups).map(g => {
268          if (valid.length < (g + 1) * SelectGroupSize) {
269            valid.takeRight(valid.length - g * SelectGroupSize)
270          } else {
271            (0 until SelectGroupSize).map(j => valid(g * SelectGroupSize + j))
272          }
273        })
274      }
275    val selectBitsGroups =
276      if (bits.length <= SelectGroupSize) {
277        Seq(bits)
278      } else {
279        (0 until numSelectGroups).map(g => {
280          if (bits.length < (g + 1) * SelectGroupSize) {
281            bits.takeRight(bits.length - g * SelectGroupSize)
282          } else {
283            (0 until SelectGroupSize).map(j => bits(g * SelectGroupSize + j))
284          }
285        })
286      }
287
288    // select logic
289    if (valid.length <= SelectGroupSize) {
290      val (selValid, selBits) = selectPartialOldest(valid, bits)
291      val selValidNext = RegNext(selValid(0))
292      val selBitsNext = RegNext(selBits(0))
293      (Seq(selValidNext && !selBitsNext.uop.robIdx.needFlush(io.redirect) && !selBitsNext.uop.robIdx.needFlush(RegNext(io.redirect))), Seq(selBitsNext))
294    } else {
295      val select = (0 until numSelectGroups).map(g => {
296        val (selValid, selBits) = selectPartialOldest(selectValidGroups(g), selectBitsGroups(g))
297        val selValidNext = RegNext(selValid(0))
298        val selBitsNext = RegNext(selBits(0))
299        (selValidNext && !selBitsNext.uop.robIdx.needFlush(io.redirect) && !selBitsNext.uop.robIdx.needFlush(RegNext(io.redirect)), selBitsNext)
300      })
301      selectOldest(select.map(_._1), select.map(_._2))
302    }
303  }
304
305  val storeIn = (io.storeIn zip io.vecStoreIn).map { case (scalar, vector) =>
306    Mux(vector.valid, vector, scalar)
307  }
308
309  def detectRollback(i: Int) = {
310    paddrModule.io.violationMdata(i) := RegNext(storeIn(i).bits.paddr)
311    maskModule.io.violationMdata(i) := RegNext(storeIn(i).bits.mask)
312
313    val addrMaskMatch = paddrModule.io.violationMmask(i).asUInt & maskModule.io.violationMmask(i).asUInt
314    val entryNeedCheck = RegNext(VecInit((0 until LoadQueueRAWSize).map(j => {
315      allocated(j) && isAfter(uop(j).robIdx, storeIn(i).bits.uop.robIdx) && datavalid(j) && !uop(j).robIdx.needFlush(io.redirect)
316    })))
317    val lqViolationSelVec = VecInit((0 until LoadQueueRAWSize).map(j => {
318      addrMaskMatch(j) && entryNeedCheck(j)
319    }))
320
321    val lqViolationSelUopExts = uop.map(uop => {
322      val wrapper = Wire(new XSBundleWithMicroOp)
323      wrapper.uop := uop
324      wrapper
325    })
326
327    // select logic
328    val lqSelect = selectOldest(lqViolationSelVec, lqViolationSelUopExts)
329
330    // select one inst
331    val lqViolation = lqSelect._1(0)
332    val lqViolationUop = lqSelect._2(0).uop
333
334    XSDebug(
335      lqViolation,
336      "need rollback (ld wb before store) pc %x robidx %d target %x\n",
337      storeIn(i).bits.uop.pc, storeIn(i).bits.uop.robIdx.asUInt, lqViolationUop.robIdx.asUInt
338    )
339
340    (lqViolation, lqViolationUop)
341  }
342
343  // select rollback (part1) and generate rollback request
344  // rollback check
345  // Lq rollback seq check is done in s3 (next stage), as getting rollbackLq MicroOp is slow
346  val rollbackLqWb = Wire(Vec(StorePipelineWidth, Valid(new DynInst)))
347  val stFtqIdx = Wire(Vec(StorePipelineWidth, new FtqPtr))
348  val stFtqOffset = Wire(Vec(StorePipelineWidth, UInt(log2Up(PredictWidth).W)))
349  for (w <- 0 until StorePipelineWidth) {
350    val detectedRollback = detectRollback(w)
351    rollbackLqWb(w).valid := detectedRollback._1 && DelayN(storeIn(w).valid && !storeIn(w).bits.miss, TotalSelectCycles)
352    rollbackLqWb(w).bits  := detectedRollback._2
353    stFtqIdx(w) := DelayN(storeIn(w).bits.uop.ftqPtr, TotalSelectCycles)
354    stFtqOffset(w) := DelayN(storeIn(w).bits.uop.ftqOffset, TotalSelectCycles)
355  }
356
357  // select rollback (part2), generate rollback request, then fire rollback request
358  // Note that we use robIdx - 1.U to flush the load instruction itself.
359  // Thus, here if last cycle's robIdx equals to this cycle's robIdx, it still triggers the redirect.
360
361  // select uop in parallel
362  def selectOldestRedirect(xs: Seq[Valid[Redirect]]): Vec[Bool] = {
363    val compareVec = (0 until xs.length).map(i => (0 until i).map(j => isAfter(xs(j).bits.robIdx, xs(i).bits.robIdx)))
364    val resultOnehot = VecInit((0 until xs.length).map(i => Cat((0 until xs.length).map(j =>
365      (if (j < i) !xs(j).valid || compareVec(i)(j)
366      else if (j == i) xs(i).valid
367      else !xs(j).valid || !compareVec(j)(i))
368    )).andR))
369    resultOnehot
370  }
371  val allRedirect = (0 until StorePipelineWidth).map(i => {
372    val redirect = Wire(Valid(new Redirect))
373    redirect.valid := rollbackLqWb(i).valid
374    redirect.bits             := DontCare
375    redirect.bits.isRVC       := rollbackLqWb(i).bits.preDecodeInfo.isRVC
376    redirect.bits.robIdx      := rollbackLqWb(i).bits.robIdx
377    redirect.bits.ftqIdx      := rollbackLqWb(i).bits.ftqPtr
378    redirect.bits.ftqOffset   := rollbackLqWb(i).bits.ftqOffset
379    redirect.bits.stFtqIdx    := stFtqIdx(i)
380    redirect.bits.stFtqOffset := stFtqOffset(i)
381    redirect.bits.level       := RedirectLevel.flush
382    redirect.bits.cfiUpdate.target := rollbackLqWb(i).bits.pc
383    redirect.bits.debug_runahead_checkpoint_id := rollbackLqWb(i).bits.debugInfo.runahead_checkpoint_id
384    redirect
385  })
386  val oldestOneHot = selectOldestRedirect(allRedirect)
387  val oldestRedirect = Mux1H(oldestOneHot, allRedirect)
388  io.rollback := oldestRedirect
389
390  // perf cnt
391  val canEnqCount = PopCount(io.query.map(_.req.fire))
392  val validCount = freeList.io.validCount
393  val allowEnqueue = validCount <= (LoadQueueRAWSize - LoadPipelineWidth).U
394
395  QueuePerf(LoadQueueRAWSize, validCount, !allowEnqueue)
396  XSPerfAccumulate("enqs", canEnqCount)
397  XSPerfAccumulate("stld_rollback", io.rollback.valid)
398  val perfEvents: Seq[(String, UInt)] = Seq(
399    ("enq ", canEnqCount),
400    ("stld_rollback", io.rollback.valid),
401  )
402  generatePerfEvent()
403  // end
404}