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* 17* Acknowledgement 18* 19* This implementation is inspired by several key papers: 20* [1] André Seznec. "[Tage-sc-l branch predictors.](https://inria.hal.science/hal-01086920)" The Journal of 21* Instruction-Level Parallelism (JILP) 4th JILP Workshop on Computer Architecture Competitions (JWAC): Championship 22* Branch Prediction (CBP). 2014. 23* [2] André Seznec. "[Tage-sc-l branch predictors again.](https://inria.hal.science/hal-01354253)" The Journal of 24* Instruction-Level Parallelism (JILP) 5th JILP Workshop on Computer Architecture Competitions (JWAC): Championship 25* Branch Prediction (CBP). 2016. 26***************************************************************************************/ 27 28package xiangshan.frontend 29 30import chisel3._ 31import chisel3.util._ 32import org.chipsalliance.cde.config.Parameters 33import scala.{Tuple2 => &} 34import scala.math.min 35import utility._ 36import utility.mbist.MbistPipeline 37import utility.sram.SRAMConflictBehavior 38import utility.sram.SRAMTemplate 39import xiangshan._ 40 41trait HasSCParameter extends TageParams {} 42 43class SCReq(implicit p: Parameters) extends TageReq 44 45abstract class SCBundle(implicit p: Parameters) extends TageBundle with HasSCParameter {} 46abstract class SCModule(implicit p: Parameters) extends TageModule with HasSCParameter {} 47 48class SCMeta(val ntables: Int)(implicit p: Parameters) extends XSBundle with HasSCParameter { 49 val scPreds = Vec(numBr, Bool()) 50 // Suppose ctrbits of all tables are identical 51 val ctrs = Vec(numBr, Vec(ntables, SInt(SCCtrBits.W))) 52} 53 54class SCResp(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle { 55 val ctrs = Vec(numBr, Vec(2, SInt(ctrBits.W))) 56} 57 58class SCUpdate(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle { 59 val pc = UInt(VAddrBits.W) 60 val ghist = UInt(HistoryLength.W) 61 val mask = Vec(numBr, Bool()) 62 val oldCtrs = Vec(numBr, SInt(ctrBits.W)) 63 val tagePreds = Vec(numBr, Bool()) 64 val takens = Vec(numBr, Bool()) 65} 66 67class SCTableIO(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle { 68 val req = Input(Valid(new SCReq)) 69 val resp = Output(new SCResp(ctrBits)) 70 val update = Input(new SCUpdate(ctrBits)) 71} 72 73class SCTable(val nRows: Int, val ctrBits: Int, val histLen: Int)(implicit p: Parameters) 74 extends SCModule with HasFoldedHistory { 75 val io = IO(new SCTableIO(ctrBits)) 76 77 // val table = Module(new SRAMTemplate(SInt(ctrBits.W), set=nRows, way=2*TageBanks, shouldReset=true, holdRead=true, singlePort=false)) 78 val table = Module(new SRAMTemplate( 79 SInt(ctrBits.W), 80 set = nRows, 81 way = 2 * TageBanks, 82 shouldReset = true, 83 holdRead = true, 84 singlePort = false, 85 conflictBehavior = SRAMConflictBehavior.BufferWriteLossy, 86 withClockGate = true, 87 hasMbist = hasMbist 88 )) 89 private val mbistPl = MbistPipeline.PlaceMbistPipeline(1, "MbistPipeSc", hasMbist) 90 // def getIdx(hist: UInt, pc: UInt) = { 91 // (compute_folded_ghist(hist, log2Ceil(nRows)) ^ (pc >> instOffsetBits))(log2Ceil(nRows)-1,0) 92 // } 93 94 val idxFhInfo = (histLen, min(log2Ceil(nRows), histLen)) 95 96 def getFoldedHistoryInfo = Set(idxFhInfo).filter(_._1 > 0) 97 98 def getIdx(pc: UInt, allFh: AllFoldedHistories) = 99 if (histLen > 0) { 100 val idx_fh = allFh.getHistWithInfo(idxFhInfo).folded_hist 101 // require(idx_fh.getWidth == log2Ceil(nRows)) 102 ((pc >> instOffsetBits) ^ idx_fh)(log2Ceil(nRows) - 1, 0) 103 } else { 104 (pc >> instOffsetBits)(log2Ceil(nRows) - 1, 0) 105 } 106 107 def ctrUpdate(ctr: SInt, cond: Bool): SInt = signedSatUpdate(ctr, ctrBits, cond) 108 109 val s0_idx = getIdx(io.req.bits.pc, io.req.bits.folded_hist) 110 val s1_idx = RegEnable(s0_idx, io.req.valid) 111 112 val s1_pc = RegEnable(io.req.bits.pc, io.req.fire) 113 val s1_unhashed_idx = s1_pc >> instOffsetBits 114 115 table.io.r.req.valid := io.req.valid 116 table.io.r.req.bits.setIdx := s0_idx 117 118 val per_br_ctrs_unshuffled = table.io.r.resp.data.sliding(2, 2).toSeq.map(VecInit(_)) 119 val per_br_ctrs = VecInit((0 until numBr).map(i => 120 Mux1H( 121 UIntToOH(get_phy_br_idx(s1_unhashed_idx, i), numBr), 122 per_br_ctrs_unshuffled 123 ) 124 )) 125 126 io.resp.ctrs := per_br_ctrs 127 128 val update_wdata = Wire(Vec(numBr, SInt(ctrBits.W))) // correspond to physical bridx 129 val update_wdata_packed = VecInit(update_wdata.map(Seq.fill(2)(_)).reduce(_ ++ _)) 130 val updateWayMask = Wire(Vec(2 * numBr, Bool())) // correspond to physical bridx 131 132 val update_unhashed_idx = io.update.pc >> instOffsetBits 133 for (pi <- 0 until numBr) { 134 updateWayMask(2 * pi) := Seq.tabulate(numBr)(li => 135 io.update.mask(li) && get_phy_br_idx(update_unhashed_idx, li) === pi.U && !io.update.tagePreds(li) 136 ).reduce(_ || _) 137 updateWayMask(2 * pi + 1) := Seq.tabulate(numBr)(li => 138 io.update.mask(li) && get_phy_br_idx(update_unhashed_idx, li) === pi.U && io.update.tagePreds(li) 139 ).reduce(_ || _) 140 } 141 142 val update_folded_hist = WireInit(0.U.asTypeOf(new AllFoldedHistories(foldedGHistInfos))) 143 if (histLen > 0) { 144 update_folded_hist.getHistWithInfo(idxFhInfo).folded_hist := compute_folded_ghist(io.update.ghist, log2Ceil(nRows)) 145 } 146 val update_idx = getIdx(io.update.pc, update_folded_hist) 147 148 table.io.w.apply( 149 valid = io.update.mask.reduce(_ || _), 150 data = update_wdata_packed, 151 setIdx = update_idx, 152 waymask = updateWayMask.asUInt 153 ) 154 155 val wrBypassEntries = 16 156 157 // let it corresponds to logical brIdx 158 val wrbypasses = Seq.fill(numBr)(Module(new WrBypass(SInt(ctrBits.W), wrBypassEntries, log2Ceil(nRows), numWays = 2))) 159 160 for (pi <- 0 until numBr) { 161 val br_lidx = get_lgc_br_idx(update_unhashed_idx, pi.U(log2Ceil(numBr).W)) 162 163 val wrbypass_io = Mux1H(UIntToOH(br_lidx, numBr), wrbypasses.map(_.io)) 164 165 val ctrPos = Mux1H(UIntToOH(br_lidx, numBr), io.update.tagePreds) 166 val bypass_ctr = wrbypass_io.hit_data(ctrPos) 167 val previous_ctr = Mux1H(UIntToOH(br_lidx, numBr), io.update.oldCtrs) 168 val hit_and_valid = wrbypass_io.hit && bypass_ctr.valid 169 val oldCtr = Mux(hit_and_valid, bypass_ctr.bits, previous_ctr) 170 val taken = Mux1H(UIntToOH(br_lidx, numBr), io.update.takens) 171 update_wdata(pi) := ctrUpdate(oldCtr, taken) 172 } 173 174 val per_br_update_wdata_packed = update_wdata_packed.sliding(2, 2).map(VecInit(_)).toSeq 175 val per_br_update_way_mask = updateWayMask.sliding(2, 2).map(VecInit(_)).toSeq 176 for (li <- 0 until numBr) { 177 val wrbypass = wrbypasses(li) 178 val br_pidx = get_phy_br_idx(update_unhashed_idx, li) 179 wrbypass.io.wen := io.update.mask(li) 180 wrbypass.io.write_idx := update_idx 181 wrbypass.io.write_data := Mux1H(UIntToOH(br_pidx, numBr), per_br_update_wdata_packed) 182 wrbypass.io.write_way_mask.map(_ := Mux1H(UIntToOH(br_pidx, numBr), per_br_update_way_mask)) 183 } 184 185 val u = io.update 186 XSDebug( 187 io.req.valid, 188 p"scTableReq: pc=0x${Hexadecimal(io.req.bits.pc)}, " + 189 p"s0_idx=${s0_idx}\n" 190 ) 191 XSDebug( 192 RegNext(io.req.valid), 193 p"scTableResp: s1_idx=${s1_idx}," + 194 p"ctr:${io.resp.ctrs}\n" 195 ) 196 XSDebug( 197 io.update.mask.reduce(_ || _), 198 p"update Table: pc:${Hexadecimal(u.pc)}, " + 199 p"tageTakens:${u.tagePreds}, taken:${u.takens}, oldCtr:${u.oldCtrs}\n" 200 ) 201} 202 203class SCThreshold(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle { 204 val ctr = UInt(ctrBits.W) 205 def satPos(ctr: UInt = this.ctr) = ctr === ((1.U << ctrBits) - 1.U) 206 def satNeg(ctr: UInt = this.ctr) = ctr === 0.U 207 def neutralVal = (1 << (ctrBits - 1)).U 208 val thres = UInt(8.W) 209 def initVal = 6.U 210 def minThres = 6.U 211 def maxThres = 31.U 212 def update(cause: Bool): SCThreshold = { 213 val res = Wire(new SCThreshold(this.ctrBits)) 214 val newCtr = satUpdate(this.ctr, this.ctrBits, cause) 215 val newThres = Mux( 216 res.satPos(newCtr) && this.thres <= maxThres, 217 this.thres + 2.U, 218 Mux(res.satNeg(newCtr) && this.thres >= minThres, this.thres - 2.U, this.thres) 219 ) 220 res.thres := newThres 221 res.ctr := Mux(res.satPos(newCtr) || res.satNeg(newCtr), res.neutralVal, newCtr) 222 // XSDebug(true.B, p"scThres Update: cause${cause} newCtr ${newCtr} newThres ${newThres}\n") 223 res 224 } 225} 226 227object SCThreshold { 228 def apply(bits: Int)(implicit p: Parameters) = { 229 val t = Wire(new SCThreshold(ctrBits = bits)) 230 t.ctr := t.neutralVal 231 t.thres := t.initVal 232 t 233 } 234} 235 236trait HasSC extends HasSCParameter with HasPerfEvents { this: Tage => 237 val update_on_mispred, update_on_unconf = WireInit(0.U.asTypeOf(Vec(TageBanks, Bool()))) 238 var sc_fh_info = Set[FoldedHistoryInfo]() 239 if (EnableSC) { 240 val scTables = SCTableInfos.map { 241 case (nRows, ctrBits, histLen) => { 242 val t = Module(new SCTable(nRows / TageBanks, ctrBits, histLen)) 243 val req = t.io.req 244 req.valid := io.s0_fire(3) 245 req.bits.pc := s0_pc_dup(3) 246 req.bits.folded_hist := io.in.bits.folded_hist(3) 247 req.bits.ghist := DontCare 248 if (!EnableSC) { t.io.update := DontCare } 249 t 250 } 251 } 252 sc_fh_info = scTables.map(_.getFoldedHistoryInfo).reduce(_ ++ _).toSet 253 254 val scThresholds = List.fill(TageBanks)(RegInit(SCThreshold(5))) 255 val useThresholds = VecInit(scThresholds map (_.thres)) 256 257 def sign(x: SInt) = x(x.getWidth - 1) 258 def pos(x: SInt) = !sign(x) 259 def neg(x: SInt) = sign(x) 260 261 def aboveThreshold(scSum: SInt, tagePvdr: SInt, threshold: UInt): Bool = { 262 val signedThres = threshold.zext 263 val totalSum = scSum +& tagePvdr 264 (scSum > signedThres - tagePvdr) && pos(totalSum) || 265 (scSum < -signedThres - tagePvdr) && neg(totalSum) 266 } 267 val updateThresholds = VecInit(useThresholds map (t => (t << 3) +& 21.U)) 268 269 val s1_scResps = VecInit(scTables.map(t => t.io.resp)) 270 271 val scUpdateMask = WireInit(0.U.asTypeOf(Vec(numBr, Vec(SCNTables, Bool())))) 272 val scUpdateTagePreds = Wire(Vec(TageBanks, Bool())) 273 val scUpdateTakens = Wire(Vec(TageBanks, Bool())) 274 val scUpdateOldCtrs = Wire(Vec(numBr, Vec(SCNTables, SInt(SCCtrBits.W)))) 275 scUpdateTagePreds := DontCare 276 scUpdateTakens := DontCare 277 scUpdateOldCtrs := DontCare 278 279 val updateSCMeta = updateMeta.scMeta.get 280 281 val s2_sc_used, s2_conf, s2_unconf, s2_agree, s2_disagree = 282 WireInit(0.U.asTypeOf(Vec(TageBanks, Bool()))) 283 val update_sc_used, update_conf, update_unconf, update_agree, update_disagree = 284 WireInit(0.U.asTypeOf(Vec(TageBanks, Bool()))) 285 val sc_misp_tage_corr, sc_corr_tage_misp = 286 WireInit(0.U.asTypeOf(Vec(TageBanks, Bool()))) 287 288 // for sc ctrs 289 def getCentered(ctr: SInt): SInt = Cat(ctr, 1.U(1.W)).asSInt 290 // for tage ctrs, (2*(ctr-4)+1)*8 291 def getPvdrCentered(ctr: UInt): SInt = Cat(ctr ^ (1 << (TageCtrBits - 1)).U, 1.U(1.W), 0.U(3.W)).asSInt 292 293 val scMeta = resp_meta.scMeta.get 294 scMeta := DontCare 295 for (w <- 0 until TageBanks) { 296 // do summation in s2 297 val s1_scTableSums = VecInit( 298 (0 to 1) map { i => 299 ParallelSingedExpandingAdd(s1_scResps map (r => getCentered(r.ctrs(w)(i)))) // TODO: rewrite with wallace tree 300 } 301 ) 302 val s2_scTableSums = RegEnable(s1_scTableSums, io.s1_fire(3)) 303 val s2_tagePrvdCtrCentered = getPvdrCentered(RegEnable(s1_providerResps(w).ctr, io.s1_fire(3))) 304 val s2_totalSums = s2_scTableSums.map(_ +& s2_tagePrvdCtrCentered) 305 val s2_sumAboveThresholds = 306 VecInit((0 to 1).map(i => aboveThreshold(s2_scTableSums(i), s2_tagePrvdCtrCentered, useThresholds(w)))) 307 val s2_scPreds = VecInit(s2_totalSums.map(_ >= 0.S)) 308 309 val s2_scResps = VecInit(RegEnable(s1_scResps, io.s1_fire(3)).map(_.ctrs(w))) 310 val s2_scCtrs = VecInit(s2_scResps.map(_(s2_tageTakens_dup(3)(w).asUInt))) 311 val s2_chooseBit = s2_tageTakens_dup(3)(w) 312 313 val s2_pred = 314 Mux(s2_provideds(w) && s2_sumAboveThresholds(s2_chooseBit), s2_scPreds(s2_chooseBit), s2_tageTakens_dup(3)(w)) 315 316 val s3_disagree = RegEnable(s2_disagree, io.s2_fire(3)) 317 io.out.last_stage_spec_info.sc_disagree.map(_ := s3_disagree) 318 319 scMeta.scPreds(w) := RegEnable(s2_scPreds(s2_chooseBit), io.s2_fire(3)) 320 scMeta.ctrs(w) := RegEnable(s2_scCtrs, io.s2_fire(3)) 321 322 val pred = s2_scPreds(s2_chooseBit) 323 val debug_pc = Cat(debug_pc_s2, w.U, 0.U(instOffsetBits.W)) 324 when(s2_provideds(w)) { 325 s2_sc_used(w) := true.B 326 s2_unconf(w) := !s2_sumAboveThresholds(s2_chooseBit) 327 s2_conf(w) := s2_sumAboveThresholds(s2_chooseBit) 328 // Use prediction from Statistical Corrector 329 when(s2_sumAboveThresholds(s2_chooseBit)) { 330 s2_agree(w) := s2_tageTakens_dup(3)(w) === pred 331 s2_disagree(w) := s2_tageTakens_dup(3)(w) =/= pred 332 // fit to always-taken condition 333 // io.out.s2.full_pred.br_taken_mask(w) := pred 334 } 335 } 336 XSDebug(s2_provideds(w), p"---------tage_bank_${w} provided so that sc used---------\n") 337 XSDebug( 338 s2_provideds(w) && s2_sumAboveThresholds(s2_chooseBit), 339 p"pc(${Hexadecimal(debug_pc)}) SC(${w.U}) overriden pred to ${pred}\n" 340 ) 341 342 val s3_pred_dup = io.s2_fire.map(f => RegEnable(s2_pred, f)) 343 val sc_enable_dup = dup(RegNext(io.ctrl.sc_enable)) 344 for ( 345 sc_enable & fp & s3_pred <- 346 sc_enable_dup zip io.out.s3.full_pred zip s3_pred_dup 347 ) { 348 when(sc_enable) { 349 fp.br_taken_mask(w) := s3_pred 350 } 351 } 352 353 val updateTageMeta = updateMeta 354 val scPred = updateSCMeta.scPreds(w) 355 val tagePred = updateTageMeta.takens(w) 356 val taken = update.br_taken_mask(w) 357 val scOldCtrs = updateSCMeta.ctrs(w) 358 val pvdrCtr = updateTageMeta.providerResps(w).ctr 359 val tableSum = ParallelSingedExpandingAdd(scOldCtrs.map(getCentered)) 360 val totalSumAbs = (tableSum +& getPvdrCentered(pvdrCtr)).abs.asUInt 361 val updateThres = updateThresholds(w) 362 val sumAboveThreshold = aboveThreshold(tableSum, getPvdrCentered(pvdrCtr), updateThres) 363 val thres = useThresholds(w) 364 val newThres = scThresholds(w).update(scPred =/= taken) 365 when(updateValids(w) && updateTageMeta.providers(w).valid) { 366 scUpdateTagePreds(w) := tagePred 367 scUpdateTakens(w) := taken 368 (scUpdateOldCtrs(w) zip scOldCtrs).foreach { case (t, c) => t := c } 369 370 update_sc_used(w) := true.B 371 update_unconf(w) := !sumAboveThreshold 372 update_conf(w) := sumAboveThreshold 373 update_agree(w) := scPred === tagePred 374 update_disagree(w) := scPred =/= tagePred 375 sc_corr_tage_misp(w) := scPred === taken && tagePred =/= taken && update_conf(w) 376 sc_misp_tage_corr(w) := scPred =/= taken && tagePred === taken && update_conf(w) 377 378 when(scPred =/= tagePred && totalSumAbs >= thres - 4.U && totalSumAbs <= thres - 2.U) { 379 scThresholds(w) := newThres 380 } 381 382 when(scPred =/= taken || !sumAboveThreshold) { 383 scUpdateMask(w).foreach(_ := true.B) 384 update_on_mispred(w) := scPred =/= taken 385 update_on_unconf(w) := scPred === taken 386 } 387 } 388 XSDebug( 389 updateValids(w) && updateTageMeta.providers(w).valid && 390 scPred =/= tagePred && totalSumAbs >= thres - 4.U && totalSumAbs <= thres - 2.U, 391 p"scThres $w update: old ${useThresholds(w)} --> new ${newThres.thres}\n" 392 ) 393 XSDebug( 394 updateValids(w) && updateTageMeta.providers(w).valid && 395 (scPred =/= taken || !sumAboveThreshold) && 396 tableSum < 0.S, 397 p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " + 398 p"scSum(-${tableSum.abs}), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n" 399 ) 400 XSDebug( 401 updateValids(w) && updateTageMeta.providers(w).valid && 402 (scPred =/= taken || !sumAboveThreshold) && 403 tableSum >= 0.S, 404 p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " + 405 p"scSum(+${tableSum.abs}), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n" 406 ) 407 XSDebug( 408 updateValids(w) && updateTageMeta.providers(w).valid && 409 (scPred =/= taken || !sumAboveThreshold), 410 p"bank(${w}), update: sc: ${updateSCMeta}\n" 411 ) 412 } 413 414 val realWens = scUpdateMask.transpose.map(v => v.reduce(_ | _)) 415 for (b <- 0 until TageBanks) { 416 for (i <- 0 until SCNTables) { 417 val realWen = realWens(i) 418 scTables(i).io.update.mask(b) := RegNext(scUpdateMask(b)(i)) 419 scTables(i).io.update.tagePreds(b) := RegEnable(scUpdateTagePreds(b), realWen) 420 scTables(i).io.update.takens(b) := RegEnable(scUpdateTakens(b), realWen) 421 scTables(i).io.update.oldCtrs(b) := RegEnable(scUpdateOldCtrs(b)(i), realWen) 422 scTables(i).io.update.pc := RegEnable(update_pc, realWen) 423 scTables(i).io.update.ghist := RegEnable(update.ghist, realWen) 424 } 425 } 426 427 tage_perf("sc_conf", PopCount(s2_conf), PopCount(update_conf)) 428 tage_perf("sc_unconf", PopCount(s2_unconf), PopCount(update_unconf)) 429 tage_perf("sc_agree", PopCount(s2_agree), PopCount(update_agree)) 430 tage_perf("sc_disagree", PopCount(s2_disagree), PopCount(update_disagree)) 431 tage_perf("sc_used", PopCount(s2_sc_used), PopCount(update_sc_used)) 432 XSPerfAccumulate("sc_update_on_mispred", PopCount(update_on_mispred)) 433 XSPerfAccumulate("sc_update_on_unconf", PopCount(update_on_unconf)) 434 XSPerfAccumulate("sc_mispred_but_tage_correct", PopCount(sc_misp_tage_corr)) 435 XSPerfAccumulate("sc_correct_and_tage_wrong", PopCount(sc_corr_tage_misp)) 436 437 } 438 439 override def getFoldedHistoryInfo = Some(tage_fh_info ++ sc_fh_info) 440 441 override val perfEvents = Seq( 442 ("tage_tht_hit ", PopCount(updateMeta.providers.map(_.valid))), 443 ("sc_update_on_mispred ", PopCount(update_on_mispred)), 444 ("sc_update_on_unconf ", PopCount(update_on_unconf)) 445 ) 446 generatePerfEvent() 447} 448