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