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