xref: /XiangShan/src/main/scala/xiangshan/backend/issue/IssueQueue.scala (revision ea159d42232ce67460c227d22d1690ff18031d36)
1package xiangshan.backend.issue
2
3import org.chipsalliance.cde.config.Parameters
4import chisel3._
5import chisel3.util._
6import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp}
7import utility.{GTimer, HasCircularQueuePtrHelper, SelectOne}
8import utils._
9import xiangshan._
10import xiangshan.backend.Bundles._
11import xiangshan.backend.decode.{ImmUnion, Imm_LUI_LOAD}
12import xiangshan.backend.datapath.DataConfig._
13import xiangshan.backend.datapath.DataSource
14import xiangshan.backend.fu.{FuConfig, FuType}
15import xiangshan.mem.{MemWaitUpdateReq, SqPtr, LqPtr}
16import xiangshan.backend.rob.RobPtr
17import xiangshan.backend.datapath.NewPipelineConnect
18
19class IssueQueue(params: IssueBlockParams)(implicit p: Parameters) extends LazyModule with HasXSParameter {
20  override def shouldBeInlined: Boolean = false
21
22  implicit val iqParams = params
23  lazy val module: IssueQueueImp = iqParams.schdType match {
24    case IntScheduler() => new IssueQueueIntImp(this)
25    case VfScheduler() => new IssueQueueVfImp(this)
26    case MemScheduler() =>
27      if (iqParams.StdCnt == 0 && !iqParams.isVecMemIQ) new IssueQueueMemAddrImp(this)
28      else if (iqParams.isVecMemIQ) new IssueQueueVecMemImp(this)
29      else new IssueQueueIntImp(this)
30    case _ => null
31  }
32}
33
34class IssueQueueStatusBundle(numEnq: Int, numEntries: Int) extends Bundle {
35  val empty = Output(Bool())
36  val full = Output(Bool())
37  val validCnt = Output(UInt(log2Ceil(numEntries).W))
38  val leftVec = Output(Vec(numEnq + 1, Bool()))
39}
40
41class IssueQueueDeqRespBundle(implicit p:Parameters, params: IssueBlockParams) extends EntryDeqRespBundle
42
43class IssueQueueIO()(implicit p: Parameters, params: IssueBlockParams) extends XSBundle {
44  // Inputs
45  val flush = Flipped(ValidIO(new Redirect))
46  val enq = Vec(params.numEnq, Flipped(DecoupledIO(new DynInst)))
47
48  val og0Resp = Vec(params.numDeq, Flipped(ValidIO(new IssueQueueDeqRespBundle)))
49  val og1Resp = Vec(params.numDeq, Flipped(ValidIO(new IssueQueueDeqRespBundle)))
50  val finalIssueResp = OptionWrapper(params.LdExuCnt > 0, Vec(params.LdExuCnt, Flipped(ValidIO(new IssueQueueDeqRespBundle))))
51  val memAddrIssueResp = OptionWrapper(params.LdExuCnt > 0, Vec(params.LdExuCnt, Flipped(ValidIO(new IssueQueueDeqRespBundle))))
52  val wbBusyTableRead = Input(params.genWbFuBusyTableReadBundle())
53  val wbBusyTableWrite = Output(params.genWbFuBusyTableWriteBundle())
54  val wakeupFromWB: MixedVec[ValidIO[IssueQueueWBWakeUpBundle]] = Flipped(params.genWBWakeUpSinkValidBundle)
55  val wakeupFromIQ: MixedVec[ValidIO[IssueQueueIQWakeUpBundle]] = Flipped(params.genIQWakeUpSinkValidBundle)
56  val og0Cancel = Input(ExuOH(backendParams.numExu))
57  val og1Cancel = Input(ExuOH(backendParams.numExu))
58  val ldCancel = Vec(backendParams.LduCnt + backendParams.HyuCnt, Flipped(new LoadCancelIO))
59
60  // Outputs
61  val deq: MixedVec[DecoupledIO[IssueQueueIssueBundle]] = params.genIssueDecoupledBundle
62  val wakeupToIQ: MixedVec[ValidIO[IssueQueueIQWakeUpBundle]] = params.genIQWakeUpSourceValidBundle
63  val status = Output(new IssueQueueStatusBundle(params.numEnq, params.numEntries))
64  // val statusNext = Output(new IssueQueueStatusBundle(params.numEnq))
65
66  val fromCancelNetwork = Flipped(params.genIssueDecoupledBundle)
67  val deqDelay: MixedVec[DecoupledIO[IssueQueueIssueBundle]] = params.genIssueDecoupledBundle// = deq.cloneType
68  def allWakeUp = wakeupFromWB ++ wakeupFromIQ
69}
70
71class IssueQueueImp(override val wrapper: IssueQueue)(implicit p: Parameters, val params: IssueBlockParams)
72  extends LazyModuleImp(wrapper)
73  with HasXSParameter {
74
75  println(s"[IssueQueueImp] ${params.getIQName} wakeupFromWB(${io.wakeupFromWB.size}), " +
76    s"wakeup exu in(${params.wakeUpInExuSources.size}): ${params.wakeUpInExuSources.map(_.name).mkString("{",",","}")}, " +
77    s"wakeup exu out(${params.wakeUpOutExuSources.size}): ${params.wakeUpOutExuSources.map(_.name).mkString("{",",","}")}, " +
78    s"numEntries: ${params.numEntries}, numRegSrc: ${params.numRegSrc}")
79
80  require(params.numExu <= 2, "IssueQueue has not supported more than 2 deq ports")
81  val deqFuCfgs     : Seq[Seq[FuConfig]] = params.exuBlockParams.map(_.fuConfigs)
82  val allDeqFuCfgs  : Seq[FuConfig] = params.exuBlockParams.flatMap(_.fuConfigs)
83  val fuCfgsCnt     : Map[FuConfig, Int] = allDeqFuCfgs.groupBy(x => x).map { case (cfg, cfgSeq) => (cfg, cfgSeq.length) }
84  val commonFuCfgs  : Seq[FuConfig] = fuCfgsCnt.filter(_._2 > 1).keys.toSeq
85  val fuLatencyMaps : Seq[Map[FuType.OHType, Int]] = params.exuBlockParams.map(x => x.fuLatencyMap)
86
87  println(s"[IssueQueueImp] ${params.getIQName} fuLatencyMaps: ${fuLatencyMaps}")
88  println(s"[IssueQueueImp] ${params.getIQName} commonFuCfgs: ${commonFuCfgs.map(_.name)}")
89  lazy val io = IO(new IssueQueueIO())
90  if(backendParams.debugEn) {
91    dontTouch(io.deq)
92  }
93  // Modules
94
95  val entries = Module(new Entries)
96  val subDeqPolicies  = deqFuCfgs.map(x => if (x.nonEmpty) Some(Module(new DeqPolicy())) else None)
97  val fuBusyTableWrite = params.exuBlockParams.map { case x => OptionWrapper(x.latencyValMax > 0, Module(new FuBusyTableWrite(x.fuLatencyMap))) }
98  val fuBusyTableRead = params.exuBlockParams.map { case x => OptionWrapper(x.latencyValMax > 0, Module(new FuBusyTableRead(x.fuLatencyMap))) }
99  val intWbBusyTableWrite = params.exuBlockParams.map { case x => OptionWrapper(x.intLatencyCertain, Module(new FuBusyTableWrite(x.intFuLatencyMap))) }
100  val intWbBusyTableRead = params.exuBlockParams.map { case x => OptionWrapper(x.intLatencyCertain, Module(new FuBusyTableRead(x.intFuLatencyMap))) }
101  val vfWbBusyTableWrite = params.exuBlockParams.map { case x => OptionWrapper(x.vfLatencyCertain, Module(new FuBusyTableWrite(x.vfFuLatencyMap))) }
102  val vfWbBusyTableRead = params.exuBlockParams.map { case x => OptionWrapper(x.vfLatencyCertain, Module(new FuBusyTableRead(x.vfFuLatencyMap))) }
103
104  class WakeupQueueFlush extends Bundle {
105    val redirect = ValidIO(new Redirect)
106    val ldCancel = Vec(backendParams.LduCnt + backendParams.HyuCnt, new LoadCancelIO)
107    val og0Fail = Output(Bool())
108    val og1Fail = Output(Bool())
109  }
110
111  private def flushFunc(exuInput: ExuInput, flush: WakeupQueueFlush, stage: Int): Bool = {
112    val redirectFlush = exuInput.robIdx.needFlush(flush.redirect)
113    val loadDependencyFlush = LoadShouldCancel(exuInput.loadDependency, flush.ldCancel)
114    val ogFailFlush = stage match {
115      case 1 => flush.og0Fail
116      case 2 => flush.og1Fail
117      case _ => false.B
118    }
119    redirectFlush || loadDependencyFlush || ogFailFlush
120  }
121
122  private def modificationFunc(exuInput: ExuInput): ExuInput = {
123    val newExuInput = WireDefault(exuInput)
124    newExuInput.loadDependency match {
125      case Some(deps) => deps.zip(exuInput.loadDependency.get).foreach(x => x._1 := x._2 << 1)
126      case None =>
127    }
128    newExuInput
129  }
130
131  val wakeUpQueues: Seq[Option[MultiWakeupQueue[ExuInput, WakeupQueueFlush]]] = params.exuBlockParams.map { x => OptionWrapper(x.isIQWakeUpSource, Module(
132    new MultiWakeupQueue(new ExuInput(x), new WakeupQueueFlush, x.fuLatancySet, flushFunc, modificationFunc)
133  ))}
134
135  val intWbBusyTableIn = io.wbBusyTableRead.map(_.intWbBusyTable)
136  val vfWbBusyTableIn = io.wbBusyTableRead.map(_.vfWbBusyTable)
137  val intWbBusyTableOut = io.wbBusyTableWrite.map(_.intWbBusyTable)
138  val vfWbBusyTableOut = io.wbBusyTableWrite.map(_.vfWbBusyTable)
139  val intDeqRespSetOut = io.wbBusyTableWrite.map(_.intDeqRespSet)
140  val vfDeqRespSetOut = io.wbBusyTableWrite.map(_.vfDeqRespSet)
141  val fuBusyTableMask = Wire(Vec(params.numDeq, UInt(params.numEntries.W)))
142  val intWbBusyTableMask = Wire(Vec(params.numDeq, UInt(params.numEntries.W)))
143  val vfWbBusyTableMask = Wire(Vec(params.numDeq, UInt(params.numEntries.W)))
144  val s0_enqValidVec = io.enq.map(_.valid)
145  val s0_enqSelValidVec = Wire(Vec(params.numEnq, Bool()))
146  val s0_enqNotFlush = !io.flush.valid
147  val s0_enqBits = WireInit(VecInit(io.enq.map(_.bits)))
148  val s0_doEnqSelValidVec = s0_enqSelValidVec.map(_ && s0_enqNotFlush) //enqValid && notFlush && enqReady
149
150
151  // One deq port only need one special deq policy
152  val subDeqSelValidVec: Seq[Option[Vec[Bool]]] = subDeqPolicies.map(_.map(_ => Wire(Vec(params.numDeq, Bool()))))
153  val subDeqSelOHVec: Seq[Option[Vec[UInt]]] = subDeqPolicies.map(_.map(_ => Wire(Vec(params.numDeq, UInt(params.numEntries.W)))))
154
155  val finalDeqSelValidVec = Wire(Vec(params.numDeq, Bool()))
156  val finalDeqSelOHVec    = Wire(Vec(params.numDeq, UInt(params.numEntries.W)))
157  val finalDeqOH: IndexedSeq[UInt] = (finalDeqSelValidVec zip finalDeqSelOHVec).map { case (valid, oh) =>
158    Mux(valid, oh, 0.U)
159  }
160  val finalDeqMask: UInt = finalDeqOH.reduce(_ | _)
161
162  val validVec = VecInit(entries.io.valid.asBools)
163  val canIssueVec = VecInit(entries.io.canIssue.asBools)
164  val clearVec = VecInit(entries.io.clear.asBools)
165  val deqFirstIssueVec = VecInit(entries.io.deq.map(_.isFirstIssue))
166
167  val dataSources: Vec[Vec[DataSource]] = entries.io.dataSources
168  val finalDataSources: Vec[Vec[DataSource]] = VecInit(finalDeqOH.map(oh => Mux1H(oh, dataSources)))
169  // (entryIdx)(srcIdx)(exuIdx)
170  val wakeUpL1ExuOH: Option[Vec[Vec[UInt]]] = entries.io.srcWakeUpL1ExuOH
171  val srcTimer: Option[Vec[Vec[UInt]]] = entries.io.srcTimer
172
173  // (deqIdx)(srcIdx)(exuIdx)
174  val finalWakeUpL1ExuOH: Option[Vec[Vec[UInt]]] = wakeUpL1ExuOH.map(x => VecInit(finalDeqOH.map(oh => Mux1H(oh, x))))
175  val finalSrcTimer = srcTimer.map(x => VecInit(finalDeqOH.map(oh => Mux1H(oh, x))))
176
177  val wakeupEnqSrcStateBypassFromWB: Vec[Vec[UInt]] = Wire(Vec(io.enq.size, Vec(io.enq.head.bits.srcType.size, SrcState())))
178  val wakeupEnqSrcStateBypassFromIQ: Vec[Vec[UInt]] = Wire(Vec(io.enq.size, Vec(io.enq.head.bits.srcType.size, SrcState())))
179  val srcWakeUpEnqByIQMatrix = Wire(Vec(params.numEnq, Vec(params.numRegSrc, Vec(params.numWakeupFromIQ, Bool()))))
180
181  val shiftedWakeupLoadDependencyByIQVec = Wire(Vec(params.numWakeupFromIQ, Vec(LoadPipelineWidth, UInt(3.W))))
182  shiftedWakeupLoadDependencyByIQVec
183    .zip(io.wakeupFromIQ.map(_.bits.loadDependency))
184    .zip(params.wakeUpInExuSources.map(_.name)).foreach {
185    case ((deps, originalDeps), name) => deps.zip(originalDeps).zipWithIndex.foreach {
186      case ((dep, originalDep), deqPortIdx) =>
187        if (params.backendParam.getLdExuIdx(params.backendParam.allExuParams.find(_.name == name).get) == deqPortIdx)
188          dep := (originalDep << 1).asUInt | 1.U
189        else
190          dep := originalDep << 1
191    }
192  }
193
194  for (i <- io.enq.indices) {
195    for (j <- s0_enqBits(i).srcType.indices) {
196      wakeupEnqSrcStateBypassFromWB(i)(j) := Cat(
197        io.wakeupFromWB.map(x => x.bits.wakeUp(Seq((s0_enqBits(i).psrc(j), s0_enqBits(i).srcType(j))), x.valid).head).toSeq
198      ).orR
199    }
200  }
201
202  for (i <- io.enq.indices) {
203    val numLsrc = s0_enqBits(i).srcType.size.min(entries.io.enq(i).bits.status.srcType.size)
204    for (j <- s0_enqBits(i).srcType.indices) {
205      val ldTransCancel = if (params.numWakeupFromIQ > 0 && j < numLsrc) Mux(
206        srcWakeUpEnqByIQMatrix(i)(j).asUInt.orR,
207        Mux1H(srcWakeUpEnqByIQMatrix(i)(j), io.wakeupFromIQ.map(_.bits.loadDependency).map(dep => LoadShouldCancel(Some(dep), io.ldCancel)).toSeq),
208        false.B
209      ) else false.B
210      wakeupEnqSrcStateBypassFromIQ(i)(j) := Cat(
211        io.wakeupFromIQ.map(x => x.bits.wakeUp(Seq((s0_enqBits(i).psrc(j), s0_enqBits(i).srcType(j))), x.valid).head).toSeq
212      ).orR && !ldTransCancel
213    }
214  }
215
216  srcWakeUpEnqByIQMatrix.zipWithIndex.foreach { case (wakeups: Vec[Vec[Bool]], i) =>
217    if (io.wakeupFromIQ.isEmpty) {
218      wakeups := 0.U.asTypeOf(wakeups)
219    } else {
220      val wakeupVec: IndexedSeq[IndexedSeq[Bool]] = io.wakeupFromIQ.map((bundle: ValidIO[IssueQueueIQWakeUpBundle]) =>
221        bundle.bits.wakeUp(s0_enqBits(i).psrc.take(params.numRegSrc) zip s0_enqBits(i).srcType.take(params.numRegSrc), bundle.valid)
222      ).toIndexedSeq.transpose
223      wakeups := wakeupVec.map(x => VecInit(x))
224    }
225  }
226
227  val fuTypeVec = Wire(Vec(params.numEntries, FuType()))
228  val transEntryDeqVec = Wire(Vec(params.numEnq, ValidIO(new EntryBundle)))
229  val deqEntryVec = Wire(Vec(params.numDeq, ValidIO(new EntryBundle)))
230  val transSelVec = Wire(Vec(params.numEnq, UInt((params.numEntries-params.numEnq).W)))
231
232  val enqEntryOldestSel = Wire(Vec(params.numDeq, ValidIO(UInt(params.numEnq.W))))
233  val othersEntryOldestSel = Wire(Vec(params.numDeq, ValidIO(UInt((params.numEntries - params.numEnq).W))))
234  val subDeqPolicyRequest = Wire(Vec(params.numDeq, UInt(params.numEntries.W)))
235  val canIssueMergeAllBusy = Wire(Vec(params.numDeq, UInt(params.numEntries.W)))
236
237  val deqSelValidVec = Wire(Vec(params.numDeq, Bool()))
238  val deqSelOHVec    = Wire(Vec(params.numDeq, UInt(params.numEntries.W)))
239
240  /**
241    * Connection of [[entries]]
242    */
243  entries.io match { case entriesIO: EntriesIO =>
244    entriesIO.flush <> io.flush
245    entriesIO.wakeUpFromWB := io.wakeupFromWB
246    entriesIO.wakeUpFromIQ := io.wakeupFromIQ
247    entriesIO.og0Cancel := io.og0Cancel
248    entriesIO.og1Cancel := io.og1Cancel
249    entriesIO.ldCancel := io.ldCancel
250    entriesIO.enq.zipWithIndex.foreach { case (enq: ValidIO[EntryBundle], i) =>
251      enq.valid := s0_doEnqSelValidVec(i)
252      val numLsrc = s0_enqBits(i).srcType.size.min(enq.bits.status.srcType.size)
253      for(j <- 0 until numLsrc) {
254        enq.bits.status.srcState(j) := s0_enqBits(i).srcState(j) |
255                                       wakeupEnqSrcStateBypassFromWB(i)(j) |
256                                       wakeupEnqSrcStateBypassFromIQ(i)(j)
257        enq.bits.status.psrc(j) := s0_enqBits(i).psrc(j)
258        enq.bits.status.srcType(j) := s0_enqBits(i).srcType(j)
259        enq.bits.status.dataSources(j).value := Mux(wakeupEnqSrcStateBypassFromIQ(i)(j).asBool, DataSource.forward, s0_enqBits(i).dataSource(j).value)
260        enq.bits.payload.debugInfo.enqRsTime := GTimer()
261      }
262      enq.bits.status.fuType := s0_enqBits(i).fuType
263      enq.bits.status.robIdx := s0_enqBits(i).robIdx
264      enq.bits.status.uopIdx.foreach(_ := s0_enqBits(i).uopIdx)
265      enq.bits.status.issueTimer := "b10".U
266      enq.bits.status.deqPortIdx := 0.U
267      enq.bits.status.issued := false.B
268      enq.bits.status.firstIssue := false.B
269      enq.bits.status.blocked := false.B
270      enq.bits.status.srcWakeUpL1ExuOH match {
271        case Some(value) => value.zip(srcWakeUpEnqByIQMatrix(i)).zipWithIndex.foreach {
272          case ((exuOH, wakeUpByIQOH), srcIdx) =>
273            when(wakeUpByIQOH.asUInt.orR) {
274              exuOH := Mux1H(wakeUpByIQOH, io.wakeupFromIQ.toSeq.map(x => MathUtils.IntToOH(x.bits.exuIdx).U(backendParams.numExu.W)))
275            }.otherwise {
276              exuOH := s0_enqBits(i).l1ExuOH(srcIdx)
277            }
278        }
279        case None =>
280      }
281      enq.bits.status.srcTimer match {
282        case Some(value) => value.zip(srcWakeUpEnqByIQMatrix(i)).zipWithIndex.foreach {
283          case ((timer, wakeUpByIQOH), srcIdx) =>
284            when(wakeUpByIQOH.asUInt.orR) {
285              timer := 1.U.asTypeOf(timer)
286            }.otherwise {
287              timer := Mux(s0_enqBits(i).dataSource(srcIdx).value === DataSource.bypass, 2.U.asTypeOf(timer), 0.U.asTypeOf(timer))
288            }
289        }
290        case None =>
291      }
292      enq.bits.status.srcLoadDependency.foreach(_.zip(srcWakeUpEnqByIQMatrix(i)).zipWithIndex.foreach {
293        case ((dep, wakeUpByIQOH), srcIdx) =>
294          dep := Mux(wakeUpByIQOH.asUInt.orR, Mux1H(wakeUpByIQOH, shiftedWakeupLoadDependencyByIQVec), 0.U.asTypeOf(dep))
295      })
296      enq.bits.imm := s0_enqBits(i).imm
297      enq.bits.payload := s0_enqBits(i)
298    }
299    entriesIO.deq.zipWithIndex.foreach { case (deq, i) =>
300      deq.enqEntryOldestSel := enqEntryOldestSel(i)
301      deq.othersEntryOldestSel := othersEntryOldestSel(i)
302      deq.subDeqPolicyRequest := { if (subDeqPolicies(i).nonEmpty) subDeqPolicyRequest(i) else 0.U }
303      deq.subDeqSelOH := subDeqSelOHVec(i).getOrElse(Seq(0.U, 0.U))
304      deq.deqReady := io.deq(i).ready
305      deq.deqSelOH.valid := deqSelValidVec(i)
306      deq.deqSelOH.bits := deqSelOHVec(i)
307      deq.finalDeqSelOH.valid := finalDeqSelValidVec(i)
308      deq.finalDeqSelOH.bits := finalDeqSelOHVec(i)
309    }
310    entriesIO.og0Resp.zipWithIndex.foreach { case (og0Resp, i) =>
311      og0Resp.valid := io.og0Resp(i).valid
312      og0Resp.bits.robIdx := io.og0Resp(i).bits.robIdx
313      og0Resp.bits.uopIdx := io.og0Resp(i).bits.uopIdx
314      og0Resp.bits.dataInvalidSqIdx := io.og0Resp(i).bits.dataInvalidSqIdx
315      og0Resp.bits.respType := io.og0Resp(i).bits.respType
316      og0Resp.bits.rfWen := io.og0Resp(i).bits.rfWen
317      og0Resp.bits.fuType := io.og0Resp(i).bits.fuType
318    }
319    entriesIO.og1Resp.zipWithIndex.foreach { case (og1Resp, i) =>
320      og1Resp.valid := io.og1Resp(i).valid
321      og1Resp.bits.robIdx := io.og1Resp(i).bits.robIdx
322      og1Resp.bits.uopIdx := io.og1Resp(i).bits.uopIdx
323      og1Resp.bits.dataInvalidSqIdx := io.og1Resp(i).bits.dataInvalidSqIdx
324      og1Resp.bits.respType := io.og1Resp(i).bits.respType
325      og1Resp.bits.rfWen := io.og1Resp(i).bits.rfWen
326      og1Resp.bits.fuType := io.og1Resp(i).bits.fuType
327    }
328    entriesIO.finalIssueResp.foreach(_.zipWithIndex.foreach { case (finalIssueResp, i) =>
329      finalIssueResp := io.finalIssueResp.get(i)
330    })
331    entriesIO.memAddrIssueResp.foreach(_.zipWithIndex.foreach { case (memAddrIssueResp, i) =>
332      memAddrIssueResp := io.memAddrIssueResp.get(i)
333    })
334    transEntryDeqVec := entriesIO.transEntryDeqVec
335    deqEntryVec := entriesIO.deq.map(_.deqEntry)
336    fuTypeVec := entriesIO.fuType
337    transSelVec := entriesIO.transSelVec
338  }
339
340
341  s0_enqSelValidVec := s0_enqValidVec.zip(io.enq).map{ case (enqValid, enq) => enqValid && enq.ready}
342
343  protected val commonAccept: UInt = Cat(fuTypeVec.map(fuType =>
344    FuType.FuTypeOrR(fuType, commonFuCfgs.map(_.fuType))
345  ).reverse)
346
347  // if deq port can accept the uop
348  protected val canAcceptVec: Seq[UInt] = deqFuCfgs.map { fuCfgs: Seq[FuConfig] =>
349    Cat(fuTypeVec.map(fuType =>
350      FuType.FuTypeOrR(fuType, fuCfgs.map(_.fuType))
351    ).reverse)
352  }
353
354  protected val deqCanAcceptVec: Seq[IndexedSeq[Bool]] = deqFuCfgs.map { fuCfgs: Seq[FuConfig] =>
355    fuTypeVec.map(fuType =>
356      FuType.FuTypeOrR(fuType, fuCfgs.map(_.fuType))) // C+E0    C+E1
357  }
358
359  canIssueMergeAllBusy.zipWithIndex.foreach { case (merge, i) =>
360    val mergeFuBusy = {
361      if (fuBusyTableWrite(i).nonEmpty) canIssueVec.asUInt & (~fuBusyTableMask(i))
362      else canIssueVec.asUInt
363    }
364    val mergeIntWbBusy = {
365      if (intWbBusyTableRead(i).nonEmpty) mergeFuBusy & (~intWbBusyTableMask(i))
366      else mergeFuBusy
367    }
368    val mergeVfWbBusy = {
369      if (vfWbBusyTableRead(i).nonEmpty) mergeIntWbBusy & (~vfWbBusyTableMask(i))
370      else mergeIntWbBusy
371    }
372    merge := mergeVfWbBusy
373  }
374
375  subDeqPolicies.zipWithIndex.foreach { case (dpOption: Option[DeqPolicy], i) =>
376    if (dpOption.nonEmpty) {
377      val dp = dpOption.get
378      dp.io.request             := subDeqPolicyRequest(i)
379      subDeqSelValidVec(i).get  := dp.io.deqSelOHVec.map(oh => oh.valid)
380      subDeqSelOHVec(i).get     := dp.io.deqSelOHVec.map(oh => oh.bits)
381    }
382  }
383
384  if (params.numDeq == 2) {
385    require(params.deqFuSame || params.deqFuDiff, "The 2 deq ports need to be identical or completely different")
386  }
387
388  if (params.numDeq == 2 && params.deqFuSame) {
389    enqEntryOldestSel(0) := NewAgeDetector(numEntries = params.numEnq,
390      enq = VecInit(s0_doEnqSelValidVec),
391      clear = VecInit(clearVec.take(params.numEnq)),
392      canIssue = canIssueVec.asUInt(params.numEnq-1, 0)
393    )
394    enqEntryOldestSel(1) := DontCare
395
396    othersEntryOldestSel(0) := AgeDetector(numEntries = params.numEntries - params.numEnq,
397      enq = VecInit(transEntryDeqVec.zip(transSelVec).map{ case (transEntry, transSel) => Fill(params.numEntries-params.numEnq, transEntry.valid) & transSel }),
398      deq = VecInit(clearVec.drop(params.numEnq)).asUInt,
399      canIssue = canIssueVec.asUInt(params.numEntries-1, params.numEnq)
400    )
401    othersEntryOldestSel(1) := DontCare
402
403    subDeqPolicyRequest.zipWithIndex.foreach { case (req, i) =>
404      req := canIssueVec.asUInt & ~Cat(othersEntryOldestSel(0).bits, enqEntryOldestSel(0).bits)
405    }
406
407    val deqRequestVec = VecInit(othersEntryOldestSel(0).valid, subDeqSelValidVec(0).getOrElse(Seq(false.B)).head, subDeqSelValidVec(0).getOrElse(Seq(false.B)).last, enqEntryOldestSel(0).valid)
408    val deqOHVec      = VecInit(Cat(othersEntryOldestSel(0).bits, 0.U((params.numEnq).W)), subDeqSelOHVec(0).getOrElse(Seq(0.U)).head, subDeqSelOHVec(0).getOrElse(Seq(0.U)).last, Cat(0.U((params.numEntries-params.numEnq).W), enqEntryOldestSel(0).bits))
409
410    deqSelValidVec.zipWithIndex.foreach { case(deqValid, i) => deqValid := SelectOne("circ", deqRequestVec, params.numDeq).getNthOH(i + 1)._1 }
411    deqSelOHVec(0) := PriorityMux(deqRequestVec, deqOHVec.map(_ & canIssueMergeAllBusy(0)))
412    deqSelOHVec(1) := PriorityMux(deqRequestVec.reverse, deqOHVec.map(_ & canIssueMergeAllBusy(1)).reverse)
413
414    finalDeqSelValidVec.zip(finalDeqSelOHVec).zip(deqSelValidVec).zip(deqSelOHVec).zipWithIndex.foreach { case ((((selValid, selOH), deqValid), deqOH), i) =>
415      selValid := deqValid && deqOH.orR && io.deq(i).ready
416      selOH := deqOH
417    }
418  }
419  else {
420    subDeqPolicyRequest.zipWithIndex.foreach { case (req, i) =>
421      req := canIssueMergeAllBusy(i) & VecInit(deqCanAcceptVec(i)).asUInt
422    }
423
424    val enqCanAcceptVec: Seq[IndexedSeq[Bool]] = deqFuCfgs.map { fuCfgs: Seq[FuConfig] =>
425      io.enq.map(_.bits.fuType).map(fuType =>
426        FuType.FuTypeOrR(fuType, fuCfgs.map(_.fuType))) // C+E0    C+E1
427    }
428
429    val transCanAcceptVec: Seq[IndexedSeq[Bool]] = deqFuCfgs.map { fuCfgs: Seq[FuConfig] =>
430      transEntryDeqVec.map(_.bits.status.fuType).zip(transEntryDeqVec.map(_.valid)).map{ case (fuType, valid) =>
431        FuType.FuTypeOrR(fuType, fuCfgs.map(_.fuType)) && valid }
432    }
433
434    enqEntryOldestSel.zipWithIndex.foreach { case (sel, deqIdx) =>
435      sel := NewAgeDetector(numEntries = params.numEnq,
436          enq = VecInit(enqCanAcceptVec(deqIdx).zip(s0_doEnqSelValidVec).map{ case (doCanAccept, valid) => doCanAccept && valid }),
437          clear = VecInit(clearVec.take(params.numEnq)),
438          canIssue = canIssueMergeAllBusy(deqIdx)(params.numEnq-1, 0)
439        )
440    }
441
442    othersEntryOldestSel.zipWithIndex.foreach { case (sel, deqIdx) =>
443      sel := AgeDetector(numEntries = params.numEntries - params.numEnq,
444          enq = VecInit(transCanAcceptVec(deqIdx).zip(transSelVec).map{ case (doCanAccept, transSel) => Fill(params.numEntries-params.numEnq, doCanAccept) & transSel }),
445          deq = VecInit(clearVec.drop(params.numEnq)).asUInt,
446          canIssue = canIssueMergeAllBusy(deqIdx)(params.numEntries-1, params.numEnq)
447        )
448    }
449
450    deqSelValidVec.zip(deqSelOHVec).zipWithIndex.foreach { case ((selValid, selOH), i) =>
451      if (params.exuBlockParams(i).fuConfigs.contains(FuConfig.FakeHystaCfg)) {
452        selValid := false.B
453        selOH := 0.U.asTypeOf(selOH)
454      } else {
455        selValid := othersEntryOldestSel(i).valid || enqEntryOldestSel(i).valid || subDeqSelValidVec(i).getOrElse(Seq(false.B)).head
456        selOH := Mux(othersEntryOldestSel(i).valid, Cat(othersEntryOldestSel(i).bits, 0.U((params.numEnq).W)),
457               Mux(enqEntryOldestSel(i).valid, Cat(0.U((params.numEntries-params.numEnq).W), enqEntryOldestSel(i).bits),
458                   subDeqSelOHVec(i).getOrElse(Seq(0.U)).head))
459      }
460    }
461
462    finalDeqSelValidVec.zip(finalDeqSelOHVec).zip(deqSelValidVec).zip(deqSelOHVec).zipWithIndex.foreach { case ((((selValid, selOH), deqValid), deqOH), i) =>
463      selValid := deqValid && io.deq(i).ready
464      selOH := deqOH
465    }
466  }
467
468  val toBusyTableDeqResp = Wire(Vec(params.numDeq, ValidIO(new IssueQueueDeqRespBundle)))
469
470  toBusyTableDeqResp.zipWithIndex.foreach { case (deqResp, i) =>
471    deqResp.valid := finalDeqSelValidVec(i)
472    deqResp.bits.respType := RSFeedbackType.issueSuccess
473    deqResp.bits.robIdx := DontCare
474    deqResp.bits.dataInvalidSqIdx := DontCare
475    deqResp.bits.rfWen := DontCare
476    deqResp.bits.fuType := io.deq(i).bits.common.fuType
477    deqResp.bits.uopIdx := DontCare
478  }
479
480  //fuBusyTable
481  fuBusyTableWrite.zip(fuBusyTableRead).zipWithIndex.foreach { case ((busyTableWrite: Option[FuBusyTableWrite], busyTableRead: Option[FuBusyTableRead]), i) =>
482    if(busyTableWrite.nonEmpty) {
483      val btwr = busyTableWrite.get
484      val btrd = busyTableRead.get
485      btwr.io.in.deqResp := toBusyTableDeqResp(i)
486      btwr.io.in.og0Resp := io.og0Resp(i)
487      btwr.io.in.og1Resp := io.og1Resp(i)
488      btrd.io.in.fuBusyTable := btwr.io.out.fuBusyTable
489      btrd.io.in.fuTypeRegVec := fuTypeVec
490      fuBusyTableMask(i) := btrd.io.out.fuBusyTableMask
491    }
492    else {
493      fuBusyTableMask(i) := 0.U(params.numEntries.W)
494    }
495  }
496
497  //wbfuBusyTable write
498  intWbBusyTableWrite.zip(intWbBusyTableOut).zip(intDeqRespSetOut).zipWithIndex.foreach { case (((busyTableWrite: Option[FuBusyTableWrite], busyTable: Option[UInt]), deqResp), i) =>
499    if(busyTableWrite.nonEmpty) {
500      val btwr = busyTableWrite.get
501      val bt = busyTable.get
502      val dq = deqResp.get
503      btwr.io.in.deqResp := toBusyTableDeqResp(i)
504      btwr.io.in.og0Resp := io.og0Resp(i)
505      btwr.io.in.og1Resp := io.og1Resp(i)
506      bt := btwr.io.out.fuBusyTable
507      dq := btwr.io.out.deqRespSet
508    }
509  }
510
511  vfWbBusyTableWrite.zip(vfWbBusyTableOut).zip(vfDeqRespSetOut).zipWithIndex.foreach { case (((busyTableWrite: Option[FuBusyTableWrite], busyTable: Option[UInt]), deqResp), i) =>
512    if (busyTableWrite.nonEmpty) {
513      val btwr = busyTableWrite.get
514      val bt = busyTable.get
515      val dq = deqResp.get
516      btwr.io.in.deqResp := toBusyTableDeqResp(i)
517      btwr.io.in.og0Resp := io.og0Resp(i)
518      btwr.io.in.og1Resp := io.og1Resp(i)
519      bt := btwr.io.out.fuBusyTable
520      dq := btwr.io.out.deqRespSet
521    }
522  }
523
524  //wbfuBusyTable read
525  intWbBusyTableRead.zip(intWbBusyTableIn).zipWithIndex.foreach { case ((busyTableRead: Option[FuBusyTableRead], busyTable: Option[UInt]), i) =>
526    if(busyTableRead.nonEmpty) {
527      val btrd = busyTableRead.get
528      val bt = busyTable.get
529      btrd.io.in.fuBusyTable := bt
530      btrd.io.in.fuTypeRegVec := fuTypeVec
531      intWbBusyTableMask(i) := btrd.io.out.fuBusyTableMask
532    }
533    else {
534      intWbBusyTableMask(i) := 0.U(params.numEntries.W)
535    }
536  }
537  vfWbBusyTableRead.zip(vfWbBusyTableIn).zipWithIndex.foreach { case ((busyTableRead: Option[FuBusyTableRead], busyTable: Option[UInt]), i) =>
538    if (busyTableRead.nonEmpty) {
539      val btrd = busyTableRead.get
540      val bt = busyTable.get
541      btrd.io.in.fuBusyTable := bt
542      btrd.io.in.fuTypeRegVec := fuTypeVec
543      vfWbBusyTableMask(i) := btrd.io.out.fuBusyTableMask
544    }
545    else {
546      vfWbBusyTableMask(i) := 0.U(params.numEntries.W)
547    }
548  }
549
550  wakeUpQueues.zipWithIndex.foreach { case (wakeUpQueueOption, i) =>
551    val og0RespEach = io.og0Resp(i)
552    val og1RespEach = io.og1Resp(i)
553    wakeUpQueueOption.foreach {
554      wakeUpQueue =>
555        val flush = Wire(new WakeupQueueFlush)
556        flush.redirect := io.flush
557        flush.ldCancel := io.ldCancel
558        flush.og0Fail := io.og0Resp(i).valid && RSFeedbackType.isBlocked(io.og0Resp(i).bits.respType)
559        flush.og1Fail := io.og1Resp(i).valid && RSFeedbackType.isBlocked(io.og1Resp(i).bits.respType)
560        wakeUpQueue.io.flush := flush
561        wakeUpQueue.io.enq.valid := io.deq(i).fire && !io.deq(i).bits.common.needCancel(io.og0Cancel, io.og1Cancel) && {
562          io.deq(i).bits.common.rfWen.getOrElse(false.B) && io.deq(i).bits.common.pdest =/= 0.U ||
563          io.deq(i).bits.common.fpWen.getOrElse(false.B) ||
564          io.deq(i).bits.common.vecWen.getOrElse(false.B)
565        }
566        wakeUpQueue.io.enq.bits.uop := io.deq(i).bits.common
567        wakeUpQueue.io.enq.bits.lat := getDeqLat(i, io.deq(i).bits.common.fuType)
568        wakeUpQueue.io.og0IssueFail := flush.og0Fail
569        wakeUpQueue.io.og1IssueFail := flush.og1Fail
570    }
571  }
572
573  io.deq.zipWithIndex.foreach { case (deq, i) =>
574    deq.valid                := finalDeqSelValidVec(i)
575    deq.bits.addrOH          := finalDeqSelOHVec(i)
576    deq.bits.common.isFirstIssue := deqFirstIssueVec(i)
577    deq.bits.common.iqIdx    := OHToUInt(finalDeqSelOHVec(i))
578    deq.bits.common.fuType   := deqEntryVec(i).bits.payload.fuType
579    deq.bits.common.fuOpType := deqEntryVec(i).bits.payload.fuOpType
580    deq.bits.common.rfWen.foreach(_ := deqEntryVec(i).bits.payload.rfWen)
581    deq.bits.common.fpWen.foreach(_ := deqEntryVec(i).bits.payload.fpWen)
582    deq.bits.common.vecWen.foreach(_ := deqEntryVec(i).bits.payload.vecWen)
583    deq.bits.common.flushPipe.foreach(_ := deqEntryVec(i).bits.payload.flushPipe)
584    deq.bits.common.pdest := deqEntryVec(i).bits.payload.pdest
585    deq.bits.common.robIdx := deqEntryVec(i).bits.payload.robIdx
586    deq.bits.common.dataSources.zip(finalDataSources(i)).zipWithIndex.foreach {
587      case ((sink, source), srcIdx) =>
588        sink.value := Mux(
589          SrcType.isXp(deqEntryVec(i).bits.payload.srcType(srcIdx)) && deqEntryVec(i).bits.payload.psrc(srcIdx) === 0.U,
590          DataSource.none,
591          source.value
592        )
593    }
594    if (deq.bits.common.l1ExuOH.size > 0) {
595      if (params.hasIQWakeUp) {
596        deq.bits.common.l1ExuOH := finalWakeUpL1ExuOH.get(i)
597      } else {
598        deq.bits.common.l1ExuOH := deqEntryVec(i).bits.payload.l1ExuOH.take(deq.bits.common.l1ExuOH.length)
599      }
600    }
601    deq.bits.common.srcTimer.foreach(_ := finalSrcTimer.get(i))
602    deq.bits.common.loadDependency.foreach(_ := deqEntryVec(i).bits.status.mergedLoadDependency.get)
603    deq.bits.common.deqLdExuIdx.foreach(_ := params.backendParam.getLdExuIdx(deq.bits.exuParams).U)
604    deq.bits.common.src := DontCare
605    deq.bits.common.preDecode.foreach(_ := deqEntryVec(i).bits.payload.preDecodeInfo)
606
607    deq.bits.rf.zip(deqEntryVec(i).bits.payload.psrc).foreach { case (rf, psrc) =>
608      rf.foreach(_.addr := psrc) // psrc in payload array can be pregIdx of IntRegFile or VfRegFile
609    }
610    deq.bits.rf.zip(deqEntryVec(i).bits.payload.srcType).foreach { case (rf, srcType) =>
611      rf.foreach(_.srcType := srcType) // psrc in payload array can be pregIdx of IntRegFile or VfRegFile
612    }
613    deq.bits.srcType.zip(deqEntryVec(i).bits.payload.srcType).foreach { case (sink, source) =>
614      sink := source
615    }
616    deq.bits.immType := deqEntryVec(i).bits.payload.selImm
617
618    if (params.inIntSchd && params.AluCnt > 0) {
619      // dirty code for lui+addi(w) fusion
620      val isLuiAddiFusion = deqEntryVec(i).bits.payload.isLUI32
621      val luiImm = Cat(deqEntryVec(i).bits.payload.lsrc(1), deqEntryVec(i).bits.payload.lsrc(0), deqEntryVec(i).bits.imm(ImmUnion.maxLen - 1, 0))
622      deq.bits.common.imm := Mux(isLuiAddiFusion, ImmUnion.LUI32.toImm32(luiImm), deqEntryVec(i).bits.imm)
623    }
624    else if (params.inMemSchd && params.LduCnt > 0) {
625      // dirty code for fused_lui_load
626      val isLuiLoadFusion = SrcType.isNotReg(deqEntryVec(i).bits.payload.srcType(0)) && FuType.isLoad(deqEntryVec(i).bits.payload.fuType)
627      deq.bits.common.imm := Mux(isLuiLoadFusion, Imm_LUI_LOAD().getLuiImm(deqEntryVec(i).bits.payload), deqEntryVec(i).bits.imm)
628    }
629    else {
630      deq.bits.common.imm := deqEntryVec(i).bits.imm
631    }
632
633    deq.bits.common.perfDebugInfo := deqEntryVec(i).bits.payload.debugInfo
634    deq.bits.common.perfDebugInfo.selectTime := GTimer()
635    deq.bits.common.perfDebugInfo.issueTime := GTimer() + 1.U
636  }
637
638  private val ldCancels = io.fromCancelNetwork.map(in =>
639    LoadShouldCancel(in.bits.common.loadDependency, io.ldCancel)
640  )
641  private val fromCancelNetworkShift = WireDefault(io.fromCancelNetwork)
642  fromCancelNetworkShift.zip(io.fromCancelNetwork).foreach {
643    case (shifted, original) =>
644      original.ready := shifted.ready // this will not cause combinational loop
645      shifted.bits.common.loadDependency.foreach(
646        _ := original.bits.common.loadDependency.get.map(_ << 1)
647      )
648  }
649  io.deqDelay.zip(fromCancelNetworkShift).zip(ldCancels).foreach { case ((deqDly, deq), ldCancel) =>
650    NewPipelineConnect(
651      deq, deqDly, deqDly.valid,
652      deq.bits.common.robIdx.needFlush(io.flush) || ldCancel,
653      Option("Scheduler2DataPathPipe")
654    )
655  }
656  if(backendParams.debugEn) {
657    dontTouch(io.deqDelay)
658  }
659  io.wakeupToIQ.zipWithIndex.foreach { case (wakeup, i) =>
660    if (wakeUpQueues(i).nonEmpty && finalWakeUpL1ExuOH.nonEmpty) {
661      wakeup.valid := wakeUpQueues(i).get.io.deq.valid
662      wakeup.bits.fromExuInput(wakeUpQueues(i).get.io.deq.bits, finalWakeUpL1ExuOH.get(i))
663      wakeup.bits.loadDependency := wakeUpQueues(i).get.io.deq.bits.loadDependency.getOrElse(0.U.asTypeOf(wakeup.bits.loadDependency))
664    } else if (wakeUpQueues(i).nonEmpty) {
665      wakeup.valid := wakeUpQueues(i).get.io.deq.valid
666      wakeup.bits.fromExuInput(wakeUpQueues(i).get.io.deq.bits)
667      wakeup.bits.loadDependency := wakeUpQueues(i).get.io.deq.bits.loadDependency.getOrElse(0.U.asTypeOf(wakeup.bits.loadDependency))
668    } else {
669      wakeup.valid := false.B
670      wakeup.bits := 0.U.asTypeOf(wakeup.bits)
671    }
672  }
673
674  // Todo: better counter implementation
675  private val enqHasValid = validVec.take(params.numEnq).reduce(_ | _)
676  private val enqEntryValidCnt = PopCount(validVec.take(params.numEnq))
677  private val othersValidCnt = PopCount(validVec.drop(params.numEnq))
678  io.status.leftVec(0) := validVec.drop(params.numEnq).reduce(_ & _)
679  for (i <- 0 until params.numEnq) {
680    io.status.leftVec(i + 1) := othersValidCnt === (params.numEntries - params.numEnq - (i + 1)).U
681  }
682  io.enq.foreach(_.ready := !Cat(io.status.leftVec).orR || !enqHasValid) // Todo: more efficient implementation
683  io.status.empty := !Cat(validVec).orR
684  io.status.full := Cat(io.status.leftVec).orR
685  io.status.validCnt := PopCount(validVec)
686
687  protected def getDeqLat(deqPortIdx: Int, fuType: UInt) : UInt = {
688    Mux1H(fuLatencyMaps(deqPortIdx) map { case (k, v) => (fuType(k.id), v.U) })
689  }
690
691  // issue perf counter
692  // enq count
693  XSPerfAccumulate("enq_valid_cnt", PopCount(io.enq.map(_.fire)))
694  XSPerfAccumulate("enq_fire_cnt", PopCount(io.enq.map(_.fire)))
695  // valid count
696  XSPerfHistogram("enq_entry_valid_cnt", enqEntryValidCnt, true.B, 0, params.numEnq + 1)
697  XSPerfHistogram("other_entry_valid_cnt", othersValidCnt, true.B, 0, params.numEntries - params.numEnq + 1)
698  XSPerfHistogram("valid_cnt", PopCount(validVec), true.B, 0, params.numEntries + 1)
699  // only split when more than 1 func type
700  if (params.getFuCfgs.size > 0) {
701    for (t <- FuType.functionNameMap.keys) {
702      val fuName = FuType.functionNameMap(t)
703      if (params.getFuCfgs.map(_.fuType == t).reduce(_ | _)) {
704        XSPerfHistogram(s"valid_cnt_hist_futype_${fuName}", PopCount(validVec.zip(fuTypeVec).map { case (v, fu) => v && fu === t.U }), true.B, 0, params.numEntries, 1)
705      }
706    }
707  }
708  // ready instr count
709  private val readyEntriesCnt = PopCount(validVec.zip(canIssueVec).map(x => x._1 && x._2))
710  XSPerfHistogram("ready_cnt", readyEntriesCnt, true.B, 0, params.numEntries + 1)
711  // only split when more than 1 func type
712  if (params.getFuCfgs.size > 0) {
713    for (t <- FuType.functionNameMap.keys) {
714      val fuName = FuType.functionNameMap(t)
715      if (params.getFuCfgs.map(_.fuType == t).reduce(_ | _)) {
716        XSPerfHistogram(s"ready_cnt_hist_futype_${fuName}", PopCount(validVec.zip(canIssueVec).zip(fuTypeVec).map { case ((v, c), fu) => v && c && fu === t.U }), true.B, 0, params.numEntries, 1)
717      }
718    }
719  }
720
721  // deq instr count
722  XSPerfAccumulate("issue_instr_pre_count", PopCount(io.deq.map(_.valid)))
723  XSPerfHistogram("issue_instr_pre_count_hist", PopCount(io.deq.map(_.valid)), true.B, 0, params.numDeq + 1, 1)
724  XSPerfAccumulate("issue_instr_count", PopCount(io.deqDelay.map(_.valid)))
725  XSPerfHistogram("issue_instr_count_hist", PopCount(io.deqDelay.map(_.valid)), true.B, 0, params.numDeq + 1, 1)
726
727  // deq instr data source count
728  XSPerfAccumulate("issue_datasource_reg", io.deq.map{ deq =>
729    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.reg && !SrcType.isNotReg(deq.bits.srcType(j)) })
730  }.reduce(_ +& _))
731  XSPerfAccumulate("issue_datasource_bypass", io.deq.map{ deq =>
732    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.bypass && !SrcType.isNotReg(deq.bits.srcType(j)) })
733  }.reduce(_ +& _))
734  XSPerfAccumulate("issue_datasource_forward", io.deq.map{ deq =>
735    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.forward && !SrcType.isNotReg(deq.bits.srcType(j)) })
736  }.reduce(_ +& _))
737  XSPerfAccumulate("issue_datasource_noreg", io.deq.map{ deq =>
738    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && SrcType.isNotReg(deq.bits.srcType(j)) })
739  }.reduce(_ +& _))
740
741  XSPerfHistogram("issue_datasource_reg_hist", io.deq.map{ deq =>
742    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.reg && !SrcType.isNotReg(deq.bits.srcType(j)) })
743  }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
744  XSPerfHistogram("issue_datasource_bypass_hist", io.deq.map{ deq =>
745    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.bypass && !SrcType.isNotReg(deq.bits.srcType(j)) })
746  }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
747  XSPerfHistogram("issue_datasource_forward_hist", io.deq.map{ deq =>
748    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.forward && !SrcType.isNotReg(deq.bits.srcType(j)) })
749  }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
750  XSPerfHistogram("issue_datasource_noreg_hist", io.deq.map{ deq =>
751    PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && SrcType.isNotReg(deq.bits.srcType(j)) })
752  }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
753
754  // deq instr data source count for each futype
755  for (t <- FuType.functionNameMap.keys) {
756    val fuName = FuType.functionNameMap(t)
757    if (params.getFuCfgs.map(_.fuType == t).reduce(_ | _)) {
758      XSPerfAccumulate(s"issue_datasource_reg_futype_${fuName}", io.deq.map{ deq =>
759        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.reg && !SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
760      }.reduce(_ +& _))
761      XSPerfAccumulate(s"issue_datasource_bypass_futype_${fuName}", io.deq.map{ deq =>
762        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.bypass && !SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
763      }.reduce(_ +& _))
764      XSPerfAccumulate(s"issue_datasource_forward_futype_${fuName}", io.deq.map{ deq =>
765        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.forward && !SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
766      }.reduce(_ +& _))
767      XSPerfAccumulate(s"issue_datasource_noreg_futype_${fuName}", io.deq.map{ deq =>
768        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
769      }.reduce(_ +& _))
770
771      XSPerfHistogram(s"issue_datasource_reg_hist_futype_${fuName}", io.deq.map{ deq =>
772        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.reg && !SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
773      }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
774      XSPerfHistogram(s"issue_datasource_bypass_hist_futype_${fuName}", io.deq.map{ deq =>
775        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.bypass && !SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
776      }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
777      XSPerfHistogram(s"issue_datasource_forward_hist_futype_${fuName}", io.deq.map{ deq =>
778        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && ds.value === DataSource.forward && !SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
779      }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
780      XSPerfHistogram(s"issue_datasource_noreg_hist_futype_${fuName}", io.deq.map{ deq =>
781        PopCount(deq.bits.common.dataSources.zipWithIndex.map{ case (ds, j) => deq.valid && SrcType.isNotReg(deq.bits.srcType(j)) && deq.bits.common.fuType === t.U })
782      }.reduce(_ +& _), true.B, 0, params.numDeq * params.numRegSrc + 1, 1)
783    }
784  }
785
786  // cancel instr count
787  if (params.hasIQWakeUp) {
788    val cancelVec: Vec[Bool] = entries.io.cancel.get
789    XSPerfAccumulate("cancel_instr_count", PopCount(validVec.zip(cancelVec).map(x => x._1 & x._2)))
790    XSPerfHistogram("cancel_instr_hist", PopCount(validVec.zip(cancelVec).map(x => x._1 & x._2)), true.B, 0, params.numEntries, 1)
791    for (t <- FuType.functionNameMap.keys) {
792      val fuName = FuType.functionNameMap(t)
793      if (params.getFuCfgs.map(_.fuType == t).reduce(_ | _)) {
794        XSPerfAccumulate(s"cancel_instr_count_futype_${fuName}", PopCount(validVec.zip(cancelVec).zip(fuTypeVec).map{ case ((x, y), fu) => x & y & fu === t.U }))
795        XSPerfHistogram(s"cancel_instr_hist_futype_${fuName}", PopCount(validVec.zip(cancelVec).zip(fuTypeVec).map{ case ((x, y), fu) => x & y & fu === t.U }), true.B, 0, params.numEntries, 1)
796      }
797    }
798  }
799}
800
801class IssueQueueJumpBundle extends Bundle {
802  val pc = UInt(VAddrData().dataWidth.W)
803}
804
805class IssueQueueLoadBundle(implicit p: Parameters) extends XSBundle {
806  val fastMatch = UInt(backendParams.LduCnt.W)
807  val fastImm = UInt(12.W)
808}
809
810class IssueQueueIntIO()(implicit p: Parameters, params: IssueBlockParams) extends IssueQueueIO
811
812class IssueQueueIntImp(override val wrapper: IssueQueue)(implicit p: Parameters, iqParams: IssueBlockParams)
813  extends IssueQueueImp(wrapper)
814{
815  io.suggestName("none")
816  override lazy val io = IO(new IssueQueueIntIO).suggestName("io")
817
818  if(params.needPc) {
819    entries.io.enq.zipWithIndex.foreach { case (entriesEnq, i) =>
820      entriesEnq.bits.status.pc.foreach(_ := io.enq(i).bits.pc)
821    }
822  }
823
824  io.deq.zipWithIndex.foreach{ case (deq, i) => {
825    deq.bits.common.pc.foreach(_ := deqEntryVec(i).bits.status.pc.get)
826    deq.bits.common.preDecode.foreach(_ := deqEntryVec(i).bits.payload.preDecodeInfo)
827    deq.bits.common.ftqIdx.foreach(_ := deqEntryVec(i).bits.payload.ftqPtr)
828    deq.bits.common.ftqOffset.foreach(_ := deqEntryVec(i).bits.payload.ftqOffset)
829    deq.bits.common.predictInfo.foreach(x => {
830      x.target := DontCare
831      x.taken := deqEntryVec(i).bits.payload.pred_taken
832    })
833    // for std
834    deq.bits.common.sqIdx.foreach(_ := deqEntryVec(i).bits.payload.sqIdx)
835    // for i2f
836    deq.bits.common.fpu.foreach(_ := deqEntryVec(i).bits.payload.fpu)
837  }}
838}
839
840class IssueQueueVfImp(override val wrapper: IssueQueue)(implicit p: Parameters, iqParams: IssueBlockParams)
841  extends IssueQueueImp(wrapper)
842{
843  s0_enqBits.foreach{ x =>
844    x.srcType(3) := SrcType.vp // v0: mask src
845    x.srcType(4) := SrcType.vp // vl&vtype
846  }
847  io.deq.zipWithIndex.foreach{ case (deq, i) => {
848    deq.bits.common.fpu.foreach(_ := deqEntryVec(i).bits.payload.fpu)
849    deq.bits.common.vpu.foreach(_ := deqEntryVec(i).bits.payload.vpu)
850    deq.bits.common.vpu.foreach(_.vuopIdx := deqEntryVec(i).bits.payload.uopIdx)
851    deq.bits.common.vpu.foreach(_.lastUop := deqEntryVec(i).bits.payload.lastUop)
852  }}
853}
854
855class IssueQueueMemBundle(implicit p: Parameters, params: IssueBlockParams) extends Bundle {
856  val feedbackIO = Flipped(Vec(params.numDeq, new MemRSFeedbackIO))
857  val checkWait = new Bundle {
858    val stIssuePtr = Input(new SqPtr)
859    val memWaitUpdateReq = Flipped(new MemWaitUpdateReq)
860  }
861  val loadFastMatch = Output(Vec(params.LduCnt, new IssueQueueLoadBundle))
862
863  // vector
864  val sqDeqPtr = OptionWrapper(params.isVecMemIQ, Input(new SqPtr))
865  val lqDeqPtr = OptionWrapper(params.isVecMemIQ, Input(new LqPtr))
866}
867
868class IssueQueueMemIO(implicit p: Parameters, params: IssueBlockParams) extends IssueQueueIO {
869  val memIO = Some(new IssueQueueMemBundle)
870}
871
872class IssueQueueMemAddrImp(override val wrapper: IssueQueue)(implicit p: Parameters, params: IssueBlockParams)
873  extends IssueQueueImp(wrapper) with HasCircularQueuePtrHelper {
874
875  require(params.StdCnt == 0 && (params.LduCnt + params.StaCnt + params.HyuCnt + params.VlduCnt) > 0, "IssueQueueMemAddrImp can only be instance of MemAddr IQ, " +
876    s"StdCnt: ${params.StdCnt}, LduCnt: ${params.LduCnt}, StaCnt: ${params.StaCnt}, HyuCnt: ${params.HyuCnt}")
877  println(s"[IssueQueueMemAddrImp] StdCnt: ${params.StdCnt}, LduCnt: ${params.LduCnt}, StaCnt: ${params.StaCnt}, HyuCnt: ${params.HyuCnt}")
878
879  io.suggestName("none")
880  override lazy val io = IO(new IssueQueueMemIO).suggestName("io")
881  private val memIO = io.memIO.get
882
883  memIO.loadFastMatch := 0.U.asTypeOf(memIO.loadFastMatch) // TODO: is still needed?
884
885  for (i <- io.enq.indices) {
886    val blockNotReleased = isAfter(io.enq(i).bits.sqIdx, memIO.checkWait.stIssuePtr)
887    val storeAddrWaitForIsIssuing = VecInit((0 until StorePipelineWidth).map(i => {
888      memIO.checkWait.memWaitUpdateReq.robIdx(i).valid &&
889        memIO.checkWait.memWaitUpdateReq.robIdx(i).bits.value === io.enq(i).bits.waitForRobIdx.value
890    })).asUInt.orR && !io.enq(i).bits.loadWaitStrict // is waiting for store addr ready
891    s0_enqBits(i).loadWaitBit := io.enq(i).bits.loadWaitBit && !storeAddrWaitForIsIssuing && blockNotReleased
892    // when have vpu
893    if (params.VlduCnt > 0 || params.VstuCnt > 0) {
894      s0_enqBits(i).srcType(3) := SrcType.vp // v0: mask src
895      s0_enqBits(i).srcType(4) := SrcType.vp // vl&vtype
896    }
897  }
898
899  for (i <- entries.io.enq.indices) {
900    entries.io.enq(i).bits.status match { case enqData =>
901      enqData.blocked := false.B // s0_enqBits(i).loadWaitBit
902      enqData.mem.get.strictWait := s0_enqBits(i).loadWaitStrict
903      enqData.mem.get.waitForStd := false.B
904      enqData.mem.get.waitForRobIdx := s0_enqBits(i).waitForRobIdx
905      enqData.mem.get.waitForSqIdx := 0.U.asTypeOf(enqData.mem.get.waitForSqIdx) // generated by sq, will be updated later
906      enqData.mem.get.sqIdx := s0_enqBits(i).sqIdx
907    }
908
909    entries.io.fromMem.get.slowResp.zipWithIndex.foreach { case (slowResp, i) =>
910      slowResp.valid                 := memIO.feedbackIO(i).feedbackSlow.valid
911      slowResp.bits.robIdx           := memIO.feedbackIO(i).feedbackSlow.bits.robIdx
912      slowResp.bits.uopIdx           := DontCare
913      slowResp.bits.respType         := Mux(memIO.feedbackIO(i).feedbackSlow.bits.hit, RSFeedbackType.fuIdle, RSFeedbackType.feedbackInvalid)
914      slowResp.bits.dataInvalidSqIdx := memIO.feedbackIO(i).feedbackSlow.bits.dataInvalidSqIdx
915      slowResp.bits.rfWen := DontCare
916      slowResp.bits.fuType := DontCare
917    }
918
919    entries.io.fromMem.get.fastResp.zipWithIndex.foreach { case (fastResp, i) =>
920      fastResp.valid                 := memIO.feedbackIO(i).feedbackFast.valid
921      fastResp.bits.robIdx           := memIO.feedbackIO(i).feedbackFast.bits.robIdx
922      fastResp.bits.uopIdx           := DontCare
923      fastResp.bits.respType         := Mux(memIO.feedbackIO(i).feedbackFast.bits.hit, RSFeedbackType.fuIdle, memIO.feedbackIO(i).feedbackFast.bits.sourceType)
924      fastResp.bits.dataInvalidSqIdx := 0.U.asTypeOf(fastResp.bits.dataInvalidSqIdx)
925      fastResp.bits.rfWen := DontCare
926      fastResp.bits.fuType := DontCare
927    }
928
929    entries.io.fromMem.get.memWaitUpdateReq := memIO.checkWait.memWaitUpdateReq
930    entries.io.fromMem.get.stIssuePtr := memIO.checkWait.stIssuePtr
931  }
932
933  io.deq.zipWithIndex.foreach { case (deq, i) =>
934    deq.bits.common.loadWaitBit.foreach(_ := deqEntryVec(i).bits.payload.loadWaitBit)
935    deq.bits.common.waitForRobIdx.foreach(_ := deqEntryVec(i).bits.payload.waitForRobIdx)
936    deq.bits.common.storeSetHit.foreach(_ := deqEntryVec(i).bits.payload.storeSetHit)
937    deq.bits.common.loadWaitStrict.foreach(_ := deqEntryVec(i).bits.payload.loadWaitStrict)
938    deq.bits.common.ssid.foreach(_ := deqEntryVec(i).bits.payload.ssid)
939    deq.bits.common.sqIdx.get := deqEntryVec(i).bits.payload.sqIdx
940    deq.bits.common.lqIdx.get := deqEntryVec(i).bits.payload.lqIdx
941    deq.bits.common.ftqIdx.foreach(_ := deqEntryVec(i).bits.payload.ftqPtr)
942    deq.bits.common.ftqOffset.foreach(_ := deqEntryVec(i).bits.payload.ftqOffset)
943    // when have vpu
944    if (params.VlduCnt > 0 || params.VstuCnt > 0) {
945      deq.bits.common.vpu.foreach(_ := deqEntryVec(i).bits.payload.vpu)
946      deq.bits.common.vpu.foreach(_.vuopIdx := deqEntryVec(i).bits.payload.uopIdx)
947    }
948  }
949}
950
951class IssueQueueVecMemImp(override val wrapper: IssueQueue)(implicit p: Parameters, params: IssueBlockParams)
952  extends IssueQueueImp(wrapper) with HasCircularQueuePtrHelper {
953
954  require((params.VstdCnt + params.VlduCnt + params.VstaCnt) > 0, "IssueQueueVecMemImp can only be instance of VecMem IQ")
955
956  io.suggestName("none")
957  override lazy val io = IO(new IssueQueueMemIO).suggestName("io")
958  private val memIO = io.memIO.get
959
960  def selectOldUop(robIdx: Seq[RobPtr], uopIdx: Seq[UInt], valid: Seq[Bool]): Vec[Bool] = {
961    val compareVec = (0 until robIdx.length).map(i => (0 until i).map(j => isAfter(robIdx(j), robIdx(i)) || (robIdx(j).value === robIdx(i).value && uopIdx(i) < uopIdx(j))))
962    val resultOnehot = VecInit((0 until robIdx.length).map(i => Cat((0 until robIdx.length).map(j =>
963      (if (j < i) !valid(j) || compareVec(i)(j)
964      else if (j == i) valid(i)
965      else !valid(j) || !compareVec(j)(i))
966    )).andR))
967    resultOnehot
968  }
969
970  val robIdxVec = entries.io.robIdx.get
971  val uopIdxVec = entries.io.uopIdx.get
972  val allEntryOldestOH = selectOldUop(robIdxVec, uopIdxVec, validVec)
973
974  finalDeqSelValidVec.head := (allEntryOldestOH.asUInt & canIssueVec.asUInt).orR
975  finalDeqSelOHVec.head := allEntryOldestOH.asUInt & canIssueVec.asUInt
976
977  if (params.isVecMemAddrIQ) {
978    s0_enqBits.foreach{ x =>
979      x.srcType(3) := SrcType.vp // v0: mask src
980      x.srcType(4) := SrcType.vp // vl&vtype
981    }
982
983    for (i <- io.enq.indices) {
984      s0_enqBits(i).loadWaitBit := false.B
985    }
986
987    for (i <- entries.io.enq.indices) {
988      entries.io.enq(i).bits.status match { case enqData =>
989        enqData.blocked := false.B // s0_enqBits(i).loadWaitBit
990        enqData.mem.get.strictWait := s0_enqBits(i).loadWaitStrict
991        enqData.mem.get.waitForStd := false.B
992        enqData.mem.get.waitForRobIdx := s0_enqBits(i).waitForRobIdx
993        enqData.mem.get.waitForSqIdx := 0.U.asTypeOf(enqData.mem.get.waitForSqIdx) // generated by sq, will be updated later
994        enqData.mem.get.sqIdx := s0_enqBits(i).sqIdx
995      }
996
997      entries.io.fromMem.get.slowResp.zipWithIndex.foreach { case (slowResp, i) =>
998        slowResp.valid                 := memIO.feedbackIO(i).feedbackSlow.valid
999        slowResp.bits.robIdx           := memIO.feedbackIO(i).feedbackSlow.bits.robIdx
1000        slowResp.bits.uopIdx           := DontCare
1001        slowResp.bits.respType         := Mux(memIO.feedbackIO(i).feedbackSlow.bits.hit, RSFeedbackType.fuIdle, RSFeedbackType.feedbackInvalid)
1002        slowResp.bits.dataInvalidSqIdx := memIO.feedbackIO(i).feedbackSlow.bits.dataInvalidSqIdx
1003        slowResp.bits.rfWen := DontCare
1004        slowResp.bits.fuType := DontCare
1005      }
1006
1007      entries.io.fromMem.get.fastResp.zipWithIndex.foreach { case (fastResp, i) =>
1008        fastResp.valid                 := memIO.feedbackIO(i).feedbackFast.valid
1009        fastResp.bits.robIdx           := memIO.feedbackIO(i).feedbackFast.bits.robIdx
1010        fastResp.bits.uopIdx           := DontCare
1011        fastResp.bits.respType         := memIO.feedbackIO(i).feedbackFast.bits.sourceType
1012        fastResp.bits.dataInvalidSqIdx := 0.U.asTypeOf(fastResp.bits.dataInvalidSqIdx)
1013        fastResp.bits.rfWen := DontCare
1014        fastResp.bits.fuType := DontCare
1015      }
1016
1017      entries.io.fromMem.get.memWaitUpdateReq := memIO.checkWait.memWaitUpdateReq
1018      entries.io.fromMem.get.stIssuePtr := memIO.checkWait.stIssuePtr
1019    }
1020  }
1021
1022  for (i <- entries.io.enq.indices) {
1023    entries.io.enq(i).bits.status match { case enqData =>
1024      enqData.vecMem.get.sqIdx := s0_enqBits(i).sqIdx
1025      enqData.vecMem.get.lqIdx := s0_enqBits(i).lqIdx
1026    }
1027  }
1028
1029  entries.io.fromLsq.get.sqDeqPtr := memIO.sqDeqPtr.get
1030  entries.io.fromLsq.get.lqDeqPtr := memIO.lqDeqPtr.get
1031
1032  io.deq.zipWithIndex.foreach { case (deq, i) =>
1033    deq.bits.common.sqIdx.foreach(_ := deqEntryVec(i).bits.payload.sqIdx)
1034    deq.bits.common.lqIdx.foreach(_ := deqEntryVec(i).bits.payload.lqIdx)
1035    if (params.isVecLdAddrIQ) {
1036      deq.bits.common.ftqIdx.get := deqEntryVec(i).bits.payload.ftqPtr
1037      deq.bits.common.ftqOffset.get := deqEntryVec(i).bits.payload.ftqOffset
1038    }
1039    deq.bits.common.fpu.foreach(_ := deqEntryVec(i).bits.payload.fpu)
1040    deq.bits.common.vpu.foreach(_ := deqEntryVec(i).bits.payload.vpu)
1041    deq.bits.common.vpu.foreach(_.vuopIdx := deqEntryVec(i).bits.payload.uopIdx)
1042    deq.bits.common.vpu.foreach(_.lastUop := deqEntryVec(i).bits.payload.lastUop)
1043  }
1044}
1045