xref: /XiangShan/src/main/scala/xiangshan/backend/Bundles.scala (revision 0f55a0d39d9e13a42b8a8ea5f45338f62ff484ef)
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 isLUI32: Bool = this.fuType === FuType.alu.U && this.selImm === SelImm.IMM_LUI32
190    def isWFI: Bool = this.fuType === FuType.csr.U && fuOpType === CSROpType.wfi
191
192    def isSvinvalBegin(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && !flush
193    def isSvinval(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.sfence && !flush
194    def isSvinvalEnd(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && flush
195
196    def srcIsReady: Vec[Bool] = {
197      VecInit(this.srcType.zip(this.srcState).map {
198        case (t, s) => SrcType.isNotReg(t) || SrcState.isReady(s)
199      })
200    }
201
202    def clearExceptions(
203      exceptionBits: Seq[Int] = Seq(),
204      flushPipe    : Boolean = false,
205      replayInst   : Boolean = false
206    ): DynInst = {
207      this.exceptionVec.zipWithIndex.filterNot(x => exceptionBits.contains(x._2)).foreach(_._1 := false.B)
208      if (!flushPipe) { this.flushPipe := false.B }
209      if (!replayInst) { this.replayInst := false.B }
210      this
211    }
212
213    def needWriteRf: Bool = (rfWen && ldest =/= 0.U) || fpWen || vecWen
214  }
215
216  trait BundleSource {
217    var wakeupSource = "undefined"
218    var idx = 0
219  }
220
221  /**
222    *
223    * @param pregIdxWidth index width of preg
224    * @param exuIndices exu indices of wakeup bundle
225    */
226  sealed abstract class IssueQueueWakeUpBaseBundle(pregIdxWidth: Int, val exuIndices: Seq[Int]) extends Bundle {
227    val rfWen = Bool()
228    val fpWen = Bool()
229    val vecWen = Bool()
230    val pdest = UInt(pregIdxWidth.W)
231
232    /**
233      * @param successor Seq[(psrc, srcType)]
234      * @return Seq[if wakeup psrc]
235      */
236    def wakeUp(successor: Seq[(UInt, UInt)], valid: Bool): Seq[Bool] = {
237      successor.map { case (thatPsrc, srcType) =>
238        val pdestMatch = pdest === thatPsrc
239        pdestMatch && (
240          SrcType.isFp(srcType) && this.fpWen ||
241            SrcType.isXp(srcType) && this.rfWen ||
242            SrcType.isVp(srcType) && this.vecWen
243          ) && valid
244      }
245    }
246
247    def hasOnlyOneSource: Boolean = exuIndices.size == 1
248
249    def hasMultiSources: Boolean = exuIndices.size > 1
250
251    def isWBWakeUp = this.isInstanceOf[IssueQueueWBWakeUpBundle]
252
253    def isIQWakeUp = this.isInstanceOf[IssueQueueIQWakeUpBundle]
254
255    def exuIdx: Int = {
256      require(hasOnlyOneSource)
257      this.exuIndices.head
258    }
259  }
260
261  class IssueQueueWBWakeUpBundle(exuIndices: Seq[Int], backendParams: BackendParams) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, exuIndices) {
262
263  }
264
265  class IssueQueueIQWakeUpBundle(exuIdx: Int, backendParams: BackendParams) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, Seq(exuIdx)) {
266    val loadDependency = Vec(backendParams.LduCnt, UInt(3.W))
267    def fromExuInput(exuInput: ExuInput, l2ExuVecs: Vec[Vec[Bool]]): Unit = {
268      this.rfWen := exuInput.rfWen.getOrElse(false.B)
269      this.fpWen := exuInput.fpWen.getOrElse(false.B)
270      this.vecWen := exuInput.vecWen.getOrElse(false.B)
271      this.pdest := exuInput.pdest
272    }
273
274    def fromExuInput(exuInput: ExuInput): Unit = {
275      this.rfWen := exuInput.rfWen.getOrElse(false.B)
276      this.fpWen := exuInput.fpWen.getOrElse(false.B)
277      this.vecWen := exuInput.vecWen.getOrElse(false.B)
278      this.pdest := exuInput.pdest
279    }
280  }
281
282  class VPUCtrlSignals(implicit p: Parameters) extends XSBundle {
283    // vtype
284    val vill      = Bool()
285    val vma       = Bool()    // 1: agnostic, 0: undisturbed
286    val vta       = Bool()    // 1: agnostic, 0: undisturbed
287    val vsew      = VSew()
288    val vlmul     = VLmul()   // 1/8~8      --> -3~3
289
290    val vm        = Bool()    // 0: need v0.t
291    val vstart    = Vl()
292
293    // float rounding mode
294    val frm       = Frm()
295    // scalar float instr and vector float reduction
296    val fpu       = Fpu()
297    // vector fix int rounding mode
298    val vxrm      = Vxrm()
299    // vector uop index, exclude other non-vector uop
300    val vuopIdx   = UopIdx()
301    // maybe used if data dependancy
302    val vmask     = UInt(MaskSrcData().dataWidth.W)
303    val vl        = Vl()
304
305    // vector load/store
306    val nf        = Nf()
307
308    val needScalaSrc       = Bool()
309    val permImmTruncate    = Bool() // opivi
310
311    val isReverse = Bool() // vrsub, vrdiv
312    val isExt     = Bool()
313    val isNarrow  = Bool()
314    val isDstMask = Bool() // vvm, vvvm, mmm
315    val isOpMask  = Bool() // vmand, vmnand
316    val isMove    = Bool() // vmv.s.x, vmv.v.v, vmv.v.x, vmv.v.i
317
318    def vtype: VType = {
319      val res = Wire(VType())
320      res.illegal := this.vill
321      res.vma     := this.vma
322      res.vta     := this.vta
323      res.vsew    := this.vsew
324      res.vlmul   := this.vlmul
325      res
326    }
327
328    def vconfig: VConfig = {
329      val res = Wire(VConfig())
330      res.vtype := this.vtype
331      res.vl    := this.vl
332      res
333    }
334  }
335
336  // DynInst --[IssueQueue]--> DataPath
337  class IssueQueueIssueBundle(
338    iqParams: IssueBlockParams,
339    val exuParams: ExeUnitParams,
340  )(implicit
341    p: Parameters
342  ) extends Bundle {
343    private val rfReadDataCfgSet: Seq[Set[DataConfig]] = exuParams.getRfReadDataCfgSet
344
345    val rf: MixedVec[MixedVec[RfReadPortWithConfig]] = Flipped(MixedVec(
346      rfReadDataCfgSet.map((set: Set[DataConfig]) =>
347        MixedVec(set.map((x: DataConfig) => new RfReadPortWithConfig(x, exuParams.rdPregIdxWidth)).toSeq)
348      )
349    ))
350
351    val srcType = Vec(exuParams.numRegSrc, SrcType()) // used to select imm or reg data
352    val immType = SelImm()                         // used to select imm extractor
353    val common = new ExuInput(exuParams)
354    val jmp = if (exuParams.needPc) Some(Flipped(new IssueQueueJumpBundle)) else None
355    val addrOH = UInt(iqParams.numEntries.W)
356
357    def exuIdx = exuParams.exuIdx
358    def getSource: SchedulerType = exuParams.getWBSource
359    def getIntWbBusyBundle = common.rfWen.toSeq
360    def getVfWbBusyBundle = common.getVfWen.toSeq
361    def getIntRfReadBundle: Seq[RfReadPortWithConfig] = rf.flatten.filter(_.readInt)
362    def getVfRfReadBundle: Seq[RfReadPortWithConfig] = rf.flatten.filter(_.readVf)
363
364    def getIntRfReadValidBundle(issueValid: Bool): Seq[ValidIO[RfReadPortWithConfig]] = {
365      getIntRfReadBundle.zip(srcType).map {
366        case (rfRd: RfReadPortWithConfig, t: UInt) =>
367          makeValid(issueValid && SrcType.isXp(t), rfRd)
368      }
369    }
370
371    def getVfRfReadValidBundle(issueValid: Bool): Seq[ValidIO[RfReadPortWithConfig]] = {
372      getVfRfReadBundle.zip(srcType).map {
373        case (rfRd: RfReadPortWithConfig, t: UInt) =>
374          makeValid(issueValid && SrcType.isVfp(t), rfRd)
375      }
376    }
377
378    def getIntRfWriteValidBundle(issueValid: Bool) = {
379
380    }
381  }
382
383  class OGRespBundle(implicit p:Parameters, params: IssueBlockParams) extends XSBundle {
384    val issueQueueParams = this.params
385    val og0resp = Valid(new EntryDeqRespBundle)
386    val og1resp = Valid(new EntryDeqRespBundle)
387  }
388
389  class fuBusyRespBundle(implicit p: Parameters, params: IssueBlockParams) extends Bundle {
390    val respType = RSFeedbackType() // update credit if needs replay
391    val rfWen = Bool() // TODO: use params to identify IntWB/VfWB
392    val fuType = FuType()
393  }
394
395  class WbFuBusyTableWriteBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
396    private val intCertainLat = params.intLatencyCertain
397    private val vfCertainLat = params.vfLatencyCertain
398    private val intLat = params.intLatencyValMax
399    private val vfLat = params.vfLatencyValMax
400
401    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
402    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
403    val intDeqRespSet = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
404    val vfDeqRespSet = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
405  }
406
407  class WbFuBusyTableReadBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
408    private val intCertainLat = params.intLatencyCertain
409    private val vfCertainLat = params.vfLatencyCertain
410    private val intLat = params.intLatencyValMax
411    private val vfLat = params.vfLatencyValMax
412
413    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
414    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
415  }
416
417  class WbConflictBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
418    private val intCertainLat = params.intLatencyCertain
419    private val vfCertainLat = params.vfLatencyCertain
420
421    val intConflict = OptionWrapper(intCertainLat, Bool())
422    val vfConflict = OptionWrapper(vfCertainLat, Bool())
423  }
424
425  // DataPath --[ExuInput]--> Exu
426  class ExuInput(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
427    val fuType        = FuType()
428    val fuOpType      = FuOpType()
429    val src           = Vec(params.numRegSrc, UInt(params.dataBitsMax.W))
430    val imm           = UInt(XLEN.W)
431    val robIdx        = new RobPtr
432    val iqIdx         = UInt(log2Up(MemIQSizeMax).W)// Only used by store yet
433    val isFirstIssue  = Bool()                      // Only used by store yet
434    val pdest         = UInt(params.wbPregIdxWidth.W)
435    val rfWen         = if (params.writeIntRf)    Some(Bool())                        else None
436    val fpWen         = if (params.writeFpRf)     Some(Bool())                        else None
437    val vecWen        = if (params.writeVecRf)    Some(Bool())                        else None
438    val fpu           = if (params.writeFflags)   Some(new FPUCtrlSignals)            else None
439    val vpu           = if (params.needVPUCtrl)   Some(new VPUCtrlSignals)            else None
440    val flushPipe     = if (params.flushPipe)     Some(Bool())                        else None
441    val pc            = if (params.needPc)        Some(UInt(VAddrData().dataWidth.W)) else None
442    val jalrTarget    = if (params.hasJmpFu)      Some(UInt(VAddrData().dataWidth.W)) else None
443    val preDecode     = if (params.hasPredecode)  Some(new PreDecodeInfo)             else None
444    val ftqIdx        = if (params.needPc || params.replayInst)
445                                                  Some(new FtqPtr)                    else None
446    val ftqOffset     = if (params.needPc || params.replayInst)
447                                                  Some(UInt(log2Up(PredictWidth).W))  else None
448    val predictInfo   = if (params.hasPredecode)  Some(new Bundle {
449      val target = UInt(VAddrData().dataWidth.W)
450      val taken = Bool()
451    }) else None
452    val sqIdx = if (params.hasMemAddrFu || params.hasStdFu) Some(new SqPtr) else None
453    val lqIdx = if (params.hasMemAddrFu) Some(new LqPtr) else None
454    val dataSources = Vec(params.numRegSrc, DataSource())
455    val l1ExuVec = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, ExuVec()))
456    val srcTimer = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, UInt(3.W)))
457    val loadDependency = OptionWrapper(params.isIQWakeUpSink, Vec(LoadPipelineWidth, UInt(3.W)))
458    val deqPortIdx = OptionWrapper(params.hasLoadFu, UInt(log2Ceil(LoadPipelineWidth).W))
459
460    def exuIdx = this.params.exuIdx
461
462    def needCancel(og0CancelVec: Vec[Bool], og1CancelVec: Vec[Bool]) : Bool = {
463      if (params.isIQWakeUpSink) {
464        require(
465          og0CancelVec.size == l1ExuVec.get.head.size,
466          s"cancelVecSize: {og0: ${og0CancelVec.size}, og1: ${og1CancelVec.size}}"
467        )
468        val l1Cancel: Bool = l1ExuVec.get.zip(srcTimer.get).map {
469          case(exuOH: Vec[Bool], srcTimer: UInt) =>
470            (exuOH.asUInt & og0CancelVec.asUInt).orR && srcTimer === 1.U
471        }.reduce(_ | _)
472        l1Cancel
473      } else {
474        false.B
475      }
476    }
477
478    def getVfWen = {
479      if (params.writeFpRf) this.fpWen
480      else if(params.writeVecRf) this.vecWen
481      else None
482    }
483
484    def fromIssueBundle(source: IssueQueueIssueBundle): Unit = {
485      // src is assigned to rfReadData
486      this.fuType        := source.common.fuType
487      this.fuOpType      := source.common.fuOpType
488      this.imm           := source.common.imm
489      this.robIdx        := source.common.robIdx
490      this.pdest         := source.common.pdest
491      this.isFirstIssue  := source.common.isFirstIssue // Only used by mem debug log
492      this.iqIdx         := source.common.iqIdx        // Only used by mem feedback
493      this.dataSources   := source.common.dataSources
494      this.rfWen         .foreach(_ := source.common.rfWen.get)
495      this.fpWen         .foreach(_ := source.common.fpWen.get)
496      this.vecWen        .foreach(_ := source.common.vecWen.get)
497      this.fpu           .foreach(_ := source.common.fpu.get)
498      this.vpu           .foreach(_ := source.common.vpu.get)
499      this.flushPipe     .foreach(_ := source.common.flushPipe.get)
500      this.pc            .foreach(_ := source.jmp.get.pc)
501      this.jalrTarget    .foreach(_ := source.jmp.get.target)
502      this.preDecode     .foreach(_ := source.common.preDecode.get)
503      this.ftqIdx        .foreach(_ := source.common.ftqIdx.get)
504      this.ftqOffset     .foreach(_ := source.common.ftqOffset.get)
505      this.predictInfo   .foreach(_ := source.common.predictInfo.get)
506      this.lqIdx         .foreach(_ := source.common.lqIdx.get)
507      this.sqIdx         .foreach(_ := source.common.sqIdx.get)
508      this.l1ExuVec      .foreach(_ := source.common.l1ExuVec.get)
509      this.srcTimer      .foreach(_ := source.common.srcTimer.get)
510      this.loadDependency.foreach(_ := source.common.loadDependency.get.map(_ << 1))
511      this.deqPortIdx    .foreach(_ := source.common.deqPortIdx.get)
512    }
513  }
514
515  // ExuInput --[FuncUnit]--> ExuOutput
516  class ExuOutput(
517    val params: ExeUnitParams,
518  )(implicit
519    val p: Parameters
520  ) extends Bundle with BundleSource with HasXSParameter {
521    val data         = UInt(params.dataBitsMax.W)
522    val pdest        = UInt(params.wbPregIdxWidth.W)
523    val robIdx       = new RobPtr
524    val intWen       = if (params.writeIntRf)   Some(Bool())                  else None
525    val fpWen        = if (params.writeFpRf)    Some(Bool())                  else None
526    val vecWen       = if (params.writeVecRf)   Some(Bool())                  else None
527    val redirect     = if (params.hasRedirect)  Some(ValidIO(new Redirect))   else None
528    val fflags       = if (params.writeFflags)  Some(UInt(5.W))               else None
529    val wflags       = if (params.writeFflags)  Some(Bool())                  else None
530    val vxsat        = if (params.writeVxsat)   Some(Bool())                  else None
531    val exceptionVec = if (params.exceptionOut.nonEmpty) Some(ExceptionVec()) else None
532    val flushPipe    = if (params.flushPipe)    Some(Bool())                  else None
533    val replay       = if (params.replayInst)   Some(Bool())                  else None
534    val lqIdx        = if (params.hasLoadFu)    Some(new LqPtr())             else None
535    val sqIdx        = if (params.hasStoreAddrFu || params.hasStdFu)
536                                                Some(new SqPtr())             else None
537    val ftqIdx       = if (params.needPc || params.replayInst)
538                                                Some(new FtqPtr)                    else None
539    val ftqOffset    = if (params.needPc || params.replayInst)
540                                                Some(UInt(log2Up(PredictWidth).W))  else None
541    // uop info
542    val predecodeInfo = if(params.hasPredecode) Some(new PreDecodeInfo) else None
543    val debug = new DebugBundle
544    val debugInfo = new PerfDebugInfo
545  }
546
547  // ExuOutput + DynInst --> WriteBackBundle
548  class WriteBackBundle(val params: PregWB, backendParams: BackendParams)(implicit p: Parameters) extends Bundle with BundleSource {
549    val rfWen = Bool()
550    val fpWen = Bool()
551    val vecWen = Bool()
552    val pdest = UInt(params.pregIdxWidth(backendParams).W)
553    val data = UInt(params.dataWidth.W)
554    val robIdx = new RobPtr()(p)
555    val flushPipe = Bool()
556    val replayInst = Bool()
557    val redirect = ValidIO(new Redirect)
558    val fflags = UInt(5.W)
559    val vxsat = Bool()
560    val exceptionVec = ExceptionVec()
561    val debug = new DebugBundle
562    val debugInfo = new PerfDebugInfo
563
564    this.wakeupSource = s"WB(${params.toString})"
565
566    def fromExuOutput(source: ExuOutput) = {
567      this.rfWen  := source.intWen.getOrElse(false.B)
568      this.fpWen  := source.fpWen.getOrElse(false.B)
569      this.vecWen := source.vecWen.getOrElse(false.B)
570      this.pdest  := source.pdest
571      this.data   := source.data
572      this.robIdx := source.robIdx
573      this.flushPipe := source.flushPipe.getOrElse(false.B)
574      this.replayInst := source.replay.getOrElse(false.B)
575      this.redirect := source.redirect.getOrElse(0.U.asTypeOf(this.redirect))
576      this.fflags := source.fflags.getOrElse(0.U.asTypeOf(this.fflags))
577      this.vxsat := source.vxsat.getOrElse(0.U.asTypeOf(this.vxsat))
578      this.exceptionVec := source.exceptionVec.getOrElse(0.U.asTypeOf(this.exceptionVec))
579      this.debug := source.debug
580      this.debugInfo := source.debugInfo
581    }
582
583    def asIntRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
584      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(IntData()).addrWidth)))
585      rfWrite.wen := this.rfWen && fire
586      rfWrite.addr := this.pdest
587      rfWrite.data := this.data
588      rfWrite.intWen := this.rfWen
589      rfWrite.fpWen := false.B
590      rfWrite.vecWen := false.B
591      rfWrite
592    }
593
594    def asVfRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
595      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(VecData()).addrWidth)))
596      rfWrite.wen := (this.fpWen || this.vecWen) && fire
597      rfWrite.addr := this.pdest
598      rfWrite.data := this.data
599      rfWrite.intWen := false.B
600      rfWrite.fpWen := this.fpWen
601      rfWrite.vecWen := this.vecWen
602      rfWrite
603    }
604  }
605
606  // ExuOutput --> ExuBypassBundle --[DataPath]-->ExuInput
607  //                                /
608  //     [IssueQueue]--> ExuInput --
609  class ExuBypassBundle(
610    val params: ExeUnitParams,
611  )(implicit
612    val p: Parameters
613  ) extends Bundle {
614    val data  = UInt(params.dataBitsMax.W)
615    val pdest = UInt(params.wbPregIdxWidth.W)
616  }
617
618  class ExceptionInfo extends Bundle {
619    val pc = UInt(VAddrData().dataWidth.W)
620    val instr = UInt(32.W)
621    val commitType = CommitType()
622    val exceptionVec = ExceptionVec()
623    val singleStep = Bool()
624    val crossPageIPFFix = Bool()
625    val isInterrupt = Bool()
626  }
627
628  object UopIdx {
629    def apply()(implicit p: Parameters): UInt = UInt(log2Up(p(XSCoreParamsKey).MaxUopSize + 1).W)
630  }
631
632  object FuLatency {
633    def apply(): UInt = UInt(width.W)
634
635    def width = 4 // 0~15 // Todo: assosiate it with FuConfig
636  }
637
638  object ExuVec {
639    def apply(exuNum: Int): Vec[Bool] = Vec(exuNum, Bool())
640
641    def apply()(implicit p: Parameters): Vec[Bool] = Vec(width, Bool())
642
643    def width(implicit p: Parameters): Int = p(XSCoreParamsKey).backendParams.numExu
644  }
645
646  class MemExuInput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
647    val uop = new DynInst
648    val src = if (isVector) Vec(5, UInt(VLEN.W)) else Vec(3, UInt(XLEN.W))
649    val iqIdx = UInt(log2Up(MemIQSizeMax).W)
650    val isFirstIssue = Bool()
651    val deqPortIdx = UInt(log2Ceil(LoadPipelineWidth).W)
652  }
653
654  class MemExuOutput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
655    val uop = new DynInst
656    val data = if (isVector) UInt(VLEN.W) else UInt(XLEN.W)
657    val debug = new DebugBundle
658  }
659
660  class MemMicroOpRbExt(implicit p: Parameters) extends XSBundle {
661    val uop = new DynInst
662    val flag = UInt(1.W)
663  }
664
665  object LoadShouldCancel {
666    def apply(loadDependency: Option[Seq[UInt]], ldCancel: Seq[LoadCancelIO]): Bool = {
667      val ld1Cancel = loadDependency.map(deps =>
668        deps.zipWithIndex.map { case (dep, ldPortIdx) =>
669          ldCancel.map(_.ld1Cancel).map(cancel => cancel.fire && dep(1) && cancel.bits === ldPortIdx.U).reduce(_ || _)
670        }.reduce(_ || _)
671      )
672      val ld2Cancel = loadDependency.map(deps =>
673        deps.zipWithIndex.map { case (dep, ldPortIdx) =>
674          ldCancel.map(_.ld2Cancel).map(cancel => cancel.fire && dep(2) && cancel.bits === ldPortIdx.U).reduce(_ || _)
675        }.reduce(_ || _)
676      )
677      ld1Cancel.map(_ || ld2Cancel.get).getOrElse(false.B)
678    }
679  }
680}
681