xref: /XiangShan/src/main/scala/xiangshan/backend/Bundles.scala (revision 92c61038092ac384201fa5f56e31f96be14a30f5)
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
25import xiangshan.backend.trace._
26
27object Bundles {
28  /**
29   * Connect Same Name Port like bundleSource := bundleSinkBudle.
30   *
31   * There is no limit to the number of ports on both sides.
32   *
33   * Don't forget to connect the remaining ports!
34   */
35  def connectSamePort (bundleSource: Bundle, bundleSink: Bundle):Unit = {
36    bundleSource.elements.foreach { case (name, data) =>
37      if (bundleSink.elements.contains(name))
38        data := bundleSink.elements(name)
39    }
40  }
41  // frontend -> backend
42  class StaticInst(implicit p: Parameters) extends XSBundle {
43    val instr           = UInt(32.W)
44    val pc              = UInt(VAddrBits.W)
45    val foldpc          = UInt(MemPredPCWidth.W)
46    val exceptionVec    = ExceptionVec()
47    val trigger         = TriggerAction()
48    val preDecodeInfo   = new PreDecodeInfo
49    val pred_taken      = Bool()
50    val crossPageIPFFix = Bool()
51    val ftqPtr          = new FtqPtr
52    val ftqOffset       = UInt(log2Up(PredictWidth).W)
53
54    def connectCtrlFlow(source: CtrlFlow): Unit = {
55      this.instr            := source.instr
56      this.pc               := source.pc
57      this.foldpc           := source.foldpc
58      this.exceptionVec     := source.exceptionVec
59      this.trigger          := source.trigger
60      this.preDecodeInfo    := source.pd
61      this.pred_taken       := source.pred_taken
62      this.crossPageIPFFix  := source.crossPageIPFFix
63      this.ftqPtr           := source.ftqPtr
64      this.ftqOffset        := source.ftqOffset
65    }
66  }
67
68  // StaticInst --[Decode]--> DecodedInst
69  class DecodedInst(implicit p: Parameters) extends XSBundle {
70    def numSrc = backendParams.numSrc
71    // passed from StaticInst
72    val instr           = UInt(32.W)
73    val pc              = UInt(VAddrBits.W)
74    val foldpc          = UInt(MemPredPCWidth.W)
75    val exceptionVec    = ExceptionVec()
76    val trigger         = TriggerAction()
77    val preDecodeInfo   = new PreDecodeInfo
78    val pred_taken      = Bool()
79    val crossPageIPFFix = Bool()
80    val ftqPtr          = new FtqPtr
81    val ftqOffset       = UInt(log2Up(PredictWidth).W)
82    // decoded
83    val srcType         = Vec(numSrc, SrcType())
84    val lsrc            = Vec(numSrc, UInt(LogicRegsWidth.W))
85    val ldest           = UInt(LogicRegsWidth.W)
86    val fuType          = FuType()
87    val fuOpType        = FuOpType()
88    val rfWen           = Bool()
89    val fpWen           = Bool()
90    val vecWen          = Bool()
91    val v0Wen           = Bool()
92    val vlWen           = Bool()
93    val isXSTrap        = Bool()
94    val waitForward     = Bool() // no speculate execution
95    val blockBackward   = Bool()
96    val flushPipe       = Bool() // This inst will flush all the pipe when commit, like exception but can commit
97    val canRobCompress  = Bool()
98    val selImm          = SelImm()
99    val imm             = UInt(ImmUnion.maxLen.W)
100    val fpu             = new FPUCtrlSignals
101    val vpu             = new VPUCtrlSignals
102    val vlsInstr        = Bool()
103    val wfflags         = Bool()
104    val isMove          = Bool()
105    val uopIdx          = UopIdx()
106    val uopSplitType    = UopSplitType()
107    val isVset          = Bool()
108    val firstUop        = Bool()
109    val lastUop         = Bool()
110    val numUops         = UInt(log2Up(MaxUopSize).W) // rob need this
111    val numWB           = UInt(log2Up(MaxUopSize).W) // rob need this
112    val commitType      = CommitType() // Todo: remove it
113    val needFrm         = new NeedFrmBundle
114
115    val debug_fuType    = OptionWrapper(backendParams.debugEn, FuType())
116
117    private def allSignals = srcType.take(3) ++ Seq(fuType, fuOpType, rfWen, fpWen, vecWen,
118      isXSTrap, waitForward, blockBackward, flushPipe, canRobCompress, uopSplitType, selImm)
119
120    def decode(inst: UInt, table: Iterable[(BitPat, List[BitPat])]): DecodedInst = {
121      val decoder: Seq[UInt] = ListLookup(
122        inst, XDecode.decodeDefault.map(bitPatToUInt),
123        table.map{ case (pat, pats) => (pat, pats.map(bitPatToUInt)) }.toArray
124      )
125      allSignals zip decoder foreach { case (s, d) => s := d }
126      debug_fuType.foreach(_ := fuType)
127      this
128    }
129
130    def isSoftPrefetch: Bool = {
131      fuType === FuType.alu.U && fuOpType === ALUOpType.or && selImm === SelImm.IMM_I && ldest === 0.U
132    }
133
134    def connectStaticInst(source: StaticInst): Unit = {
135      for ((name, data) <- this.elements) {
136        if (source.elements.contains(name)) {
137          data := source.elements(name)
138        }
139      }
140    }
141  }
142
143  class TrapInstInfo(implicit p: Parameters) extends XSBundle {
144    val instr = UInt(32.W)
145    val ftqPtr = new FtqPtr
146    val ftqOffset = UInt(log2Up(PredictWidth).W)
147
148    def needFlush(ftqPtr: FtqPtr, ftqOffset: UInt): Bool ={
149      val sameFlush = this.ftqPtr === ftqPtr && this.ftqOffset > ftqOffset
150      sameFlush || isAfter(this.ftqPtr, ftqPtr)
151    }
152
153    def fromDecodedInst(decodedInst: DecodedInst): this.type = {
154      this.instr     := decodedInst.instr
155      this.ftqPtr    := decodedInst.ftqPtr
156      this.ftqOffset := decodedInst.ftqOffset
157      this
158    }
159  }
160
161  // DecodedInst --[Rename]--> DynInst
162  class DynInst(implicit p: Parameters) extends XSBundle {
163    def numSrc          = backendParams.numSrc
164    // passed from StaticInst
165    val instr           = UInt(32.W)
166    val pc              = UInt(VAddrBits.W)
167    val foldpc          = UInt(MemPredPCWidth.W)
168    val exceptionVec    = ExceptionVec()
169    val hasException    = Bool()
170    val trigger         = TriggerAction()
171    val preDecodeInfo   = new PreDecodeInfo
172    val pred_taken      = Bool()
173    val crossPageIPFFix = Bool()
174    val ftqPtr          = new FtqPtr
175    val ftqOffset       = UInt(log2Up(PredictWidth).W)
176    // passed from DecodedInst
177    val srcType         = Vec(numSrc, SrcType())
178    val ldest           = UInt(LogicRegsWidth.W)
179    val fuType          = FuType()
180    val fuOpType        = FuOpType()
181    val rfWen           = Bool()
182    val fpWen           = Bool()
183    val vecWen          = Bool()
184    val v0Wen           = Bool()
185    val vlWen           = Bool()
186    val isXSTrap        = Bool()
187    val waitForward     = Bool() // no speculate execution
188    val blockBackward   = Bool()
189    val flushPipe       = Bool() // This inst will flush all the pipe when commit, like exception but can commit
190    val canRobCompress  = Bool()
191    val selImm          = SelImm()
192    val imm             = UInt(32.W)
193    val fpu             = new FPUCtrlSignals
194    val vpu             = new VPUCtrlSignals
195    val vlsInstr        = Bool()
196    val wfflags         = Bool()
197    val isMove          = Bool()
198    val uopIdx          = UopIdx()
199    val isVset          = Bool()
200    val firstUop        = Bool()
201    val lastUop         = Bool()
202    val numUops         = UInt(log2Up(MaxUopSize).W) // rob need this
203    val numWB           = UInt(log2Up(MaxUopSize).W) // rob need this
204    val commitType      = CommitType()
205    // rename
206    val srcState        = Vec(numSrc, SrcState())
207    val srcLoadDependency  = Vec(numSrc, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W)))
208    val psrc            = Vec(numSrc, UInt(PhyRegIdxWidth.W))
209    val pdest           = UInt(PhyRegIdxWidth.W)
210    // reg cache
211    val useRegCache     = Vec(backendParams.numIntRegSrc, Bool())
212    val regCacheIdx     = Vec(backendParams.numIntRegSrc, UInt(RegCacheIdxWidth.W))
213    val robIdx          = new RobPtr
214    val instrSize       = UInt(log2Ceil(RenameWidth + 1).W)
215    val dirtyFs         = Bool()
216    val dirtyVs         = Bool()
217    val traceBlockInPipe = new TracePipe(log2Up(RenameWidth * 2))
218
219    val eliminatedMove  = Bool()
220    // Take snapshot at this CFI inst
221    val snapshot        = Bool()
222    val debugInfo       = new PerfDebugInfo
223    val storeSetHit     = Bool() // inst has been allocated an store set
224    val waitForRobIdx   = new RobPtr // store set predicted previous store robIdx
225    // Load wait is needed
226    // load inst will not be executed until former store (predicted by mdp) addr calcuated
227    val loadWaitBit     = Bool()
228    // If (loadWaitBit && loadWaitStrict), strict load wait is needed
229    // load inst will not be executed until ALL former store addr calcuated
230    val loadWaitStrict  = Bool()
231    val ssid            = UInt(SSIDWidth.W)
232    // Todo
233    val lqIdx = new LqPtr
234    val sqIdx = new SqPtr
235    // debug module
236    val singleStep      = Bool()
237    // schedule
238    val replayInst      = Bool()
239
240    val debug_fuType    = OptionWrapper(backendParams.debugEn, FuType())
241
242    val numLsElem       = NumLsElem()
243
244    def getDebugFuType: UInt = debug_fuType.getOrElse(fuType)
245
246    def isLUI: Bool = this.fuType === FuType.alu.U && (this.selImm === SelImm.IMM_U || this.selImm === SelImm.IMM_LUI32)
247    def isLUI32: Bool = this.selImm === SelImm.IMM_LUI32
248    def isWFI: Bool = this.fuType === FuType.csr.U && fuOpType === CSROpType.wfi
249
250    def isSvinvalBegin(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && !flush
251    def isSvinval(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.sfence && !flush
252    def isSvinvalEnd(flush: Bool) = FuType.isFence(fuType) && fuOpType === FenceOpType.nofence && flush
253    def isNotSvinval = !FuType.isFence(fuType)
254
255    def isHls: Bool = {
256      fuType === FuType.ldu.U && LSUOpType.isHlv(fuOpType) || fuType === FuType.stu.U && LSUOpType.isHsv(fuOpType)
257    }
258
259    def srcIsReady: Vec[Bool] = {
260      VecInit(this.srcType.zip(this.srcState).map {
261        case (t, s) => SrcType.isNotReg(t) || SrcState.isReady(s)
262      })
263    }
264
265    def clearExceptions(
266      exceptionBits: Seq[Int] = Seq(),
267      flushPipe    : Boolean = false,
268      replayInst   : Boolean = false
269    ): DynInst = {
270      this.exceptionVec.zipWithIndex.filterNot(x => exceptionBits.contains(x._2)).foreach(_._1 := false.B)
271      if (!flushPipe) { this.flushPipe := false.B }
272      if (!replayInst) { this.replayInst := false.B }
273      this
274    }
275
276    def needWriteRf: Bool = (rfWen && ldest =/= 0.U) || fpWen || vecWen || v0Wen || vlWen
277  }
278
279  trait BundleSource {
280    var wakeupSource = "undefined"
281    var idx = 0
282  }
283
284  /**
285    *
286    * @param pregIdxWidth index width of preg
287    * @param exuIndices exu indices of wakeup bundle
288    */
289  sealed abstract class IssueQueueWakeUpBaseBundle(pregIdxWidth: Int, val exuIndices: Seq[Int])(implicit p: Parameters) extends XSBundle {
290    val rfWen = Bool()
291    val fpWen = Bool()
292    val vecWen = Bool()
293    val v0Wen = Bool()
294    val vlWen = Bool()
295    val pdest = UInt(pregIdxWidth.W)
296
297    /**
298      * @param successor Seq[(psrc, srcType)]
299      * @return Seq[if wakeup psrc]
300      */
301    def wakeUp(successor: Seq[(UInt, UInt)], valid: Bool): Seq[Bool] = {
302      successor.map { case (thatPsrc, srcType) =>
303        val pdestMatch = pdest === thatPsrc
304        pdestMatch && (
305          SrcType.isFp(srcType) && this.fpWen ||
306            SrcType.isXp(srcType) && this.rfWen ||
307            SrcType.isVp(srcType) && this.vecWen
308          ) && valid
309      }
310    }
311    def wakeUpV0(successor: (UInt, UInt), valid: Bool): Bool = {
312      val (thatPsrc, srcType) = successor
313      val pdestMatch = pdest === thatPsrc
314      pdestMatch && (
315        SrcType.isV0(srcType) && this.v0Wen
316      ) && valid
317    }
318    def wakeUpVl(successor: (UInt, UInt), valid: Bool): Bool = {
319      val (thatPsrc, srcType) = successor
320      val pdestMatch = pdest === thatPsrc
321      pdestMatch && (
322        SrcType.isVp(srcType) && this.vlWen
323      ) && valid
324    }
325    def wakeUpFromIQ(successor: Seq[(UInt, UInt)]): Seq[Bool] = {
326      successor.map { case (thatPsrc, srcType) =>
327        val pdestMatch = pdest === thatPsrc
328        pdestMatch && (
329          SrcType.isFp(srcType) && this.fpWen ||
330            SrcType.isXp(srcType) && this.rfWen ||
331            SrcType.isVp(srcType) && this.vecWen
332          )
333      }
334    }
335    def wakeUpV0FromIQ(successor: (UInt, UInt)): Bool = {
336      val (thatPsrc, srcType) = successor
337      val pdestMatch = pdest === thatPsrc
338      pdestMatch && (
339        SrcType.isV0(srcType) && this.v0Wen
340      )
341    }
342    def wakeUpVlFromIQ(successor: (UInt, UInt)): Bool = {
343      val (thatPsrc, srcType) = successor
344      val pdestMatch = pdest === thatPsrc
345      pdestMatch && (
346        SrcType.isVp(srcType) && this.vlWen
347      )
348    }
349
350    def hasOnlyOneSource: Boolean = exuIndices.size == 1
351
352    def hasMultiSources: Boolean = exuIndices.size > 1
353
354    def isWBWakeUp = this.isInstanceOf[IssueQueueWBWakeUpBundle]
355
356    def isIQWakeUp = this.isInstanceOf[IssueQueueIQWakeUpBundle]
357
358    def exuIdx: Int = {
359      require(hasOnlyOneSource)
360      this.exuIndices.head
361    }
362  }
363
364  class IssueQueueWBWakeUpBundle(exuIndices: Seq[Int], backendParams: BackendParams)(implicit p: Parameters) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, exuIndices) {
365
366  }
367
368  class IssueQueueIQWakeUpBundle(
369    exuIdx: Int,
370    backendParams: BackendParams,
371    copyWakeupOut: Boolean = false,
372    copyNum: Int = 0
373  )(implicit p: Parameters) extends IssueQueueWakeUpBaseBundle(backendParams.pregIdxWidth, Seq(exuIdx)) {
374    val loadDependency = Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W))
375    val is0Lat = Bool()
376    val params = backendParams.allExuParams.filter(_.exuIdx == exuIdx).head
377    val rcDest = OptionWrapper(params.needWriteRegCache, UInt(RegCacheIdxWidth.W))
378    val pdestCopy  = OptionWrapper(copyWakeupOut, Vec(copyNum, UInt(params.wbPregIdxWidth.W)))
379    val rfWenCopy  = OptionWrapper(copyWakeupOut && params.needIntWen, Vec(copyNum, Bool()))
380    val fpWenCopy  = OptionWrapper(copyWakeupOut && params.needFpWen, Vec(copyNum, Bool()))
381    val vecWenCopy = OptionWrapper(copyWakeupOut && params.needVecWen, Vec(copyNum, Bool()))
382    val v0WenCopy = OptionWrapper(copyWakeupOut && params.needV0Wen, Vec(copyNum, Bool()))
383    val vlWenCopy = OptionWrapper(copyWakeupOut && params.needVlWen, Vec(copyNum, Bool()))
384    val loadDependencyCopy = OptionWrapper(copyWakeupOut && params.isIQWakeUpSink, Vec(copyNum, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W))))
385
386    def fromExuInput(exuInput: ExuInput): Unit = {
387      this.rfWen := exuInput.rfWen.getOrElse(false.B)
388      this.fpWen := exuInput.fpWen.getOrElse(false.B)
389      this.vecWen := exuInput.vecWen.getOrElse(false.B)
390      this.v0Wen := exuInput.v0Wen.getOrElse(false.B)
391      this.vlWen := exuInput.vlWen.getOrElse(false.B)
392      this.pdest := exuInput.pdest
393    }
394  }
395
396  class VPUCtrlSignals(implicit p: Parameters) extends XSBundle {
397    // vtype
398    val vill      = Bool()
399    val vma       = Bool()    // 1: agnostic, 0: undisturbed
400    val vta       = Bool()    // 1: agnostic, 0: undisturbed
401    val vsew      = VSew()
402    val vlmul     = VLmul()   // 1/8~8      --> -3~3
403
404    // spec vtype
405    val specVill  = Bool()
406    val specVma   = Bool()    // 1: agnostic, 0: undisturbed
407    val specVta   = Bool()    // 1: agnostic, 0: undisturbed
408    val specVsew  = VSew()
409    val specVlmul = VLmul()   // 1/8~8      --> -3~3
410
411    val vm        = Bool()    // 0: need v0.t
412    val vstart    = Vl()
413
414    // float rounding mode
415    val frm       = Frm()
416    // scalar float instr and vector float reduction
417    val fpu       = Fpu()
418    // vector fix int rounding mode
419    val vxrm      = Vxrm()
420    // vector uop index, exclude other non-vector uop
421    val vuopIdx   = UopIdx()
422    val lastUop   = Bool()
423    // maybe used if data dependancy
424    val vmask     = UInt(V0Data().dataWidth.W)
425    val vl        = Vl()
426
427    // vector load/store
428    val nf        = Nf()
429    val veew      = VEew()
430
431    val isReverse = Bool() // vrsub, vrdiv
432    val isExt     = Bool()
433    val isNarrow  = Bool()
434    val isDstMask = Bool() // vvm, vvvm, mmm
435    val isOpMask  = Bool() // vmand, vmnand
436    val isMove    = Bool() // vmv.s.x, vmv.v.v, vmv.v.x, vmv.v.i
437
438    val isDependOldvd = Bool() // some instruction's computation depends on oldvd
439    val isWritePartVd = Bool() // some instruction's computation writes part of vd, such as vredsum
440
441    def vtype: VType = {
442      val res = Wire(VType())
443      res.illegal := this.vill
444      res.vma     := this.vma
445      res.vta     := this.vta
446      res.vsew    := this.vsew
447      res.vlmul   := this.vlmul
448      res
449    }
450
451    def specVType: VType = {
452      val res = Wire(VType())
453      res.illegal := this.specVill
454      res.vma     := this.specVma
455      res.vta     := this.specVta
456      res.vsew    := this.specVsew
457      res.vlmul   := this.specVlmul
458      res
459    }
460
461    def vconfig: VConfig = {
462      val res = Wire(VConfig())
463      res.vtype := this.vtype
464      res.vl    := this.vl
465      res
466    }
467
468    def connectVType(source: VType): Unit = {
469      this.vill  := source.illegal
470      this.vma   := source.vma
471      this.vta   := source.vta
472      this.vsew  := source.vsew
473      this.vlmul := source.vlmul
474    }
475  }
476
477  class NeedFrmBundle(implicit p: Parameters) extends XSBundle {
478    val scalaNeedFrm = Bool()
479    val vectorNeedFrm = Bool()
480  }
481
482  // DynInst --[IssueQueue]--> DataPath
483  class IssueQueueIssueBundle(
484    iqParams: IssueBlockParams,
485    val exuParams: ExeUnitParams,
486  )(implicit
487    p: Parameters
488  ) extends XSBundle {
489    private val rfReadDataCfgSet: Seq[Set[DataConfig]] = exuParams.getRfReadDataCfgSet
490
491    val rf: MixedVec[MixedVec[RfReadPortWithConfig]] = Flipped(MixedVec(
492      rfReadDataCfgSet.map((set: Set[DataConfig]) =>
493        MixedVec(set.map((x: DataConfig) => new RfReadPortWithConfig(x, exuParams.rdPregIdxWidth)).toSeq)
494      )
495    ))
496
497    val srcType = Vec(exuParams.numRegSrc, SrcType()) // used to select imm or reg data
498    val rcIdx = OptionWrapper(exuParams.needReadRegCache, Vec(exuParams.numRegSrc, UInt(RegCacheIdxWidth.W))) // used to select regcache data
499    val immType = SelImm()                         // used to select imm extractor
500    val common = new ExuInput(exuParams)
501    val addrOH = UInt(iqParams.numEntries.W)
502
503    def exuIdx = exuParams.exuIdx
504    def getSource: SchedulerType = exuParams.getWBSource
505
506    def getRfReadValidBundle(issueValid: Bool): Seq[ValidIO[RfReadPortWithConfig]] = {
507      rf.zip(srcType).map {
508        case (rfRd: MixedVec[RfReadPortWithConfig], t: UInt) =>
509          makeValid(issueValid, rfRd.head)
510      }.toSeq
511    }
512  }
513
514  class OGRespBundle(implicit p:Parameters, params: IssueBlockParams) extends XSBundle {
515    val issueQueueParams = this.params
516    val og0resp = Valid(new EntryDeqRespBundle)
517    val og1resp = Valid(new EntryDeqRespBundle)
518  }
519
520  class WbFuBusyTableWriteBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
521    private val intCertainLat = params.intLatencyCertain
522    private val fpCertainLat = params.fpLatencyCertain
523    private val vfCertainLat = params.vfLatencyCertain
524    private val v0CertainLat = params.v0LatencyCertain
525    private val vlCertainLat = params.vlLatencyCertain
526    private val intLat = params.intLatencyValMax
527    private val fpLat = params.fpLatencyValMax
528    private val vfLat = params.vfLatencyValMax
529    private val v0Lat = params.v0LatencyValMax
530    private val vlLat = params.vlLatencyValMax
531
532    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
533    val fpWbBusyTable = OptionWrapper(fpCertainLat, UInt((fpLat + 1).W))
534    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
535    val v0WbBusyTable = OptionWrapper(v0CertainLat, UInt((v0Lat + 1).W))
536    val vlWbBusyTable = OptionWrapper(vlCertainLat, UInt((vlLat + 1).W))
537    val intDeqRespSet = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
538    val fpDeqRespSet = OptionWrapper(fpCertainLat, UInt((fpLat + 1).W))
539    val vfDeqRespSet = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
540    val v0DeqRespSet = OptionWrapper(v0CertainLat, UInt((v0Lat + 1).W))
541    val vlDeqRespSet = OptionWrapper(vlCertainLat, UInt((vlLat + 1).W))
542  }
543
544  class WbFuBusyTableReadBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
545    private val intCertainLat = params.intLatencyCertain
546    private val fpCertainLat = params.fpLatencyCertain
547    private val vfCertainLat = params.vfLatencyCertain
548    private val v0CertainLat = params.v0LatencyCertain
549    private val vlCertainLat = params.vlLatencyCertain
550    private val intLat = params.intLatencyValMax
551    private val fpLat = params.fpLatencyValMax
552    private val vfLat = params.vfLatencyValMax
553    private val v0Lat = params.v0LatencyValMax
554    private val vlLat = params.vlLatencyValMax
555
556    val intWbBusyTable = OptionWrapper(intCertainLat, UInt((intLat + 1).W))
557    val fpWbBusyTable = OptionWrapper(fpCertainLat, UInt((fpLat + 1).W))
558    val vfWbBusyTable = OptionWrapper(vfCertainLat, UInt((vfLat + 1).W))
559    val v0WbBusyTable = OptionWrapper(v0CertainLat, UInt((v0Lat + 1).W))
560    val vlWbBusyTable = OptionWrapper(vlCertainLat, UInt((vlLat + 1).W))
561  }
562
563  class WbConflictBundle(val params: ExeUnitParams)(implicit p: Parameters) extends XSBundle {
564    private val intCertainLat = params.intLatencyCertain
565    private val fpCertainLat = params.fpLatencyCertain
566    private val vfCertainLat = params.vfLatencyCertain
567    private val v0CertainLat = params.v0LatencyCertain
568    private val vlCertainLat = params.vlLatencyCertain
569
570    val intConflict = OptionWrapper(intCertainLat, Bool())
571    val fpConflict = OptionWrapper(fpCertainLat, Bool())
572    val vfConflict = OptionWrapper(vfCertainLat, Bool())
573    val v0Conflict = OptionWrapper(v0CertainLat, Bool())
574    val vlConflict = OptionWrapper(vlCertainLat, Bool())
575  }
576
577  class ImmInfo extends Bundle {
578    val imm = UInt(32.W)
579    val immType = SelImm()
580  }
581
582  // DataPath --[ExuInput]--> Exu
583  class ExuInput(val params: ExeUnitParams, copyWakeupOut:Boolean = false, copyNum:Int = 0)(implicit p: Parameters) extends XSBundle {
584    val fuType        = FuType()
585    val fuOpType      = FuOpType()
586    val src           = Vec(params.numRegSrc, UInt(params.srcDataBitsMax.W))
587    val imm           = UInt(32.W)
588    val robIdx        = new RobPtr
589    val iqIdx         = UInt(log2Up(MemIQSizeMax).W)// Only used by store yet
590    val isFirstIssue  = Bool()                      // Only used by store yet
591    val pdestCopy  = OptionWrapper(copyWakeupOut, Vec(copyNum, UInt(params.wbPregIdxWidth.W)))
592    val rfWenCopy  = OptionWrapper(copyWakeupOut && params.needIntWen, Vec(copyNum, Bool()))
593    val fpWenCopy  = OptionWrapper(copyWakeupOut && params.needFpWen, Vec(copyNum, Bool()))
594    val vecWenCopy = OptionWrapper(copyWakeupOut && params.needVecWen, Vec(copyNum, Bool()))
595    val v0WenCopy  = OptionWrapper(copyWakeupOut && params.needV0Wen, Vec(copyNum, Bool()))
596    val vlWenCopy  = OptionWrapper(copyWakeupOut && params.needVlWen, Vec(copyNum, Bool()))
597    val loadDependencyCopy = OptionWrapper(copyWakeupOut && params.isIQWakeUpSink, Vec(copyNum, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W))))
598    val pdest         = UInt(params.wbPregIdxWidth.W)
599    val rfWen         = if (params.needIntWen)    Some(Bool())                        else None
600    val fpWen         = if (params.needFpWen)     Some(Bool())                        else None
601    val vecWen        = if (params.needVecWen)    Some(Bool())                        else None
602    val v0Wen         = if (params.needV0Wen)     Some(Bool())                        else None
603    val vlWen         = if (params.needVlWen)     Some(Bool())                        else None
604    val fpu           = if (params.writeFflags)   Some(new FPUCtrlSignals)            else None
605    val vpu           = if (params.needVPUCtrl)   Some(new VPUCtrlSignals)            else None
606    val flushPipe     = if (params.flushPipe)     Some(Bool())                        else None
607    val pc            = if (params.needPc)        Some(UInt(VAddrData().dataWidth.W)) else None
608    val preDecode     = if (params.hasPredecode)  Some(new PreDecodeInfo)             else None
609    val ftqIdx        = if (params.needPc || params.replayInst || params.hasStoreAddrFu || params.hasCSR)
610                                                  Some(new FtqPtr)                    else None
611    val ftqOffset     = if (params.needPc || params.replayInst || params.hasStoreAddrFu || params.hasCSR)
612                                                  Some(UInt(log2Up(PredictWidth).W))  else None
613    val predictInfo   = if (params.needPdInfo)  Some(new Bundle {
614      val target = UInt(VAddrData().dataWidth.W)
615      val taken = Bool()
616    }) else None
617    val loadWaitBit    = OptionWrapper(params.hasLoadExu, Bool())
618    val waitForRobIdx  = OptionWrapper(params.hasLoadExu, new RobPtr) // store set predicted previous store robIdx
619    val storeSetHit    = OptionWrapper(params.hasLoadExu, Bool()) // inst has been allocated an store set
620    val loadWaitStrict = OptionWrapper(params.hasLoadExu, Bool()) // load inst will not be executed until ALL former store addr calcuated
621    val ssid           = OptionWrapper(params.hasLoadExu, UInt(SSIDWidth.W))
622    // only vector load store need
623    val numLsElem      = OptionWrapper(params.hasVecLsFu, NumLsElem())
624
625    val sqIdx = if (params.hasMemAddrFu || params.hasStdFu) Some(new SqPtr) else None
626    val lqIdx = if (params.hasMemAddrFu) Some(new LqPtr) else None
627    val dataSources = Vec(params.numRegSrc, DataSource())
628    val l1ExuOH = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, ExuVec()))
629    val srcTimer = OptionWrapper(params.isIQWakeUpSink, Vec(params.numRegSrc, UInt(3.W)))
630    val loadDependency = OptionWrapper(params.needLoadDependency, Vec(LoadPipelineWidth, UInt(LoadDependencyWidth.W)))
631
632    val perfDebugInfo = new PerfDebugInfo()
633
634    def exuIdx = this.params.exuIdx
635
636    def needCancel(og0CancelOH: UInt, og1CancelOH: UInt) : Bool = {
637      if (params.isIQWakeUpSink) {
638        require(
639          og0CancelOH.getWidth == l1ExuOH.get.head.getWidth,
640          s"cancelVecSize: {og0: ${og0CancelOH.getWidth}, og1: ${og1CancelOH.getWidth}}"
641        )
642        val l1Cancel: Bool = l1ExuOH.get.zip(srcTimer.get).map {
643          case(exuOH: Vec[Bool], srcTimer: UInt) =>
644            (exuOH.asUInt & og0CancelOH).orR && srcTimer === 1.U
645        }.reduce(_ | _)
646        l1Cancel
647      } else {
648        false.B
649      }
650    }
651
652    def fromIssueBundle(source: IssueQueueIssueBundle): Unit = {
653      // src is assigned to rfReadData
654      this.fuType        := source.common.fuType
655      this.fuOpType      := source.common.fuOpType
656      this.imm           := source.common.imm
657      this.robIdx        := source.common.robIdx
658      this.pdest         := source.common.pdest
659      this.isFirstIssue  := source.common.isFirstIssue // Only used by mem debug log
660      this.iqIdx         := source.common.iqIdx        // Only used by mem feedback
661      this.dataSources   := source.common.dataSources
662      this.l1ExuOH       .foreach(_ := source.common.l1ExuOH.get)
663      this.rfWen         .foreach(_ := source.common.rfWen.get)
664      this.fpWen         .foreach(_ := source.common.fpWen.get)
665      this.vecWen        .foreach(_ := source.common.vecWen.get)
666      this.v0Wen         .foreach(_ := source.common.v0Wen.get)
667      this.vlWen         .foreach(_ := source.common.vlWen.get)
668      this.fpu           .foreach(_ := source.common.fpu.get)
669      this.vpu           .foreach(_ := source.common.vpu.get)
670      this.flushPipe     .foreach(_ := source.common.flushPipe.get)
671      this.pc            .foreach(_ := source.common.pc.get)
672      this.preDecode     .foreach(_ := source.common.preDecode.get)
673      this.ftqIdx        .foreach(_ := source.common.ftqIdx.get)
674      this.ftqOffset     .foreach(_ := source.common.ftqOffset.get)
675      this.predictInfo   .foreach(_ := source.common.predictInfo.get)
676      this.loadWaitBit   .foreach(_ := source.common.loadWaitBit.get)
677      this.waitForRobIdx .foreach(_ := source.common.waitForRobIdx.get)
678      this.storeSetHit   .foreach(_ := source.common.storeSetHit.get)
679      this.loadWaitStrict.foreach(_ := source.common.loadWaitStrict.get)
680      this.ssid          .foreach(_ := source.common.ssid.get)
681      this.lqIdx         .foreach(_ := source.common.lqIdx.get)
682      this.sqIdx         .foreach(_ := source.common.sqIdx.get)
683      this.numLsElem     .foreach(_ := source.common.numLsElem.get)
684      this.srcTimer      .foreach(_ := source.common.srcTimer.get)
685      this.loadDependency.foreach(_ := source.common.loadDependency.get.map(_ << 1))
686    }
687  }
688
689  // ExuInput --[FuncUnit]--> ExuOutput
690  class ExuOutput(
691    val params: ExeUnitParams,
692  )(implicit
693    val p: Parameters
694  ) extends Bundle with BundleSource with HasXSParameter {
695    val data         = Vec(params.wbPathNum, UInt(params.destDataBitsMax.W))
696    val pdest        = UInt(params.wbPregIdxWidth.W)
697    val robIdx       = new RobPtr
698    val intWen       = if (params.needIntWen)   Some(Bool())                  else None
699    val fpWen        = if (params.needFpWen)    Some(Bool())                  else None
700    val vecWen       = if (params.needVecWen)   Some(Bool())                  else None
701    val v0Wen        = if (params.needV0Wen)    Some(Bool())                  else None
702    val vlWen        = if (params.needVlWen)    Some(Bool())                  else None
703    val redirect     = if (params.hasRedirect)  Some(ValidIO(new Redirect))   else None
704    val fflags       = if (params.writeFflags)  Some(UInt(5.W))               else None
705    val wflags       = if (params.writeFflags)  Some(Bool())                  else None
706    val vxsat        = if (params.writeVxsat)   Some(Bool())                  else None
707    val exceptionVec = if (params.exceptionOut.nonEmpty) Some(ExceptionVec()) else None
708    val flushPipe    = if (params.flushPipe)    Some(Bool())                  else None
709    val replay       = if (params.replayInst)   Some(Bool())                  else None
710    val lqIdx        = if (params.hasLoadFu)    Some(new LqPtr())             else None
711    val sqIdx        = if (params.hasStoreAddrFu || params.hasStdFu)
712                                                Some(new SqPtr())             else None
713    val trigger      = if (params.trigger)      Some(TriggerAction())           else None
714    // uop info
715    val predecodeInfo = if(params.hasPredecode) Some(new PreDecodeInfo) else None
716    // vldu used only
717    val vls = OptionWrapper(params.hasVLoadFu, new Bundle {
718      val vpu = new VPUCtrlSignals
719      val oldVdPsrc = UInt(PhyRegIdxWidth.W)
720      val vdIdx = UInt(3.W)
721      val vdIdxInField = UInt(3.W)
722      val isIndexed = Bool()
723      val isMasked = Bool()
724    })
725    val debug = new DebugBundle
726    val debugInfo = new PerfDebugInfo
727  }
728
729  // ExuOutput + DynInst --> WriteBackBundle
730  class WriteBackBundle(val params: PregWB, backendParams: BackendParams)(implicit p: Parameters) extends Bundle with BundleSource {
731    val rfWen = Bool()
732    val fpWen = Bool()
733    val vecWen = Bool()
734    val v0Wen = Bool()
735    val vlWen = Bool()
736    val pdest = UInt(params.pregIdxWidth(backendParams).W)
737    val data = UInt(params.dataWidth.W)
738    val robIdx = new RobPtr()(p)
739    val flushPipe = Bool()
740    val replayInst = Bool()
741    val redirect = ValidIO(new Redirect)
742    val fflags = UInt(5.W)
743    val vxsat = Bool()
744    val exceptionVec = ExceptionVec()
745    val debug = new DebugBundle
746    val debugInfo = new PerfDebugInfo
747
748    this.wakeupSource = s"WB(${params.toString})"
749
750    def fromExuOutput(source: ExuOutput, wbType: String) = {
751      val typeMap = Map("int" -> 0, "fp" -> 1, "vf" -> 2, "v0" -> 3, "vl" -> 4)
752      this.rfWen  := source.intWen.getOrElse(false.B)
753      this.fpWen  := source.fpWen.getOrElse(false.B)
754      this.vecWen := source.vecWen.getOrElse(false.B)
755      this.v0Wen  := source.v0Wen.getOrElse(false.B)
756      this.vlWen  := source.vlWen.getOrElse(false.B)
757      this.pdest  := source.pdest
758      this.data   := source.data(source.params.wbIndex(typeMap(wbType)))
759      this.robIdx := source.robIdx
760      this.flushPipe := source.flushPipe.getOrElse(false.B)
761      this.replayInst := source.replay.getOrElse(false.B)
762      this.redirect := source.redirect.getOrElse(0.U.asTypeOf(this.redirect))
763      this.fflags := source.fflags.getOrElse(0.U.asTypeOf(this.fflags))
764      this.vxsat := source.vxsat.getOrElse(0.U.asTypeOf(this.vxsat))
765      this.exceptionVec := source.exceptionVec.getOrElse(0.U.asTypeOf(this.exceptionVec))
766      this.debug := source.debug
767      this.debugInfo := source.debugInfo
768    }
769
770    def asIntRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
771      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(IntData()).addrWidth)))
772      rfWrite.wen := this.rfWen && fire
773      rfWrite.addr := this.pdest
774      rfWrite.data := this.data
775      rfWrite.intWen := this.rfWen
776      rfWrite.fpWen := false.B
777      rfWrite.vecWen := false.B
778      rfWrite.v0Wen := false.B
779      rfWrite.vlWen := false.B
780      rfWrite
781    }
782
783    def asFpRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
784      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(FpData()).addrWidth)))
785      rfWrite.wen := this.fpWen && fire
786      rfWrite.addr := this.pdest
787      rfWrite.data := this.data
788      rfWrite.intWen := false.B
789      rfWrite.fpWen := this.fpWen
790      rfWrite.vecWen := false.B
791      rfWrite.v0Wen := false.B
792      rfWrite.vlWen := false.B
793      rfWrite
794    }
795
796    def asVfRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
797      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(VecData()).addrWidth)))
798      rfWrite.wen := this.vecWen && fire
799      rfWrite.addr := this.pdest
800      rfWrite.data := this.data
801      rfWrite.intWen := false.B
802      rfWrite.fpWen := false.B
803      rfWrite.vecWen := this.vecWen
804      rfWrite.v0Wen := false.B
805      rfWrite.vlWen := false.B
806      rfWrite
807    }
808
809    def asV0RfWriteBundle(fire: Bool): RfWritePortWithConfig = {
810      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(V0Data()).addrWidth)))
811      rfWrite.wen := this.v0Wen && fire
812      rfWrite.addr := this.pdest
813      rfWrite.data := this.data
814      rfWrite.intWen := false.B
815      rfWrite.fpWen := false.B
816      rfWrite.vecWen := false.B
817      rfWrite.v0Wen := this.v0Wen
818      rfWrite.vlWen := false.B
819      rfWrite
820    }
821
822    def asVlRfWriteBundle(fire: Bool): RfWritePortWithConfig = {
823      val rfWrite = Wire(Output(new RfWritePortWithConfig(this.params.dataCfg, backendParams.getPregParams(VlData()).addrWidth)))
824      rfWrite.wen := this.vlWen && fire
825      rfWrite.addr := this.pdest
826      rfWrite.data := this.data
827      rfWrite.intWen := false.B
828      rfWrite.fpWen := false.B
829      rfWrite.vecWen := false.B
830      rfWrite.v0Wen := false.B
831      rfWrite.vlWen := this.vlWen
832      rfWrite
833    }
834  }
835
836  // ExuOutput --> ExuBypassBundle --[DataPath]-->ExuInput
837  //                                /
838  //     [IssueQueue]--> ExuInput --
839  class ExuBypassBundle(
840    val params: ExeUnitParams,
841  )(implicit p: Parameters) extends XSBundle {
842    val intWen = Bool()
843    val data   = UInt(params.destDataBitsMax.W)
844    val pdest  = UInt(params.wbPregIdxWidth.W)
845  }
846
847  class ExceptionInfo(implicit p: Parameters) extends XSBundle {
848    val pc = UInt(VAddrData().dataWidth.W)
849    val instr = UInt(32.W)
850    val commitType = CommitType()
851    val exceptionVec = ExceptionVec()
852    val gpaddr = UInt(GPAddrBits.W)
853    val singleStep = Bool()
854    val crossPageIPFFix = Bool()
855    val isInterrupt = Bool()
856    val isHls = Bool()
857    val vls = Bool()
858    val trigger = TriggerAction()
859  }
860
861  object UopIdx {
862    def apply()(implicit p: Parameters): UInt = UInt(log2Up(p(XSCoreParamsKey).MaxUopSize + 1).W)
863  }
864
865  object FuLatency {
866    def apply(): UInt = UInt(width.W)
867
868    def width = 4 // 0~15 // Todo: assosiate it with FuConfig
869  }
870
871  object ExuOH {
872    def apply(exuNum: Int): UInt = UInt(exuNum.W)
873
874    def apply()(implicit p: Parameters): UInt = UInt(width.W)
875
876    def width(implicit p: Parameters): Int = p(XSCoreParamsKey).backendParams.numExu
877  }
878
879  object ExuVec {
880    def apply(exuNum: Int): Vec[Bool] = Vec(exuNum, Bool())
881
882    def apply()(implicit p: Parameters): Vec[Bool] = Vec(width, Bool())
883
884    def width(implicit p: Parameters): Int = p(XSCoreParamsKey).backendParams.numExu
885  }
886
887  class CancelSignal(implicit p: Parameters) extends XSBundle {
888    val rfWen = Bool()
889    val fpWen = Bool()
890    val vecWen = Bool()
891    val v0Wen = Bool()
892    val vlWen = Bool()
893    val pdest = UInt(PhyRegIdxWidth.W)
894  }
895
896  class MemExuInput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
897    val uop = new DynInst
898    val src = if (isVector) Vec(5, UInt(VLEN.W)) else Vec(3, UInt(XLEN.W))
899    val iqIdx = UInt(log2Up(MemIQSizeMax).W)
900    val isFirstIssue = Bool()
901    val flowNum      = OptionWrapper(isVector, NumLsElem())
902
903    def src_rs1 = src(0)
904    def src_stride = src(1)
905    def src_vs3 = src(2)
906    def src_mask = if (isVector) src(3) else 0.U
907    def src_vl = if (isVector) src(4) else 0.U
908  }
909
910  class MemExuOutput(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
911    val uop = new DynInst
912    val data = if (isVector) UInt(VLEN.W) else UInt(XLEN.W)
913    val mask = if (isVector) Some(UInt(VLEN.W)) else None
914    val vdIdx = if (isVector) Some(UInt(3.W)) else None // TODO: parameterize width
915    val vdIdxInField = if (isVector) Some(UInt(3.W)) else None
916    val debug = new DebugBundle
917
918    def isVls = FuType.isVls(uop.fuType)
919  }
920
921  class MemMicroOpRbExt(implicit p: Parameters) extends XSBundle {
922    val uop = new DynInst
923    val flag = UInt(1.W)
924  }
925
926  object LoadShouldCancel {
927    def apply(loadDependency: Option[Seq[UInt]], ldCancel: Seq[LoadCancelIO]): Bool = {
928      val ld1Cancel = loadDependency.map(_.zip(ldCancel.map(_.ld1Cancel)).map { case (dep, cancel) => cancel && dep(0)}.reduce(_ || _))
929      val ld2Cancel = loadDependency.map(_.zip(ldCancel.map(_.ld2Cancel)).map { case (dep, cancel) => cancel && dep(1)}.reduce(_ || _))
930      ld1Cancel.map(_ || ld2Cancel.get).getOrElse(false.B)
931    }
932  }
933}
934