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} 213 214class FtqEntry(implicit p: Parameters) extends XSBundle { 215 // fetch pc, pc of each inst could be generated by concatenation 216 val ftqPC = UInt(VAddrBits.W) 217 val lastPacketPC = ValidUndirectioned(UInt(VAddrBits.W)) 218 // prediction metas 219 val hist = new GlobalHistory 220 val predHist = new GlobalHistory 221 val rasSp = UInt(log2Ceil(RasSize).W) 222 val rasTop = new RASEntry() 223 val specCnt = Vec(PredictWidth, UInt(10.W)) 224 val metas = Vec(PredictWidth, new BpuMeta) 225 226 val cfiIsCall, cfiIsRet, cfiIsJalr, cfiIsRVC = Bool() 227 val rvc_mask = Vec(PredictWidth, Bool()) 228 val br_mask = Vec(PredictWidth, Bool()) 229 val cfiIndex = ValidUndirectioned(UInt(log2Up(PredictWidth).W)) 230 val valids = Vec(PredictWidth, Bool()) 231 232 // backend update 233 val mispred = Vec(PredictWidth, Bool()) 234 val target = UInt(VAddrBits.W) 235 236 // For perf counters 237 val pd = Vec(PredictWidth, new PreDecodeInfoForDebug(!env.FPGAPlatform)) 238 239 def takens = VecInit((0 until PredictWidth).map(i => cfiIndex.valid && cfiIndex.bits === i.U)) 240 def hasLastPrev = lastPacketPC.valid 241 242 override def toPrintable: Printable = { 243 p"ftqPC: ${Hexadecimal(ftqPC)} lastPacketPC: ${Hexadecimal(lastPacketPC.bits)} hasLastPrev:$hasLastPrev " + 244 p"rasSp:$rasSp specCnt:$specCnt brmask:${Binary(Cat(br_mask))} rvcmask:${Binary(Cat(rvc_mask))} " + 245 p"valids:${Binary(valids.asUInt())} cfi valid: ${cfiIndex.valid} " + 246 p"cfi index: ${cfiIndex.bits} isCall:$cfiIsCall isRet:$cfiIsRet isJalr:$cfiIsJalr, isRvc:$cfiIsRVC " + 247 p"mispred:${Binary(Cat(mispred))} target:${Hexadecimal(target)}\n" 248 } 249 250} 251 252 253class FPUCtrlSignals(implicit p: Parameters) extends XSBundle { 254 val isAddSub = Bool() // swap23 255 val typeTagIn = UInt(1.W) 256 val typeTagOut = UInt(1.W) 257 val fromInt = Bool() 258 val wflags = Bool() 259 val fpWen = Bool() 260 val fmaCmd = UInt(2.W) 261 val div = Bool() 262 val sqrt = Bool() 263 val fcvt = Bool() 264 val typ = UInt(2.W) 265 val fmt = UInt(2.W) 266 val ren3 = Bool() //TODO: remove SrcType.fp 267 val rm = UInt(3.W) 268} 269 270// Decode DecodeWidth insts at Decode Stage 271class CtrlSignals(implicit p: Parameters) extends XSBundle { 272 val srcType = Vec(3, SrcType()) 273 val lsrc = Vec(3, UInt(5.W)) 274 val ldest = UInt(5.W) 275 val fuType = FuType() 276 val fuOpType = FuOpType() 277 val rfWen = Bool() 278 val fpWen = Bool() 279 val isXSTrap = Bool() 280 val noSpecExec = Bool() // wait forward 281 val blockBackward = Bool() // block backward 282 val flushPipe = Bool() // This inst will flush all the pipe when commit, like exception but can commit 283 val isRVF = Bool() 284 val selImm = SelImm() 285 val imm = UInt(ImmUnion.maxLen.W) 286 val commitType = CommitType() 287 val fpu = new FPUCtrlSignals 288 val isMove = Bool() 289 val singleStep = Bool() 290 291 def decode(inst: UInt, table: Iterable[(BitPat, List[BitPat])]) = { 292 val decoder = freechips.rocketchip.rocket.DecodeLogic(inst, XDecode.decodeDefault, table) 293 val signals = 294 Seq(srcType(0), srcType(1), srcType(2), fuType, fuOpType, rfWen, fpWen, 295 isXSTrap, noSpecExec, blockBackward, flushPipe, isRVF, selImm) 296 signals zip decoder map { case (s, d) => s := d } 297 commitType := DontCare 298 this 299 } 300} 301 302class CfCtrl(implicit p: Parameters) extends XSBundle { 303 val cf = new CtrlFlow 304 val ctrl = new CtrlSignals 305} 306 307class PerfDebugInfo(implicit p: Parameters) extends XSBundle { 308 val eliminatedMove = Bool() 309 // val fetchTime = UInt(64.W) 310 val renameTime = UInt(64.W) 311 val dispatchTime = UInt(64.W) 312 val issueTime = UInt(64.W) 313 val writebackTime = UInt(64.W) 314 // val commitTime = UInt(64.W) 315} 316 317// Separate LSQ 318class LSIdx(implicit p: Parameters) extends XSBundle { 319 val lqIdx = new LqPtr 320 val sqIdx = new SqPtr 321} 322 323// CfCtrl -> MicroOp at Rename Stage 324class MicroOp(implicit p: Parameters) extends CfCtrl { 325 val srcState = Vec(3, SrcState()) 326 val psrc = Vec(3, UInt(PhyRegIdxWidth.W)) 327 val pdest = UInt(PhyRegIdxWidth.W) 328 val old_pdest = UInt(PhyRegIdxWidth.W) 329 val roqIdx = new RoqPtr 330 val lqIdx = new LqPtr 331 val sqIdx = new SqPtr 332 val diffTestDebugLrScValid = Bool() 333 val eliminatedMove = Bool() 334 val debugInfo = new PerfDebugInfo 335 def needRfRPort(index: Int, rfType: Int, ignoreState: Boolean = true) : Bool = { 336 (index, rfType) match { 337 case (0, 0) => ctrl.srcType(0) === SrcType.reg && ctrl.lsrc(0) =/= 0.U && (srcState(0) === SrcState.rdy || ignoreState.B) 338 case (1, 0) => ctrl.srcType(1) === SrcType.reg && ctrl.lsrc(1) =/= 0.U && (srcState(1) === SrcState.rdy || ignoreState.B) 339 case (0, 1) => ctrl.srcType(0) === SrcType.fp && (srcState(0) === SrcState.rdy || ignoreState.B) 340 case (1, 1) => ctrl.srcType(1) === SrcType.fp && (srcState(1) === SrcState.rdy || ignoreState.B) 341 case (2, 1) => ctrl.srcType(2) === SrcType.fp && (srcState(2) === SrcState.rdy || ignoreState.B) 342 case _ => false.B 343 } 344 } 345 def srcIsReady: Vec[Bool] = { 346 VecInit(ctrl.srcType.zip(srcState).map{ case (t, s) => SrcType.isPcImm(t) || s === SrcState.rdy }) 347 } 348 def doWriteIntRf: Bool = ctrl.rfWen && ctrl.ldest =/= 0.U 349 def doWriteFpRf: Bool = ctrl.fpWen 350} 351 352class MicroOpRbExt(implicit p: Parameters) extends XSBundle { 353 val uop = new MicroOp 354 val flag = UInt(1.W) 355} 356 357class Redirect(implicit p: Parameters) extends XSBundle { 358 val roqIdx = new RoqPtr 359 val ftqIdx = new FtqPtr 360 val ftqOffset = UInt(log2Up(PredictWidth).W) 361 val level = RedirectLevel() 362 val interrupt = Bool() 363 val cfiUpdate = new CfiUpdateInfo 364 365 val stFtqIdx = new FtqPtr // for load violation predict 366 val stFtqOffset = UInt(log2Up(PredictWidth).W) 367 368 // def isUnconditional() = RedirectLevel.isUnconditional(level) 369 def flushItself() = RedirectLevel.flushItself(level) 370 // def isException() = RedirectLevel.isException(level) 371} 372 373class Dp1ToDp2IO(implicit p: Parameters) extends XSBundle { 374 val intDqToDp2 = Vec(dpParams.IntDqDeqWidth, DecoupledIO(new MicroOp)) 375 val fpDqToDp2 = Vec(dpParams.FpDqDeqWidth, DecoupledIO(new MicroOp)) 376 val lsDqToDp2 = Vec(dpParams.LsDqDeqWidth, DecoupledIO(new MicroOp)) 377} 378 379class ReplayPregReq(implicit p: Parameters) extends XSBundle { 380 // NOTE: set isInt and isFp both to 'false' when invalid 381 val isInt = Bool() 382 val isFp = Bool() 383 val preg = UInt(PhyRegIdxWidth.W) 384} 385 386class DebugBundle(implicit p: Parameters) extends XSBundle { 387 val isMMIO = Bool() 388 val isPerfCnt = Bool() 389 val paddr = UInt(PAddrBits.W) 390} 391 392class ExuInput(implicit p: Parameters) extends XSBundle { 393 val uop = new MicroOp 394 val src = Vec(3, UInt(XLEN.W)) 395} 396 397class ExuOutput(implicit p: Parameters) extends XSBundle { 398 val uop = new MicroOp 399 val data = UInt(XLEN.W) 400 val fflags = UInt(5.W) 401 val redirectValid = Bool() 402 val redirect = new Redirect 403 val debug = new DebugBundle 404} 405 406class ExternalInterruptIO(implicit p: Parameters) extends XSBundle { 407 val mtip = Input(Bool()) 408 val msip = Input(Bool()) 409 val meip = Input(Bool()) 410 val debug = Input(Bool()) 411} 412 413class CSRSpecialIO(implicit p: Parameters) extends XSBundle { 414 val exception = Flipped(ValidIO(new MicroOp)) 415 val isInterrupt = Input(Bool()) 416 val memExceptionVAddr = Input(UInt(VAddrBits.W)) 417 val trapTarget = Output(UInt(VAddrBits.W)) 418 val externalInterrupt = new ExternalInterruptIO 419 val interrupt = Output(Bool()) 420} 421 422class ExceptionInfo(implicit p: Parameters) extends XSBundle { 423 val uop = new MicroOp 424 val isInterrupt = Bool() 425} 426 427class RoqCommitInfo(implicit p: Parameters) extends XSBundle { 428 val ldest = UInt(5.W) 429 val rfWen = Bool() 430 val fpWen = Bool() 431 val wflags = Bool() 432 val commitType = CommitType() 433 val eliminatedMove = Bool() 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