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