xref: /XiangShan/src/main/scala/xiangshan/backend/Bundles.scala (revision ceba215ad376611ba6c994765c6e33e6b5749316)
1package xiangshan.backend
2
3import org.chipsalliance.cde.config.Parameters
4import chisel3._
5import chisel3.util.BitPat.bitPatToUInt
6import chisel3.util._
7import utils.BundleUtils.makeValid
8import utils.OptionWrapper
9import xiangshan._
10import xiangshan.backend.datapath.DataConfig._
11import xiangshan.backend.datapath.DataSource
12import xiangshan.backend.datapath.WbConfig.PregWB
13import xiangshan.backend.decode.{ImmUnion, XDecode}
14import xiangshan.backend.exu.ExeUnitParams
15import xiangshan.backend.fu.FuType
16import xiangshan.backend.fu.fpu.Bundles.Frm
17import xiangshan.backend.fu.vector.Bundles._
18import xiangshan.backend.issue.{IssueBlockParams, IssueQueueDeqRespBundle, SchedulerType}
19import xiangshan.backend.issue.EntryBundles._
20import xiangshan.backend.regfile.{RfReadPortWithConfig, RfWritePortWithConfig}
21import xiangshan.backend.rob.RobPtr
22import xiangshan.frontend._
23import xiangshan.mem.{LqPtr, SqPtr}
24import yunsuan.vector.VIFuParam
25
26object Bundles {
27  /**
28   * Connect Same Name Port like bundleSource := bundleSinkBudle.
29   *
30   * There is no limit to the number of ports on both sides.
31   *
32   * Don't forget to connect the remaining ports!
33   */
34  def connectSamePort (bundleSource: Bundle, bundleSink: Bundle):Unit = {
35    bundleSource.elements.foreach { case (name, data) =>
36      if (bundleSink.elements.contains(name))
37        data := bundleSink.elements(name)
38    }
39  }
40  // frontend -> backend
41  class StaticInst(implicit p: Parameters) extends XSBundle {
42    val instr           = UInt(32.W)
43    val pc              = UInt(VAddrBits.W)
44    val foldpc          = UInt(MemPredPCWidth.W)
45    val exceptionVec    = ExceptionVec()
46    val trigger         = new TriggerCf
47    val preDecodeInfo   = new PreDecodeInfo
48    val pred_taken      = Bool()
49    val crossPageIPFFix = Bool()
50    val ftqPtr          = new FtqPtr
51    val ftqOffset       = UInt(log2Up(PredictWidth).W)
52
53    def connectCtrlFlow(source: CtrlFlow): Unit = {
54      this.instr            := source.instr
55      this.pc               := source.pc
56      this.foldpc           := source.foldpc
57      this.exceptionVec     := source.exceptionVec
58      this.trigger          := source.trigger
59      this.preDecodeInfo    := source.pd
60      this.pred_taken       := source.pred_taken
61      this.crossPageIPFFix  := source.crossPageIPFFix
62      this.ftqPtr           := source.ftqPtr
63      this.ftqOffset        := source.ftqOffset
64    }
65  }
66
67  // StaticInst --[Decode]--> DecodedInst
68  class DecodedInst(implicit p: Parameters) extends XSBundle {
69    def numSrc = backendParams.numSrc
70    // passed from StaticInst
71    val instr           = UInt(32.W)
72    val pc              = UInt(VAddrBits.W)
73    val foldpc          = UInt(MemPredPCWidth.W)
74    val exceptionVec    = ExceptionVec()
75    val trigger         = new TriggerCf
76    val preDecodeInfo   = new PreDecodeInfo
77    val pred_taken      = Bool()
78    val crossPageIPFFix = Bool()
79    val ftqPtr          = new FtqPtr
80    val ftqOffset       = UInt(log2Up(PredictWidth).W)
81    // decoded
82    val srcType         = Vec(numSrc, SrcType())
83    val lsrc            = Vec(numSrc, UInt(LogicRegsWidth.W))
84    val ldest           = UInt(LogicRegsWidth.W)
85    val fuType          = FuType()
86    val fuOpType        = FuOpType()
87    val rfWen           = Bool()
88    val fpWen           = Bool()
89    val vecWen          = Bool()
90    val v0Wen           = Bool()
91    val vlWen           = Bool()
92    val isXSTrap        = Bool()
93    val waitForward     = Bool() // no speculate execution
94    val blockBackward   = Bool()
95    val flushPipe       = Bool() // This inst will flush all the pipe when commit, like exception but can commit
96    val canRobCompress  = Bool()
97    val selImm          = SelImm()
98    val imm             = UInt(ImmUnion.maxLen.W)
99    val fpu             = new FPUCtrlSignals
100    val vpu             = new VPUCtrlSignals
101    val vlsInstr        = Bool()
102    val wfflags         = Bool()
103    val isMove          = Bool()
104    val uopIdx          = UopIdx()
105    val uopSplitType    = UopSplitType()
106    val isVset          = Bool()
107    val firstUop        = Bool()
108    val lastUop         = Bool()
109    val numUops         = UInt(log2Up(MaxUopSize).W) // rob need this
110    val numWB           = UInt(log2Up(MaxUopSize).W) // rob need this
111    val commitType      = CommitType() // Todo: remove it
112
113    val debug_fuType    = OptionWrapper(backendParams.debugEn, FuType())
114
115    private def allSignals = srcType.take(3) ++ Seq(fuType, fuOpType, rfWen, fpWen, vecWen,
116      isXSTrap, waitForward, blockBackward, flushPipe, canRobCompress, uopSplitType, selImm)
117
118    def decode(inst: UInt, table: Iterable[(BitPat, List[BitPat])]): DecodedInst = {
119      val decoder: Seq[UInt] = ListLookup(
120        inst, XDecode.decodeDefault.map(bitPatToUInt),
121        table.map{ case (pat, pats) => (pat, pats.map(bitPatToUInt)) }.toArray
122      )
123      allSignals zip decoder foreach { case (s, d) => s := d }
124      debug_fuType.foreach(_ := fuType)
125      this
126    }
127
128    def isSoftPrefetch: Bool = {
129      fuType === FuType.alu.U && fuOpType === ALUOpType.or && selImm === SelImm.IMM_I && ldest === 0.U
130    }
131
132    def connectStaticInst(source: StaticInst): Unit = {
133      for ((name, data) <- this.elements) {
134        if (source.elements.contains(name)) {
135          data := source.elements(name)
136        }
137      }
138    }
139  }
140
141  // DecodedInst --[Rename]--> DynInst
142  class DynInst(implicit p: Parameters) extends XSBundle {
143    def numSrc          = backendParams.numSrc
144    // passed from StaticInst
145    val instr           = UInt(32.W)
146    val pc              = UInt(VAddrBits.W)
147    val foldpc          = UInt(MemPredPCWidth.W)
148    val exceptionVec    = ExceptionVec()
149    val hasException    = Bool()
150    val trigger         = new TriggerCf
151    val preDecodeInfo   = new PreDecodeInfo
152    val pred_taken      = Bool()
153    val crossPageIPFFix = Bool()
154    val ftqPtr          = new FtqPtr
155    val ftqOffset       = UInt(log2Up(PredictWidth).W)
156    // passed from DecodedInst
157    val srcType         = Vec(numSrc, SrcType())
158    val ldest           = UInt(LogicRegsWidth.W)
159    val fuType          = FuType()
160    val fuOpType        = FuOpType()
161    val rfWen           = Bool()
162    val fpWen           = Bool()
163    val vecWen          = Bool()
164    val v0Wen           = Bool()
165    val vlWen           = Bool()
166    val isXSTrap        = Bool()
167    val waitForward     = Bool() // no speculate execution
168    val blockBackward   = Bool()
169    val flushPipe       = Bool() // This inst will flush all the pipe when commit, like exception but can commit
170    val canRobCompress  = Bool()
171    val selImm          = SelImm()
172    val imm             = UInt(32.W)
173    val fpu             = new FPUCtrlSignals
174    val vpu             = new VPUCtrlSignals
175    val vlsInstr        = Bool()
176    val wfflags         = Bool()
177    val isMove          = Bool()
178    val uopIdx          = UopIdx()
179    val isVset          = Bool()
180    val firstUop        = Bool()
181    val lastUop         = Bool()
182    val numUops         = UInt(log2Up(MaxUopSize).W) // rob need this
183    val numWB           = UInt(log2Up(MaxUopSize).W) // rob need this
184    val commitType      = CommitType()
185    // rename
186    val srcState        = Vec(numSrc, SrcState())
187    val srcLoadDependency  = Vec(numSrc, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W)))
188    val psrc            = Vec(numSrc, UInt(PhyRegIdxWidth.W))
189    val pdest           = UInt(PhyRegIdxWidth.W)
190    // reg cache
191    val useRegCache     = Vec(backendParams.numIntRegSrc, Bool())
192    val regCacheIdx     = Vec(backendParams.numIntRegSrc, UInt(RegCacheIdxWidth.W))
193    val robIdx          = new RobPtr
194    val instrSize       = UInt(log2Ceil(RenameWidth + 1).W)
195    val dirtyFs         = Bool()
196    val dirtyVs         = Bool()
197
198    val eliminatedMove  = Bool()
199    // Take snapshot at this CFI inst
200    val snapshot        = Bool()
201    val debugInfo       = new PerfDebugInfo
202    val storeSetHit     = Bool() // inst has been allocated an store set
203    val waitForRobIdx   = new RobPtr // store set predicted previous store robIdx
204    // Load wait is needed
205    // load inst will not be executed until former store (predicted by mdp) addr calcuated
206    val loadWaitBit     = Bool()
207    // If (loadWaitBit && loadWaitStrict), strict load wait is needed
208    // load inst will not be executed until ALL former store addr calcuated
209    val loadWaitStrict  = Bool()
210    val ssid            = UInt(SSIDWidth.W)
211    // Todo
212    val lqIdx = new LqPtr
213    val sqIdx = new SqPtr
214    // debug module
215    val singleStep      = Bool()
216    // schedule
217    val replayInst      = Bool()
218
219    val debug_fuType    = OptionWrapper(backendParams.debugEn, FuType())
220
221    val numLsElem       = NumLsElem()
222
223    def getDebugFuType: UInt = debug_fuType.getOrElse(fuType)
224
225    def isLUI: Bool = this.fuType === FuType.alu.U && (this.selImm === SelImm.IMM_U || this.selImm === SelImm.IMM_LUI32)
226    def isLUI32: Bool = this.selImm === SelImm.IMM_LUI32
227    def isWFI: Bool = this.fuType === FuType.csr.U && fuOpType === CSROpType.wfi
228
229    def isSvinvalBegin(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && !flush
230    def isSvinval(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.sfence && !flush
231    def isSvinvalEnd(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && flush
232    def isNotSvinval = !FuType.isFence(fuType)
233
234    def isHls: Bool = {
235      fuType === FuType.ldu.U && LSUOpType.isHlv(fuOpType) || fuType === FuType.stu.U && LSUOpType.isHsv(fuOpType)
236    }
237
238    def isVecOPF: Bool = {
239      FuType.isVecOPF(fuType)
240    }
241
242    def srcIsReady: Vec[Bool] = {
243      VecInit(this.srcType.zip(this.srcState).map {
244        case (t, s) => SrcType.isNotReg(t) || SrcState.isReady(s)
245      })
246    }
247
248    def clearExceptions(
249      exceptionBits: Seq[Int] = Seq(),
250      flushPipe    : Boolean = false,
251      replayInst   : Boolean = false
252    ): DynInst = {
253      this.exceptionVec.zipWithIndex.filterNot(x => exceptionBits.contains(x._2)).foreach(_._1 := false.B)
254      if (!flushPipe) { this.flushPipe := false.B }
255      if (!replayInst) { this.replayInst := false.B }
256      this
257    }
258
259    def needWriteRf: Bool = (rfWen && ldest =/= 0.U) || fpWen || vecWen || v0Wen || vlWen
260  }
261
262  trait BundleSource {
263    var wakeupSource = "undefined"
264    var idx = 0
265  }
266
267  /**
268    *
269    * @param pregIdxWidth index width of preg
270    * @param exuIndices exu indices of wakeup bundle
271    */
272  sealed abstract class IssueQueueWakeUpBaseBundle(pregIdxWidth: Int, val exuIndices: Seq[Int])(implicit p: Parameters) extends XSBundle {
273    val rfWen = Bool()
274    val fpWen = Bool()
275    val vecWen = Bool()
276    val v0Wen = Bool()
277    val vlWen = Bool()
278    val pdest = UInt(pregIdxWidth.W)
279
280    /**
281      * @param successor Seq[(psrc, srcType)]
282      * @return Seq[if wakeup psrc]
283      */
284    def wakeUp(successor: Seq[(UInt, UInt)], valid: Bool): Seq[Bool] = {
285      successor.map { case (thatPsrc, srcType) =>
286        val pdestMatch = pdest === thatPsrc
287        pdestMatch && (
288          SrcType.isFp(srcType) && this.fpWen ||
289            SrcType.isXp(srcType) && this.rfWen ||
290            SrcType.isVp(srcType) && this.vecWen
291          ) && valid
292      }
293    }
294    def wakeUpV0(successor: (UInt, UInt), valid: Bool): Bool = {
295      val (thatPsrc, srcType) = successor
296      val pdestMatch = pdest === thatPsrc
297      pdestMatch && (
298        SrcType.isV0(srcType) && this.v0Wen
299      ) && valid
300    }
301    def wakeUpVl(successor: (UInt, UInt), valid: Bool): Bool = {
302      val (thatPsrc, srcType) = successor
303      val pdestMatch = pdest === thatPsrc
304      pdestMatch && (
305        SrcType.isVp(srcType) && this.vlWen
306      ) && valid
307    }
308    def wakeUpFromIQ(successor: Seq[(UInt, UInt)]): Seq[Bool] = {
309      successor.map { case (thatPsrc, srcType) =>
310        val pdestMatch = pdest === thatPsrc
311        pdestMatch && (
312          SrcType.isFp(srcType) && this.fpWen ||
313            SrcType.isXp(srcType) && this.rfWen ||
314            SrcType.isVp(srcType) && this.vecWen
315          )
316      }
317    }
318    def wakeUpV0FromIQ(successor: (UInt, UInt)): Bool = {
319      val (thatPsrc, srcType) = successor
320      val pdestMatch = pdest === thatPsrc
321      pdestMatch && (
322        SrcType.isV0(srcType) && this.v0Wen
323      )
324    }
325    def wakeUpVlFromIQ(successor: (UInt, UInt)): Bool = {
326      val (thatPsrc, srcType) = successor
327      val pdestMatch = pdest === thatPsrc
328      pdestMatch && (
329        SrcType.isVp(srcType) && this.vlWen
330      )
331    }
332
333    def hasOnlyOneSource: Boolean = exuIndices.size == 1
334
335    def hasMultiSources: Boolean = exuIndices.size > 1
336
337    def isWBWakeUp = this.isInstanceOf[IssueQueueWBWakeUpBundle]
338
339    def isIQWakeUp = this.isInstanceOf[IssueQueueIQWakeUpBundle]
340
341    def exuIdx: Int = {
342      require(hasOnlyOneSource)
343      this.exuIndices.head
344    }
345  }
346
347  class IssueQueueWBWakeUpBundle(exuIndices: Seq[Int], backendParams: BackendParams)(implicit p: Parameters) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, exuIndices) {
348
349  }
350
351  class IssueQueueIQWakeUpBundle(
352    exuIdx: Int,
353    backendParams: BackendParams,
354    copyWakeupOut: Boolean = false,
355    copyNum: Int = 0
356  )(implicit p: Parameters) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, Seq(exuIdx)) {
357    val loadDependency = Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W))
358    val is0Lat = Bool()
359    val params = backendParams.allExuParams.filter(_.exuIdx == exuIdx).head
360    val rcDest = OptionWrapper(params.needWriteRegCache, UInt(RegCacheIdxWidth.W))
361    val pdestCopy  = OptionWrapper(copyWakeupOut, Vec(copyNum, UInt(params.wbPregIdxWidth.W)))
362    val rfWenCopy  = OptionWrapper(copyWakeupOut && params.needIntWen, Vec(copyNum, Bool()))
363    val fpWenCopy  = OptionWrapper(copyWakeupOut && params.needFpWen, Vec(copyNum, Bool()))
364    val vecWenCopy = OptionWrapper(copyWakeupOut && params.needVecWen, Vec(copyNum, Bool()))
365    val v0WenCopy = OptionWrapper(copyWakeupOut && params.needV0Wen, Vec(copyNum, Bool()))
366    val vlWenCopy = OptionWrapper(copyWakeupOut && params.needVlWen, Vec(copyNum, Bool()))
367    val loadDependencyCopy = OptionWrapper(copyWakeupOut && params.isIQWakeUpSink, Vec(copyNum, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W))))
368
369    def fromExuInput(exuInput: ExuInput): Unit = {
370      this.rfWen := exuInput.rfWen.getOrElse(false.B)
371      this.fpWen := exuInput.fpWen.getOrElse(false.B)
372      this.vecWen := exuInput.vecWen.getOrElse(false.B)
373      this.v0Wen := exuInput.v0Wen.getOrElse(false.B)
374      this.vlWen := exuInput.vlWen.getOrElse(false.B)
375      this.pdest := exuInput.pdest
376    }
377  }
378
379  class VPUCtrlSignals(implicit p: Parameters) extends XSBundle {
380    // vtype
381    val vill      = Bool()
382    val vma       = Bool()    // 1: agnostic, 0: undisturbed
383    val vta       = Bool()    // 1: agnostic, 0: undisturbed
384    val vsew      = VSew()
385    val vlmul     = VLmul()   // 1/8~8      --> -3~3
386
387    // spec vtype
388    val specVill  = Bool()
389    val specVma   = Bool()    // 1: agnostic, 0: undisturbed
390    val specVta   = Bool()    // 1: agnostic, 0: undisturbed
391    val specVsew  = VSew()
392    val specVlmul = VLmul()   // 1/8~8      --> -3~3
393
394    val vm        = Bool()    // 0: need v0.t
395    val vstart    = Vl()
396
397    // float rounding mode
398    val frm       = Frm()
399    // scalar float instr and vector float reduction
400    val fpu       = Fpu()
401    // vector fix int rounding mode
402    val vxrm      = Vxrm()
403    // vector uop index, exclude other non-vector uop
404    val vuopIdx   = UopIdx()
405    val lastUop   = Bool()
406    // maybe used if data dependancy
407    val vmask     = UInt(V0Data().dataWidth.W)
408    val vl        = Vl()
409
410    // vector load/store
411    val nf        = Nf()
412    val veew      = VEew()
413
414    val isReverse = Bool() // vrsub, vrdiv
415    val isExt     = Bool()
416    val isNarrow  = Bool()
417    val isDstMask = Bool() // vvm, vvvm, mmm
418    val isOpMask  = Bool() // vmand, vmnand
419    val isMove    = Bool() // vmv.s.x, vmv.v.v, vmv.v.x, vmv.v.i
420
421    val isDependOldvd = Bool() // some instruction's computation depends on oldvd
422    val isWritePartVd = Bool() // some instruction's computation writes part of vd, such as vredsum
423
424    def vtype: VType = {
425      val res = Wire(VType())
426      res.illegal := this.vill
427      res.vma     := this.vma
428      res.vta     := this.vta
429      res.vsew    := this.vsew
430      res.vlmul   := this.vlmul
431      res
432    }
433
434    def specVType: VType = {
435      val res = Wire(VType())
436      res.illegal := this.specVill
437      res.vma     := this.specVma
438      res.vta     := this.specVta
439      res.vsew    := this.specVsew
440      res.vlmul   := this.specVlmul
441      res
442    }
443
444    def vconfig: VConfig = {
445      val res = Wire(VConfig())
446      res.vtype := this.vtype
447      res.vl    := this.vl
448      res
449    }
450
451    def connectVType(source: VType): Unit = {
452      this.vill  := source.illegal
453      this.vma   := source.vma
454      this.vta   := source.vta
455      this.vsew  := source.vsew
456      this.vlmul := source.vlmul
457    }
458  }
459
460  // DynInst --[IssueQueue]--> DataPath
461  class IssueQueueIssueBundle(
462    iqParams: IssueBlockParams,
463    val exuParams: ExeUnitParams,
464  )(implicit
465    p: Parameters
466  ) extends XSBundle {
467    private val rfReadDataCfgSet: Seq[Set[DataConfig]] = exuParams.getRfReadDataCfgSet
468
469    val rf: MixedVec[MixedVec[RfReadPortWithConfig]] = Flipped(MixedVec(
470      rfReadDataCfgSet.map((set: Set[DataConfig]) =>
471        MixedVec(set.map((x: DataConfig) => new RfReadPortWithConfig(x, exuParams.rdPregIdxWidth)).toSeq)
472      )
473    ))
474
475    val srcType = Vec(exuParams.numRegSrc, SrcType()) // used to select imm or reg data
476    val rcIdx = OptionWrapper(exuParams.needReadRegCache, Vec(exuParams.numRegSrc, UInt(RegCacheIdxWidth.W))) // used to select regcache data
477    val immType = SelImm()                         // used to select imm extractor
478    val common = new ExuInput(exuParams)
479    val addrOH = UInt(iqParams.numEntries.W)
480
481    def exuIdx = exuParams.exuIdx
482    def getSource: SchedulerType = exuParams.getWBSource
483
484    def getRfReadValidBundle(issueValid: Bool): Seq[ValidIO[RfReadPortWithConfig]] = {
485      rf.zip(srcType).map {
486        case (rfRd: MixedVec[RfReadPortWithConfig], t: UInt) =>
487          makeValid(issueValid, rfRd.head)
488      }.toSeq
489    }
490  }
491
492  class OGRespBundle(implicit p:Parameters, params: IssueBlockParams) extends XSBundle {
493    val issueQueueParams = this.params
494    val og0resp = Valid(new EntryDeqRespBundle)
495    val og1resp = Valid(new EntryDeqRespBundle)
496  }
497
498  class WbFuBusyTableWriteBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
499    private val intCertainLat = params.intLatencyCertain
500    private val fpCertainLat = params.fpLatencyCertain
501    private val vfCertainLat = params.vfLatencyCertain
502    private val v0CertainLat = params.v0LatencyCertain
503    private val vlCertainLat = params.vlLatencyCertain
504    private val intLat = params.intLatencyValMax
505    private val fpLat = params.fpLatencyValMax
506    private val vfLat = params.vfLatencyValMax
507    private val v0Lat = params.v0LatencyValMax
508    private val vlLat = params.vlLatencyValMax
509
510    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
511    val fpWbBusyTable = OptionWrapper(fpCertainLat, UInt((fpLat + 1).W))
512    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
513    val v0WbBusyTable = OptionWrapper(v0CertainLat, UInt((v0Lat + 1).W))
514    val vlWbBusyTable = OptionWrapper(vlCertainLat, UInt((vlLat + 1).W))
515    val intDeqRespSet = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
516    val fpDeqRespSet = OptionWrapper(fpCertainLat, UInt((fpLat + 1).W))
517    val vfDeqRespSet = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
518    val v0DeqRespSet = OptionWrapper(v0CertainLat, UInt((v0Lat + 1).W))
519    val vlDeqRespSet = OptionWrapper(vlCertainLat, UInt((vlLat + 1).W))
520  }
521
522  class WbFuBusyTableReadBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
523    private val intCertainLat = params.intLatencyCertain
524    private val fpCertainLat = params.fpLatencyCertain
525    private val vfCertainLat = params.vfLatencyCertain
526    private val v0CertainLat = params.v0LatencyCertain
527    private val vlCertainLat = params.vlLatencyCertain
528    private val intLat = params.intLatencyValMax
529    private val fpLat = params.fpLatencyValMax
530    private val vfLat = params.vfLatencyValMax
531    private val v0Lat = params.v0LatencyValMax
532    private val vlLat = params.vlLatencyValMax
533
534    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
535    val fpWbBusyTable = OptionWrapper(fpCertainLat, UInt((fpLat + 1).W))
536    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
537    val v0WbBusyTable = OptionWrapper(v0CertainLat, UInt((v0Lat + 1).W))
538    val vlWbBusyTable = OptionWrapper(vlCertainLat, UInt((vlLat + 1).W))
539  }
540
541  class WbConflictBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
542    private val intCertainLat = params.intLatencyCertain
543    private val fpCertainLat = params.fpLatencyCertain
544    private val vfCertainLat = params.vfLatencyCertain
545    private val v0CertainLat = params.v0LatencyCertain
546    private val vlCertainLat = params.vlLatencyCertain
547
548    val intConflict = OptionWrapper(intCertainLat, Bool())
549    val fpConflict = OptionWrapper(fpCertainLat, Bool())
550    val vfConflict = OptionWrapper(vfCertainLat, Bool())
551    val v0Conflict = OptionWrapper(v0CertainLat, Bool())
552    val vlConflict = OptionWrapper(vlCertainLat, Bool())
553  }
554
555  class ImmInfo extends Bundle {
556    val imm = UInt(32.W)
557    val immType = SelImm()
558  }
559
560  // DataPath --[ExuInput]--> Exu
561  class ExuInput(val params: ExeUnitParams, copyWakeupOut:Boolean = false, copyNum:Int = 0)(implicit p: Parameters) extends XSBundle {
562    val fuType        = FuType()
563    val fuOpType      = FuOpType()
564    val src           = Vec(params.numRegSrc, UInt(params.srcDataBitsMax.W))
565    val imm           = UInt(32.W)
566    val robIdx        = new RobPtr
567    val iqIdx         = UInt(log2Up(MemIQSizeMax).W)// Only used by store yet
568    val isFirstIssue  = Bool()                      // Only used by store yet
569    val pdestCopy  = OptionWrapper(copyWakeupOut, Vec(copyNum, UInt(params.wbPregIdxWidth.W)))
570    val rfWenCopy  = OptionWrapper(copyWakeupOut && params.needIntWen, Vec(copyNum, Bool()))
571    val fpWenCopy  = OptionWrapper(copyWakeupOut && params.needFpWen, Vec(copyNum, Bool()))
572    val vecWenCopy = OptionWrapper(copyWakeupOut && params.needVecWen, Vec(copyNum, Bool()))
573    val v0WenCopy  = OptionWrapper(copyWakeupOut && params.needV0Wen, Vec(copyNum, Bool()))
574    val vlWenCopy  = OptionWrapper(copyWakeupOut && params.needVlWen, Vec(copyNum, Bool()))
575    val loadDependencyCopy = OptionWrapper(copyWakeupOut && params.isIQWakeUpSink, Vec(copyNum, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W))))
576    val pdest         = UInt(params.wbPregIdxWidth.W)
577    val rfWen         = if (params.needIntWen)    Some(Bool())                        else None
578    val fpWen         = if (params.needFpWen)     Some(Bool())                        else None
579    val vecWen        = if (params.needVecWen)    Some(Bool())                        else None
580    val v0Wen         = if (params.needV0Wen)     Some(Bool())                        else None
581    val vlWen         = if (params.needVlWen)     Some(Bool())                        else None
582    val fpu           = if (params.writeFflags)   Some(new FPUCtrlSignals)            else None
583    val vpu           = if (params.needVPUCtrl)   Some(new VPUCtrlSignals)            else None
584    val flushPipe     = if (params.flushPipe)     Some(Bool())                        else None
585    val pc            = if (params.needPc)        Some(UInt(VAddrData().dataWidth.W)) else None
586    val preDecode     = if (params.hasPredecode)  Some(new PreDecodeInfo)             else None
587    val ftqIdx        = if (params.needPc || params.replayInst || params.hasStoreAddrFu || params.hasCSR)
588                                                  Some(new FtqPtr)                    else None
589    val ftqOffset     = if (params.needPc || params.replayInst || params.hasStoreAddrFu || params.hasCSR)
590                                                  Some(UInt(log2Up(PredictWidth).W))  else None
591    val predictInfo   = if (params.needPdInfo)  Some(new Bundle {
592      val target = UInt(VAddrData().dataWidth.W)
593      val taken = Bool()
594    }) else None
595    val loadWaitBit    = OptionWrapper(params.hasLoadExu, Bool())
596    val waitForRobIdx  = OptionWrapper(params.hasLoadExu, new RobPtr) // store set predicted previous store robIdx
597    val storeSetHit    = OptionWrapper(params.hasLoadExu, Bool()) // inst has been allocated an store set
598    val loadWaitStrict = OptionWrapper(params.hasLoadExu, Bool()) // load inst will not be executed until ALL former store addr calcuated
599    val ssid           = OptionWrapper(params.hasLoadExu, UInt(SSIDWidth.W))
600    // only vector load store need
601    val numLsElem      = OptionWrapper(params.hasVecLsFu, NumLsElem())
602
603    val sqIdx = if (params.hasMemAddrFu || params.hasStdFu) Some(new SqPtr) else None
604    val lqIdx = if (params.hasMemAddrFu) Some(new LqPtr) else None
605    val dataSources = Vec(params.numRegSrc, DataSource())
606    val l1ExuOH = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, ExuVec()))
607    val srcTimer = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, UInt(3.W)))
608    val loadDependency = OptionWrapper(params.isIQWakeUpSink, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W)))
609
610    val perfDebugInfo = new PerfDebugInfo()
611
612    def exuIdx = this.params.exuIdx
613
614    def needCancel(og0CancelOH: UInt, og1CancelOH: UInt) : Bool = {
615      if (params.isIQWakeUpSink) {
616        require(
617          og0CancelOH.getWidth == l1ExuOH.get.head.getWidth,
618          s"cancelVecSize: {og0: ${og0CancelOH.getWidth}, og1: ${og1CancelOH.getWidth}}"
619        )
620        val l1Cancel: Bool = l1ExuOH.get.zip(srcTimer.get).map {
621          case(exuOH: Vec[Bool], srcTimer: UInt) =>
622            (exuOH.asUInt & og0CancelOH).orR && srcTimer === 1.U
623        }.reduce(_ | _)
624        l1Cancel
625      } else {
626        false.B
627      }
628    }
629
630    def fromIssueBundle(source: IssueQueueIssueBundle): Unit = {
631      // src is assigned to rfReadData
632      this.fuType        := source.common.fuType
633      this.fuOpType      := source.common.fuOpType
634      this.imm           := source.common.imm
635      this.robIdx        := source.common.robIdx
636      this.pdest         := source.common.pdest
637      this.isFirstIssue  := source.common.isFirstIssue // Only used by mem debug log
638      this.iqIdx         := source.common.iqIdx        // Only used by mem feedback
639      this.dataSources   := source.common.dataSources
640      this.l1ExuOH       .foreach(_ := source.common.l1ExuOH.get)
641      this.rfWen         .foreach(_ := source.common.rfWen.get)
642      this.fpWen         .foreach(_ := source.common.fpWen.get)
643      this.vecWen        .foreach(_ := source.common.vecWen.get)
644      this.v0Wen         .foreach(_ := source.common.v0Wen.get)
645      this.vlWen         .foreach(_ := source.common.vlWen.get)
646      this.fpu           .foreach(_ := source.common.fpu.get)
647      this.vpu           .foreach(_ := source.common.vpu.get)
648      this.flushPipe     .foreach(_ := source.common.flushPipe.get)
649      this.pc            .foreach(_ := source.common.pc.get)
650      this.preDecode     .foreach(_ := source.common.preDecode.get)
651      this.ftqIdx        .foreach(_ := source.common.ftqIdx.get)
652      this.ftqOffset     .foreach(_ := source.common.ftqOffset.get)
653      this.predictInfo   .foreach(_ := source.common.predictInfo.get)
654      this.loadWaitBit   .foreach(_ := source.common.loadWaitBit.get)
655      this.waitForRobIdx .foreach(_ := source.common.waitForRobIdx.get)
656      this.storeSetHit   .foreach(_ := source.common.storeSetHit.get)
657      this.loadWaitStrict.foreach(_ := source.common.loadWaitStrict.get)
658      this.ssid          .foreach(_ := source.common.ssid.get)
659      this.lqIdx         .foreach(_ := source.common.lqIdx.get)
660      this.sqIdx         .foreach(_ := source.common.sqIdx.get)
661      this.numLsElem     .foreach(_ := source.common.numLsElem.get)
662      this.srcTimer      .foreach(_ := source.common.srcTimer.get)
663      this.loadDependency.foreach(_ := source.common.loadDependency.get.map(_ << 1))
664    }
665  }
666
667  // ExuInput --[FuncUnit]--> ExuOutput
668  class ExuOutput(
669    val params: ExeUnitParams,
670  )(implicit
671    val p: Parameters
672  ) extends Bundle with BundleSource with HasXSParameter {
673    val data         = Vec(params.wbPathNum, UInt(params.destDataBitsMax.W))
674    val pdest        = UInt(params.wbPregIdxWidth.W)
675    val robIdx       = new RobPtr
676    val intWen       = if (params.needIntWen)   Some(Bool())                  else None
677    val fpWen        = if (params.needFpWen)    Some(Bool())                  else None
678    val vecWen       = if (params.needVecWen)   Some(Bool())                  else None
679    val v0Wen        = if (params.needV0Wen)    Some(Bool())                  else None
680    val vlWen        = if (params.needVlWen)    Some(Bool())                  else None
681    val redirect     = if (params.hasRedirect)  Some(ValidIO(new Redirect))   else None
682    val fflags       = if (params.writeFflags)  Some(UInt(5.W))               else None
683    val wflags       = if (params.writeFflags)  Some(Bool())                  else None
684    val vxsat        = if (params.writeVxsat)   Some(Bool())                  else None
685    val exceptionVec = if (params.exceptionOut.nonEmpty) Some(ExceptionVec()) else None
686    val flushPipe    = if (params.flushPipe)    Some(Bool())                  else None
687    val replay       = if (params.replayInst)   Some(Bool())                  else None
688    val lqIdx        = if (params.hasLoadFu)    Some(new LqPtr())             else None
689    val sqIdx        = if (params.hasStoreAddrFu || params.hasStdFu)
690                                                Some(new SqPtr())             else None
691    val trigger      = if (params.trigger)      Some(new TriggerCf)           else None
692    // uop info
693    val predecodeInfo = if(params.hasPredecode) Some(new PreDecodeInfo) else None
694    // vldu used only
695    val vls = OptionWrapper(params.hasVLoadFu, new Bundle {
696      val vpu = new VPUCtrlSignals
697      val oldVdPsrc = UInt(PhyRegIdxWidth.W)
698      val vdIdx = UInt(3.W)
699      val vdIdxInField = UInt(3.W)
700      val isIndexed = Bool()
701      val isMasked = Bool()
702    })
703    val debug = new DebugBundle
704    val debugInfo = new PerfDebugInfo
705  }
706
707  // ExuOutput + DynInst --> WriteBackBundle
708  class WriteBackBundle(val params: PregWB, backendParams: BackendParams)(implicit p: Parameters) extends Bundle with BundleSource {
709    val rfWen = Bool()
710    val fpWen = Bool()
711    val vecWen = Bool()
712    val v0Wen = Bool()
713    val vlWen = Bool()
714    val pdest = UInt(params.pregIdxWidth(backendParams).W)
715    val data = UInt(params.dataWidth.W)
716    val robIdx = new RobPtr()(p)
717    val flushPipe = Bool()
718    val replayInst = Bool()
719    val redirect = ValidIO(new Redirect)
720    val fflags = UInt(5.W)
721    val vxsat = Bool()
722    val exceptionVec = ExceptionVec()
723    val debug = new DebugBundle
724    val debugInfo = new PerfDebugInfo
725
726    this.wakeupSource = s"WB(${params.toString})"
727
728    def fromExuOutput(source: ExuOutput, wbType: String) = {
729      val typeMap = Map("int" -> 0, "fp" -> 1, "vf" -> 2, "v0" -> 3, "vl" -> 4)
730      this.rfWen  := source.intWen.getOrElse(false.B)
731      this.fpWen  := source.fpWen.getOrElse(false.B)
732      this.vecWen := source.vecWen.getOrElse(false.B)
733      this.v0Wen  := source.v0Wen.getOrElse(false.B)
734      this.vlWen  := source.vlWen.getOrElse(false.B)
735      this.pdest  := source.pdest
736      this.data   := source.data(source.params.wbIndex(typeMap(wbType)))
737      this.robIdx := source.robIdx
738      this.flushPipe := source.flushPipe.getOrElse(false.B)
739      this.replayInst := source.replay.getOrElse(false.B)
740      this.redirect := source.redirect.getOrElse(0.U.asTypeOf(this.redirect))
741      this.fflags := source.fflags.getOrElse(0.U.asTypeOf(this.fflags))
742      this.vxsat := source.vxsat.getOrElse(0.U.asTypeOf(this.vxsat))
743      this.exceptionVec := source.exceptionVec.getOrElse(0.U.asTypeOf(this.exceptionVec))
744      this.debug := source.debug
745      this.debugInfo := source.debugInfo
746    }
747
748    def asIntRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
749      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(IntData()).addrWidth)))
750      rfWrite.wen := this.rfWen && fire
751      rfWrite.addr := this.pdest
752      rfWrite.data := this.data
753      rfWrite.intWen := this.rfWen
754      rfWrite.fpWen := false.B
755      rfWrite.vecWen := false.B
756      rfWrite.v0Wen := false.B
757      rfWrite.vlWen := false.B
758      rfWrite
759    }
760
761    def asFpRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
762      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(FpData()).addrWidth)))
763      rfWrite.wen := this.fpWen && fire
764      rfWrite.addr := this.pdest
765      rfWrite.data := this.data
766      rfWrite.intWen := false.B
767      rfWrite.fpWen := this.fpWen
768      rfWrite.vecWen := false.B
769      rfWrite.v0Wen := false.B
770      rfWrite.vlWen := false.B
771      rfWrite
772    }
773
774    def asVfRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
775      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(VecData()).addrWidth)))
776      rfWrite.wen := this.vecWen && fire
777      rfWrite.addr := this.pdest
778      rfWrite.data := this.data
779      rfWrite.intWen := false.B
780      rfWrite.fpWen := false.B
781      rfWrite.vecWen := this.vecWen
782      rfWrite.v0Wen := false.B
783      rfWrite.vlWen := false.B
784      rfWrite
785    }
786
787    def asV0RfWriteBundle(fire: Bool): RfWritePortWithConfig = {
788      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(V0Data()).addrWidth)))
789      rfWrite.wen := this.v0Wen && fire
790      rfWrite.addr := this.pdest
791      rfWrite.data := this.data
792      rfWrite.intWen := false.B
793      rfWrite.fpWen := false.B
794      rfWrite.vecWen := false.B
795      rfWrite.v0Wen := this.v0Wen
796      rfWrite.vlWen := false.B
797      rfWrite
798    }
799
800    def asVlRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
801      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(VlData()).addrWidth)))
802      rfWrite.wen := this.vlWen && fire
803      rfWrite.addr := this.pdest
804      rfWrite.data := this.data
805      rfWrite.intWen := false.B
806      rfWrite.fpWen := false.B
807      rfWrite.vecWen := false.B
808      rfWrite.v0Wen := false.B
809      rfWrite.vlWen := this.vlWen
810      rfWrite
811    }
812  }
813
814  // ExuOutput --> ExuBypassBundle --[DataPath]-->ExuInput
815  //                                /
816  //     [IssueQueue]--> ExuInput --
817  class ExuBypassBundle(
818    val params: ExeUnitParams,
819  )(implicit p: Parameters) extends XSBundle {
820    val intWen = Bool()
821    val data   = UInt(params.destDataBitsMax.W)
822    val pdest  = UInt(params.wbPregIdxWidth.W)
823  }
824
825  class ExceptionInfo(implicit p: Parameters) extends XSBundle {
826    val pc = UInt(VAddrData().dataWidth.W)
827    val instr = UInt(32.W)
828    val commitType = CommitType()
829    val exceptionVec = ExceptionVec()
830    val gpaddr = UInt(GPAddrBits.W)
831    val singleStep = Bool()
832    val crossPageIPFFix = Bool()
833    val isInterrupt = Bool()
834    val isHls = Bool()
835    val vls = Bool()
836    val trigger  = new TriggerCf
837  }
838
839  object UopIdx {
840    def apply()(implicit p: Parameters): UInt = UInt(log2Up(p(XSCoreParamsKey).MaxUopSize + 1).W)
841  }
842
843  object FuLatency {
844    def apply(): UInt = UInt(width.W)
845
846    def width = 4 // 0~15 // Todo: assosiate it with FuConfig
847  }
848
849  object ExuOH {
850    def apply(exuNum: Int): UInt = UInt(exuNum.W)
851
852    def apply()(implicit p: Parameters): UInt = UInt(width.W)
853
854    def width(implicit p: Parameters): Int = p(XSCoreParamsKey).backendParams.numExu
855  }
856
857  object ExuVec {
858    def apply(exuNum: Int): Vec[Bool] = Vec(exuNum, Bool())
859
860    def apply()(implicit p: Parameters): Vec[Bool] = Vec(width, Bool())
861
862    def width(implicit p: Parameters): Int = p(XSCoreParamsKey).backendParams.numExu
863  }
864
865  class CancelSignal(implicit p: Parameters) extends XSBundle {
866    val rfWen = Bool()
867    val fpWen = Bool()
868    val vecWen = Bool()
869    val v0Wen = Bool()
870    val vlWen = Bool()
871    val pdest = UInt(PhyRegIdxWidth.W)
872  }
873
874  class MemExuInput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
875    val uop = new DynInst
876    val src = if (isVector) Vec(5, UInt(VLEN.W)) else Vec(3, UInt(XLEN.W))
877    val iqIdx = UInt(log2Up(MemIQSizeMax).W)
878    val isFirstIssue = Bool()
879    val flowNum      = OptionWrapper(isVector, NumLsElem())
880
881    def src_rs1 = src(0)
882    def src_stride = src(1)
883    def src_vs3 = src(2)
884    def src_mask = if (isVector) src(3) else 0.U
885    def src_vl = if (isVector) src(4) else 0.U
886  }
887
888  class MemExuOutput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
889    val uop = new DynInst
890    val data = if (isVector) UInt(VLEN.W) else UInt(XLEN.W)
891    val mask = if (isVector) Some(UInt(VLEN.W)) else None
892    val vdIdx = if (isVector) Some(UInt(3.W)) else None // TODO: parameterize width
893    val vdIdxInField = if (isVector) Some(UInt(3.W)) else None
894    val debug = new DebugBundle
895
896    def isVls = FuType.isVls(uop.fuType)
897  }
898
899  class MemMicroOpRbExt(implicit p: Parameters) extends XSBundle {
900    val uop = new DynInst
901    val flag = UInt(1.W)
902  }
903
904  object LoadShouldCancel {
905    def apply(loadDependency: Option[Seq[UInt]], ldCancel: Seq[LoadCancelIO]): Bool = {
906      val ld1Cancel = loadDependency.map(_.zip(ldCancel.map(_.ld1Cancel)).map { case (dep, cancel) => cancel && dep(0)}.reduce(_ || _))
907      val ld2Cancel = loadDependency.map(_.zip(ldCancel.map(_.ld2Cancel)).map { case (dep, cancel) => cancel && dep(1)}.reduce(_ || _))
908      ld1Cancel.map(_ || ld2Cancel.get).getOrElse(false.B)
909    }
910  }
911}
912