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.rob.RobPtr 22import xiangshan.backend.CtrlToFtqIO 23import xiangshan.backend.decode.{ImmUnion, XDecode} 24import xiangshan.mem.{LqPtr, SqPtr} 25import xiangshan.frontend.PreDecodeInfo 26import xiangshan.frontend.HasBPUParameter 27import xiangshan.frontend.{GlobalHistory, ShiftingGlobalHistory, CircularGlobalHistory, AllFoldedHistories} 28import xiangshan.frontend.RASEntry 29import xiangshan.frontend.BPUCtrl 30import xiangshan.frontend.FtqPtr 31import xiangshan.frontend.CGHPtr 32import xiangshan.frontend.FtqRead 33import xiangshan.frontend.FtqToCtrlIO 34import utils._ 35 36import scala.math.max 37import Chisel.experimental.chiselName 38import chipsalliance.rocketchip.config.Parameters 39import chisel3.util.BitPat.bitPatToUInt 40import xiangshan.backend.fu.PMPEntry 41import xiangshan.frontend.Ftq_Redirect_SRAMEntry 42import xiangshan.frontend.AllFoldedHistories 43 44class ValidUndirectioned[T <: Data](gen: T) extends Bundle { 45 val valid = Bool() 46 val bits = gen.cloneType.asInstanceOf[T] 47 48 override def cloneType = new ValidUndirectioned(gen).asInstanceOf[this.type] 49} 50 51object ValidUndirectioned { 52 def apply[T <: Data](gen: T) = { 53 new ValidUndirectioned[T](gen) 54 } 55} 56 57object RSFeedbackType { 58 val tlbMiss = 0.U(3.W) 59 val mshrFull = 1.U(3.W) 60 val dataInvalid = 2.U(3.W) 61 val bankConflict = 3.U(3.W) 62 val ldVioCheckRedo = 4.U(3.W) 63 64 def apply() = UInt(3.W) 65} 66 67class PredictorAnswer(implicit p: Parameters) extends XSBundle { 68 val hit = if (!env.FPGAPlatform) Bool() else UInt(0.W) 69 val taken = if (!env.FPGAPlatform) Bool() else UInt(0.W) 70 val target = if (!env.FPGAPlatform) UInt(VAddrBits.W) else UInt(0.W) 71} 72 73class CfiUpdateInfo(implicit p: Parameters) extends XSBundle with HasBPUParameter { 74 // from backend 75 val pc = UInt(VAddrBits.W) 76 // frontend -> backend -> frontend 77 val pd = new PreDecodeInfo 78 val rasSp = UInt(log2Up(RasSize).W) 79 val rasEntry = new RASEntry 80 // val hist = new ShiftingGlobalHistory 81 val folded_hist = new AllFoldedHistories(foldedGHistInfos) 82 val histPtr = new CGHPtr 83 val phist = UInt(PathHistoryLength.W) 84 val specCnt = Vec(numBr, UInt(10.W)) 85 val phNewBit = Bool() 86 // need pipeline update 87 val br_hit = Bool() 88 val predTaken = Bool() 89 val target = UInt(VAddrBits.W) 90 val taken = Bool() 91 val isMisPred = Bool() 92 val shift = UInt((log2Ceil(numBr)+1).W) 93 val addIntoHist = Bool() 94 95 def fromFtqRedirectSram(entry: Ftq_Redirect_SRAMEntry) = { 96 // this.hist := entry.ghist 97 this.folded_hist := entry.folded_hist 98 this.histPtr := entry.histPtr 99 this.phist := entry.phist 100 this.phNewBit := entry.phNewBit 101 this.rasSp := entry.rasSp 102 this.rasEntry := entry.rasEntry 103 this.specCnt := entry.specCnt 104 this 105 } 106} 107 108// Dequeue DecodeWidth insts from Ibuffer 109class CtrlFlow(implicit p: Parameters) extends XSBundle { 110 val instr = UInt(32.W) 111 val pc = UInt(VAddrBits.W) 112 val foldpc = UInt(MemPredPCWidth.W) 113 val exceptionVec = ExceptionVec() 114 val trigger = new TriggerCf 115 val intrVec = Vec(12, Bool()) 116 val pd = new PreDecodeInfo 117 val pred_taken = Bool() 118 val crossPageIPFFix = Bool() 119 val storeSetHit = Bool() // inst has been allocated an store set 120 val waitForRobIdx = new RobPtr // store set predicted previous store robIdx 121 // Load wait is needed 122 // load inst will not be executed until former store (predicted by mdp) addr calcuated 123 val loadWaitBit = Bool() 124 // If (loadWaitBit && loadWaitStrict), strict load wait is needed 125 // load inst will not be executed until ALL former store addr calcuated 126 val loadWaitStrict = Bool() 127 val ssid = UInt(SSIDWidth.W) 128 val ftqPtr = new FtqPtr 129 val ftqOffset = UInt(log2Up(PredictWidth).W) 130 // This inst will flush all the pipe when it is the oldest inst in ROB, 131 // then replay from this inst itself 132 val replayInst = Bool() 133} 134 135 136class FPUCtrlSignals(implicit p: Parameters) extends XSBundle { 137 val isAddSub = Bool() // swap23 138 val typeTagIn = UInt(1.W) 139 val typeTagOut = UInt(1.W) 140 val fromInt = Bool() 141 val wflags = Bool() 142 val fpWen = Bool() 143 val fmaCmd = UInt(2.W) 144 val div = Bool() 145 val sqrt = Bool() 146 val fcvt = Bool() 147 val typ = UInt(2.W) 148 val fmt = UInt(2.W) 149 val ren3 = Bool() //TODO: remove SrcType.fp 150 val rm = UInt(3.W) 151} 152 153// Decode DecodeWidth insts at Decode Stage 154class CtrlSignals(implicit p: Parameters) extends XSBundle { 155 val srcType = Vec(3, SrcType()) 156 val lsrc = Vec(3, UInt(5.W)) 157 val ldest = UInt(5.W) 158 val fuType = FuType() 159 val fuOpType = FuOpType() 160 val rfWen = Bool() 161 val fpWen = Bool() 162 val isXSTrap = Bool() 163 val noSpecExec = Bool() // wait forward 164 val blockBackward = Bool() // block backward 165 val flushPipe = Bool() // This inst will flush all the pipe when commit, like exception but can commit 166 val isRVF = Bool() 167 val selImm = SelImm() 168 val imm = UInt(ImmUnion.maxLen.W) 169 val commitType = CommitType() 170 val fpu = new FPUCtrlSignals 171 val isMove = Bool() 172 val singleStep = Bool() 173 // This inst will flush all the pipe when it is the oldest inst in ROB, 174 // then replay from this inst itself 175 val replayInst = Bool() 176 177 private def allSignals = srcType ++ Seq(fuType, fuOpType, rfWen, fpWen, 178 isXSTrap, noSpecExec, blockBackward, flushPipe, isRVF, selImm) 179 180 def decode(inst: UInt, table: Iterable[(BitPat, List[BitPat])]): CtrlSignals = { 181 val decoder = freechips.rocketchip.rocket.DecodeLogic(inst, XDecode.decodeDefault, table) 182 allSignals zip decoder foreach { case (s, d) => s := d } 183 commitType := DontCare 184 this 185 } 186 187 def decode(bit: List[BitPat]): CtrlSignals = { 188 allSignals.zip(bit.map(bitPatToUInt(_))).foreach{ case (s, d) => s := d } 189 this 190 } 191} 192 193class CfCtrl(implicit p: Parameters) extends XSBundle { 194 val cf = new CtrlFlow 195 val ctrl = new CtrlSignals 196} 197 198class PerfDebugInfo(implicit p: Parameters) extends XSBundle { 199 val eliminatedMove = Bool() 200 // val fetchTime = UInt(64.W) 201 val renameTime = UInt(XLEN.W) 202 val dispatchTime = UInt(XLEN.W) 203 val enqRsTime = UInt(XLEN.W) 204 val selectTime = UInt(XLEN.W) 205 val issueTime = UInt(XLEN.W) 206 val writebackTime = UInt(XLEN.W) 207 // val commitTime = UInt(64.W) 208 val runahead_checkpoint_id = UInt(64.W) 209} 210 211// Separate LSQ 212class LSIdx(implicit p: Parameters) extends XSBundle { 213 val lqIdx = new LqPtr 214 val sqIdx = new SqPtr 215} 216 217// CfCtrl -> MicroOp at Rename Stage 218class MicroOp(implicit p: Parameters) extends CfCtrl { 219 val srcState = Vec(3, SrcState()) 220 val psrc = Vec(3, UInt(PhyRegIdxWidth.W)) 221 val pdest = UInt(PhyRegIdxWidth.W) 222 val old_pdest = UInt(PhyRegIdxWidth.W) 223 val robIdx = new RobPtr 224 val lqIdx = new LqPtr 225 val sqIdx = new SqPtr 226 val eliminatedMove = Bool() 227 val debugInfo = new PerfDebugInfo 228 def needRfRPort(index: Int, isFp: Boolean, ignoreState: Boolean = true) : Bool = { 229 isFp match { 230 case false => ctrl.srcType(index) === SrcType.reg && ctrl.lsrc(index) =/= 0.U && (srcState(index) === SrcState.rdy || ignoreState.B) 231 case _ => ctrl.srcType(index) === SrcType.fp && (srcState(index) === SrcState.rdy || ignoreState.B) 232 } 233 } 234 def srcIsReady: Vec[Bool] = { 235 VecInit(ctrl.srcType.zip(srcState).map{ case (t, s) => SrcType.isPcOrImm(t) || s === SrcState.rdy }) 236 } 237 def doWriteIntRf: Bool = ctrl.rfWen && ctrl.ldest =/= 0.U 238 def doWriteFpRf: Bool = ctrl.fpWen 239 def clearExceptions( 240 exceptionBits: Seq[Int] = Seq(), 241 flushPipe: Boolean = false, 242 replayInst: Boolean = false 243 ): MicroOp = { 244 cf.exceptionVec.zipWithIndex.filterNot(x => exceptionBits.contains(x._2)).foreach(_._1 := false.B) 245 if (!flushPipe) { ctrl.flushPipe := false.B } 246 if (!replayInst) { ctrl.replayInst := false.B } 247 this 248 } 249} 250 251class MicroOpRbExt(implicit p: Parameters) extends XSBundle { 252 val uop = new MicroOp 253 val flag = UInt(1.W) 254} 255 256class Redirect(implicit p: Parameters) extends XSBundle { 257 val robIdx = new RobPtr 258 val ftqIdx = new FtqPtr 259 val ftqOffset = UInt(log2Up(PredictWidth).W) 260 val level = RedirectLevel() 261 val interrupt = Bool() 262 val cfiUpdate = new CfiUpdateInfo 263 264 val stFtqIdx = new FtqPtr // for load violation predict 265 val stFtqOffset = UInt(log2Up(PredictWidth).W) 266 267 val debug_runahead_checkpoint_id = UInt(64.W) 268 269 // def isUnconditional() = RedirectLevel.isUnconditional(level) 270 def flushItself() = RedirectLevel.flushItself(level) 271 // def isException() = RedirectLevel.isException(level) 272} 273 274class Dp1ToDp2IO(implicit p: Parameters) extends XSBundle { 275 val intDqToDp2 = Vec(dpParams.IntDqDeqWidth, DecoupledIO(new MicroOp)) 276 val fpDqToDp2 = Vec(dpParams.FpDqDeqWidth, DecoupledIO(new MicroOp)) 277 val lsDqToDp2 = Vec(dpParams.LsDqDeqWidth, DecoupledIO(new MicroOp)) 278} 279 280class ResetPregStateReq(implicit p: Parameters) extends XSBundle { 281 // NOTE: set isInt and isFp both to 'false' when invalid 282 val isInt = Bool() 283 val isFp = Bool() 284 val preg = UInt(PhyRegIdxWidth.W) 285} 286 287class DebugBundle(implicit p: Parameters) extends XSBundle { 288 val isMMIO = Bool() 289 val isPerfCnt = Bool() 290 val paddr = UInt(PAddrBits.W) 291 val vaddr = UInt(VAddrBits.W) 292} 293 294class ExuInput(implicit p: Parameters) extends XSBundle { 295 val uop = new MicroOp 296 val src = Vec(3, UInt(XLEN.W)) 297} 298 299class ExuOutput(implicit p: Parameters) extends XSBundle { 300 val uop = new MicroOp 301 val data = UInt(XLEN.W) 302 val fflags = UInt(5.W) 303 val redirectValid = Bool() 304 val redirect = new Redirect 305 val debug = new DebugBundle 306} 307 308class ExternalInterruptIO(implicit p: Parameters) extends XSBundle { 309 val mtip = Input(Bool()) 310 val msip = Input(Bool()) 311 val meip = Input(Bool()) 312 val seip = Input(Bool()) 313 val debug = Input(Bool()) 314} 315 316class CSRSpecialIO(implicit p: Parameters) extends XSBundle { 317 val exception = Flipped(ValidIO(new MicroOp)) 318 val isInterrupt = Input(Bool()) 319 val memExceptionVAddr = Input(UInt(VAddrBits.W)) 320 val trapTarget = Output(UInt(VAddrBits.W)) 321 val externalInterrupt = new ExternalInterruptIO 322 val interrupt = Output(Bool()) 323} 324 325class ExceptionInfo(implicit p: Parameters) extends XSBundle { 326 val uop = new MicroOp 327 val isInterrupt = Bool() 328} 329 330class RobCommitInfo(implicit p: Parameters) extends XSBundle { 331 val ldest = UInt(5.W) 332 val rfWen = Bool() 333 val fpWen = Bool() 334 val wflags = Bool() 335 val commitType = CommitType() 336 val pdest = UInt(PhyRegIdxWidth.W) 337 val old_pdest = UInt(PhyRegIdxWidth.W) 338 val ftqIdx = new FtqPtr 339 val ftqOffset = UInt(log2Up(PredictWidth).W) 340 341 // these should be optimized for synthesis verilog 342 val pc = UInt(VAddrBits.W) 343} 344 345class RobCommitIO(implicit p: Parameters) extends XSBundle { 346 val isWalk = Output(Bool()) 347 val valid = Vec(CommitWidth, Output(Bool())) 348 val info = Vec(CommitWidth, Output(new RobCommitInfo)) 349 350 def hasWalkInstr = isWalk && valid.asUInt.orR 351 352 def hasCommitInstr = !isWalk && valid.asUInt.orR 353} 354 355class RSFeedback(implicit p: Parameters) extends XSBundle { 356 val rsIdx = UInt(log2Up(IssQueSize).W) 357 val hit = Bool() 358 val flushState = Bool() 359 val sourceType = RSFeedbackType() 360 val dataInvalidSqIdx = new SqPtr 361} 362 363class MemRSFeedbackIO(implicit p: Parameters) extends XSBundle { 364 // Note: you need to update in implicit Parameters p before imp MemRSFeedbackIO 365 // for instance: MemRSFeedbackIO()(updateP) 366 val feedbackSlow = ValidIO(new RSFeedback()) // dcache miss queue full, dtlb miss 367 val feedbackFast = ValidIO(new RSFeedback()) // bank conflict 368 val rsIdx = Input(UInt(log2Up(IssQueSize).W)) 369 val isFirstIssue = Input(Bool()) 370} 371 372class FrontendToCtrlIO(implicit p: Parameters) extends XSBundle { 373 // to backend end 374 val cfVec = Vec(DecodeWidth, DecoupledIO(new CtrlFlow)) 375 val fromFtq = new FtqToCtrlIO 376 // from backend 377 val toFtq = Flipped(new CtrlToFtqIO) 378} 379 380class SatpStruct extends Bundle { 381 val mode = UInt(4.W) 382 val asid = UInt(16.W) 383 val ppn = UInt(44.W) 384} 385 386class TlbCsrBundle(implicit p: Parameters) extends XSBundle { 387 val satp = new Bundle { 388 val changed = Bool() 389 val mode = UInt(4.W) // TODO: may change number to parameter 390 val asid = UInt(16.W) 391 val ppn = UInt(44.W) // just use PAddrBits - 3 - vpnnLen 392 393 def apply(satp_value: UInt): Unit = { 394 require(satp_value.getWidth == XLEN) 395 val sa = satp_value.asTypeOf(new SatpStruct) 396 mode := sa.mode 397 asid := sa.asid 398 ppn := sa.ppn 399 changed := DataChanged(sa.asid) // when ppn is changed, software need do the flush 400 } 401 } 402 val priv = new Bundle { 403 val mxr = Bool() 404 val sum = Bool() 405 val imode = UInt(2.W) 406 val dmode = UInt(2.W) 407 } 408 409 override def toPrintable: Printable = { 410 p"Satp mode:0x${Hexadecimal(satp.mode)} asid:0x${Hexadecimal(satp.asid)} ppn:0x${Hexadecimal(satp.ppn)} " + 411 p"Priv mxr:${priv.mxr} sum:${priv.sum} imode:${priv.imode} dmode:${priv.dmode}" 412 } 413} 414 415class SfenceBundle(implicit p: Parameters) extends XSBundle { 416 val valid = Bool() 417 val bits = new Bundle { 418 val rs1 = Bool() 419 val rs2 = Bool() 420 val addr = UInt(VAddrBits.W) 421 val asid = UInt(AsidLength.W) 422 } 423 424 override def toPrintable: Printable = { 425 p"valid:0x${Hexadecimal(valid)} rs1:${bits.rs1} rs2:${bits.rs2} addr:${Hexadecimal(bits.addr)}" 426 } 427} 428 429// Bundle for load violation predictor updating 430class MemPredUpdateReq(implicit p: Parameters) extends XSBundle { 431 val valid = Bool() 432 433 // wait table update 434 val waddr = UInt(MemPredPCWidth.W) 435 val wdata = Bool() // true.B by default 436 437 // store set update 438 // by default, ldpc/stpc should be xor folded 439 val ldpc = UInt(MemPredPCWidth.W) 440 val stpc = UInt(MemPredPCWidth.W) 441} 442 443class CustomCSRCtrlIO(implicit p: Parameters) extends XSBundle { 444 // Prefetcher 445 val l1plus_pf_enable = Output(Bool()) 446 val l2_pf_enable = Output(Bool()) 447 // Labeled XiangShan 448 val dsid = Output(UInt(8.W)) // TODO: DsidWidth as parameter 449 // Load violation predictor 450 val lvpred_disable = Output(Bool()) 451 val no_spec_load = Output(Bool()) 452 val storeset_wait_store = Output(Bool()) 453 val storeset_no_fast_wakeup = Output(Bool()) 454 val lvpred_timeout = Output(UInt(5.W)) 455 // Branch predictor 456 val bp_ctrl = Output(new BPUCtrl) 457 // Memory Block 458 val sbuffer_threshold = Output(UInt(4.W)) 459 val ldld_vio_check_enable = Output(Bool()) 460 val soft_prefetch_enable = Output(Bool()) 461 val cache_error_enable = Output(Bool()) 462 // Rename 463 val move_elim_enable = Output(Bool()) 464 // Decode 465 val svinval_enable = Output(Bool()) 466 467 // distribute csr write signal 468 val distribute_csr = new DistributedCSRIO() 469 470 val singlestep = Output(Bool()) 471 val frontend_trigger = new FrontendTdataDistributeIO() 472 val mem_trigger = new MemTdataDistributeIO() 473 val trigger_enable = Output(Vec(10, Bool())) 474} 475 476class DistributedCSRIO(implicit p: Parameters) extends XSBundle { 477 // CSR has been writen by csr inst, copies of csr should be updated 478 val w = ValidIO(new Bundle { 479 val addr = Output(UInt(12.W)) 480 val data = Output(UInt(XLEN.W)) 481 }) 482} 483 484class DistributedCSRUpdateReq(implicit p: Parameters) extends XSBundle { 485 // Request csr to be updated 486 // 487 // Note that this request will ONLY update CSR Module it self, 488 // copies of csr will NOT be updated, use it with care! 489 // 490 // For each cycle, no more than 1 DistributedCSRUpdateReq is valid 491 val w = ValidIO(new Bundle { 492 val addr = Output(UInt(12.W)) 493 val data = Output(UInt(XLEN.W)) 494 }) 495 def apply(valid: Bool, addr: UInt, data: UInt, src_description: String) = { 496 when(valid){ 497 w.bits.addr := addr 498 w.bits.data := data 499 } 500 println("Distributed CSR update req registered for " + src_description) 501 } 502} 503 504 505/* TODO how to trigger on next inst? 5061. If hit is determined at frontend, then set a "next instr" trap at dispatch like singlestep 5072. If it is determined at Load(meaning it must be "hit after", then it must not be a jump. So we can let it commit and set 508xret csr to pc + 4/ + 2 5092.5 The problem is to let it commit. This is the real TODO 5103. If it is load and hit before just treat it as regular load exception 511 */ 512 513// This bundle carries trigger hit info along the pipeline 514// Now there are 10 triggers divided into 5 groups of 2 515// These groups are 516// (if if) (store store) (load loid) (if store) (if load) 517 518// Triggers in the same group can chain, meaning that they only 519// fire is both triggers in the group matches (the triggerHitVec bit is asserted) 520// Chaining of trigger No. (2i) and (2i+1) is indicated by triggerChainVec(i) 521// Timing of 0 means trap at current inst, 1 means trap at next inst 522// Chaining and timing and the validness of a trigger is controlled by csr 523// In two chained triggers, if they have different timing, both won't fire 524//class TriggerCf (implicit p: Parameters) extends XSBundle { 525// val triggerHitVec = Vec(10, Bool()) 526// val triggerTiming = Vec(10, Bool()) 527// val triggerChainVec = Vec(5, Bool()) 528//} 529 530class TriggerCf(implicit p: Parameters) extends XSBundle { 531 // frontend 532 val frontendHit = Vec(4, Bool()) 533// val frontendTiming = Vec(4, Bool()) 534// val frontendHitNext = Vec(4, Bool()) 535 536// val frontendException = Bool() 537 // backend 538 val backendEn = Vec(2, Bool()) // Hit(6) && chain(4) , Hit(8) && chain(4) 539 val backendHit = Vec(6, Bool()) 540// val backendTiming = Vec(6, Bool()) // trigger enable fro chain 541 542 // Two situations not allowed: 543 // 1. load data comparison 544 // 2. store chaining with store 545 def getHitFrontend = frontendHit.reduce(_ || _) 546 def getHitBackend = backendHit.reduce(_ || _) 547 def hit = getHitFrontend || getHitBackend 548} 549 550// these 3 bundles help distribute trigger control signals from CSR 551// to Frontend, Load and Store. 552class FrontendTdataDistributeIO(implicit p: Parameters) extends XSBundle { 553 val t = Valid(new Bundle { 554 val addr = Output(UInt(2.W)) 555 val tdata = new MatchTriggerIO 556 }) 557 } 558 559class MemTdataDistributeIO(implicit p: Parameters) extends XSBundle { 560 val t = Valid(new Bundle { 561 val addr = Output(UInt(3.W)) 562 val tdata = new MatchTriggerIO 563 }) 564} 565 566class MatchTriggerIO(implicit p: Parameters) extends XSBundle { 567 val matchType = Output(UInt(2.W)) 568 val select = Output(Bool()) 569 val timing = Output(Bool()) 570 val action = Output(Bool()) 571 val chain = Output(Bool()) 572 val tdata2 = Output(UInt(64.W)) 573} 574