xref: /XiangShan/src/main/scala/xiangshan/backend/Bundles.scala (revision 30fcc710d13c696046a56a1253a73e868022ba97)
1package xiangshan.backend
2
3import chipsalliance.rocketchip.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, IssueQueueJumpBundle, SchedulerType, EntryDeqRespBundle}
19import xiangshan.backend.regfile.{RfReadPortWithConfig, RfWritePortWithConfig}
20import xiangshan.backend.rob.RobPtr
21import xiangshan.frontend._
22import xiangshan.mem.{LqPtr, SqPtr}
23
24object Bundles {
25
26  // frontend -> backend
27  class StaticInst(implicit p: Parameters) extends XSBundle {
28    val instr           = UInt(32.W)
29    val pc              = UInt(VAddrBits.W)
30    val foldpc          = UInt(MemPredPCWidth.W)
31    val exceptionVec    = ExceptionVec()
32    val trigger         = new TriggerCf
33    val preDecodeInfo   = new PreDecodeInfo
34    val pred_taken      = Bool()
35    val crossPageIPFFix = Bool()
36    val ftqPtr          = new FtqPtr
37    val ftqOffset       = UInt(log2Up(PredictWidth).W)
38
39    def connectCtrlFlow(source: CtrlFlow): Unit = {
40      this.instr            := source.instr
41      this.pc               := source.pc
42      this.foldpc           := source.foldpc
43      this.exceptionVec     := source.exceptionVec
44      this.trigger          := source.trigger
45      this.preDecodeInfo    := source.pd
46      this.pred_taken       := source.pred_taken
47      this.crossPageIPFFix  := source.crossPageIPFFix
48      this.ftqPtr           := source.ftqPtr
49      this.ftqOffset        := source.ftqOffset
50    }
51  }
52
53  // StaticInst --[Decode]--> DecodedInst
54  class DecodedInst(implicit p: Parameters) extends XSBundle {
55    def numSrc = backendParams.numSrc
56    // passed from StaticInst
57    val instr           = UInt(32.W)
58    val pc              = UInt(VAddrBits.W)
59    val foldpc          = UInt(MemPredPCWidth.W)
60    val exceptionVec    = ExceptionVec()
61    val trigger         = new TriggerCf
62    val preDecodeInfo   = new PreDecodeInfo
63    val pred_taken      = Bool()
64    val crossPageIPFFix = Bool()
65    val ftqPtr          = new FtqPtr
66    val ftqOffset       = UInt(log2Up(PredictWidth).W)
67    // decoded
68    val srcType         = Vec(numSrc, SrcType())
69    val lsrc            = Vec(numSrc, UInt(6.W))
70    val ldest           = UInt(6.W)
71    val fuType          = FuType()
72    val fuOpType        = FuOpType()
73    val rfWen           = Bool()
74    val fpWen           = Bool()
75    val vecWen          = Bool()
76    val isXSTrap        = Bool()
77    val waitForward     = Bool() // no speculate execution
78    val blockBackward   = Bool()
79    val flushPipe       = Bool() // This inst will flush all the pipe when commit, like exception but can commit
80    val canRobCompress  = Bool()
81    val selImm          = SelImm()
82    val imm             = UInt(ImmUnion.maxLen.W)
83    val fpu             = new FPUCtrlSignals
84    val vpu             = new VPUCtrlSignals
85    val wfflags         = Bool()
86    val isMove          = Bool()
87    val uopIdx          = UInt(5.W)
88    val uopSplitType    = UopSplitType()
89    val isVset          = Bool()
90    val firstUop        = Bool()
91    val lastUop         = Bool()
92    val numUops         = UInt(log2Up(MaxUopSize).W) // rob need this
93    val commitType      = CommitType() // Todo: remove it
94
95    private def allSignals = srcType.take(3) ++ Seq(fuType, fuOpType, rfWen, fpWen, vecWen,
96      isXSTrap, waitForward, blockBackward, flushPipe, canRobCompress, uopSplitType, selImm)
97
98    def decode(inst: UInt, table: Iterable[(BitPat, List[BitPat])]): DecodedInst = {
99      val decoder: Seq[UInt] = ListLookup(
100        inst, XDecode.decodeDefault.map(bitPatToUInt),
101        table.map{ case (pat, pats) => (pat, pats.map(bitPatToUInt)) }.toArray
102      )
103      allSignals zip decoder foreach { case (s, d) => s := d }
104      this
105    }
106
107    def isSoftPrefetch: Bool = {
108      fuType === FuType.alu.U && fuOpType === ALUOpType.or && selImm === SelImm.IMM_I && ldest === 0.U
109    }
110
111    def connectStaticInst(source: StaticInst): Unit = {
112      for ((name, data) <- this.elements) {
113        if (source.elements.contains(name)) {
114          data := source.elements(name)
115        }
116      }
117    }
118  }
119
120  // DecodedInst --[Rename]--> DynInst
121  class DynInst(implicit p: Parameters) extends XSBundle {
122    def numSrc          = backendParams.numSrc
123    // passed from StaticInst
124    val instr           = UInt(32.W)
125    val pc              = UInt(VAddrBits.W)
126    val foldpc          = UInt(MemPredPCWidth.W)
127    val exceptionVec    = ExceptionVec()
128    val trigger         = new TriggerCf
129    val preDecodeInfo   = new PreDecodeInfo
130    val pred_taken      = Bool()
131    val crossPageIPFFix = Bool()
132    val ftqPtr          = new FtqPtr
133    val ftqOffset       = UInt(log2Up(PredictWidth).W)
134    // passed from DecodedInst
135    val srcType         = Vec(numSrc, SrcType())
136    val lsrc            = Vec(numSrc, UInt(6.W))
137    val ldest           = UInt(6.W)
138    val fuType          = FuType()
139    val fuOpType        = FuOpType()
140    val rfWen           = Bool()
141    val fpWen           = Bool()
142    val vecWen          = Bool()
143    val isXSTrap        = Bool()
144    val waitForward     = Bool() // no speculate execution
145    val blockBackward   = Bool()
146    val flushPipe       = Bool() // This inst will flush all the pipe when commit, like exception but can commit
147    val canRobCompress  = Bool()
148    val selImm          = SelImm()
149    val imm             = UInt(XLEN.W) // Todo: check if it need minimized
150    val fpu             = new FPUCtrlSignals
151    val vpu             = new VPUCtrlSignals
152    val wfflags         = Bool()
153    val isMove          = Bool()
154    val uopIdx          = UInt(5.W)
155    val isVset          = Bool()
156    val firstUop        = Bool()
157    val lastUop         = Bool()
158    val numUops         = UInt(log2Up(MaxUopSize).W) // rob need this
159    val commitType      = CommitType()
160    // rename
161    val srcState        = Vec(numSrc, SrcState())
162    val psrc            = Vec(numSrc, UInt(PhyRegIdxWidth.W))
163    val pdest           = UInt(PhyRegIdxWidth.W)
164    val robIdx          = new RobPtr
165    val instrSize       = UInt(log2Ceil(RenameWidth + 1).W)
166
167    val eliminatedMove  = Bool()
168    // Take snapshot at this CFI inst
169    val snapshot        = Bool()
170    val debugInfo       = new PerfDebugInfo
171    val storeSetHit     = Bool() // inst has been allocated an store set
172    val waitForRobIdx   = new RobPtr // store set predicted previous store robIdx
173    // Load wait is needed
174    // load inst will not be executed until former store (predicted by mdp) addr calcuated
175    val loadWaitBit     = Bool()
176    // If (loadWaitBit && loadWaitStrict), strict load wait is needed
177    // load inst will not be executed until ALL former store addr calcuated
178    val loadWaitStrict  = Bool()
179    val ssid            = UInt(SSIDWidth.W)
180    // Todo
181    val lqIdx = new LqPtr
182    val sqIdx = new SqPtr
183    // debug module
184    val singleStep      = Bool()
185    // schedule
186    val replayInst      = Bool()
187
188    def isLUI: Bool = this.fuType === FuType.alu.U && (this.selImm === SelImm.IMM_U || this.selImm === SelImm.IMM_LUI32)
189    def isWFI: Bool = this.fuType === FuType.csr.U && fuOpType === CSROpType.wfi
190
191    def isSvinvalBegin(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && !flush
192    def isSvinval(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.sfence && !flush
193    def isSvinvalEnd(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && flush
194
195    def srcIsReady: Vec[Bool] = {
196      VecInit(this.srcType.zip(this.srcState).map {
197        case (t, s) => SrcType.isNotReg(t) || SrcState.isReady(s)
198      })
199    }
200
201    def clearExceptions(
202      exceptionBits: Seq[Int] = Seq(),
203      flushPipe    : Boolean = false,
204      replayInst   : Boolean = false
205    ): DynInst = {
206      this.exceptionVec.zipWithIndex.filterNot(x => exceptionBits.contains(x._2)).foreach(_._1 := false.B)
207      if (!flushPipe) { this.flushPipe := false.B }
208      if (!replayInst) { this.replayInst := false.B }
209      this
210    }
211
212    def needWriteRf: Bool = (rfWen && ldest =/= 0.U) || fpWen || vecWen
213  }
214
215  trait BundleSource {
216    var wakeupSource = "undefined"
217    var idx = 0
218  }
219
220  /**
221    *
222    * @param pregIdxWidth index width of preg
223    * @param exuIndices exu indices of wakeup bundle
224    */
225  sealed abstract class IssueQueueWakeUpBaseBundle(pregIdxWidth: Int, val exuIndices: Seq[Int]) extends Bundle {
226    val rfWen = Bool()
227    val fpWen = Bool()
228    val vecWen = Bool()
229    val pdest = UInt(pregIdxWidth.W)
230
231    /**
232      * @param successor Seq[(psrc, srcType)]
233      * @return Seq[if wakeup psrc]
234      */
235    def wakeUp(successor: Seq[(UInt, UInt)], valid: Bool): Seq[Bool] = {
236      successor.map { case (thatPsrc, srcType) =>
237        val pdestMatch = pdest === thatPsrc
238        pdestMatch && (
239          SrcType.isFp(srcType) && this.fpWen ||
240            SrcType.isXp(srcType) && this.rfWen ||
241            SrcType.isVp(srcType) && this.vecWen
242          ) && valid
243      }
244    }
245
246    def hasOnlyOneSource: Boolean = exuIndices.size == 1
247
248    def hasMultiSources: Boolean = exuIndices.size > 1
249
250    def isWBWakeUp = this.isInstanceOf[IssueQueueWBWakeUpBundle]
251
252    def isIQWakeUp = this.isInstanceOf[IssueQueueIQWakeUpBundle]
253
254    def exuIdx: Int = {
255      require(hasOnlyOneSource)
256      this.exuIndices.head
257    }
258  }
259
260  class IssueQueueWBWakeUpBundle(exuIndices: Seq[Int], backendParams: BackendParams) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, exuIndices) {
261
262  }
263
264  class IssueQueueIQWakeUpBundle(exuIdx: Int, backendParams: BackendParams) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, Seq(exuIdx)) {
265    def fromExuInput(exuInput: ExuInput, l2ExuVecs: Vec[Vec[Bool]]): Unit = {
266      this.rfWen := exuInput.rfWen.getOrElse(false.B)
267      this.fpWen := exuInput.fpWen.getOrElse(false.B)
268      this.vecWen := exuInput.vecWen.getOrElse(false.B)
269      this.pdest := exuInput.pdest
270    }
271
272    def fromExuInput(exuInput: ExuInput): Unit = {
273      this.rfWen := exuInput.rfWen.getOrElse(false.B)
274      this.fpWen := exuInput.fpWen.getOrElse(false.B)
275      this.vecWen := exuInput.vecWen.getOrElse(false.B)
276      this.pdest := exuInput.pdest
277    }
278  }
279
280  class VPUCtrlSignals(implicit p: Parameters) extends XSBundle {
281    // vtype
282    val vill      = Bool()
283    val vma       = Bool()    // 1: agnostic, 0: undisturbed
284    val vta       = Bool()    // 1: agnostic, 0: undisturbed
285    val vsew      = VSew()
286    val vlmul     = VLmul()   // 1/8~8      --> -3~3
287
288    val vm        = Bool()    // 0: need v0.t
289    val vstart    = Vl()
290
291    // float rounding mode
292    val frm       = Frm()
293    // scalar float instr
294    val fpu       = Fpu()
295    // vector fix int rounding mode
296    val vxrm      = Vxrm()
297    // vector uop index, exclude other non-vector uop
298    val vuopIdx   = UopIdx()
299    // maybe used if data dependancy
300    val vmask     = UInt(MaskSrcData().dataWidth.W)
301    val vl        = Vl()
302
303    // vector load/store
304    val nf        = Nf()
305
306    val needScalaSrc       = Bool()
307    val permImmTruncate    = Bool() // opivi
308
309    val isReverse = Bool() // vrsub, vrdiv
310    val isExt     = Bool()
311    val isNarrow  = Bool()
312    val isDstMask = Bool() // vvm, vvvm, mmm
313    val isOpMask  = Bool() // vmand, vmnand
314    val isMove    = Bool() // vmv.s.x, vmv.v.v, vmv.v.x, vmv.v.i
315
316    def vtype: VType = {
317      val res = Wire(VType())
318      res.illegal := this.vill
319      res.vma     := this.vma
320      res.vta     := this.vta
321      res.vsew    := this.vsew
322      res.vlmul   := this.vlmul
323      res
324    }
325
326    def vconfig: VConfig = {
327      val res = Wire(VConfig())
328      res.vtype := this.vtype
329      res.vl    := this.vl
330      res
331    }
332  }
333
334  // DynInst --[IssueQueue]--> DataPath
335  class IssueQueueIssueBundle(
336    iqParams: IssueBlockParams,
337    val exuParams: ExeUnitParams,
338  )(implicit
339    p: Parameters
340  ) extends Bundle {
341    private val rfReadDataCfgSet: Seq[Set[DataConfig]] = exuParams.getRfReadDataCfgSet
342
343    val rf: MixedVec[MixedVec[RfReadPortWithConfig]] = Flipped(MixedVec(
344      rfReadDataCfgSet.map((set: Set[DataConfig]) =>
345        MixedVec(set.map((x: DataConfig) => new RfReadPortWithConfig(x, exuParams.rdPregIdxWidth)).toSeq)
346      )
347    ))
348
349    val srcType = Vec(exuParams.numRegSrc, SrcType()) // used to select imm or reg data
350    val immType = SelImm()                         // used to select imm extractor
351    val common = new ExuInput(exuParams)
352    val jmp = if (exuParams.needPc) Some(Flipped(new IssueQueueJumpBundle)) else None
353    val addrOH = UInt(iqParams.numEntries.W)
354
355    def exuIdx = exuParams.exuIdx
356    def getSource: SchedulerType = exuParams.getWBSource
357    def getIntWbBusyBundle = common.rfWen.toSeq
358    def getVfWbBusyBundle = common.getVfWen.toSeq
359    def getIntRfReadBundle: Seq[RfReadPortWithConfig] = rf.flatten.filter(_.readInt)
360    def getVfRfReadBundle: Seq[RfReadPortWithConfig] = rf.flatten.filter(_.readVf)
361
362    def getIntRfReadValidBundle(issueValid: Bool): Seq[ValidIO[RfReadPortWithConfig]] = {
363      getIntRfReadBundle.zip(srcType).map {
364        case (rfRd: RfReadPortWithConfig, t: UInt) =>
365          makeValid(issueValid && SrcType.isXp(t), rfRd)
366      }
367    }
368
369    def getVfRfReadValidBundle(issueValid: Bool): Seq[ValidIO[RfReadPortWithConfig]] = {
370      getVfRfReadBundle.zip(srcType).map {
371        case (rfRd: RfReadPortWithConfig, t: UInt) =>
372          makeValid(issueValid && SrcType.isVfp(t), rfRd)
373      }
374    }
375
376    def getIntRfWriteValidBundle(issueValid: Bool) = {
377
378    }
379  }
380
381  class OGRespBundle(implicit p:Parameters, params: IssueBlockParams) extends XSBundle {
382    val issueQueueParams = this.params
383    val og0resp = Valid(new EntryDeqRespBundle)
384    val og1resp = Valid(new EntryDeqRespBundle)
385  }
386
387  class fuBusyRespBundle(implicit p: Parameters, params: IssueBlockParams) extends Bundle {
388    val respType = RSFeedbackType() // update credit if needs replay
389    val rfWen = Bool() // TODO: use params to identify IntWB/VfWB
390    val fuType = FuType()
391  }
392
393  class WbFuBusyTableWriteBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
394    private val intCertainLat = params.intLatencyCertain
395    private val vfCertainLat = params.vfLatencyCertain
396    private val intLat = params.intLatencyValMax
397    private val vfLat = params.vfLatencyValMax
398
399    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
400    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
401    val intDeqRespSet = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
402    val vfDeqRespSet = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
403  }
404
405  class WbFuBusyTableReadBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
406    private val intCertainLat = params.intLatencyCertain
407    private val vfCertainLat = params.vfLatencyCertain
408    private val intLat = params.intLatencyValMax
409    private val vfLat = params.vfLatencyValMax
410
411    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
412    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
413  }
414
415  class WbConflictBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
416    private val intCertainLat = params.intLatencyCertain
417    private val vfCertainLat = params.vfLatencyCertain
418
419    val intConflict = OptionWrapper(intCertainLat, Bool())
420    val vfConflict = OptionWrapper(vfCertainLat, Bool())
421  }
422
423  // DataPath --[ExuInput]--> Exu
424  class ExuInput(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
425    val fuType        = FuType()
426    val fuOpType      = FuOpType()
427    val src           = Vec(params.numRegSrc, UInt(params.dataBitsMax.W))
428    val imm           = UInt(XLEN.W)
429    val robIdx        = new RobPtr
430    val iqIdx         = UInt(log2Up(MemIQSizeMax).W)// Only used by store yet
431    val isFirstIssue  = Bool()                      // Only used by store yet
432    val pdest         = UInt(params.wbPregIdxWidth.W)
433    val rfWen         = if (params.writeIntRf)    Some(Bool())                        else None
434    val fpWen         = if (params.writeFpRf)     Some(Bool())                        else None
435    val vecWen        = if (params.writeVecRf)    Some(Bool())                        else None
436    val fpu           = if (params.writeFflags)   Some(new FPUCtrlSignals)            else None
437    val vpu           = if (params.needVPUCtrl)   Some(new VPUCtrlSignals)            else None
438    val flushPipe     = if (params.flushPipe)     Some(Bool())                        else None
439    val pc            = if (params.needPc)        Some(UInt(VAddrData().dataWidth.W)) else None
440    val jalrTarget    = if (params.hasJmpFu)      Some(UInt(VAddrData().dataWidth.W)) else None
441    val preDecode     = if (params.hasPredecode)  Some(new PreDecodeInfo)             else None
442    val ftqIdx        = if (params.needPc || params.replayInst)
443                                                  Some(new FtqPtr)                    else None
444    val ftqOffset     = if (params.needPc || params.replayInst)
445                                                  Some(UInt(log2Up(PredictWidth).W))  else None
446    val predictInfo   = if (params.hasPredecode)  Some(new Bundle {
447      val target = UInt(VAddrData().dataWidth.W)
448      val taken = Bool()
449    }) else None
450    val sqIdx = if (params.hasMemAddrFu || params.hasStdFu) Some(new SqPtr) else None
451    val lqIdx = if (params.hasMemAddrFu) Some(new LqPtr) else None
452    val dataSources = Vec(params.numRegSrc, DataSource())
453    val l1ExuVec = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, ExuVec()))
454    val srcTimer = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, UInt(3.W)))
455
456    def exuIdx = this.params.exuIdx
457
458    def needCancel(og0CancelVec: Vec[Bool], og1CancelVec: Vec[Bool]) : Bool = {
459      if (params.isIQWakeUpSink) {
460        require(
461          og0CancelVec.size == l1ExuVec.get.head.size,
462          s"cancelVecSize: {og0: ${og0CancelVec.size}, og1: ${og1CancelVec.size}}"
463        )
464        val l1Cancel: Bool = l1ExuVec.get.zip(srcTimer.get).map {
465          case(exuOH: Vec[Bool], srcTimer: UInt) =>
466            (exuOH.asUInt & og0CancelVec.asUInt).orR && srcTimer === 1.U
467        }.reduce(_ | _)
468        l1Cancel
469      } else {
470        false.B
471      }
472    }
473
474    def getVfWen = {
475      if (params.writeFpRf) this.fpWen
476      else if(params.writeVecRf) this.vecWen
477      else None
478    }
479
480    def fromIssueBundle(source: IssueQueueIssueBundle): Unit = {
481      // src is assigned to rfReadData
482      this.fuType       := source.common.fuType
483      this.fuOpType     := source.common.fuOpType
484      this.imm          := source.common.imm
485      this.robIdx       := source.common.robIdx
486      this.pdest        := source.common.pdest
487      this.isFirstIssue := source.common.isFirstIssue // Only used by mem debug log
488      this.iqIdx        := source.common.iqIdx        // Only used by mem feedback
489      this.dataSources  := source.common.dataSources
490      this.rfWen        .foreach(_ := source.common.rfWen.get)
491      this.fpWen        .foreach(_ := source.common.fpWen.get)
492      this.vecWen       .foreach(_ := source.common.vecWen.get)
493      this.fpu          .foreach(_ := source.common.fpu.get)
494      this.vpu          .foreach(_ := source.common.vpu.get)
495      this.flushPipe    .foreach(_ := source.common.flushPipe.get)
496      this.pc           .foreach(_ := source.jmp.get.pc)
497      this.jalrTarget   .foreach(_ := source.jmp.get.target)
498      this.preDecode    .foreach(_ := source.common.preDecode.get)
499      this.ftqIdx       .foreach(_ := source.common.ftqIdx.get)
500      this.ftqOffset    .foreach(_ := source.common.ftqOffset.get)
501      this.predictInfo  .foreach(_ := source.common.predictInfo.get)
502      this.lqIdx        .foreach(_ := source.common.lqIdx.get)
503      this.sqIdx        .foreach(_ := source.common.sqIdx.get)
504      this.l1ExuVec     .foreach(_ := source.common.l1ExuVec.get)
505      this.srcTimer     .foreach(_ := source.common.srcTimer.get)
506    }
507  }
508
509  // ExuInput --[FuncUnit]--> ExuOutput
510  class ExuOutput(
511    val params: ExeUnitParams,
512  )(implicit
513    val p: Parameters
514  ) extends Bundle with BundleSource with HasXSParameter {
515    val data         = UInt(params.dataBitsMax.W)
516    val pdest        = UInt(params.wbPregIdxWidth.W)
517    val robIdx       = new RobPtr
518    val intWen       = if (params.writeIntRf)   Some(Bool())                  else None
519    val fpWen        = if (params.writeFpRf)    Some(Bool())                  else None
520    val vecWen       = if (params.writeVecRf)   Some(Bool())                  else None
521    val redirect     = if (params.hasRedirect)  Some(ValidIO(new Redirect))   else None
522    val fflags       = if (params.writeFflags)  Some(UInt(5.W))               else None
523    val wflags       = if (params.writeFflags)  Some(Bool())                  else None
524    val vxsat        = if (params.writeVxsat)   Some(Bool())                  else None
525    val exceptionVec = if (params.exceptionOut.nonEmpty) Some(ExceptionVec()) else None
526    val flushPipe    = if (params.flushPipe)    Some(Bool())                  else None
527    val replay       = if (params.replayInst)   Some(Bool())                  else None
528    val lqIdx        = if (params.hasLoadFu)    Some(new LqPtr())             else None
529    val sqIdx        = if (params.hasStoreAddrFu || params.hasStdFu)
530                                                Some(new SqPtr())             else None
531    val ftqIdx       = if (params.needPc || params.replayInst)
532                                                Some(new FtqPtr)                    else None
533    val ftqOffset    = if (params.needPc || params.replayInst)
534                                                Some(UInt(log2Up(PredictWidth).W))  else None
535    // uop info
536    val predecodeInfo = if(params.hasPredecode) Some(new PreDecodeInfo) else None
537    val debug = new DebugBundle
538    val debugInfo = new PerfDebugInfo
539  }
540
541  // ExuOutput + DynInst --> WriteBackBundle
542  class WriteBackBundle(val params: PregWB, backendParams: BackendParams)(implicit p: Parameters) extends Bundle with BundleSource {
543    val rfWen = Bool()
544    val fpWen = Bool()
545    val vecWen = Bool()
546    val pdest = UInt(params.pregIdxWidth(backendParams).W)
547    val data = UInt(params.dataWidth.W)
548    val robIdx = new RobPtr()(p)
549    val flushPipe = Bool()
550    val replayInst = Bool()
551    val redirect = ValidIO(new Redirect)
552    val fflags = UInt(5.W)
553    val vxsat = Bool()
554    val exceptionVec = ExceptionVec()
555    val debug = new DebugBundle
556    val debugInfo = new PerfDebugInfo
557
558    this.wakeupSource = s"WB(${params.toString})"
559
560    def fromExuOutput(source: ExuOutput) = {
561      this.rfWen  := source.intWen.getOrElse(false.B)
562      this.fpWen  := source.fpWen.getOrElse(false.B)
563      this.vecWen := source.vecWen.getOrElse(false.B)
564      this.pdest  := source.pdest
565      this.data   := source.data
566      this.robIdx := source.robIdx
567      this.flushPipe := source.flushPipe.getOrElse(false.B)
568      this.replayInst := source.replay.getOrElse(false.B)
569      this.redirect := source.redirect.getOrElse(0.U.asTypeOf(this.redirect))
570      this.fflags := source.fflags.getOrElse(0.U.asTypeOf(this.fflags))
571      this.vxsat := source.vxsat.getOrElse(0.U.asTypeOf(this.vxsat))
572      this.exceptionVec := source.exceptionVec.getOrElse(0.U.asTypeOf(this.exceptionVec))
573      this.debug := source.debug
574      this.debugInfo := source.debugInfo
575    }
576
577    def asIntRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
578      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(IntData()).addrWidth)))
579      rfWrite.wen := this.rfWen && fire
580      rfWrite.addr := this.pdest
581      rfWrite.data := this.data
582      rfWrite.intWen := this.rfWen
583      rfWrite.fpWen := false.B
584      rfWrite.vecWen := false.B
585      rfWrite
586    }
587
588    def asVfRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
589      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(VecData()).addrWidth)))
590      rfWrite.wen := (this.fpWen || this.vecWen) && fire
591      rfWrite.addr := this.pdest
592      rfWrite.data := this.data
593      rfWrite.intWen := false.B
594      rfWrite.fpWen := this.fpWen
595      rfWrite.vecWen := this.vecWen
596      rfWrite
597    }
598  }
599
600  // ExuOutput --> ExuBypassBundle --[DataPath]-->ExuInput
601  //                                /
602  //     [IssueQueue]--> ExuInput --
603  class ExuBypassBundle(
604    val params: ExeUnitParams,
605  )(implicit
606    val p: Parameters
607  ) extends Bundle {
608    val data  = UInt(params.dataBitsMax.W)
609    val pdest = UInt(params.wbPregIdxWidth.W)
610  }
611
612  class ExceptionInfo extends Bundle {
613    val pc = UInt(VAddrData().dataWidth.W)
614    val instr = UInt(32.W)
615    val commitType = CommitType()
616    val exceptionVec = ExceptionVec()
617    val singleStep = Bool()
618    val crossPageIPFFix = Bool()
619    val isInterrupt = Bool()
620  }
621
622  object UopIdx {
623    def apply()(implicit p: Parameters): UInt = UInt(log2Up(p(XSCoreParamsKey).MaxUopSize + 1).W)
624  }
625
626  object FuLatency {
627    def apply(): UInt = UInt(width.W)
628
629    def width = 4 // 0~15 // Todo: assosiate it with FuConfig
630  }
631
632  object ExuVec {
633    def apply(exuNum: Int): Vec[Bool] = Vec(exuNum, Bool())
634
635    def apply()(implicit p: Parameters): Vec[Bool] = Vec(width, Bool())
636
637    def width(implicit p: Parameters): Int = p(XSCoreParamsKey).backendParams.numExu
638  }
639
640  class MemExuInput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
641    val uop = new DynInst
642    val src = if (isVector) Vec(5, UInt(VLEN.W)) else Vec(3, UInt(XLEN.W))
643    val iqIdx = UInt(log2Up(MemIQSizeMax).W)
644    val isFirstIssue = Bool()
645  }
646
647  class MemExuOutput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
648    val uop = new DynInst
649    val data = if (isVector) UInt(VLEN.W) else UInt(XLEN.W)
650    val debug = new DebugBundle
651  }
652
653  class MemMicroOpRbExt(implicit p: Parameters) extends XSBundle {
654    val uop = new DynInst
655    val flag = UInt(1.W)
656  }
657}
658