xref: /XiangShan/src/main/scala/xiangshan/backend/BackendParams.scala (revision 2aa3a76140dbd5875aa34625a2e1495c0cd33d92)
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.backend
18
19import org.chipsalliance.cde.config.Parameters
20import chisel3._
21import chisel3.util._
22import xiangshan.backend.Bundles._
23import xiangshan.backend.datapath.DataConfig._
24import xiangshan.backend.datapath.RdConfig._
25import xiangshan.backend.datapath.WbConfig._
26import xiangshan.backend.datapath.{WakeUpConfig, WbArbiterParams}
27import xiangshan.backend.exu.ExeUnitParams
28import xiangshan.backend.issue._
29import xiangshan.backend.regfile._
30import xiangshan.{DebugOptionsKey, XSCoreParamsKey}
31
32import scala.collection.mutable
33import scala.reflect.{ClassTag, classTag}
34
35case class BackendParams(
36  schdParams : Map[SchedulerType, SchdBlockParams],
37  pregParams : Seq[PregParams],
38  iqWakeUpParams : Seq[WakeUpConfig],
39) {
40
41  def debugEn(implicit p: Parameters): Boolean = p(DebugOptionsKey).AlwaysBasicDiff || p(DebugOptionsKey).EnableDifftest
42
43  val copyPdestInfo = mutable.HashMap[Int, (Int, Int)]()
44
45  def updateCopyPdestInfo: Unit = allExuParams.filter(_.copyWakeupOut).map(x => getExuIdx(x.name) -> (x.copyDistance, -1)).foreach { x =>
46    copyPdestInfo.addOne(x)
47  }
48  def isCopyPdest(exuIdx: Int): Boolean = {
49    copyPdestInfo.contains(exuIdx)
50  }
51  def connectWakeup(exuIdx: Int): Unit = {
52    println(s"[Backend] copyPdestInfo ${copyPdestInfo}")
53    if (copyPdestInfo.contains(exuIdx)) {
54      println(s"[Backend] exuIdx ${exuIdx} be connected, old info ${copyPdestInfo(exuIdx)}")
55      val newInfo = exuIdx -> (copyPdestInfo(exuIdx)._1, copyPdestInfo(exuIdx)._2 + 1)
56      copyPdestInfo.remove(exuIdx)
57      copyPdestInfo += newInfo
58      println(s"[Backend] exuIdx ${exuIdx} be connected, new info ${copyPdestInfo(exuIdx)}")
59    }
60  }
61  def getCopyPdestIndex(exuIdx: Int): Int = {
62    copyPdestInfo(exuIdx)._2 / copyPdestInfo(exuIdx)._1
63  }
64  def intSchdParams = schdParams.get(IntScheduler())
65  def fpSchdParams = schdParams.get(FpScheduler())
66  def vfSchdParams = schdParams.get(VfScheduler())
67  def memSchdParams = schdParams.get(MemScheduler())
68  def allSchdParams: Seq[SchdBlockParams] =
69    (Seq(intSchdParams) :+ fpSchdParams :+ vfSchdParams :+ memSchdParams)
70    .filter(_.nonEmpty)
71    .map(_.get)
72  def allIssueParams: Seq[IssueBlockParams] =
73    allSchdParams.map(_.issueBlockParams).flatten
74  def allExuParams: Seq[ExeUnitParams] =
75    allIssueParams.map(_.exuBlockParams).flatten
76
77  // filter not fake exu unit
78  def allRealExuParams =
79    allExuParams.filterNot(_.fakeUnit)
80
81  def intPregParams: IntPregParams = pregParams.collectFirst { case x: IntPregParams => x }.get
82  def fpPregParams: FpPregParams = pregParams.collectFirst { case x: FpPregParams => x }.get
83  def vfPregParams: VfPregParams = pregParams.collectFirst { case x: VfPregParams => x }.get
84  def v0PregParams: V0PregParams = pregParams.collectFirst { case x: V0PregParams => x }.get
85  def vlPregParams: VlPregParams = pregParams.collectFirst { case x: VlPregParams => x }.get
86  def getPregParams: Map[DataConfig, PregParams] = {
87    pregParams.map(x => (x.dataCfg, x)).toMap
88  }
89
90  def pregIdxWidth = pregParams.map(_.addrWidth).max
91
92  def numSrc      : Int = allSchdParams.map(_.issueBlockParams.map(_.numSrc).max).max
93  def numRegSrc   : Int = allSchdParams.map(_.issueBlockParams.map(_.numRegSrc).max).max
94  def numVecRegSrc: Int = allSchdParams.map(_.issueBlockParams.map(_.numVecSrc).max).max
95
96
97  def AluCnt = allSchdParams.map(_.AluCnt).sum
98  def StaCnt = allSchdParams.map(_.StaCnt).sum
99  def StdCnt = allSchdParams.map(_.StdCnt).sum
100  def LduCnt = allSchdParams.map(_.LduCnt).sum
101  def HyuCnt = allSchdParams.map(_.HyuCnt).sum
102  def VlduCnt = allSchdParams.map(_.VlduCnt).sum
103  def VstuCnt = allSchdParams.map(_.VstuCnt).sum
104  def LsExuCnt = StaCnt + LduCnt + HyuCnt
105  val LdExuCnt = LduCnt + HyuCnt
106  val StaExuCnt = StaCnt + HyuCnt
107  def JmpCnt = allSchdParams.map(_.JmpCnt).sum
108  def BrhCnt = allSchdParams.map(_.BrhCnt).sum
109  def CsrCnt = allSchdParams.map(_.CsrCnt).sum
110  def IqCnt = allSchdParams.map(_.issueBlockParams.length).sum
111
112  def numPcReadPort = allSchdParams.map(_.numPcReadPort).sum
113  def numPcMemReadPort = allExuParams.filter(_.needPc).size
114  def numTargetReadPort = allRealExuParams.count(x => x.needTarget)
115
116  def numPregRd(dataCfg: DataConfig) = this.getRfReadSize(dataCfg)
117  def numPregWb(dataCfg: DataConfig) = this.getRfWriteSize(dataCfg)
118
119  def numNoDataWB = allSchdParams.map(_.numNoDataWB).sum
120  def numExu = allSchdParams.map(_.numExu).sum
121
122  def numException = allRealExuParams.count(_.exceptionOut.nonEmpty)
123
124  def numRedirect = allSchdParams.map(_.numRedirect).sum
125
126  def numLoadDp = memSchdParams.get.issueBlockParams.filter(x => x.isLdAddrIQ || x.isHyAddrIQ).map(_.numEnq).sum
127
128  def numStoreDp = memSchdParams.get.issueBlockParams.filter(x => x.isStAddrIQ || x.isHyAddrIQ).map(_.numEnq).sum
129
130  def genIntIQValidNumBundle(implicit p: Parameters) = {
131    this.intSchdParams.get.issueBlockParams.map(x => Vec(x.numDeq, UInt((x.numEntries).U.getWidth.W)))
132  }
133
134  def genFpIQValidNumBundle(implicit p: Parameters) = {
135    this.fpSchdParams.get.issueBlockParams.map(x => Vec(x.numDeq, UInt((x.numEntries).U.getWidth.W)))
136  }
137
138  def genIntWriteBackBundle(implicit p: Parameters) = {
139    Seq.fill(this.getIntRfWriteSize)(new RfWritePortWithConfig(IntData(), intPregParams.addrWidth))
140  }
141
142  def genFpWriteBackBundle(implicit p: Parameters) = {
143    Seq.fill(this.getFpRfWriteSize)(new RfWritePortWithConfig(FpData(), fpPregParams.addrWidth))
144  }
145
146  def genVfWriteBackBundle(implicit p: Parameters) = {
147    Seq.fill(this.getVfRfWriteSize)(new RfWritePortWithConfig(VecData(), vfPregParams.addrWidth))
148  }
149
150  def genWriteBackBundles(implicit p: Parameters): Seq[RfWritePortWithConfig] = {
151    genIntWriteBackBundle ++ genVfWriteBackBundle
152  }
153
154  def genWrite2CtrlBundles(implicit p: Parameters): MixedVec[ValidIO[ExuOutput]] = {
155    MixedVec(allSchdParams.map(_.genExuOutputValidBundle.flatten).flatten)
156  }
157
158  def getIntWbArbiterParams: WbArbiterParams = {
159    val intWbCfgs: Seq[IntWB] = allSchdParams.flatMap(_.getWbCfgs.flatten.flatten.filter(_.writeInt)).map(_.asInstanceOf[IntWB])
160    datapath.WbArbiterParams(intWbCfgs, intPregParams, this)
161  }
162
163  def getVfWbArbiterParams: WbArbiterParams = {
164    val vfWbCfgs: Seq[VfWB] = allSchdParams.flatMap(_.getWbCfgs.flatten.flatten.filter(x => x.writeVec)).map(_.asInstanceOf[VfWB])
165    datapath.WbArbiterParams(vfWbCfgs, vfPregParams, this)
166  }
167
168  def getFpWbArbiterParams: WbArbiterParams = {
169    val fpWbCfgs: Seq[FpWB] = allSchdParams.flatMap(_.getWbCfgs.flatten.flatten.filter(x => x.writeFp)).map(_.asInstanceOf[FpWB])
170    datapath.WbArbiterParams(fpWbCfgs, vfPregParams, this)
171  }
172
173  /**
174    * Get regfile read port params
175    *
176    * @param dataCfg [[IntData]] or [[VecData]]
177    * @return Seq[port->Seq[(exuIdx, priority)]
178    */
179  def getRdPortParams(dataCfg: DataConfig) = {
180    // port -> Seq[exuIdx, priority]
181    val cfgs: Seq[(Int, Seq[(Int, Int)])] = allRealExuParams
182      .flatMap(x => x.rfrPortConfigs.flatten.map(xx => (xx, x.exuIdx)))
183      .filter { x => x._1.getDataConfig == dataCfg }
184      .map(x => (x._1.port, (x._2, x._1.priority)))
185      .groupBy(_._1)
186      .map(x => (x._1, x._2.map(_._2).sortBy({ case (priority, _) => priority })))
187      .toSeq
188      .sortBy(_._1)
189    cfgs
190  }
191
192  /**
193    * Get regfile write back port params
194    *
195    * @param dataCfg [[IntData]] or [[VecData]]
196    * @return Seq[port->Seq[(exuIdx, priority)]
197    */
198  def getWbPortParams(dataCfg: DataConfig) = {
199    val cfgs: Seq[(Int, Seq[(Int, Int)])] = allRealExuParams
200      .flatMap(x => x.wbPortConfigs.map(xx => (xx, x.exuIdx)))
201      .filter { x => x._1.dataCfg == dataCfg }
202      .map(x => (x._1.port, (x._2, x._1.priority)))
203      .groupBy(_._1)
204      .map(x => (x._1, x._2.map(_._2)))
205      .toSeq
206      .sortBy(_._1)
207    cfgs
208  }
209
210  def getRdPortIndices(dataCfg: DataConfig) = {
211    this.getRdPortParams(dataCfg).map(_._1)
212  }
213
214  def getWbPortIndices(dataCfg: DataConfig) = {
215    this.getWbPortParams(dataCfg).map(_._1)
216  }
217
218  def getRdCfgs[T <: RdConfig](implicit tag: ClassTag[T]): Seq[Seq[Seq[RdConfig]]] = {
219    val rdCfgs: Seq[Seq[Seq[RdConfig]]] = allIssueParams.map(
220      _.exuBlockParams.map(
221        _.rfrPortConfigs.map(
222          _.collectFirst{ case x: T => x }
223            .getOrElse(NoRD())
224        )
225      )
226    )
227    rdCfgs
228  }
229
230  def getAllWbCfgs: Seq[Seq[Set[PregWB]]] = {
231    allIssueParams.map(_.exuBlockParams.map(_.wbPortConfigs.toSet))
232  }
233
234  def getWbCfgs[T <: PregWB](implicit tag: ClassTag[T]): Seq[Seq[PregWB]] = {
235    val wbCfgs: Seq[Seq[PregWB]] = allIssueParams.map(_.exuBlockParams.map(_.wbPortConfigs.collectFirst{ case x: T => x }.getOrElse(NoWB())))
236    wbCfgs
237  }
238
239  /**
240    * Get size of read ports of int regfile
241    *
242    * @return if [[IntPregParams.numRead]] is [[None]], get size of ports in [[IntRD]]
243    */
244  def getIntRfReadSize = {
245    this.intPregParams.numRead.getOrElse(this.getRdPortIndices(IntData()).size)
246  }
247
248  /**
249    * Get size of write ports of vf regfile
250    *
251    * @return if [[IntPregParams.numWrite]] is [[None]], get size of ports in [[IntWB]]
252    */
253  def getIntRfWriteSize = {
254    this.intPregParams.numWrite.getOrElse(this.getWbPortIndices(IntData()).size)
255  }
256
257  /**
258   * Get size of write ports of fp regfile
259   *
260   * @return if [[FpPregParams.numWrite]] is [[None]], get size of ports in [[FpWB]]
261   */
262  def getFpRfWriteSize = {
263    this.fpPregParams.numWrite.getOrElse(this.getWbPortIndices(FpData()).size)
264  }
265
266  /**
267    * Get size of read ports of int regfile
268    *
269    * @return if [[VfPregParams.numRead]] is [[None]], get size of ports in [[VfRD]]
270    */
271  def getVfRfReadSize = {
272    this.vfPregParams.numRead.getOrElse(this.getRdPortIndices(VecData()).size)
273  }
274
275  /**
276    * Get size of write ports of vf regfile
277    *
278    * @return if [[VfPregParams.numWrite]] is [[None]], get size of ports in [[VfWB]]
279    */
280  def getVfRfWriteSize = {
281    this.vfPregParams.numWrite.getOrElse(this.getWbPortIndices(VecData()).size)
282  }
283
284  def getRfReadSize(dataCfg: DataConfig) = {
285    dataCfg match{
286      case IntData() => this.getPregParams(dataCfg).numRead.getOrElse(this.getRdPortIndices(dataCfg).size)
287      case FpData()  => this.getPregParams(dataCfg).numRead.getOrElse(this.getRdPortIndices(dataCfg).size)
288      case VecData() => this.getPregParams(dataCfg).numRead.getOrElse(this.getRdPortIndices(dataCfg).size)
289    }
290  }
291
292  def getRfWriteSize(dataCfg: DataConfig) = {
293    this.getPregParams(dataCfg).numWrite.getOrElse(this.getWbPortIndices(dataCfg).size)
294  }
295
296  def getExuIdx(name: String): Int = {
297    val exuParams = allRealExuParams
298    if (name != "WB") {
299      val foundExu = exuParams.find(_.name == name)
300      require(foundExu.nonEmpty, s"exu $name not find")
301      foundExu.get.exuIdx
302    } else
303      -1
304  }
305
306  def getExuName(idx: Int): String = {
307    val exuParams = allRealExuParams
308    exuParams(idx).name
309  }
310
311  def getExuParamByName(name: String): ExeUnitParams = {
312    val exuParams = allExuParams
313    exuParams.find(_.name == name).get
314  }
315
316  def getLdExuIdx(exu: ExeUnitParams): Int = {
317    val ldExuParams = allRealExuParams.filter(x => x.hasHyldaFu || x.hasLoadFu)
318    ldExuParams.indexOf(exu)
319  }
320
321  def getIntWBExeGroup: Map[Int, Seq[ExeUnitParams]] = allRealExuParams.groupBy(x => x.getIntWBPort.getOrElse(IntWB(port = -1)).port).filter(_._1 != -1)
322  def getFpWBExeGroup: Map[Int, Seq[ExeUnitParams]] = allRealExuParams.groupBy(x => x.getFpWBPort.getOrElse(FpWB(port = -1)).port).filter(_._1 != -1)
323  def getVfWBExeGroup: Map[Int, Seq[ExeUnitParams]] = allRealExuParams.groupBy(x => x.getVfWBPort.getOrElse(VfWB(port = -1)).port).filter(_._1 != -1)
324
325  private def isContinuous(portIndices: Seq[Int]): Boolean = {
326    val portIndicesSet = portIndices.toSet
327    portIndicesSet.min == 0 && portIndicesSet.max == portIndicesSet.size - 1
328  }
329
330  def configChecks = {
331    checkReadPortContinuous
332    checkWritePortContinuous
333    configCheck
334  }
335
336  def checkReadPortContinuous = {
337    pregParams.filterNot(_.isFake).foreach { x =>
338      if (x.numRead.isEmpty) {
339        val portIndices: Seq[Int] = getRdPortIndices(x.dataCfg)
340        require(isContinuous(portIndices),
341          s"The read ports of ${x.getClass.getSimpleName} should be continuous, " +
342            s"when numRead of ${x.getClass.getSimpleName} is None. The read port indices are $portIndices")
343      }
344    }
345  }
346
347  def checkWritePortContinuous = {
348    pregParams.filterNot(_.isFake).foreach { x =>
349      if (x.numWrite.isEmpty) {
350        val portIndices: Seq[Int] = getWbPortIndices(x.dataCfg)
351        require(
352          isContinuous(portIndices),
353          s"The write ports of ${x.getClass.getSimpleName} should be continuous, " +
354            s"when numWrite of ${x.getClass.getSimpleName} is None. The write port indices are $portIndices"
355        )
356      }
357    }
358  }
359
360  def configCheck = {
361    // check 0
362    val maxPortSource = 4
363
364    allRealExuParams.map {
365      case exuParam => exuParam.wbPortConfigs.collectFirst { case x: IntWB => x }
366    }.filter(_.isDefined).groupBy(_.get.port).foreach {
367      case (wbPort, priorities) => assert(priorities.size <= maxPortSource, "There has " + priorities.size + " exu's " + "Int WBport is " + wbPort + ", but the maximum is " + maxPortSource + ".")
368    }
369    allRealExuParams.map {
370      case exuParam => exuParam.wbPortConfigs.collectFirst { case x: VfWB => x }
371    }.filter(_.isDefined).groupBy(_.get.port).foreach {
372      case (wbPort, priorities) => assert(priorities.size <= maxPortSource, "There has " + priorities.size + " exu's " + "Vf  WBport is " + wbPort + ", but the maximum is " + maxPortSource + ".")
373    }
374
375    // check 1
376    // if some exus share the same wb port and rd ports,
377    // the exu with high priority at wb must also have high priority at rd.
378    val wbTypes = Seq(IntWB(), FpWB(), VfWB())
379    val rdTypes = Seq(IntRD(), FpRD(), VfRD())
380    for(wbType <- wbTypes){
381      for(rdType <- rdTypes){
382        println(s"[BackendParams] wbType: ${wbType}, rdType: ${rdType}")
383        allRealExuParams.map {
384          case exuParam =>
385            val wbPortConfigs = exuParam.wbPortConfigs
386            val wbConfigs = wbType match{
387              case _: IntWB => wbPortConfigs.collectFirst { case x: IntWB => x }
388              case _: FpWB  => wbPortConfigs.collectFirst { case x: FpWB => x }
389              case _: VfWB  => wbPortConfigs.collectFirst { case x: VfWB => x }
390              case _        => None
391            }
392            val rfReadPortConfigs = exuParam.rfrPortConfigs
393            val rdConfigs = rdType match{
394              case _: IntRD => rfReadPortConfigs.flatten.filter(_.isInstanceOf[IntRD])
395              case _: FpRD  => rfReadPortConfigs.flatten.filter(_.isInstanceOf[FpRD])
396              case _: VfRD  => rfReadPortConfigs.flatten.filter(_.isInstanceOf[VfRD])
397              case _        => Seq()
398            }
399            (wbConfigs, rdConfigs)
400        }.filter(_._1.isDefined)
401          .sortBy(_._1.get.priority)
402          .groupBy(_._1.get.port).map { case (wbPort, intWbRdPairs) =>
403            val rdCfgs = intWbRdPairs.map(_._2).flatten
404            println(s"[BackendParams] wb port ${wbPort} rdcfgs: ${rdCfgs}")
405            rdCfgs.groupBy(_.port).foreach { case (p, rdCfg) =>
406              //println(s"[BackendParams] rdport: ${p}, cfgs: ${rdCfg}")
407              rdCfg.zip(rdCfg.drop(1)).foreach { case (cfg0, cfg1) => assert(cfg0.priority <= cfg1.priority, s"an exu has high priority at ${wbType} wb port ${wbPort}, but has low priority at ${rdType} rd port ${p}") }
408            }
409        }
410      }
411    }
412  }
413}
414