xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/VirtualLoadQueue.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***************************************************************************************/
16package xiangshan.mem
17
18import chisel3._
19import chisel3.util._
20import org.chipsalliance.cde.config._
21import xiangshan._
22import xiangshan.backend.rob.{RobLsqIO, RobPtr}
23import xiangshan.ExceptionNO._
24import xiangshan.cache._
25import utils._
26import utility._
27import xiangshan.backend.Bundles.{DynInst, MemExuOutput}
28import xiangshan.backend.fu.FuConfig.LduCfg
29
30class VirtualLoadQueue(implicit p: Parameters) extends XSModule
31  with HasDCacheParameters
32  with HasCircularQueuePtrHelper
33  with HasLoadHelper
34  with HasPerfEvents
35{
36  val io = IO(new Bundle() {
37    // control
38    val redirect    = Flipped(Valid(new Redirect))
39    // from dispatch
40    val enq         = new LqEnqIO
41    // from ldu s3
42    val ldin        = Vec(LoadPipelineWidth, Flipped(DecoupledIO(new LqWriteBundle)))
43    // to LoadQueueReplay and LoadQueueRAR
44    val ldWbPtr     = Output(new LqPtr)
45    // global
46    val lqFull      = Output(Bool())
47    val lqEmpty     = Output(Bool())
48    // to dispatch
49    val lqDeq       = Output(UInt(log2Up(CommitWidth + 1).W))
50    val lqCancelCnt = Output(UInt(log2Up(VirtualLoadQueueSize+1).W))
51    // vector load writeback
52    val vecWriteback = Flipped(ValidIO(new MemExuOutput(isVector = true)))
53  })
54
55  println("VirtualLoadQueue: size: " + VirtualLoadQueueSize)
56  //  VirtualLoadQueue field
57  //  +-----------+---------+-------+
58  //  | Allocated | MicroOp | Flags |
59  //  +-----------+---------+-------+
60  //  Allocated   : entry has been allocated already
61  //  MicroOp     : inst's microOp
62  //  Flags       : load flags
63  val allocated = RegInit(VecInit(List.fill(VirtualLoadQueueSize)(false.B))) // The control signals need to explicitly indicate the initial value
64  val uop = Reg(Vec(VirtualLoadQueueSize, new DynInst))
65  val addrvalid = RegInit(VecInit(List.fill(VirtualLoadQueueSize)(false.B))) // non-mmio addr is valid
66  val datavalid = RegInit(VecInit(List.fill(VirtualLoadQueueSize)(false.B))) // non-mmio data is valid
67
68  /**
69   * used for debug
70   */
71  val debug_mmio = Reg(Vec(VirtualLoadQueueSize, Bool())) // mmio: inst is an mmio inst
72  val debug_paddr = Reg(Vec(VirtualLoadQueueSize, UInt(PAddrBits.W))) // mmio: inst's paddr
73
74  //  maintain pointers
75  val enqPtrExt = RegInit(VecInit((0 until io.enq.req.length).map(_.U.asTypeOf(new LqPtr))))
76  val enqPtr = enqPtrExt(0).value
77  val deqPtr = Wire(new LqPtr)
78  val deqPtrNext = Wire(new LqPtr)
79
80  /**
81   * update pointer
82   */
83  val lastCycleRedirect = RegNext(io.redirect)
84  val lastLastCycleRedirect = RegNext(lastCycleRedirect)
85
86  val validCount = distanceBetween(enqPtrExt(0), deqPtr)
87  val allowEnqueue = validCount <= (VirtualLoadQueueSize - LSQLdEnqWidth).U
88  val canEnqueue = io.enq.req.map(_.valid)
89  val needCancel = WireInit(VecInit((0 until VirtualLoadQueueSize).map(i => {
90    uop(i).robIdx.needFlush(io.redirect) && allocated(i)
91  })))
92  val lastNeedCancel = RegNext(needCancel)
93  val enqCancel = io.enq.req.map(_.bits.robIdx.needFlush(io.redirect))
94  val lastEnqCancel = PopCount(RegNext(VecInit(canEnqueue.zip(enqCancel).map(x => x._1 && x._2))))
95  val lastCycleCancelCount = PopCount(lastNeedCancel)
96  val redirectCancelCount = RegEnable(lastCycleCancelCount + lastEnqCancel, 0.U, lastCycleRedirect.valid)
97
98  // update enqueue pointer
99  val enqNumber = Mux(io.enq.canAccept && io.enq.sqCanAccept, PopCount(io.enq.req.map(_.valid)), 0.U)
100  val enqPtrExtNextVec = Wire(Vec(io.enq.req.length, new LqPtr))
101  val enqPtrExtNext = Wire(Vec(io.enq.req.length, new LqPtr))
102  when (lastLastCycleRedirect.valid) {
103    // we recover the pointers in the next cycle after redirect
104    enqPtrExtNextVec := VecInit(enqPtrExt.map(_ - redirectCancelCount))
105  } .otherwise {
106    enqPtrExtNextVec := VecInit(enqPtrExt.map(_ + enqNumber))
107  }
108  assert(!(lastCycleRedirect.valid && enqNumber =/= 0.U))
109
110  when (isAfter(enqPtrExtNextVec(0), deqPtrNext)) {
111    enqPtrExtNext := enqPtrExtNextVec
112  } .otherwise {
113    enqPtrExtNext := VecInit((0 until io.enq.req.length).map(i => deqPtrNext + i.U))
114  }
115  enqPtrExt := enqPtrExtNext
116
117  // update dequeue pointer
118  val DeqPtrMoveStride = CommitWidth
119  require(DeqPtrMoveStride == CommitWidth, "DeqPtrMoveStride must be equal to CommitWidth!")
120  val deqLookupVec = VecInit((0 until DeqPtrMoveStride).map(deqPtr + _.U))
121  val deqLookup = VecInit(deqLookupVec.map(ptr => allocated(ptr.value) && datavalid(ptr.value) && addrvalid(ptr.value) && ptr =/= enqPtrExt(0)))
122  val deqInSameRedirectCycle = VecInit(deqLookupVec.map(ptr => needCancel(ptr.value)))
123  // make chisel happy
124  val deqCountMask = Wire(UInt(DeqPtrMoveStride.W))
125  deqCountMask := deqLookup.asUInt & (~deqInSameRedirectCycle.asUInt).asUInt
126  val commitCount = PopCount(PriorityEncoderOH(~deqCountMask) - 1.U)
127  val lastCommitCount = RegNext(commitCount)
128
129  // update deqPtr
130  // cycle 1: generate deqPtrNext
131  // cycle 2: update deqPtr
132  val deqPtrUpdateEna = lastCommitCount =/= 0.U
133  deqPtrNext := deqPtr + lastCommitCount
134  deqPtr := RegEnable(deqPtrNext, 0.U.asTypeOf(new LqPtr), deqPtrUpdateEna)
135
136  io.lqDeq := RegNext(lastCommitCount)
137  io.lqCancelCnt := redirectCancelCount
138  io.ldWbPtr := deqPtr
139  io.lqEmpty := RegNext(validCount === 0.U)
140
141  /**
142   * Enqueue at dispatch
143   *
144   * Currently, VirtualLoadQueue only allows enqueue when #emptyEntries > EnqWidth
145   */
146  io.enq.canAccept := allowEnqueue
147  for (i <- 0 until io.enq.req.length) {
148    val offset = PopCount(io.enq.needAlloc.take(i))
149    val lqIdx = enqPtrExt(offset)
150    val index = io.enq.req(i).bits.lqIdx.value
151    when (canEnqueue(i) && !enqCancel(i)) {
152      allocated(index) := true.B
153      uop(index) := io.enq.req(i).bits
154      uop(index).lqIdx := lqIdx
155
156      // init
157      addrvalid(index) := false.B
158      datavalid(index) := false.B
159
160      debug_mmio(index) := false.B
161      debug_paddr(index) := 0.U
162
163      XSError(!io.enq.canAccept || !io.enq.sqCanAccept, s"must accept $i\n")
164      XSError(index =/= lqIdx.value, s"must be the same entry $i\n")
165    }
166    io.enq.resp(i) := lqIdx
167  }
168
169  /**
170    * Load commits
171    *
172    * When load commited, mark it as !allocated and move deqPtr forward.
173    */
174  (0 until DeqPtrMoveStride).map(i => {
175    when (commitCount > i.U) {
176      allocated((deqPtr+i.U).value) := false.B
177      XSError(!allocated((deqPtr+i.U).value), s"why commit invalid entry $i?\n")
178    }
179  })
180
181  // misprediction recovery / exception redirect
182  // invalidate lq term using robIdx
183  for (i <- 0 until VirtualLoadQueueSize) {
184    when (needCancel(i)) {
185      allocated(i) := false.B
186    }
187  }
188
189  XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(io.enq.req.map(_.valid)))}\n")
190
191  /**
192    * Writeback load from load units
193    *
194    * Most load instructions writeback to regfile at the same time.
195    * However,
196    *   (1) For ready load instruction (no need replay), it writes back to ROB immediately.
197    */
198  for(i <- 0 until LoadPipelineWidth) {
199    //   most lq status need to be updated immediately after load writeback to lq
200    //   flag bits in lq needs to be updated accurately
201    io.ldin(i).ready := true.B
202    val loadWbIndex = io.ldin(i).bits.uop.lqIdx.value
203    val isvec = io.ldin(i).bits.isvec // vector loads are writebacked from uop queue instead of ldus
204
205    when (io.ldin(i).valid && !isvec) {
206      val hasExceptions = ExceptionNO.selectByFu(io.ldin(i).bits.uop.exceptionVec, LduCfg).asUInt.orR
207      val need_rep = io.ldin(i).bits.rep_info.need_rep
208
209      when (!need_rep) {
210      // update control flag
211        addrvalid(loadWbIndex) := hasExceptions || !io.ldin(i).bits.tlbMiss
212        datavalid(loadWbIndex) :=
213          (if (EnableFastForward) {
214              hasExceptions ||
215              io.ldin(i).bits.mmio ||
216             !io.ldin(i).bits.miss && // dcache miss
217             !io.ldin(i).bits.dcacheRequireReplay // do not writeback if that inst will be resend from rs
218           } else {
219              hasExceptions ||
220              io.ldin(i).bits.mmio ||
221             !io.ldin(i).bits.miss
222           })
223
224        //
225        when (io.ldin(i).bits.data_wen_dup(1)) {
226          uop(loadWbIndex) := io.ldin(i).bits.uop
227        }
228        when (io.ldin(i).bits.data_wen_dup(4)) {
229          uop(loadWbIndex).debugInfo := io.ldin(i).bits.uop.debugInfo
230        }
231        uop(loadWbIndex).debugInfo := io.ldin(i).bits.rep_info.debug
232
233        //  Debug info
234        debug_mmio(loadWbIndex) := io.ldin(i).bits.mmio
235        debug_paddr(loadWbIndex) := io.ldin(i).bits.paddr
236
237        XSInfo(io.ldin(i).valid, "load hit write to lq idx %d pc 0x%x vaddr %x paddr %x mask %x forwardData %x forwardMask: %x mmio %x\n",
238          io.ldin(i).bits.uop.lqIdx.asUInt,
239          io.ldin(i).bits.uop.pc,
240          io.ldin(i).bits.vaddr,
241          io.ldin(i).bits.paddr,
242          io.ldin(i).bits.mask,
243          io.ldin(i).bits.forwardData.asUInt,
244          io.ldin(i).bits.forwardMask.asUInt,
245          io.ldin(i).bits.mmio
246        )
247      }
248    }
249  }
250
251  XSError(io.vecWriteback.valid && !allocated(io.vecWriteback.bits.uop.lqIdx.value),
252    "wb lqIdx should be allocated at dispatch stage")
253  when (io.vecWriteback.valid) {
254    val vecWbIndex = io.vecWriteback.bits.uop.lqIdx.value
255    addrvalid(vecWbIndex) := true.B
256    datavalid(vecWbIndex) := true.B
257  }
258
259  //  perf counter
260  QueuePerf(VirtualLoadQueueSize, validCount, !allowEnqueue)
261  io.lqFull := !allowEnqueue
262  val perfEvents: Seq[(String, UInt)] = Seq()
263  generatePerfEvent()
264
265  // debug info
266  XSDebug("enqPtrExt %d:%d deqPtrExt %d:%d\n", enqPtrExt(0).flag, enqPtr, deqPtr.flag, deqPtr.value)
267
268  def PrintFlag(flag: Bool, name: String): Unit = {
269    when(flag) {
270      XSDebug(false, true.B, name)
271    }.otherwise {
272      XSDebug(false, true.B, " ")
273    }
274  }
275
276  for (i <- 0 until VirtualLoadQueueSize) {
277    XSDebug(i + " pc %x pa %x ", uop(i).pc, debug_paddr(i))
278    PrintFlag(allocated(i), "v")
279    PrintFlag(allocated(i) && datavalid(i), "d")
280    PrintFlag(allocated(i) && addrvalid(i), "a")
281    PrintFlag(allocated(i) && addrvalid(i) && datavalid(i), "w")
282    XSDebug(false, true.B, "\n")
283  }
284  // end
285}
286