1/*************************************************************************************** 2* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC) 3* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences 4* Copyright (c) 2020-2021 Peng Cheng Laboratory 5* 6* XiangShan is licensed under Mulan PSL v2. 7* You can use this software according to the terms and conditions of the Mulan PSL v2. 8* You may obtain a copy of Mulan PSL v2 at: 9* http://license.coscl.org.cn/MulanPSL2 10* 11* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14* 15* See the Mulan PSL v2 for more details. 16***************************************************************************************/ 17package xiangshan.frontend 18 19import org.chipsalliance.cde.config.Parameters 20import chisel3._ 21import chisel3.util._ 22import xiangshan._ 23import xiangshan.frontend.icache._ 24import utils._ 25import utility._ 26import xiangshan.cache.mmu.TlbResp 27import xiangshan.backend.fu.PMPRespBundle 28 29import scala.math._ 30import java.util.ResourceBundle.Control 31 32class FrontendTopDownBundle(implicit p: Parameters) extends XSBundle { 33 val reasons = Vec(TopDownCounters.NumStallReasons.id, Bool()) 34 val stallWidth = UInt(log2Ceil(PredictWidth).W) 35} 36 37class FetchRequestBundle(implicit p: Parameters) extends XSBundle with HasICacheParameters { 38 39 //fast path: Timing critical 40 val startAddr = UInt(VAddrBits.W) 41 val nextlineStart = UInt(VAddrBits.W) 42 val nextStartAddr = UInt(VAddrBits.W) 43 //slow path 44 val ftqIdx = new FtqPtr 45 val ftqOffset = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)) 46 47 val topdown_info = new FrontendTopDownBundle 48 49 def crossCacheline = startAddr(blockOffBits - 1) === 1.U 50 51 def fromFtqPcBundle(b: Ftq_RF_Components) = { 52 this.startAddr := b.startAddr 53 this.nextlineStart := b.nextLineAddr 54 when (b.fallThruError) { 55 val nextBlockHigherTemp = Mux(startAddr(log2Ceil(PredictWidth)+instOffsetBits), b.nextLineAddr, b.startAddr) 56 val nextBlockHigher = nextBlockHigherTemp(VAddrBits-1, log2Ceil(PredictWidth)+instOffsetBits+1) 57 this.nextStartAddr := 58 Cat(nextBlockHigher, 59 startAddr(log2Ceil(PredictWidth)+instOffsetBits) ^ 1.U(1.W), 60 startAddr(log2Ceil(PredictWidth)+instOffsetBits-1, instOffsetBits), 61 0.U(instOffsetBits.W) 62 ) 63 } 64 this 65 } 66 override def toPrintable: Printable = { 67 p"[start] ${Hexadecimal(startAddr)} [next] ${Hexadecimal(nextlineStart)}" + 68 p"[tgt] ${Hexadecimal(nextStartAddr)} [ftqIdx] $ftqIdx [jmp] v:${ftqOffset.valid}" + 69 p" offset: ${ftqOffset.bits}\n" 70 } 71} 72 73class FtqICacheInfo(implicit p: Parameters)extends XSBundle with HasICacheParameters{ 74 val startAddr = UInt(VAddrBits.W) 75 val nextlineStart = UInt(VAddrBits.W) 76 val ftqIdx = new FtqPtr 77 def crossCacheline = startAddr(blockOffBits - 1) === 1.U 78 def fromFtqPcBundle(b: Ftq_RF_Components) = { 79 this.startAddr := b.startAddr 80 this.nextlineStart := b.nextLineAddr 81 this 82 } 83} 84 85class IFUICacheIO(implicit p: Parameters)extends XSBundle with HasICacheParameters{ 86 val icacheReady = Output(Bool()) 87 val resp = Vec(PortNumber, ValidIO(new ICacheMainPipeResp)) 88 val topdownIcacheMiss = Output(Bool()) 89 val topdownItlbMiss = Output(Bool()) 90} 91 92class FtqToICacheRequestBundle(implicit p: Parameters)extends XSBundle with HasICacheParameters{ 93 val pcMemRead = Vec(5, new FtqICacheInfo) 94 val readValid = Vec(5, Bool()) 95} 96 97 98class PredecodeWritebackBundle(implicit p:Parameters) extends XSBundle { 99 val pc = Vec(PredictWidth, UInt(VAddrBits.W)) 100 val pd = Vec(PredictWidth, new PreDecodeInfo) // TODO: redefine Predecode 101 val ftqIdx = new FtqPtr 102 val ftqOffset = UInt(log2Ceil(PredictWidth).W) 103 val misOffset = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)) 104 val cfiOffset = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)) 105 val target = UInt(VAddrBits.W) 106 val jalTarget = UInt(VAddrBits.W) 107 val instrRange = Vec(PredictWidth, Bool()) 108} 109 110class mmioCommitRead(implicit p: Parameters) extends XSBundle { 111 val mmioFtqPtr = Output(new FtqPtr) 112 val mmioLastCommit = Input(Bool()) 113} 114 115object ExceptionType { 116 def none : UInt = "b00".U 117 def pf : UInt = "b01".U // instruction page fault 118 def gpf : UInt = "b10".U // instruction guest page fault 119 def af : UInt = "b11".U // instruction access fault 120 def width : Int = 2 121 122 // raise pf/gpf/af according to itlb response 123 def fromTlbResp(resp: TlbResp, useDup: Int = 0): UInt = { 124 require(useDup >= 0 && useDup < resp.excp.length) 125 assert( 126 PopCount(VecInit(resp.excp(useDup).af.instr, resp.excp(useDup).pf.instr, resp.excp(useDup).gpf.instr)) <= 1.U, 127 "tlb resp has more than 1 exception, af=%d, pf=%d, gpf=%d", 128 resp.excp(useDup).af.instr, resp.excp(useDup).pf.instr, resp.excp(useDup).gpf.instr 129 ) 130 // itlb is guaranteed to respond at most one exception, so we don't worry about priority here. 131 MuxCase(none, Seq( 132 resp.excp(useDup).pf.instr -> pf, 133 resp.excp(useDup).gpf.instr -> gpf, 134 resp.excp(useDup).af.instr -> af 135 )) 136 } 137 138 // raise af if pmp check failed 139 def fromPMPResp(resp: PMPRespBundle): UInt = { 140 Mux(resp.instr, af, none) 141 } 142 143 // raise af if meta/data array ecc check failed or l2 cache respond with tilelink corrupt 144 /* FIXME: RISC-V Machine ISA v1.13 (draft) introduced a "hardware error" exception, described as: 145 * > A Hardware Error exception is a synchronous exception triggered when corrupted or 146 * > uncorrectable data is accessed explicitly or implicitly by an instruction. In this context, 147 * > "data" encompasses all types of information used within a RISC-V hart. Upon a hardware 148 * > error exception, the xepc register is set to the address of the instruction that attempted to 149 * > access corrupted data, while the xtval register is set either to 0 or to the virtual address 150 * > of an instruction fetch, load, or store that attempted to access corrupted data. The priority 151 * > of Hardware Error exception is implementation-defined, but any given occurrence is 152 * > generally expected to be recognized at the point in the overall priority order at which the 153 * > hardware error is discovered. 154 * Maybe it's better to raise hardware error instead of access fault when ECC check failed. 155 * But it's draft and XiangShan backend does not implement this exception code yet, so we still raise af here. 156 */ 157 def fromECC(enable: Bool, corrupt: Bool): UInt = { 158 Mux(enable && corrupt, af, none) 159 } 160 161 /**Generates exception mux tree 162 * 163 * Exceptions that are further to the left in the parameter list have higher priority 164 * @example 165 * {{{ 166 * val itlb_exception = ExceptionType.fromTlbResp(io.itlb.resp.bits) 167 * // so as pmp_exception, meta_corrupt 168 * // ExceptionType.merge(itlb_exception, pmp_exception, meta_corrupt) is equivalent to: 169 * Mux( 170 * itlb_exception =/= none, 171 * itlb_exception, 172 * Mux(pmp_exception =/= none, pmp_exception, meta_corrupt) 173 * ) 174 * }}} 175 */ 176 def merge(exceptions: UInt*): UInt = { 177// // recursively generate mux tree 178// if (exceptions.length == 1) { 179// require(exceptions.head.getWidth == width) 180// exceptions.head 181// } else { 182// Mux(exceptions.head =/= none, exceptions.head, merge(exceptions.tail: _*)) 183// } 184 // use MuxCase with default 185 exceptions.foreach(e => require(e.getWidth == width)) 186 val mapping = exceptions.init.map(e => (e =/= none) -> e) 187 val default = exceptions.last 188 MuxCase(default, mapping) 189 } 190 191 /**Generates exception mux tree for multi-port exception vectors 192 * 193 * Exceptions that are further to the left in the parameter list have higher priority 194 * @example 195 * {{{ 196 * val itlb_exception = VecInit((0 until PortNumber).map(i => ExceptionType.fromTlbResp(io.itlb(i).resp.bits))) 197 * // so as pmp_exception, meta_corrupt 198 * // ExceptionType.merge(itlb_exception, pmp_exception, meta_corrupt) is equivalent to: 199 * VecInit((0 until PortNumber).map(i => Mux( 200 * itlb_exception(i) =/= none, 201 * itlb_exception(i), 202 * Mux(pmp_exception(i) =/= none, pmp_exception(i), meta_corrupt(i)) 203 * )) 204 * }}} 205 */ 206 def merge(exceptionVecs: Vec[UInt]*): Vec[UInt] = { 207// // recursively generate mux tree 208// if (exceptionVecs.length == 1) { 209// exceptionVecs.head.foreach(e => require(e.getWidth == width)) 210// exceptionVecs.head 211// } else { 212// require(exceptionVecs.head.length == exceptionVecs.last.length) 213// VecInit((exceptionVecs.head zip merge(exceptionVecs.tail: _*)).map{ case (high, low) => 214// Mux(high =/= none, high, low) 215// }) 216// } 217 // merge port-by-port 218 val length = exceptionVecs.head.length 219 exceptionVecs.tail.foreach(vec => require(vec.length == length)) 220 VecInit((0 until length).map{ i => 221 merge(exceptionVecs.map(_(i)): _*) 222 }) 223 } 224} 225 226class FetchToIBuffer(implicit p: Parameters) extends XSBundle { 227 val instrs = Vec(PredictWidth, UInt(32.W)) 228 val valid = UInt(PredictWidth.W) 229 val enqEnable = UInt(PredictWidth.W) 230 val pd = Vec(PredictWidth, new PreDecodeInfo) 231 val pc = Vec(PredictWidth, UInt(VAddrBits.W)) 232 val foldpc = Vec(PredictWidth, UInt(MemPredPCWidth.W)) 233 val ftqPtr = new FtqPtr 234 val ftqOffset = Vec(PredictWidth, ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))) 235 val exceptionType = Vec(PredictWidth, UInt(ExceptionType.width.W)) 236 val crossPageIPFFix = Vec(PredictWidth, Bool()) 237 val illegalInstr = Vec(PredictWidth, Bool()) 238 val triggered = Vec(PredictWidth, TriggerAction()) 239 val topdown_info = new FrontendTopDownBundle 240} 241 242// class BitWiseUInt(val width: Int, val init: UInt) extends Module { 243// val io = IO(new Bundle { 244// val set 245// }) 246// } 247// Move from BPU 248abstract class GlobalHistory(implicit p: Parameters) extends XSBundle with HasBPUConst { 249 def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): GlobalHistory 250} 251 252class ShiftingGlobalHistory(implicit p: Parameters) extends GlobalHistory { 253 val predHist = UInt(HistoryLength.W) 254 255 def update(shift: UInt, taken: Bool, hist: UInt = this.predHist): ShiftingGlobalHistory = { 256 val g = Wire(new ShiftingGlobalHistory) 257 g.predHist := (hist << shift) | taken 258 g 259 } 260 261 def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): ShiftingGlobalHistory = { 262 require(br_valids.length == numBr) 263 require(real_taken_mask.length == numBr) 264 val last_valid_idx = PriorityMux( 265 br_valids.reverse :+ true.B, 266 (numBr to 0 by -1).map(_.U(log2Ceil(numBr+1).W)) 267 ) 268 val first_taken_idx = PriorityEncoder(false.B +: real_taken_mask) 269 val smaller = Mux(last_valid_idx < first_taken_idx, 270 last_valid_idx, 271 first_taken_idx 272 ) 273 val shift = smaller 274 val taken = real_taken_mask.reduce(_||_) 275 update(shift, taken, this.predHist) 276 } 277 278 // static read 279 def read(n: Int): Bool = predHist.asBools(n) 280 281 final def === (that: ShiftingGlobalHistory): Bool = { 282 predHist === that.predHist 283 } 284 285 final def =/= (that: ShiftingGlobalHistory): Bool = !(this === that) 286} 287 288// circular global history pointer 289class CGHPtr(implicit p: Parameters) extends CircularQueuePtr[CGHPtr]( 290 p => p(XSCoreParamsKey).HistoryLength 291){ 292} 293 294object CGHPtr { 295 def apply(f: Bool, v: UInt)(implicit p: Parameters): CGHPtr = { 296 val ptr = Wire(new CGHPtr) 297 ptr.flag := f 298 ptr.value := v 299 ptr 300 } 301 def inverse(ptr: CGHPtr)(implicit p: Parameters): CGHPtr = { 302 apply(!ptr.flag, ptr.value) 303 } 304} 305 306class CircularGlobalHistory(implicit p: Parameters) extends GlobalHistory { 307 val buffer = Vec(HistoryLength, Bool()) 308 type HistPtr = UInt 309 def update(br_valids: Vec[Bool], real_taken_mask: Vec[Bool]): CircularGlobalHistory = { 310 this 311 } 312} 313 314class FoldedHistory(val len: Int, val compLen: Int, val max_update_num: Int)(implicit p: Parameters) 315 extends XSBundle with HasBPUConst { 316 require(compLen >= 1) 317 require(len > 0) 318 // require(folded_len <= len) 319 require(compLen >= max_update_num) 320 val folded_hist = UInt(compLen.W) 321 322 def need_oldest_bits = len > compLen 323 def info = (len, compLen) 324 def oldest_bit_to_get_from_ghr = (0 until max_update_num).map(len - _ - 1) 325 def oldest_bit_pos_in_folded = oldest_bit_to_get_from_ghr map (_ % compLen) 326 def oldest_bit_wrap_around = oldest_bit_to_get_from_ghr map (_ / compLen > 0) 327 def oldest_bit_start = oldest_bit_pos_in_folded.head 328 329 def get_oldest_bits_from_ghr(ghr: Vec[Bool], histPtr: CGHPtr) = { 330 // TODO: wrap inc for histPtr value 331 oldest_bit_to_get_from_ghr.map(i => ghr((histPtr + (i+1).U).value)) 332 } 333 334 def circular_shift_left(src: UInt, shamt: Int) = { 335 val srcLen = src.getWidth 336 val src_doubled = Cat(src, src) 337 val shifted = src_doubled(srcLen*2-1-shamt, srcLen-shamt) 338 shifted 339 } 340 341 // slow path, read bits from ghr 342 def update(ghr: Vec[Bool], histPtr: CGHPtr, num: Int, taken: Bool): FoldedHistory = { 343 val oldest_bits = VecInit(get_oldest_bits_from_ghr(ghr, histPtr)) 344 update(oldest_bits, num, taken) 345 } 346 347 348 // fast path, use pre-read oldest bits 349 def update(ob: Vec[Bool], num: Int, taken: Bool): FoldedHistory = { 350 // do xors for several bitsets at specified bits 351 def bitsets_xor(len: Int, bitsets: Seq[Seq[Tuple2[Int, Bool]]]) = { 352 val res = Wire(Vec(len, Bool())) 353 // println(f"num bitsets: ${bitsets.length}") 354 // println(f"bitsets $bitsets") 355 val resArr = Array.fill(len)(List[Bool]()) 356 for (bs <- bitsets) { 357 for ((n, b) <- bs) { 358 resArr(n) = b :: resArr(n) 359 } 360 } 361 // println(f"${resArr.mkString}") 362 // println(f"histLen: ${this.len}, foldedLen: $folded_len") 363 for (i <- 0 until len) { 364 // println(f"bit[$i], ${resArr(i).mkString}") 365 if (resArr(i).length == 0) { 366 println(f"[error] bits $i is not assigned in folded hist update logic! histlen:${this.len}, compLen:$compLen") 367 } 368 res(i) := resArr(i).foldLeft(false.B)(_^_) 369 } 370 res.asUInt 371 } 372 373 val new_folded_hist = if (need_oldest_bits) { 374 val oldest_bits = ob 375 require(oldest_bits.length == max_update_num) 376 // mask off bits that do not update 377 val oldest_bits_masked = oldest_bits.zipWithIndex.map{ 378 case (ob, i) => ob && (i < num).B 379 } 380 // if a bit does not wrap around, it should not be xored when it exits 381 val oldest_bits_set = (0 until max_update_num).filter(oldest_bit_wrap_around).map(i => (oldest_bit_pos_in_folded(i), oldest_bits_masked(i))) 382 383 // println(f"old bits pos ${oldest_bits_set.map(_._1)}") 384 385 // only the last bit could be 1, as we have at most one taken branch at a time 386 val newest_bits_masked = VecInit((0 until max_update_num).map(i => taken && ((i+1) == num).B)).asUInt 387 // if a bit does not wrap around, newest bits should not be xored onto it either 388 val newest_bits_set = (0 until max_update_num).map(i => (compLen-1-i, newest_bits_masked(i))) 389 390 // println(f"new bits set ${newest_bits_set.map(_._1)}") 391 // 392 val original_bits_masked = VecInit(folded_hist.asBools.zipWithIndex.map{ 393 case (fb, i) => fb && !(num >= (len-i)).B 394 }) 395 val original_bits_set = (0 until compLen).map(i => (i, original_bits_masked(i))) 396 397 // do xor then shift 398 val xored = bitsets_xor(compLen, Seq(original_bits_set, oldest_bits_set, newest_bits_set)) 399 circular_shift_left(xored, num) 400 } else { 401 // histLen too short to wrap around 402 ((folded_hist << num) | taken)(compLen-1,0) 403 } 404 405 val fh = WireInit(this) 406 fh.folded_hist := new_folded_hist 407 fh 408 } 409} 410 411class AheadFoldedHistoryOldestBits(val len: Int, val max_update_num: Int)(implicit p: Parameters) extends XSBundle { 412 val bits = Vec(max_update_num*2, Bool()) 413 // def info = (len, compLen) 414 def getRealOb(brNumOH: UInt): Vec[Bool] = { 415 val ob = Wire(Vec(max_update_num, Bool())) 416 for (i <- 0 until max_update_num) { 417 ob(i) := Mux1H(brNumOH, bits.drop(i).take(numBr+1)) 418 } 419 ob 420 } 421} 422 423class AllAheadFoldedHistoryOldestBits(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle with HasBPUConst { 424 val afhob = MixedVec(gen.filter(t => t._1 > t._2).map{_._1} 425 .toSet.toList.map(l => new AheadFoldedHistoryOldestBits(l, numBr))) // remove duplicates 426 require(gen.toSet.toList.equals(gen)) 427 def getObWithInfo(info: Tuple2[Int, Int]) = { 428 val selected = afhob.filter(_.len == info._1) 429 require(selected.length == 1) 430 selected(0) 431 } 432 def read(ghv: Vec[Bool], ptr: CGHPtr) = { 433 val hisLens = afhob.map(_.len) 434 val bitsToRead = hisLens.flatMap(l => (0 until numBr*2).map(i => l-i-1)).toSet // remove duplicates 435 val bitsWithInfo = bitsToRead.map(pos => (pos, ghv((ptr+(pos+1).U).value))) 436 for (ob <- afhob) { 437 for (i <- 0 until numBr*2) { 438 val pos = ob.len - i - 1 439 val bit_found = bitsWithInfo.filter(_._1 == pos).toList 440 require(bit_found.length == 1) 441 ob.bits(i) := bit_found(0)._2 442 } 443 } 444 } 445} 446 447class AllFoldedHistories(val gen: Seq[Tuple2[Int, Int]])(implicit p: Parameters) extends XSBundle with HasBPUConst { 448 val hist = MixedVec(gen.map{case (l, cl) => new FoldedHistory(l, cl, numBr)}) 449 // println(gen.mkString) 450 require(gen.toSet.toList.equals(gen)) 451 def getHistWithInfo(info: Tuple2[Int, Int]) = { 452 val selected = hist.filter(_.info.equals(info)) 453 require(selected.length == 1) 454 selected(0) 455 } 456 def autoConnectFrom(that: AllFoldedHistories) = { 457 require(this.hist.length <= that.hist.length) 458 for (h <- this.hist) { 459 h := that.getHistWithInfo(h.info) 460 } 461 } 462 def update(ghv: Vec[Bool], ptr: CGHPtr, shift: Int, taken: Bool): AllFoldedHistories = { 463 val res = WireInit(this) 464 for (i <- 0 until this.hist.length) { 465 res.hist(i) := this.hist(i).update(ghv, ptr, shift, taken) 466 } 467 res 468 } 469 def update(afhob: AllAheadFoldedHistoryOldestBits, lastBrNumOH: UInt, shift: Int, taken: Bool): AllFoldedHistories = { 470 val res = WireInit(this) 471 for (i <- 0 until this.hist.length) { 472 val fh = this.hist(i) 473 if (fh.need_oldest_bits) { 474 val info = fh.info 475 val selectedAfhob = afhob.getObWithInfo(info) 476 val ob = selectedAfhob.getRealOb(lastBrNumOH) 477 res.hist(i) := this.hist(i).update(ob, shift, taken) 478 } else { 479 val dumb = Wire(Vec(numBr, Bool())) // not needed 480 dumb := DontCare 481 res.hist(i) := this.hist(i).update(dumb, shift, taken) 482 } 483 } 484 res 485 } 486 487 def display(cond: Bool) = { 488 for (h <- hist) { 489 XSDebug(cond, p"hist len ${h.len}, folded len ${h.compLen}, value ${Binary(h.folded_hist)}\n") 490 } 491 } 492} 493 494class TableAddr(val idxBits: Int, val banks: Int)(implicit p: Parameters) extends XSBundle{ 495 def tagBits = VAddrBits - idxBits - instOffsetBits 496 497 val tag = UInt(tagBits.W) 498 val idx = UInt(idxBits.W) 499 val offset = UInt(instOffsetBits.W) 500 501 def fromUInt(x: UInt) = x.asTypeOf(UInt(VAddrBits.W)).asTypeOf(this) 502 def getTag(x: UInt) = fromUInt(x).tag 503 def getIdx(x: UInt) = fromUInt(x).idx 504 def getBank(x: UInt) = if (banks > 1) getIdx(x)(log2Up(banks) - 1, 0) else 0.U 505 def getBankIdx(x: UInt) = if (banks > 1) getIdx(x)(idxBits - 1, log2Up(banks)) else getIdx(x) 506} 507 508trait BasicPrediction extends HasXSParameter { 509 def cfiIndex: ValidUndirectioned[UInt] 510 def target(pc: UInt): UInt 511 def lastBrPosOH: Vec[Bool] 512 def brTaken: Bool 513 def shouldShiftVec: Vec[Bool] 514 def fallThruError: Bool 515} 516 517// selectByTaken selects some data according to takenMask 518// allTargets should be in a Vec, like [taken0, taken1, ..., not taken, not hit] 519object selectByTaken { 520 def apply[T <: Data](takenMask: Vec[Bool], hit: Bool, allTargets: Vec[T]): T = { 521 val selVecOH = 522 takenMask.zipWithIndex.map { case (t, i) => !takenMask.take(i).fold(false.B)(_ || _) && t && hit } :+ 523 (!takenMask.asUInt.orR && hit) :+ !hit 524 Mux1H(selVecOH, allTargets) 525 } 526} 527 528class FullBranchPrediction(implicit p: Parameters) extends XSBundle with HasBPUConst with BasicPrediction { 529 val br_taken_mask = Vec(numBr, Bool()) 530 531 val slot_valids = Vec(totalSlot, Bool()) 532 533 val targets = Vec(totalSlot, UInt(VAddrBits.W)) 534 val jalr_target = UInt(VAddrBits.W) // special path for indirect predictors 535 val offsets = Vec(totalSlot, UInt(log2Ceil(PredictWidth).W)) 536 val fallThroughAddr = UInt(VAddrBits.W) 537 val fallThroughErr = Bool() 538 val multiHit = Bool() 539 540 val is_jal = Bool() 541 val is_jalr = Bool() 542 val is_call = Bool() 543 val is_ret = Bool() 544 val last_may_be_rvi_call = Bool() 545 val is_br_sharing = Bool() 546 547 // val call_is_rvc = Bool() 548 val hit = Bool() 549 550 val predCycle = if (!env.FPGAPlatform) Some(UInt(64.W)) else None 551 552 def br_slot_valids = slot_valids.init 553 def tail_slot_valid = slot_valids.last 554 555 def br_valids = { 556 VecInit(br_slot_valids :+ (tail_slot_valid && is_br_sharing)) 557 } 558 559 def taken_mask_on_slot = { 560 VecInit( 561 (br_slot_valids zip br_taken_mask.init).map{ case (t, v) => t && v } :+ ( 562 tail_slot_valid && ( 563 is_br_sharing && br_taken_mask.last || !is_br_sharing 564 ) 565 ) 566 ) 567 } 568 569 def real_slot_taken_mask(): Vec[Bool] = { 570 VecInit(taken_mask_on_slot.map(_ && hit)) 571 } 572 573 // len numBr 574 def real_br_taken_mask(): Vec[Bool] = { 575 VecInit( 576 taken_mask_on_slot.map(_ && hit).init :+ 577 (br_taken_mask.last && tail_slot_valid && is_br_sharing && hit) 578 ) 579 } 580 581 // the vec indicating if ghr should shift on each branch 582 def shouldShiftVec = 583 VecInit(br_valids.zipWithIndex.map{ case (v, i) => 584 v && !real_br_taken_mask().take(i).reduceOption(_||_).getOrElse(false.B)}) 585 586 def lastBrPosOH = 587 VecInit((!hit || !br_valids.reduce(_||_)) +: // not hit or no brs in entry 588 (0 until numBr).map(i => 589 br_valids(i) && 590 !real_br_taken_mask().take(i).reduceOption(_||_).getOrElse(false.B) && // no brs taken in front it 591 (real_br_taken_mask()(i) || !br_valids.drop(i+1).reduceOption(_||_).getOrElse(false.B)) && // no brs behind it 592 hit 593 ) 594 ) 595 596 def brTaken = (br_valids zip br_taken_mask).map{ case (a, b) => a && b && hit}.reduce(_||_) 597 598 def target(pc: UInt): UInt = { 599 selectByTaken(taken_mask_on_slot, hit, allTarget(pc)) 600 } 601 602 // allTarget return a Vec of all possible target of a BP stage 603 // in the following order: [taken_target0, taken_target1, ..., fallThroughAddr, not hit (plus fetch width)] 604 // 605 // This exposes internal targets for timing optimization, 606 // since usually targets are generated quicker than taken 607 def allTarget(pc: UInt): Vec[UInt] = { 608 VecInit(targets :+ fallThroughAddr :+ (pc + (FetchWidth * 4).U)) 609 } 610 611 def fallThruError: Bool = hit && fallThroughErr 612 def ftbMultiHit: Bool = hit && multiHit 613 614 def hit_taken_on_jmp = 615 !real_slot_taken_mask().init.reduce(_||_) && 616 real_slot_taken_mask().last && !is_br_sharing 617 def hit_taken_on_call = hit_taken_on_jmp && is_call 618 def hit_taken_on_ret = hit_taken_on_jmp && is_ret 619 def hit_taken_on_jalr = hit_taken_on_jmp && is_jalr 620 621 def cfiIndex = { 622 val cfiIndex = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W))) 623 cfiIndex.valid := real_slot_taken_mask().asUInt.orR 624 // when no takens, set cfiIndex to PredictWidth-1 625 cfiIndex.bits := 626 ParallelPriorityMux(real_slot_taken_mask(), offsets) | 627 Fill(log2Ceil(PredictWidth), (!real_slot_taken_mask().asUInt.orR).asUInt) 628 cfiIndex 629 } 630 631 def taken = br_taken_mask.reduce(_||_) || slot_valids.last // || (is_jal || is_jalr) 632 633 def fromFtbEntry( 634 entry: FTBEntry, 635 pc: UInt, 636 last_stage_pc: Option[Tuple2[UInt, Bool]] = None, 637 last_stage_entry: Option[Tuple2[FTBEntry, Bool]] = None 638 ) = { 639 slot_valids := entry.brSlots.map(_.valid) :+ entry.tailSlot.valid 640 targets := entry.getTargetVec(pc, last_stage_pc) // Use previous stage pc for better timing 641 jalr_target := targets.last 642 offsets := entry.getOffsetVec 643 is_jal := entry.tailSlot.valid && entry.isJal 644 is_jalr := entry.tailSlot.valid && entry.isJalr 645 is_call := entry.tailSlot.valid && entry.isCall 646 is_ret := entry.tailSlot.valid && entry.isRet 647 last_may_be_rvi_call := entry.last_may_be_rvi_call 648 is_br_sharing := entry.tailSlot.valid && entry.tailSlot.sharing 649 predCycle.map(_ := GTimer()) 650 651 val startLower = Cat(0.U(1.W), pc(instOffsetBits+log2Ceil(PredictWidth)-1, instOffsetBits)) 652 val endLowerwithCarry = Cat(entry.carry, entry.pftAddr) 653 fallThroughErr := startLower >= endLowerwithCarry || endLowerwithCarry > (startLower + (PredictWidth).U) 654 fallThroughAddr := Mux(fallThroughErr, pc + (FetchWidth * 4).U, entry.getFallThrough(pc, last_stage_entry)) 655 } 656 657 def display(cond: Bool): Unit = { 658 XSDebug(cond, p"[taken_mask] ${Binary(br_taken_mask.asUInt)} [hit] $hit\n") 659 } 660} 661 662class SpeculativeInfo(implicit p: Parameters) extends XSBundle 663 with HasBPUConst with BPUUtils { 664 val histPtr = new CGHPtr 665 val ssp = UInt(log2Up(RasSize).W) 666 val sctr = UInt(RasCtrSize.W) 667 val TOSW = new RASPtr 668 val TOSR = new RASPtr 669 val NOS = new RASPtr 670 val topAddr = UInt(VAddrBits.W) 671} 672 673class BranchPredictionBundle(implicit p: Parameters) extends XSBundle 674 with HasBPUConst with BPUUtils { 675 val pc = Vec(numDup, UInt(VAddrBits.W)) 676 val valid = Vec(numDup, Bool()) 677 val hasRedirect = Vec(numDup, Bool()) 678 val ftq_idx = new FtqPtr 679 val full_pred = Vec(numDup, new FullBranchPrediction) 680 681 682 def target(pc: UInt) = VecInit(full_pred.map(_.target(pc))) 683 def targets(pc: Vec[UInt]) = VecInit(pc.zipWithIndex.map{case (pc, idx) => full_pred(idx).target(pc)}) 684 def allTargets(pc: Vec[UInt]) = VecInit(pc.zipWithIndex.map{case (pc, idx) => full_pred(idx).allTarget(pc)}) 685 def cfiIndex = VecInit(full_pred.map(_.cfiIndex)) 686 def lastBrPosOH = VecInit(full_pred.map(_.lastBrPosOH)) 687 def brTaken = VecInit(full_pred.map(_.brTaken)) 688 def shouldShiftVec = VecInit(full_pred.map(_.shouldShiftVec)) 689 def fallThruError = VecInit(full_pred.map(_.fallThruError)) 690 def ftbMultiHit = VecInit(full_pred.map(_.ftbMultiHit)) 691 692 def taken = VecInit(cfiIndex.map(_.valid)) 693 694 def getTarget = targets(pc) 695 def getAllTargets = allTargets(pc) 696 697 def display(cond: Bool): Unit = { 698 XSDebug(cond, p"[pc] ${Hexadecimal(pc(0))}\n") 699 full_pred(0).display(cond) 700 } 701} 702 703class BranchPredictionResp(implicit p: Parameters) extends XSBundle with HasBPUConst { 704 val s1 = new BranchPredictionBundle 705 val s2 = new BranchPredictionBundle 706 val s3 = new BranchPredictionBundle 707 708 val s1_uftbHit = Bool() 709 val s1_uftbHasIndirect = Bool() 710 val s1_ftbCloseReq = Bool() 711 712 val last_stage_meta = UInt(MaxMetaLength.W) 713 val last_stage_spec_info = new Ftq_Redirect_SRAMEntry 714 val last_stage_ftb_entry = new FTBEntry 715 716 val topdown_info = new FrontendTopDownBundle 717 718 def selectedResp ={ 719 val res = 720 PriorityMux(Seq( 721 ((s3.valid(3) && s3.hasRedirect(3)) -> s3), 722 ((s2.valid(3) && s2.hasRedirect(3)) -> s2), 723 (s1.valid(3) -> s1) 724 )) 725 res 726 } 727 def selectedRespIdxForFtq = 728 PriorityMux(Seq( 729 ((s3.valid(3) && s3.hasRedirect(3)) -> BP_S3), 730 ((s2.valid(3) && s2.hasRedirect(3)) -> BP_S2), 731 (s1.valid(3) -> BP_S1) 732 )) 733 def lastStage = s3 734} 735 736class BpuToFtqBundle(implicit p: Parameters) extends BranchPredictionResp {} 737 738class BranchPredictionUpdate(implicit p: Parameters) extends XSBundle with HasBPUConst { 739 val pc = UInt(VAddrBits.W) 740 val spec_info = new SpeculativeInfo 741 val ftb_entry = new FTBEntry() 742 743 val cfi_idx = ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)) 744 val br_taken_mask = Vec(numBr, Bool()) 745 val br_committed = Vec(numBr, Bool()) // High only when br valid && br committed 746 val jmp_taken = Bool() 747 val mispred_mask = Vec(numBr+1, Bool()) 748 val pred_hit = Bool() 749 val false_hit = Bool() 750 val new_br_insert_pos = Vec(numBr, Bool()) 751 val old_entry = Bool() 752 val meta = UInt(MaxMetaLength.W) 753 val full_target = UInt(VAddrBits.W) 754 val from_stage = UInt(2.W) 755 val ghist = UInt(HistoryLength.W) 756 757 def is_jal = ftb_entry.tailSlot.valid && ftb_entry.isJal 758 def is_jalr = ftb_entry.tailSlot.valid && ftb_entry.isJalr 759 def is_call = ftb_entry.tailSlot.valid && ftb_entry.isCall 760 def is_ret = ftb_entry.tailSlot.valid && ftb_entry.isRet 761 762 def is_call_taken = is_call && jmp_taken && cfi_idx.valid && cfi_idx.bits === ftb_entry.tailSlot.offset 763 def is_ret_taken = is_ret && jmp_taken && cfi_idx.valid && cfi_idx.bits === ftb_entry.tailSlot.offset 764 765 def display(cond: Bool) = { 766 XSDebug(cond, p"-----------BranchPredictionUpdate-----------\n") 767 XSDebug(cond, p"[mispred_mask] ${Binary(mispred_mask.asUInt)} [false_hit] $false_hit\n") 768 XSDebug(cond, p"[new_br_insert_pos] ${Binary(new_br_insert_pos.asUInt)}\n") 769 XSDebug(cond, p"--------------------------------------------\n") 770 } 771} 772 773class BranchPredictionRedirect(implicit p: Parameters) extends Redirect with HasBPUConst { 774 // override def toPrintable: Printable = { 775 // p"-----------BranchPredictionRedirect----------- " + 776 // p"-----------cfiUpdate----------- " + 777 // p"[pc] ${Hexadecimal(cfiUpdate.pc)} " + 778 // p"[predTaken] ${cfiUpdate.predTaken}, [taken] ${cfiUpdate.taken}, [isMisPred] ${cfiUpdate.isMisPred} " + 779 // p"[target] ${Hexadecimal(cfiUpdate.target)} " + 780 // p"------------------------------- " + 781 // p"[robPtr] f=${robIdx.flag} v=${robIdx.value} " + 782 // p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} " + 783 // p"[ftqOffset] ${ftqOffset} " + 784 // p"[level] ${level}, [interrupt] ${interrupt} " + 785 // p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value} " + 786 // p"[stFtqOffset] ${stFtqOffset} " + 787 // p"\n" 788 789 // } 790 791 // TODO: backend should pass topdown signals here 792 // must not change its parent since BPU has used asTypeOf(this type) from its parent class 793 require(isInstanceOf[Redirect]) 794 val BTBMissBubble = Bool() 795 def ControlRedirectBubble = debugIsCtrl 796 // if mispred br not in ftb, count as BTB miss 797 def ControlBTBMissBubble = ControlRedirectBubble && !cfiUpdate.br_hit && !cfiUpdate.jr_hit 798 def TAGEMissBubble = ControlRedirectBubble && cfiUpdate.br_hit && !cfiUpdate.sc_hit 799 def SCMissBubble = ControlRedirectBubble && cfiUpdate.br_hit && cfiUpdate.sc_hit 800 def ITTAGEMissBubble = ControlRedirectBubble && cfiUpdate.jr_hit && !cfiUpdate.pd.isRet 801 def RASMissBubble = ControlRedirectBubble && cfiUpdate.jr_hit && cfiUpdate.pd.isRet 802 def MemVioRedirectBubble = debugIsMemVio 803 def OtherRedirectBubble = !debugIsCtrl && !debugIsMemVio 804 805 def connectRedirect(source: Redirect): Unit = { 806 for ((name, data) <- this.elements) { 807 if (source.elements.contains(name)) { 808 data := source.elements(name) 809 } 810 } 811 } 812 813 def display(cond: Bool): Unit = { 814 XSDebug(cond, p"-----------BranchPredictionRedirect----------- \n") 815 XSDebug(cond, p"-----------cfiUpdate----------- \n") 816 XSDebug(cond, p"[pc] ${Hexadecimal(cfiUpdate.pc)}\n") 817 // XSDebug(cond, p"[hist] ${Binary(cfiUpdate.hist.predHist)}\n") 818 XSDebug(cond, p"[br_hit] ${cfiUpdate.br_hit} [isMisPred] ${cfiUpdate.isMisPred}\n") 819 XSDebug(cond, p"[pred_taken] ${cfiUpdate.predTaken} [taken] ${cfiUpdate.taken} [isMisPred] ${cfiUpdate.isMisPred}\n") 820 XSDebug(cond, p"[target] ${Hexadecimal(cfiUpdate.target)} \n") 821 XSDebug(cond, p"[shift] ${cfiUpdate.shift}\n") 822 XSDebug(cond, p"------------------------------- \n") 823 XSDebug(cond, p"[robPtr] f=${robIdx.flag} v=${robIdx.value}\n") 824 XSDebug(cond, p"[ftqPtr] f=${ftqIdx.flag} v=${ftqIdx.value} \n") 825 XSDebug(cond, p"[ftqOffset] ${ftqOffset} \n") 826 XSDebug(cond, p"[stFtqIdx] f=${stFtqIdx.flag} v=${stFtqIdx.value}\n") 827 XSDebug(cond, p"[stFtqOffset] ${stFtqOffset}\n") 828 XSDebug(cond, p"---------------------------------------------- \n") 829 } 830} 831