xref: /XiangShan/src/main/scala/xiangshan/backend/Bundles.scala (revision 3952421b35cdab0f2e47eb99cae2bd35b8b98455)
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(6.W))
84    val ldest           = UInt(6.W)
85    val fuType          = FuType()
86    val fuOpType        = FuOpType()
87    val rfWen           = Bool()
88    val fpWen           = Bool()
89    val vecWen          = Bool()
90    val isXSTrap        = Bool()
91    val waitForward     = Bool() // no speculate execution
92    val blockBackward   = Bool()
93    val flushPipe       = Bool() // This inst will flush all the pipe when commit, like exception but can commit
94    val canRobCompress  = Bool()
95    val selImm          = SelImm()
96    val imm             = UInt(ImmUnion.maxLen.W)
97    val fpu             = new FPUCtrlSignals
98    val vpu             = new VPUCtrlSignals
99    val vlsInstr        = Bool()
100    val wfflags         = Bool()
101    val isMove          = Bool()
102    val uopIdx          = UopIdx()
103    val uopSplitType    = UopSplitType()
104    val isVset          = Bool()
105    val firstUop        = Bool()
106    val lastUop         = Bool()
107    val numUops         = UInt(log2Up(MaxUopSize).W) // rob need this
108    val numWB           = UInt(log2Up(MaxUopSize).W) // rob need this
109    val commitType      = CommitType() // Todo: remove it
110
111    val debug_fuType    = OptionWrapper(backendParams.debugEn, FuType())
112
113    private def allSignals = srcType.take(3) ++ Seq(fuType, fuOpType, rfWen, fpWen, vecWen,
114      isXSTrap, waitForward, blockBackward, flushPipe, canRobCompress, uopSplitType, selImm)
115
116    def decode(inst: UInt, table: Iterable[(BitPat, List[BitPat])]): DecodedInst = {
117      val decoder: Seq[UInt] = ListLookup(
118        inst, XDecode.decodeDefault.map(bitPatToUInt),
119        table.map{ case (pat, pats) => (pat, pats.map(bitPatToUInt)) }.toArray
120      )
121      allSignals zip decoder foreach { case (s, d) => s := d }
122      debug_fuType.foreach(_ := fuType)
123      this
124    }
125
126    def isSoftPrefetch: Bool = {
127      fuType === FuType.alu.U && fuOpType === ALUOpType.or && selImm === SelImm.IMM_I && ldest === 0.U
128    }
129
130    def connectStaticInst(source: StaticInst): Unit = {
131      for ((name, data) <- this.elements) {
132        if (source.elements.contains(name)) {
133          data := source.elements(name)
134        }
135      }
136    }
137  }
138
139  // DecodedInst --[Rename]--> DynInst
140  class DynInst(implicit p: Parameters) extends XSBundle {
141    def numSrc          = backendParams.numSrc
142    // passed from StaticInst
143    val instr           = UInt(32.W)
144    val pc              = UInt(VAddrBits.W)
145    val foldpc          = UInt(MemPredPCWidth.W)
146    val exceptionVec    = ExceptionVec()
147    val trigger         = new TriggerCf
148    val preDecodeInfo   = new PreDecodeInfo
149    val pred_taken      = Bool()
150    val crossPageIPFFix = Bool()
151    val ftqPtr          = new FtqPtr
152    val ftqOffset       = UInt(log2Up(PredictWidth).W)
153    // passed from DecodedInst
154    val srcType         = Vec(numSrc, SrcType())
155    val lsrc            = Vec(numSrc, UInt(6.W))
156    val ldest           = UInt(6.W)
157    val fuType          = FuType()
158    val fuOpType        = FuOpType()
159    val rfWen           = Bool()
160    val fpWen           = Bool()
161    val vecWen          = Bool()
162    val isXSTrap        = Bool()
163    val waitForward     = Bool() // no speculate execution
164    val blockBackward   = Bool()
165    val flushPipe       = Bool() // This inst will flush all the pipe when commit, like exception but can commit
166    val canRobCompress  = Bool()
167    val selImm          = SelImm()
168    val imm             = UInt(32.W)
169    val fpu             = new FPUCtrlSignals
170    val vpu             = new VPUCtrlSignals
171    val vlsInstr        = Bool()
172    val wfflags         = Bool()
173    val isMove          = Bool()
174    val uopIdx          = UopIdx()
175    val isVset          = Bool()
176    val firstUop        = Bool()
177    val lastUop         = Bool()
178    val numUops         = UInt(log2Up(MaxUopSize).W) // rob need this
179    val numWB           = UInt(log2Up(MaxUopSize).W) // rob need this
180    val commitType      = CommitType()
181    // rename
182    val srcState        = Vec(numSrc, SrcState())
183    val srcLoadDependency  = Vec(numSrc, Vec(LoadPipelineWidth, UInt(3.W)))
184    val psrc            = Vec(numSrc, UInt(PhyRegIdxWidth.W))
185    val pdest           = UInt(PhyRegIdxWidth.W)
186    val robIdx          = new RobPtr
187    val instrSize       = UInt(log2Ceil(RenameWidth + 1).W)
188    val dirtyFs         = Bool()
189
190    val eliminatedMove  = Bool()
191    // Take snapshot at this CFI inst
192    val snapshot        = Bool()
193    val debugInfo       = new PerfDebugInfo
194    val storeSetHit     = Bool() // inst has been allocated an store set
195    val waitForRobIdx   = new RobPtr // store set predicted previous store robIdx
196    // Load wait is needed
197    // load inst will not be executed until former store (predicted by mdp) addr calcuated
198    val loadWaitBit     = Bool()
199    // If (loadWaitBit && loadWaitStrict), strict load wait is needed
200    // load inst will not be executed until ALL former store addr calcuated
201    val loadWaitStrict  = Bool()
202    val ssid            = UInt(SSIDWidth.W)
203    // Todo
204    val lqIdx = new LqPtr
205    val sqIdx = new SqPtr
206    // debug module
207    val singleStep      = Bool()
208    // schedule
209    val replayInst      = Bool()
210
211    val debug_fuType    = OptionWrapper(backendParams.debugEn, FuType())
212
213    def getDebugFuType: UInt = debug_fuType.getOrElse(fuType)
214
215    def isLUI: Bool = this.fuType === FuType.alu.U && (this.selImm === SelImm.IMM_U || this.selImm === SelImm.IMM_LUI32)
216    def isLUI32: Bool = this.selImm === SelImm.IMM_LUI32
217    def isWFI: Bool = this.fuType === FuType.csr.U && fuOpType === CSROpType.wfi
218
219    def isSvinvalBegin(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && !flush
220    def isSvinval(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.sfence && !flush
221    def isSvinvalEnd(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && flush
222
223    def srcIsReady: Vec[Bool] = {
224      VecInit(this.srcType.zip(this.srcState).map {
225        case (t, s) => SrcType.isNotReg(t) || SrcState.isReady(s)
226      })
227    }
228
229    def clearExceptions(
230      exceptionBits: Seq[Int] = Seq(),
231      flushPipe    : Boolean = false,
232      replayInst   : Boolean = false
233    ): DynInst = {
234      this.exceptionVec.zipWithIndex.filterNot(x => exceptionBits.contains(x._2)).foreach(_._1 := false.B)
235      if (!flushPipe) { this.flushPipe := false.B }
236      if (!replayInst) { this.replayInst := false.B }
237      this
238    }
239
240    def needWriteRf: Bool = (rfWen && ldest =/= 0.U) || fpWen || vecWen
241  }
242
243  trait BundleSource {
244    var wakeupSource = "undefined"
245    var idx = 0
246  }
247
248  /**
249    *
250    * @param pregIdxWidth index width of preg
251    * @param exuIndices exu indices of wakeup bundle
252    */
253  sealed abstract class IssueQueueWakeUpBaseBundle(pregIdxWidth: Int, val exuIndices: Seq[Int]) extends Bundle {
254    val rfWen = Bool()
255    val fpWen = Bool()
256    val vecWen = Bool()
257    val pdest = UInt(pregIdxWidth.W)
258
259    /**
260      * @param successor Seq[(psrc, srcType)]
261      * @return Seq[if wakeup psrc]
262      */
263    def wakeUp(successor: Seq[(UInt, UInt)], valid: Bool): Seq[Bool] = {
264      successor.map { case (thatPsrc, srcType) =>
265        val pdestMatch = pdest === thatPsrc
266        pdestMatch && (
267          SrcType.isFp(srcType) && this.fpWen ||
268            SrcType.isXp(srcType) && this.rfWen ||
269            SrcType.isVp(srcType) && this.vecWen
270          ) && valid
271      }
272    }
273    def wakeUpFromIQ(successor: Seq[(UInt, UInt)]): Seq[Bool] = {
274      successor.map { case (thatPsrc, srcType) =>
275        val pdestMatch = pdest === thatPsrc
276        pdestMatch && (
277          SrcType.isFp(srcType) && this.fpWen ||
278            SrcType.isXp(srcType) && this.rfWen ||
279            SrcType.isVp(srcType) && this.vecWen
280          )
281      }
282    }
283
284    def hasOnlyOneSource: Boolean = exuIndices.size == 1
285
286    def hasMultiSources: Boolean = exuIndices.size > 1
287
288    def isWBWakeUp = this.isInstanceOf[IssueQueueWBWakeUpBundle]
289
290    def isIQWakeUp = this.isInstanceOf[IssueQueueIQWakeUpBundle]
291
292    def exuIdx: Int = {
293      require(hasOnlyOneSource)
294      this.exuIndices.head
295    }
296  }
297
298  class IssueQueueWBWakeUpBundle(exuIndices: Seq[Int], backendParams: BackendParams) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, exuIndices) {
299
300  }
301
302class IssueQueueIQWakeUpBundle(
303  exuIdx: Int,
304  backendParams: BackendParams,
305  copyWakeupOut: Boolean = false,
306  copyNum: Int = 0
307) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, Seq(exuIdx)) {
308    val loadDependency = Vec(backendParams.LduCnt + backendParams.HyuCnt, UInt(3.W))
309    val is0Lat = Bool()
310    val params = backendParams.allExuParams.filter(_.exuIdx == exuIdx).head
311    val pdestCopy  = OptionWrapper(copyWakeupOut, Vec(copyNum, UInt(params.wbPregIdxWidth.W)))
312    val rfWenCopy  = OptionWrapper(copyWakeupOut && params.needIntWen, Vec(copyNum, Bool()))
313    val fpWenCopy  = OptionWrapper(copyWakeupOut && params.needFpWen, Vec(copyNum, Bool()))
314    val vecWenCopy = OptionWrapper(copyWakeupOut && params.needVecWen, Vec(copyNum, Bool()))
315    val loadDependencyCopy = OptionWrapper(copyWakeupOut && params.isIQWakeUpSink, Vec(copyNum,Vec(backendParams.LdExuCnt, UInt(3.W))))
316    def fromExuInput(exuInput: ExuInput, l2ExuVecs: Vec[UInt]): Unit = {
317      this.rfWen := exuInput.rfWen.getOrElse(false.B)
318      this.fpWen := exuInput.fpWen.getOrElse(false.B)
319      this.vecWen := exuInput.vecWen.getOrElse(false.B)
320      this.pdest := exuInput.pdest
321    }
322
323    def fromExuInput(exuInput: ExuInput): Unit = {
324      this.rfWen := exuInput.rfWen.getOrElse(false.B)
325      this.fpWen := exuInput.fpWen.getOrElse(false.B)
326      this.vecWen := exuInput.vecWen.getOrElse(false.B)
327      this.pdest := exuInput.pdest
328    }
329  }
330
331  class VPUCtrlSignals(implicit p: Parameters) extends XSBundle {
332    // vtype
333    val vill      = Bool()
334    val vma       = Bool()    // 1: agnostic, 0: undisturbed
335    val vta       = Bool()    // 1: agnostic, 0: undisturbed
336    val vsew      = VSew()
337    val vlmul     = VLmul()   // 1/8~8      --> -3~3
338
339    val vm        = Bool()    // 0: need v0.t
340    val vstart    = Vl()
341
342    // float rounding mode
343    val frm       = Frm()
344    // scalar float instr and vector float reduction
345    val fpu       = Fpu()
346    // vector fix int rounding mode
347    val vxrm      = Vxrm()
348    // vector uop index, exclude other non-vector uop
349    val vuopIdx   = UopIdx()
350    val lastUop   = Bool()
351    // maybe used if data dependancy
352    val vmask     = UInt(MaskSrcData().dataWidth.W)
353    val vl        = Vl()
354
355    // vector load/store
356    val nf        = Nf()
357    val veew      = VEew()
358
359    val isReverse = Bool() // vrsub, vrdiv
360    val isExt     = Bool()
361    val isNarrow  = Bool()
362    val isDstMask = Bool() // vvm, vvvm, mmm
363    val isOpMask  = Bool() // vmand, vmnand
364    val isMove    = Bool() // vmv.s.x, vmv.v.v, vmv.v.x, vmv.v.i
365
366    def vtype: VType = {
367      val res = Wire(VType())
368      res.illegal := this.vill
369      res.vma     := this.vma
370      res.vta     := this.vta
371      res.vsew    := this.vsew
372      res.vlmul   := this.vlmul
373      res
374    }
375
376    def vconfig: VConfig = {
377      val res = Wire(VConfig())
378      res.vtype := this.vtype
379      res.vl    := this.vl
380      res
381    }
382
383    def connectVType(source: VType): Unit = {
384      this.vill  := source.illegal
385      this.vma   := source.vma
386      this.vta   := source.vta
387      this.vsew  := source.vsew
388      this.vlmul := source.vlmul
389    }
390  }
391
392  // DynInst --[IssueQueue]--> DataPath
393  class IssueQueueIssueBundle(
394    iqParams: IssueBlockParams,
395    val exuParams: ExeUnitParams,
396  )(implicit
397    p: Parameters
398  ) extends Bundle {
399    private val rfReadDataCfgSet: Seq[Set[DataConfig]] = exuParams.getRfReadDataCfgSet
400    // check which set both have fp and vec and remove fp
401    private val rfReadDataCfgSetFilterFp = rfReadDataCfgSet.map((set: Set[DataConfig]) =>
402      if (set.contains(FpData()) && set.contains(VecData())) set.filter(_ != FpData())
403      else set
404    )
405
406    val rf: MixedVec[MixedVec[RfReadPortWithConfig]] = Flipped(MixedVec(
407      rfReadDataCfgSetFilterFp.map((set: Set[DataConfig]) =>
408        MixedVec(set.map((x: DataConfig) => new RfReadPortWithConfig(x, exuParams.rdPregIdxWidth)).toSeq)
409      )
410    ))
411
412    val srcType = Vec(exuParams.numRegSrc, SrcType()) // used to select imm or reg data
413    val immType = SelImm()                         // used to select imm extractor
414    val common = new ExuInput(exuParams)
415    val addrOH = UInt(iqParams.numEntries.W)
416
417    def exuIdx = exuParams.exuIdx
418    def getSource: SchedulerType = exuParams.getWBSource
419    def getIntWbBusyBundle = common.rfWen.toSeq
420    def getVfWbBusyBundle = common.getVfWen.toSeq
421
422    def getIntRfReadValidBundle(issueValid: Bool): Seq[ValidIO[RfReadPortWithConfig]] = {
423      rf.zip(srcType).map {
424        case (rfRd: MixedVec[RfReadPortWithConfig], t: UInt) =>
425          makeValid(issueValid, rfRd.head)
426      }.toSeq
427    }
428
429    def getVfRfReadValidBundle(issueValid: Bool): Seq[ValidIO[RfReadPortWithConfig]] = {
430      rf.zip(srcType).map {
431        case (rfRd: MixedVec[RfReadPortWithConfig], t: UInt) =>
432          makeValid(issueValid, rfRd.head)
433      }.toSeq
434    }
435
436    def getIntRfWriteValidBundle(issueValid: Bool) = {
437
438    }
439  }
440
441  class OGRespBundle(implicit p:Parameters, params: IssueBlockParams) extends XSBundle {
442    val issueQueueParams = this.params
443    val og0resp = Valid(new EntryDeqRespBundle)
444    val og1resp = Valid(new EntryDeqRespBundle)
445  }
446
447  class fuBusyRespBundle(implicit p: Parameters, params: IssueBlockParams) extends Bundle {
448    val respType = RSFeedbackType() // update credit if needs replay
449    val rfWen = Bool() // TODO: use params to identify IntWB/VfWB
450    val fuType = FuType()
451  }
452
453  class WbFuBusyTableWriteBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
454    private val intCertainLat = params.intLatencyCertain
455    private val vfCertainLat = params.vfLatencyCertain
456    private val intLat = params.intLatencyValMax
457    private val vfLat = params.vfLatencyValMax
458
459    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
460    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
461    val intDeqRespSet = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
462    val vfDeqRespSet = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
463  }
464
465  class WbFuBusyTableReadBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
466    private val intCertainLat = params.intLatencyCertain
467    private val vfCertainLat = params.vfLatencyCertain
468    private val intLat = params.intLatencyValMax
469    private val vfLat = params.vfLatencyValMax
470
471    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
472    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
473  }
474
475  class WbConflictBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
476    private val intCertainLat = params.intLatencyCertain
477    private val vfCertainLat = params.vfLatencyCertain
478
479    val intConflict = OptionWrapper(intCertainLat, Bool())
480    val vfConflict = OptionWrapper(vfCertainLat, Bool())
481  }
482
483  class ImmInfo extends Bundle {
484    val imm = UInt(32.W)
485    val immType = SelImm()
486  }
487
488  // DataPath --[ExuInput]--> Exu
489  class ExuInput(val params: ExeUnitParams, copyWakeupOut:Boolean = false, copyNum:Int = 0)(implicit p: Parameters) extends XSBundle {
490    val fuType        = FuType()
491    val fuOpType      = FuOpType()
492    val src           = Vec(params.numRegSrc, UInt(params.dataBitsMax.W))
493    val imm           = UInt(32.W)
494    val robIdx        = new RobPtr
495    val iqIdx         = UInt(log2Up(MemIQSizeMax).W)// Only used by store yet
496    val isFirstIssue  = Bool()                      // Only used by store yet
497    val pdestCopy  = OptionWrapper(copyWakeupOut, Vec(copyNum, UInt(params.wbPregIdxWidth.W)))
498    val rfWenCopy  = OptionWrapper(copyWakeupOut && params.needIntWen, Vec(copyNum, Bool()))
499    val fpWenCopy  = OptionWrapper(copyWakeupOut && params.needFpWen, Vec(copyNum, Bool()))
500    val vecWenCopy = OptionWrapper(copyWakeupOut && params.needVecWen, Vec(copyNum, Bool()))
501    val loadDependencyCopy = OptionWrapper(copyWakeupOut && params.isIQWakeUpSink, Vec(copyNum,Vec(LoadPipelineWidth, UInt(3.W))))
502    val pdest         = UInt(params.wbPregIdxWidth.W)
503    val rfWen         = if (params.needIntWen)    Some(Bool())                        else None
504    val fpWen         = if (params.needFpWen)     Some(Bool())                        else None
505    val vecWen        = if (params.needVecWen)    Some(Bool())                        else None
506    val fpu           = if (params.writeFflags)   Some(new FPUCtrlSignals)            else None
507    val vpu           = if (params.needVPUCtrl)   Some(new VPUCtrlSignals)            else None
508    val flushPipe     = if (params.flushPipe)     Some(Bool())                        else None
509    val pc            = if (params.needPc)        Some(UInt(VAddrData().dataWidth.W)) else None
510    val preDecode     = if (params.hasPredecode)  Some(new PreDecodeInfo)             else None
511    val ftqIdx        = if (params.needPc || params.replayInst || params.hasStoreAddrFu)
512                                                  Some(new FtqPtr)                    else None
513    val ftqOffset     = if (params.needPc || params.replayInst || params.hasStoreAddrFu)
514                                                  Some(UInt(log2Up(PredictWidth).W))  else None
515    val predictInfo   = if (params.needPdInfo)  Some(new Bundle {
516      val target = UInt(VAddrData().dataWidth.W)
517      val taken = Bool()
518    }) else None
519    val loadWaitBit    = OptionWrapper(params.hasLoadExu, Bool())
520    val waitForRobIdx  = OptionWrapper(params.hasLoadExu, new RobPtr) // store set predicted previous store robIdx
521    val storeSetHit    = OptionWrapper(params.hasLoadExu, Bool()) // inst has been allocated an store set
522    val loadWaitStrict = OptionWrapper(params.hasLoadExu, Bool()) // load inst will not be executed until ALL former store addr calcuated
523    val ssid           = OptionWrapper(params.hasLoadExu, UInt(SSIDWidth.W))
524    val sqIdx = if (params.hasMemAddrFu || params.hasStdFu) Some(new SqPtr) else None
525    val lqIdx = if (params.hasMemAddrFu) Some(new LqPtr) else None
526    val dataSources = Vec(params.numRegSrc, DataSource())
527    val l1ExuOH = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, ExuOH()))
528    val srcTimer = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, UInt(3.W)))
529    val loadDependency = OptionWrapper(params.isIQWakeUpSink, Vec(LoadPipelineWidth, UInt(3.W)))
530
531    val perfDebugInfo = new PerfDebugInfo()
532
533    def exuIdx = this.params.exuIdx
534
535    def needCancel(og0CancelOH: UInt, og1CancelOH: UInt) : Bool = {
536      if (params.isIQWakeUpSink) {
537        require(
538          og0CancelOH.getWidth == l1ExuOH.get.head.getWidth,
539          s"cancelVecSize: {og0: ${og0CancelOH.getWidth}, og1: ${og1CancelOH.getWidth}}"
540        )
541        val l1Cancel: Bool = l1ExuOH.get.zip(srcTimer.get).map {
542          case(exuOH: UInt, srcTimer: UInt) =>
543            (exuOH & og0CancelOH).orR && srcTimer === 1.U
544        }.reduce(_ | _)
545        l1Cancel
546      } else {
547        false.B
548      }
549    }
550
551    def getVfWen = {
552      if (params.writeFpRf) this.fpWen
553      else if(params.writeVecRf) this.vecWen
554      else None
555    }
556
557    def fromIssueBundle(source: IssueQueueIssueBundle): Unit = {
558      // src is assigned to rfReadData
559      this.fuType        := source.common.fuType
560      this.fuOpType      := source.common.fuOpType
561      this.imm           := source.common.imm
562      this.robIdx        := source.common.robIdx
563      this.pdest         := source.common.pdest
564      this.isFirstIssue  := source.common.isFirstIssue // Only used by mem debug log
565      this.iqIdx         := source.common.iqIdx        // Only used by mem feedback
566      this.dataSources   := source.common.dataSources
567      this.l1ExuOH       .foreach(_ := source.common.l1ExuOH.get)
568      this.rfWen         .foreach(_ := source.common.rfWen.get)
569      this.fpWen         .foreach(_ := source.common.fpWen.get)
570      this.vecWen        .foreach(_ := source.common.vecWen.get)
571      this.fpu           .foreach(_ := source.common.fpu.get)
572      this.vpu           .foreach(_ := source.common.vpu.get)
573      this.flushPipe     .foreach(_ := source.common.flushPipe.get)
574      this.pc            .foreach(_ := source.common.pc.get)
575      this.preDecode     .foreach(_ := source.common.preDecode.get)
576      this.ftqIdx        .foreach(_ := source.common.ftqIdx.get)
577      this.ftqOffset     .foreach(_ := source.common.ftqOffset.get)
578      this.predictInfo   .foreach(_ := source.common.predictInfo.get)
579      this.loadWaitBit   .foreach(_ := source.common.loadWaitBit.get)
580      this.waitForRobIdx .foreach(_ := source.common.waitForRobIdx.get)
581      this.storeSetHit   .foreach(_ := source.common.storeSetHit.get)
582      this.loadWaitStrict.foreach(_ := source.common.loadWaitStrict.get)
583      this.ssid          .foreach(_ := source.common.ssid.get)
584      this.lqIdx         .foreach(_ := source.common.lqIdx.get)
585      this.sqIdx         .foreach(_ := source.common.sqIdx.get)
586      this.srcTimer      .foreach(_ := source.common.srcTimer.get)
587      this.loadDependency.foreach(_ := source.common.loadDependency.get.map(_ << 1))
588    }
589  }
590
591  // ExuInput --[FuncUnit]--> ExuOutput
592  class ExuOutput(
593    val params: ExeUnitParams,
594  )(implicit
595    val p: Parameters
596  ) extends Bundle with BundleSource with HasXSParameter {
597    val data         = UInt(params.dataBitsMax.W)
598    val pdest        = UInt(params.wbPregIdxWidth.W)
599    val robIdx       = new RobPtr
600    val intWen       = if (params.needIntWen)   Some(Bool())                  else None
601    val fpWen        = if (params.needFpWen)    Some(Bool())                  else None
602    val vecWen       = if (params.needVecWen)   Some(Bool())                  else None
603    val redirect     = if (params.hasRedirect)  Some(ValidIO(new Redirect))   else None
604    val fflags       = if (params.writeFflags)  Some(UInt(5.W))               else None
605    val wflags       = if (params.writeFflags)  Some(Bool())                  else None
606    val vxsat        = if (params.writeVxsat)   Some(Bool())                  else None
607    val exceptionVec = if (params.exceptionOut.nonEmpty) Some(ExceptionVec()) else None
608    val flushPipe    = if (params.flushPipe)    Some(Bool())                  else None
609    val replay       = if (params.replayInst)   Some(Bool())                  else None
610    val lqIdx        = if (params.hasLoadFu)    Some(new LqPtr())             else None
611    val sqIdx        = if (params.hasStoreAddrFu || params.hasStdFu)
612                                                Some(new SqPtr())             else None
613    val trigger      = if (params.trigger)      Some(new TriggerCf)           else None
614    // uop info
615    val predecodeInfo = if(params.hasPredecode) Some(new PreDecodeInfo) else None
616    // vldu used only
617    val vls = OptionWrapper(params.hasVLoadFu, new Bundle {
618      val vpu = new VPUCtrlSignals
619      val oldVdPsrc = UInt(PhyRegIdxWidth.W)
620      val vdIdx = UInt(3.W)
621      val vdIdxInField = UInt(3.W)
622      val isIndexed = Bool()
623      val isMasked = Bool()
624    })
625    val debug = new DebugBundle
626    val debugInfo = new PerfDebugInfo
627  }
628
629  // ExuOutput + DynInst --> WriteBackBundle
630  class WriteBackBundle(val params: PregWB, backendParams: BackendParams)(implicit p: Parameters) extends Bundle with BundleSource {
631    val rfWen = Bool()
632    val fpWen = Bool()
633    val vecWen = Bool()
634    val pdest = UInt(params.pregIdxWidth(backendParams).W)
635    val data = UInt(params.dataWidth.W)
636    val robIdx = new RobPtr()(p)
637    val flushPipe = Bool()
638    val replayInst = Bool()
639    val redirect = ValidIO(new Redirect)
640    val fflags = UInt(5.W)
641    val vxsat = Bool()
642    val exceptionVec = ExceptionVec()
643    val debug = new DebugBundle
644    val debugInfo = new PerfDebugInfo
645
646    this.wakeupSource = s"WB(${params.toString})"
647
648    def fromExuOutput(source: ExuOutput) = {
649      this.rfWen  := source.intWen.getOrElse(false.B)
650      this.fpWen  := source.fpWen.getOrElse(false.B)
651      this.vecWen := source.vecWen.getOrElse(false.B)
652      this.pdest  := source.pdest
653      this.data   := source.data
654      this.robIdx := source.robIdx
655      this.flushPipe := source.flushPipe.getOrElse(false.B)
656      this.replayInst := source.replay.getOrElse(false.B)
657      this.redirect := source.redirect.getOrElse(0.U.asTypeOf(this.redirect))
658      this.fflags := source.fflags.getOrElse(0.U.asTypeOf(this.fflags))
659      this.vxsat := source.vxsat.getOrElse(0.U.asTypeOf(this.vxsat))
660      this.exceptionVec := source.exceptionVec.getOrElse(0.U.asTypeOf(this.exceptionVec))
661      this.debug := source.debug
662      this.debugInfo := source.debugInfo
663    }
664
665    def asIntRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
666      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(IntData()).addrWidth)))
667      rfWrite.wen := this.rfWen && fire
668      rfWrite.addr := this.pdest
669      rfWrite.data := this.data
670      rfWrite.intWen := this.rfWen
671      rfWrite.fpWen := false.B
672      rfWrite.vecWen := false.B
673      rfWrite
674    }
675
676    def asVfRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
677      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(VecData()).addrWidth)))
678      rfWrite.wen := (this.fpWen || this.vecWen) && fire
679      rfWrite.addr := this.pdest
680      rfWrite.data := this.data
681      rfWrite.intWen := false.B
682      rfWrite.fpWen := this.fpWen
683      rfWrite.vecWen := this.vecWen
684      rfWrite
685    }
686  }
687
688  // ExuOutput --> ExuBypassBundle --[DataPath]-->ExuInput
689  //                                /
690  //     [IssueQueue]--> ExuInput --
691  class ExuBypassBundle(
692    val params: ExeUnitParams,
693  )(implicit
694    val p: Parameters
695  ) extends Bundle {
696    val data  = UInt(params.dataBitsMax.W)
697    val pdest = UInt(params.wbPregIdxWidth.W)
698  }
699
700  class ExceptionInfo(implicit p: Parameters) extends Bundle {
701    val pc = UInt(VAddrData().dataWidth.W)
702    val instr = UInt(32.W)
703    val commitType = CommitType()
704    val exceptionVec = ExceptionVec()
705    val singleStep = Bool()
706    val crossPageIPFFix = Bool()
707    val isInterrupt = Bool()
708    val vls = Bool()
709    val trigger  = new TriggerCf
710  }
711
712  object UopIdx {
713    def apply()(implicit p: Parameters): UInt = UInt(log2Up(p(XSCoreParamsKey).MaxUopSize + 1).W)
714  }
715
716  object FuLatency {
717    def apply(): UInt = UInt(width.W)
718
719    def width = 4 // 0~15 // Todo: assosiate it with FuConfig
720  }
721
722  object ExuOH {
723    def apply(exuNum: Int): UInt = UInt(exuNum.W)
724
725    def apply()(implicit p: Parameters): UInt = UInt(width.W)
726
727    def width(implicit p: Parameters): Int = p(XSCoreParamsKey).backendParams.numExu
728  }
729
730  object ExuVec {
731    def apply(exuNum: Int): Vec[Bool] = Vec(exuNum, Bool())
732
733    def apply()(implicit p: Parameters): Vec[Bool] = Vec(width, Bool())
734
735    def width(implicit p: Parameters): Int = p(XSCoreParamsKey).backendParams.numExu
736  }
737
738  class CancelSignal(implicit p: Parameters) extends XSBundle {
739    val rfWen = Bool()
740    val fpWen = Bool()
741    val vecWen = Bool()
742    val pdest = UInt(PhyRegIdxWidth.W)
743
744    def needCancel(srcType: UInt, psrc: UInt, valid: Bool): Bool = {
745      val pdestMatch = pdest === psrc
746      pdestMatch && (
747        SrcType.isFp(srcType) && !this.rfWen ||
748          SrcType.isXp(srcType) && this.rfWen ||
749          SrcType.isVp(srcType) && !this.rfWen
750        ) && valid
751    }
752  }
753
754  class MemExuInput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
755    val uop = new DynInst
756    val src = if (isVector) Vec(5, UInt(VLEN.W)) else Vec(3, UInt(XLEN.W))
757    val iqIdx = UInt(log2Up(MemIQSizeMax).W)
758    val isFirstIssue = Bool()
759    val flowNum      = OptionWrapper(isVector, UInt(log2Up(VLEN/8).W))
760
761    def src_rs1 = src(0)
762    def src_stride = src(1)
763    def src_vs3 = src(2)
764    def src_mask = if (isVector) src(3) else 0.U
765    def src_vl = if (isVector) src(4) else 0.U
766  }
767
768  class MemExuOutput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
769    val uop = new DynInst
770    val data = if (isVector) UInt(VLEN.W) else UInt(XLEN.W)
771    val mask = if (isVector) Some(UInt(VLEN.W)) else None
772    val vdIdx = if (isVector) Some(UInt(3.W)) else None // TODO: parameterize width
773    val vdIdxInField = if (isVector) Some(UInt(3.W)) else None
774    val debug = new DebugBundle
775
776    def isVls = FuType.isVls(uop.fuType)
777  }
778
779  class MemMicroOpRbExt(implicit p: Parameters) extends XSBundle {
780    val uop = new DynInst
781    val flag = UInt(1.W)
782  }
783
784  object LoadShouldCancel {
785    def apply(loadDependency: Option[Seq[UInt]], ldCancel: Seq[LoadCancelIO]): Bool = {
786      val ld1Cancel = loadDependency.map(_.zip(ldCancel.map(_.ld1Cancel)).map { case (dep, cancel) => cancel && dep(1)}.reduce(_ || _))
787      val ld2Cancel = loadDependency.map(_.zip(ldCancel.map(_.ld2Cancel)).map { case (dep, cancel) => cancel && dep(2)}.reduce(_ || _))
788      ld1Cancel.map(_ || ld2Cancel.get).getOrElse(false.B)
789    }
790  }
791}
792