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