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