xref: /XiangShan/src/main/scala/xiangshan/Bundle.scala (revision 6a2edd8a8b39d7320fa1ccd85015de85dec8f3f3)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan
18
19import chisel3._
20import chisel3.util._
21import xiangshan.backend.roq.RoqPtr
22import xiangshan.backend.decode.{ImmUnion, XDecode}
23import xiangshan.mem.{LqPtr, SqPtr}
24import xiangshan.frontend.PreDecodeInfoForDebug
25import xiangshan.frontend.PreDecodeInfo
26import xiangshan.frontend.HasBPUParameter
27import xiangshan.frontend.PreDecodeInfo
28import xiangshan.frontend.HasTageParameter
29import xiangshan.frontend.HasSCParameter
30import xiangshan.frontend.HasIFUConst
31import xiangshan.frontend.GlobalHistory
32import xiangshan.frontend.RASEntry
33import xiangshan.frontend.BPUCtrl
34import utils._
35
36import scala.math.max
37import Chisel.experimental.chiselName
38import chipsalliance.rocketchip.config.Parameters
39import xiangshan.backend.ftq.FtqPtr
40
41// Fetch FetchWidth x 32-bit insts from Icache
42class FetchPacket(implicit p: Parameters) extends XSBundle {
43  val instrs = Vec(PredictWidth, UInt(32.W))
44  val mask = UInt(PredictWidth.W)
45  val pdmask = UInt(PredictWidth.W)
46  // val pc = UInt(VAddrBits.W)
47  val pc = Vec(PredictWidth, UInt(VAddrBits.W))
48  val foldpc = Vec(PredictWidth, UInt(MemPredPCWidth.W))
49  val pd = Vec(PredictWidth, new PreDecodeInfo)
50  val ipf = Bool()
51  val acf = Bool()
52  val crossPageIPFFix = Bool()
53  val pred_taken = UInt(PredictWidth.W)
54  val ftqPtr = new FtqPtr
55}
56
57class ValidUndirectioned[T <: Data](gen: T) extends Bundle {
58  val valid = Bool()
59  val bits = gen.cloneType.asInstanceOf[T]
60
61  override def cloneType = new ValidUndirectioned(gen).asInstanceOf[this.type]
62}
63
64object ValidUndirectioned {
65  def apply[T <: Data](gen: T) = {
66    new ValidUndirectioned[T](gen)
67  }
68}
69
70object RSFeedbackType {
71  val tlbMiss = 0.U(2.W)
72  val mshrFull = 1.U(2.W)
73  val dataInvalid = 2.U(2.W)
74
75  def apply() = UInt(2.W)
76}
77
78class SCMeta(val useSC: Boolean)(implicit p: Parameters) extends XSBundle with HasSCParameter {
79  val tageTaken = if (useSC) Bool() else UInt(0.W)
80  val scUsed = if (useSC) Bool() else UInt(0.W)
81  val scPred = if (useSC) Bool() else UInt(0.W)
82  // Suppose ctrbits of all tables are identical
83  val ctrs = if (useSC) Vec(SCNTables, SInt(SCCtrBits.W)) else Vec(SCNTables, SInt(0.W))
84}
85
86class TageMeta(implicit p: Parameters) extends XSBundle with HasTageParameter {
87  val provider = ValidUndirectioned(UInt(log2Ceil(TageNTables).W))
88  val altDiffers = Bool()
89  val providerU = UInt(2.W)
90  val providerCtr = UInt(3.W)
91  val allocate = ValidUndirectioned(UInt(log2Ceil(TageNTables).W))
92  val taken = Bool()
93  val scMeta = new SCMeta(EnableSC)
94}
95
96@chiselName
97class BranchPrediction(implicit p: Parameters) extends XSBundle with HasIFUConst {
98  // val redirect = Bool()
99  val takens = UInt(PredictWidth.W)
100  // val jmpIdx = UInt(log2Up(PredictWidth).W)
101  val brMask = UInt(PredictWidth.W)
102  val jalMask = UInt(PredictWidth.W)
103  val targets = Vec(PredictWidth, UInt(VAddrBits.W))
104
105  // half RVI could only start at the end of a packet
106  val hasHalfRVI = Bool()
107
108  def brNotTakens = (~takens & brMask)
109
110  def sawNotTakenBr = VecInit((0 until PredictWidth).map(i =>
111    (if (i == 0) false.B else ParallelORR(brNotTakens(i - 1, 0)))))
112
113  // if not taken before the half RVI inst
114  def saveHalfRVI = hasHalfRVI && !(ParallelORR(takens(PredictWidth - 2, 0)))
115
116  // could get PredictWidth-1 when only the first bank is valid
117  def jmpIdx = ParallelPriorityEncoder(takens)
118
119  // only used when taken
120  def target = {
121    val generator = new PriorityMuxGenerator[UInt]
122    generator.register(takens.asBools, targets, List.fill(PredictWidth)(None))
123    generator()
124  }
125
126  def taken = ParallelORR(takens)
127
128  def takenOnBr = taken && ParallelPriorityMux(takens, brMask.asBools)
129
130  def hasNotTakenBrs = Mux(taken, ParallelPriorityMux(takens, sawNotTakenBr), ParallelORR(brNotTakens))
131}
132
133class PredictorAnswer(implicit p: Parameters) extends XSBundle {
134  val hit    = if (!env.FPGAPlatform) Bool() else UInt(0.W)
135  val taken  = if (!env.FPGAPlatform) Bool() else UInt(0.W)
136  val target = if (!env.FPGAPlatform) UInt(VAddrBits.W) else UInt(0.W)
137}
138
139class BpuMeta(implicit p: Parameters) extends XSBundle with HasBPUParameter {
140  val btbWriteWay = UInt(log2Up(BtbWays).W)
141  val btbHit = Bool()
142  val bimCtr = UInt(2.W)
143  val tageMeta = new TageMeta
144  // for global history
145
146  val debug_ubtb_cycle = if (EnableBPUTimeRecord) UInt(64.W) else UInt(0.W)
147  val debug_btb_cycle = if (EnableBPUTimeRecord) UInt(64.W) else UInt(0.W)
148  val debug_tage_cycle = if (EnableBPUTimeRecord) UInt(64.W) else UInt(0.W)
149
150  val predictor = if (BPUDebug) UInt(log2Up(4).W) else UInt(0.W) // Mark which component this prediction comes from {ubtb, btb, tage, loopPredictor}
151
152  val ubtbHit = if (BPUDebug) UInt(1.W) else UInt(0.W)
153
154  val ubtbAns = new PredictorAnswer
155  val btbAns = new PredictorAnswer
156  val tageAns = new PredictorAnswer
157  val rasAns = new PredictorAnswer
158  val loopAns = new PredictorAnswer
159
160  // def apply(histPtr: UInt, tageMeta: TageMeta, rasSp: UInt, rasTopCtr: UInt) = {
161  //   this.histPtr := histPtr
162  //   this.tageMeta := tageMeta
163  //   this.rasSp := rasSp
164  //   this.rasTopCtr := rasTopCtr
165  //   this.asUInt
166  // }
167  def size = 0.U.asTypeOf(this).getWidth
168
169  def fromUInt(x: UInt) = x.asTypeOf(this)
170}
171
172class Predecode(implicit p: Parameters) extends XSBundle with HasIFUConst {
173  val hasLastHalfRVI = Bool()
174  val mask = UInt(PredictWidth.W)
175  val lastHalf = Bool()
176  val pd = Vec(PredictWidth, (new PreDecodeInfo))
177}
178
179class CfiUpdateInfo(implicit p: Parameters) extends XSBundle with HasBPUParameter {
180  // from backend
181  val pc = UInt(VAddrBits.W)
182  // frontend -> backend -> frontend
183  val pd = new PreDecodeInfo
184  val rasSp = UInt(log2Up(RasSize).W)
185  val rasEntry = new RASEntry
186  val hist = new GlobalHistory
187  val predHist = new GlobalHistory
188  val specCnt = Vec(PredictWidth, UInt(10.W))
189  // need pipeline update
190  val sawNotTakenBranch = Bool()
191  val predTaken = Bool()
192  val target = UInt(VAddrBits.W)
193  val taken = Bool()
194  val isMisPred = Bool()
195}
196
197// Dequeue DecodeWidth insts from Ibuffer
198class CtrlFlow(implicit p: Parameters) extends XSBundle {
199  val instr = UInt(32.W)
200  val pc = UInt(VAddrBits.W)
201  val foldpc = UInt(MemPredPCWidth.W)
202  val exceptionVec = ExceptionVec()
203  val intrVec = Vec(12, Bool())
204  val pd = new PreDecodeInfo
205  val pred_taken = Bool()
206  val crossPageIPFFix = Bool()
207  val storeSetHit = Bool() // inst has been allocated an store set
208  val loadWaitBit = Bool() // load inst should not be executed until all former store addr calcuated
209  val ssid = UInt(SSIDWidth.W)
210  val ftqPtr = new FtqPtr
211  val ftqOffset = UInt(log2Up(PredictWidth).W)
212  // This inst will flush all the pipe when it is the oldest inst in ROB,
213  // then replay from this inst itself
214  val replayInst = Bool()
215}
216
217class FtqEntry(implicit p: Parameters) extends XSBundle {
218  // fetch pc, pc of each inst could be generated by concatenation
219  val ftqPC = UInt(VAddrBits.W)
220  val lastPacketPC = ValidUndirectioned(UInt(VAddrBits.W))
221  // prediction metas
222  val hist = new GlobalHistory
223  val predHist = new GlobalHistory
224  val rasSp = UInt(log2Ceil(RasSize).W)
225  val rasTop = new RASEntry()
226  val specCnt = Vec(PredictWidth, UInt(10.W))
227  val metas = Vec(PredictWidth, new BpuMeta)
228
229  val cfiIsCall, cfiIsRet, cfiIsJalr, cfiIsRVC = Bool()
230  val rvc_mask = Vec(PredictWidth, Bool())
231  val br_mask = Vec(PredictWidth, Bool())
232  val cfiIndex = ValidUndirectioned(UInt(log2Up(PredictWidth).W))
233  val valids = Vec(PredictWidth, Bool())
234
235  // backend update
236  val mispred = Vec(PredictWidth, Bool())
237  val target = UInt(VAddrBits.W)
238
239  // For perf counters
240  val pd = Vec(PredictWidth, new PreDecodeInfoForDebug(!env.FPGAPlatform))
241
242  def takens = VecInit((0 until PredictWidth).map(i => cfiIndex.valid && cfiIndex.bits === i.U))
243  def hasLastPrev = lastPacketPC.valid
244
245  override def toPrintable: Printable = {
246    p"ftqPC: ${Hexadecimal(ftqPC)} lastPacketPC: ${Hexadecimal(lastPacketPC.bits)} hasLastPrev:$hasLastPrev " +
247      p"rasSp:$rasSp specCnt:$specCnt brmask:${Binary(Cat(br_mask))} rvcmask:${Binary(Cat(rvc_mask))} " +
248      p"valids:${Binary(valids.asUInt())} cfi valid: ${cfiIndex.valid} " +
249      p"cfi index: ${cfiIndex.bits} isCall:$cfiIsCall isRet:$cfiIsRet isJalr:$cfiIsJalr, isRvc:$cfiIsRVC " +
250      p"mispred:${Binary(Cat(mispred))} target:${Hexadecimal(target)}\n"
251  }
252
253}
254
255
256class FPUCtrlSignals(implicit p: Parameters) extends XSBundle {
257  val isAddSub = Bool() // swap23
258  val typeTagIn = UInt(2.W)
259  val typeTagOut = UInt(2.W)
260  val fromInt = Bool()
261  val wflags = Bool()
262  val fpWen = Bool()
263  val fmaCmd = UInt(2.W)
264  val div = Bool()
265  val sqrt = Bool()
266  val fcvt = Bool()
267  val typ = UInt(2.W)
268  val fmt = UInt(2.W)
269  val ren3 = Bool() //TODO: remove SrcType.fp
270  val rm = UInt(3.W)
271}
272
273// Decode DecodeWidth insts at Decode Stage
274class CtrlSignals(implicit p: Parameters) extends XSBundle {
275  val srcType = Vec(3, SrcType())
276  val lsrc = Vec(3, UInt(5.W))
277  val ldest = UInt(5.W)
278  val fuType = FuType()
279  val fuOpType = FuOpType()
280  val rfWen = Bool()
281  val fpWen = Bool()
282  val isXSTrap = Bool()
283  val noSpecExec = Bool() // wait forward
284  val blockBackward = Bool() // block backward
285  val flushPipe = Bool() // This inst will flush all the pipe when commit, like exception but can commit
286  val isRVF = Bool()
287  val selImm = SelImm()
288  val imm = UInt(ImmUnion.maxLen.W)
289  val commitType = CommitType()
290  val fpu = new FPUCtrlSignals
291  val isMove = Bool()
292
293  def decode(inst: UInt, table: Iterable[(BitPat, List[BitPat])]) = {
294    val decoder = freechips.rocketchip.rocket.DecodeLogic(inst, XDecode.decodeDefault, table)
295    val signals =
296      Seq(srcType(0), srcType(1), srcType(2), fuType, fuOpType, rfWen, fpWen,
297        isXSTrap, noSpecExec, blockBackward, flushPipe, isRVF, selImm)
298    signals zip decoder map { case (s, d) => s := d }
299    commitType := DontCare
300    this
301  }
302}
303
304class CfCtrl(implicit p: Parameters) extends XSBundle {
305  val cf = new CtrlFlow
306  val ctrl = new CtrlSignals
307}
308
309class PerfDebugInfo(implicit p: Parameters) extends XSBundle {
310  val src1MoveElim = Bool()
311  val src2MoveElim = Bool()
312  // val fetchTime = UInt(64.W)
313  val renameTime = UInt(64.W)
314  val dispatchTime = UInt(64.W)
315  val issueTime = UInt(64.W)
316  val writebackTime = UInt(64.W)
317  // val commitTime = UInt(64.W)
318}
319
320// Separate LSQ
321class LSIdx(implicit p: Parameters) extends XSBundle {
322  val lqIdx = new LqPtr
323  val sqIdx = new SqPtr
324}
325
326// CfCtrl -> MicroOp at Rename Stage
327class MicroOp(implicit p: Parameters) extends CfCtrl {
328  val srcState = Vec(3, SrcState())
329  val psrc = Vec(3, UInt(PhyRegIdxWidth.W))
330  val pdest = UInt(PhyRegIdxWidth.W)
331  val old_pdest = UInt(PhyRegIdxWidth.W)
332  val roqIdx = new RoqPtr
333  val lqIdx = new LqPtr
334  val sqIdx = new SqPtr
335  val diffTestDebugLrScValid = Bool()
336  val debugInfo = new PerfDebugInfo
337  def needRfRPort(index: Int, rfType: Int, ignoreState: Boolean = true) : Bool = {
338    (index, rfType) match {
339      case (0, 0) => ctrl.srcType(0) === SrcType.reg && ctrl.lsrc(0) =/= 0.U && (srcState(0) === SrcState.rdy || ignoreState.B)
340      case (1, 0) => ctrl.srcType(1) === SrcType.reg && ctrl.lsrc(1) =/= 0.U && (srcState(1) === SrcState.rdy || ignoreState.B)
341      case (0, 1) => ctrl.srcType(0) === SrcType.fp && (srcState(0) === SrcState.rdy || ignoreState.B)
342      case (1, 1) => ctrl.srcType(1) === SrcType.fp && (srcState(1) === SrcState.rdy || ignoreState.B)
343      case (2, 1) => ctrl.srcType(2) === SrcType.fp && (srcState(2) === SrcState.rdy || ignoreState.B)
344      case _ => false.B
345    }
346  }
347  def srcIsReady: Vec[Bool] = {
348    VecInit(ctrl.srcType.zip(srcState).map{ case (t, s) => SrcType.isPcImm(t) || s === SrcState.rdy })
349  }
350  def doWriteIntRf: Bool = ctrl.rfWen && ctrl.ldest =/= 0.U
351  def doWriteFpRf: Bool = ctrl.fpWen
352}
353
354class MicroOpRbExt(implicit p: Parameters) extends XSBundle {
355  val uop = new MicroOp
356  val flag = UInt(1.W)
357}
358
359class Redirect(implicit p: Parameters) extends XSBundle {
360  val roqIdx = new RoqPtr
361  val ftqIdx = new FtqPtr
362  val ftqOffset = UInt(log2Up(PredictWidth).W)
363  val level = RedirectLevel()
364  val interrupt = Bool()
365  val cfiUpdate = new CfiUpdateInfo
366
367  val stFtqIdx = new FtqPtr // for load violation predict
368  val stFtqOffset = UInt(log2Up(PredictWidth).W)
369
370  // def isUnconditional() = RedirectLevel.isUnconditional(level)
371  def flushItself() = RedirectLevel.flushItself(level)
372  // def isException() = RedirectLevel.isException(level)
373}
374
375class Dp1ToDp2IO(implicit p: Parameters) extends XSBundle {
376  val intDqToDp2 = Vec(dpParams.IntDqDeqWidth, DecoupledIO(new MicroOp))
377  val fpDqToDp2 = Vec(dpParams.FpDqDeqWidth, DecoupledIO(new MicroOp))
378  val lsDqToDp2 = Vec(dpParams.LsDqDeqWidth, DecoupledIO(new MicroOp))
379}
380
381class ReplayPregReq(implicit p: Parameters) extends XSBundle {
382  // NOTE: set isInt and isFp both to 'false' when invalid
383  val isInt = Bool()
384  val isFp = Bool()
385  val preg = UInt(PhyRegIdxWidth.W)
386}
387
388class DebugBundle(implicit p: Parameters) extends XSBundle {
389  val isMMIO = Bool()
390  val isPerfCnt = Bool()
391  val paddr = UInt(PAddrBits.W)
392}
393
394class ExuInput(implicit p: Parameters) extends XSBundle {
395  val uop = new MicroOp
396  val src = Vec(3, UInt((XLEN + 1).W))
397}
398
399class ExuOutput(implicit p: Parameters) extends XSBundle {
400  val uop = new MicroOp
401  val data = UInt((XLEN + 1).W)
402  val fflags = UInt(5.W)
403  val redirectValid = Bool()
404  val redirect = new Redirect
405  val debug = new DebugBundle
406}
407
408class ExternalInterruptIO(implicit p: Parameters) extends XSBundle {
409  val mtip = Input(Bool())
410  val msip = Input(Bool())
411  val meip = Input(Bool())
412}
413
414class CSRSpecialIO(implicit p: Parameters) extends XSBundle {
415  val exception = Flipped(ValidIO(new MicroOp))
416  val isInterrupt = Input(Bool())
417  val memExceptionVAddr = Input(UInt(VAddrBits.W))
418  val trapTarget = Output(UInt(VAddrBits.W))
419  val externalInterrupt = new ExternalInterruptIO
420  val interrupt = Output(Bool())
421}
422
423class ExceptionInfo(implicit p: Parameters) extends XSBundle {
424  val uop = new MicroOp
425  val isInterrupt = Bool()
426}
427
428class RoqCommitInfo(implicit p: Parameters) extends XSBundle {
429  val ldest = UInt(5.W)
430  val rfWen = Bool()
431  val fpWen = Bool()
432  val wflags = Bool()
433  val commitType = CommitType()
434  val pdest = UInt(PhyRegIdxWidth.W)
435  val old_pdest = UInt(PhyRegIdxWidth.W)
436  val ftqIdx = new FtqPtr
437  val ftqOffset = UInt(log2Up(PredictWidth).W)
438
439  // these should be optimized for synthesis verilog
440  val pc = UInt(VAddrBits.W)
441}
442
443class RoqCommitIO(implicit p: Parameters) extends XSBundle {
444  val isWalk = Output(Bool())
445  val valid = Vec(CommitWidth, Output(Bool()))
446  val info = Vec(CommitWidth, Output(new RoqCommitInfo))
447
448  def hasWalkInstr = isWalk && valid.asUInt.orR
449
450  def hasCommitInstr = !isWalk && valid.asUInt.orR
451}
452
453class RSFeedback(implicit p: Parameters) extends XSBundle {
454  val rsIdx = UInt(log2Up(IssQueSize).W)
455  val hit = Bool()
456  val flushState = Bool()
457  val sourceType = RSFeedbackType()
458}
459
460class FrontendToBackendIO(implicit p: Parameters) extends XSBundle {
461  // to backend end
462  val cfVec = Vec(DecodeWidth, DecoupledIO(new CtrlFlow))
463  val fetchInfo = DecoupledIO(new FtqEntry)
464  // from backend
465  val redirect_cfiUpdate = Flipped(ValidIO(new Redirect))
466  val commit_cfiUpdate = Flipped(ValidIO(new FtqEntry))
467  val ftqEnqPtr = Input(new FtqPtr)
468  val ftqLeftOne = Input(Bool())
469}
470
471class TlbCsrBundle(implicit p: Parameters) extends XSBundle {
472  val satp = new Bundle {
473    val mode = UInt(4.W) // TODO: may change number to parameter
474    val asid = UInt(16.W)
475    val ppn = UInt(44.W) // just use PAddrBits - 3 - vpnnLen
476  }
477  val priv = new Bundle {
478    val mxr = Bool()
479    val sum = Bool()
480    val imode = UInt(2.W)
481    val dmode = UInt(2.W)
482  }
483
484  override def toPrintable: Printable = {
485    p"Satp mode:0x${Hexadecimal(satp.mode)} asid:0x${Hexadecimal(satp.asid)} ppn:0x${Hexadecimal(satp.ppn)} " +
486      p"Priv mxr:${priv.mxr} sum:${priv.sum} imode:${priv.imode} dmode:${priv.dmode}"
487  }
488}
489
490class SfenceBundle(implicit p: Parameters) extends XSBundle {
491  val valid = Bool()
492  val bits = new Bundle {
493    val rs1 = Bool()
494    val rs2 = Bool()
495    val addr = UInt(VAddrBits.W)
496  }
497
498  override def toPrintable: Printable = {
499    p"valid:0x${Hexadecimal(valid)} rs1:${bits.rs1} rs2:${bits.rs2} addr:${Hexadecimal(bits.addr)}"
500  }
501}
502
503// Bundle for load violation predictor updating
504class MemPredUpdateReq(implicit p: Parameters) extends XSBundle  {
505  val valid = Bool()
506
507  // wait table update
508  val waddr = UInt(MemPredPCWidth.W)
509  val wdata = Bool() // true.B by default
510
511  // store set update
512  // by default, ldpc/stpc should be xor folded
513  val ldpc = UInt(MemPredPCWidth.W)
514  val stpc = UInt(MemPredPCWidth.W)
515}
516
517class CustomCSRCtrlIO(implicit p: Parameters) extends XSBundle {
518  // Prefetcher
519  val l1plus_pf_enable = Output(Bool())
520  val l2_pf_enable = Output(Bool())
521  // Labeled XiangShan
522  val dsid = Output(UInt(8.W)) // TODO: DsidWidth as parameter
523  // Load violation predictor
524  val lvpred_disable = Output(Bool())
525  val no_spec_load = Output(Bool())
526  val waittable_timeout = Output(UInt(5.W))
527  // Branch predictor
528  val bp_ctrl = Output(new BPUCtrl)
529  // Memory Block
530  val sbuffer_threshold = Output(UInt(4.W))
531  // Rename
532  val move_elim_enable = Output(Bool())
533}
534