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.frontend 18 19import chipsalliance.rocketchip.config.Parameters 20import chisel3._ 21import chisel3.util._ 22import xiangshan._ 23import utils._ 24import chisel3.experimental.chiselName 25 26import scala.math.min 27 28trait HasSCParameter extends TageParams { 29} 30 31class SCReq(implicit p: Parameters) extends TageReq 32 33abstract class SCBundle(implicit p: Parameters) extends TageBundle with HasSCParameter {} 34abstract class SCModule(implicit p: Parameters) extends TageModule with HasSCParameter {} 35 36 37class SCMeta(val useSC: Boolean, val ntables: Int)(implicit p: Parameters) extends XSBundle with HasSCParameter { 38 val tageTaken = if (useSC) Bool() else UInt(0.W) 39 val scUsed = if (useSC) Bool() else UInt(0.W) 40 val scPred = if (useSC) Bool() else UInt(0.W) 41 // Suppose ctrbits of all tables are identical 42 val ctrs = if (useSC) Vec(ntables, SInt(SCCtrBits.W)) else Vec(ntables, SInt(0.W)) 43} 44 45 46class SCResp(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle { 47 val ctr = Vec(2, SInt(ctrBits.W)) 48} 49 50class SCUpdate(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle { 51 val pc = UInt(VAddrBits.W) 52 val folded_hist = new AllFoldedHistories(foldedGHistInfos) 53 val mask = Bool() 54 val oldCtr = SInt(ctrBits.W) 55 val tagePred = Bool() 56 val taken = Bool() 57} 58 59class SCTableIO(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle { 60 val req = Input(Valid(new SCReq)) 61 val resp = Output(new SCResp(ctrBits)) 62 val update = Input(new SCUpdate(ctrBits)) 63} 64 65@chiselName 66class SCTable(val nRows: Int, val ctrBits: Int, val histLen: Int)(implicit p: Parameters) 67 extends SCModule with HasFoldedHistory { 68 val io = IO(new SCTableIO(ctrBits)) 69 70 // val table = Module(new SRAMTemplate(SInt(ctrBits.W), set=nRows, way=2*TageBanks, shouldReset=true, holdRead=true, singlePort=false)) 71 val table = Module(new SRAMTemplate(SInt(ctrBits.W), set=nRows, way=2, shouldReset=true, holdRead=true, singlePort=false)) 72 73 // def getIdx(hist: UInt, pc: UInt) = { 74 // (compute_folded_ghist(hist, log2Ceil(nRows)) ^ (pc >> instOffsetBits))(log2Ceil(nRows)-1,0) 75 // } 76 77 78 val idxFhInfo = (histLen, min(log2Ceil(nRows), histLen)) 79 80 def getFoldedHistoryInfo = Set(idxFhInfo).filter(_._1 > 0) 81 82 def getIdx(pc: UInt, allFh: AllFoldedHistories) = { 83 if (histLen > 0) { 84 val idx_fh = allFh.getHistWithInfo(idxFhInfo).folded_hist 85 // require(idx_fh.getWidth == log2Ceil(nRows)) 86 ((pc >> instOffsetBits) ^ idx_fh)(log2Ceil(nRows)-1,0) 87 } 88 else { 89 pc(log2Ceil(nRows)-1,0) 90 } 91 } 92 93 def ctrUpdate(ctr: SInt, cond: Bool): SInt = signedSatUpdate(ctr, ctrBits, cond) 94 95 val s0_idx = getIdx(io.req.bits.pc, io.req.bits.folded_hist) 96 val s1_idx = RegEnable(s0_idx, enable=io.req.valid) 97 98 table.io.r.req.valid := io.req.valid 99 table.io.r.req.bits.setIdx := s0_idx 100 101 io.resp.ctr := table.io.r.resp.data 102 103 val update_wdata = Wire(SInt(ctrBits.W)) 104 val updateWayMask = 105 VecInit((0 to 1).map(io.update.mask && _.U === io.update.tagePred.asUInt)).asUInt 106 107 val update_idx = getIdx(io.update.pc, io.update.folded_hist) 108 109 table.io.w.apply( 110 valid = io.update.mask, 111 data = VecInit(Seq.fill(2)(update_wdata)), 112 setIdx = update_idx, 113 waymask = updateWayMask 114 ) 115 116 val wrBypassEntries = 4 117 118 val wrbypass = Module(new WrBypass(SInt(ctrBits.W), wrBypassEntries, log2Ceil(nRows), numWays=2)) 119 120 val ctrPos = io.update.tagePred 121 val altPos = !io.update.tagePred 122 val bypass_ctr = wrbypass.io.hit_data(ctrPos) 123 val hit_and_valid = wrbypass.io.hit && bypass_ctr.valid 124 val oldCtr = Mux(hit_and_valid, bypass_ctr.bits, io.update.oldCtr) 125 update_wdata := ctrUpdate(oldCtr, io.update.taken) 126 127 wrbypass.io.wen := io.update.mask 128 wrbypass.io.write_data.map(_ := update_wdata) // only one of them are used 129 wrbypass.io.write_idx := update_idx 130 wrbypass.io.write_way_mask.map(_ := UIntToOH(ctrPos).asTypeOf(Vec(2, Bool()))) 131 132 val u = io.update 133 XSDebug(io.req.valid, 134 p"scTableReq: pc=0x${Hexadecimal(io.req.bits.pc)}, " + 135 p"s0_idx=${s0_idx}\n") 136 XSDebug(RegNext(io.req.valid), 137 p"scTableResp: s1_idx=${s1_idx}," + 138 p"ctr:${io.resp.ctr}\n") 139 XSDebug(io.update.mask, 140 p"update Table: pc:${Hexadecimal(u.pc)}, " + 141 p"tageTaken:${u.tagePred}, taken:${u.taken}, oldCtr:${u.oldCtr}\n") 142} 143 144class SCThreshold(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle { 145 val ctr = UInt(ctrBits.W) 146 def satPos(ctr: UInt = this.ctr) = ctr === ((1.U << ctrBits) - 1.U) 147 def satNeg(ctr: UInt = this.ctr) = ctr === 0.U 148 def neutralVal = (1.U << (ctrBits - 1)) 149 val thres = UInt(8.W) 150 def initVal = 6.U 151 def minThres = 6.U 152 def maxThres = 31.U 153 def update(cause: Bool): SCThreshold = { 154 val res = Wire(new SCThreshold(this.ctrBits)) 155 val newCtr = satUpdate(this.ctr, this.ctrBits, cause) 156 val newThres = Mux(res.satPos(newCtr) && this.thres <= maxThres, this.thres + 2.U, 157 Mux(res.satNeg(newCtr) && this.thres >= minThres, this.thres - 2.U, 158 this.thres)) 159 res.thres := newThres 160 res.ctr := Mux(res.satPos(newCtr) || res.satNeg(newCtr), res.neutralVal, newCtr) 161 // XSDebug(true.B, p"scThres Update: cause${cause} newCtr ${newCtr} newThres ${newThres}\n") 162 res 163 } 164} 165 166object SCThreshold { 167 def apply(bits: Int)(implicit p: Parameters) = { 168 val t = Wire(new SCThreshold(ctrBits=bits)) 169 t.ctr := t.neutralVal 170 t.thres := t.initVal 171 t 172 } 173} 174 175 176trait HasSC extends HasSCParameter with HasPerfEvents { this: Tage => 177 val update_on_mispred, update_on_unconf = WireInit(0.U.asTypeOf(Vec(TageBanks, Bool()))) 178 var sc_fh_info = Set[FoldedHistoryInfo]() 179 if (EnableSC) { 180 val bank_scTables = BankSCTableInfos.zipWithIndex.map { 181 case (info, b) => 182 val tables = info.map { 183 case (nRows, ctrBits, histLen) => { 184 val t = Module(new SCTable(nRows/TageBanks, ctrBits, histLen)) 185 val req = t.io.req 186 req.valid := io.s0_fire 187 req.bits.pc := s0_pc 188 req.bits.folded_hist := io.in.bits.folded_hist 189 if (!EnableSC) {t.io.update := DontCare} 190 t 191 } 192 } 193 tables 194 } 195 sc_fh_info = bank_scTables.flatMap(_.map(_.getFoldedHistoryInfo).reduce(_++_)).toSet 196 197 val scThresholds = List.fill(TageBanks)(RegInit(SCThreshold(5))) 198 val useThresholds = VecInit(scThresholds map (_.thres)) 199 def aboveThreshold(sum: SInt, threshold: UInt) = { 200 def sign(x: SInt) = x(x.getWidth-1) 201 def pos(x: SInt) = !sign(x) 202 def neg(x: SInt) = sign(x) 203 val signedThres = threshold.zext 204 sum > signedThres && pos(sum) || sum < -signedThres && neg(sum) 205 } 206 val updateThresholds = VecInit(useThresholds map (t => (t << 3) +& 21.U)) 207 208 val s1_scResps = MixedVecInit(bank_scTables.map(b => VecInit(b.map(t => t.io.resp)))) 209 210 val scUpdateMask = WireInit(0.U.asTypeOf(MixedVec(BankSCNTables.map(Vec(_, Bool()))))) 211 val scUpdateTagePreds = Wire(Vec(TageBanks, Bool())) 212 val scUpdateTakens = Wire(Vec(TageBanks, Bool())) 213 val scUpdateOldCtrs = Wire(MixedVec(BankSCNTables.map(Vec(_, SInt(SCCtrBits.W))))) 214 scUpdateTagePreds := DontCare 215 scUpdateTakens := DontCare 216 scUpdateOldCtrs := DontCare 217 218 val updateSCMetas = VecInit(updateMetas.map(_.scMeta)) 219 220 val s2_sc_used, s2_conf, s2_unconf, s2_agree, s2_disagree = 221 0.U.asTypeOf(Vec(TageBanks, Bool())) 222 val update_sc_used, update_conf, update_unconf, update_agree, update_disagree = 223 0.U.asTypeOf(Vec(TageBanks, Bool())) 224 val sc_misp_tage_corr, sc_corr_tage_misp = 225 0.U.asTypeOf(Vec(TageBanks, Bool())) 226 227 // for sc ctrs 228 def getCentered(ctr: SInt): SInt = (ctr << 1).asSInt + 1.S 229 // for tage ctrs 230 def getPvdrCentered(ctr: UInt): SInt = ((((ctr.zext -& 4.S) << 1).asSInt + 1.S) << 3).asSInt 231 232 for (w <- 0 until TageBanks) { 233 val scMeta = resp_meta(w).scMeta 234 scMeta := DontCare 235 // do summation in s2 236 val s1_scTableSums = VecInit( 237 (0 to 1) map { i => 238 ParallelSingedExpandingAdd(s1_scResps(w) map (r => getCentered(r.ctr(i)))) // TODO: rewrite with wallace tree 239 } 240 ) 241 242 val providerCtr = s1_providerCtrs(w) 243 val s1_pvdrCtrCentered = getPvdrCentered(providerCtr) 244 val s1_totalSums = VecInit(s1_scTableSums.map(_ +& s1_pvdrCtrCentered)) 245 val s1_sumAboveThresholds = VecInit((s1_totalSums zip useThresholds) map { case (sum, thres) => aboveThreshold(sum, thres)}) 246 val s1_scPreds = VecInit(s1_totalSums.map (_ >= 0.S)) 247 248 val s2_sumAboveThresholds = RegEnable(s1_sumAboveThresholds, io.s1_fire) 249 val s2_scPreds = RegEnable(s1_scPreds, io.s1_fire) 250 val s2_scResps = VecInit(RegEnable(s1_scResps(w), io.s1_fire).map(_.ctr)) 251 val s2_scCtrs = VecInit(s2_scResps.map(_(s2_tageTakens(w).asUInt))) 252 val s2_chooseBit = s2_tageTakens(w) 253 scMeta.tageTaken := s2_tageTakens(w) 254 scMeta.scUsed := s2_provideds(w) 255 scMeta.scPred := s2_scPreds(s2_chooseBit) 256 scMeta.ctrs := s2_scCtrs 257 258 when (s2_provideds(w)) { 259 s2_sc_used(w) := true.B 260 s2_unconf(w) := !s2_sumAboveThresholds(s2_chooseBit) 261 s2_conf(w) := s2_sumAboveThresholds(s2_chooseBit) 262 // Use prediction from Statistical Corrector 263 XSDebug(p"---------tage_bank_${w} provided so that sc used---------\n") 264 when (s2_sumAboveThresholds(s2_chooseBit)) { 265 val pred = s2_scPreds(s2_chooseBit) 266 val debug_pc = Cat(debug_pc_s2, w.U, 0.U(instOffsetBits.W)) 267 s2_agree(w) := s2_tageTakens(w) === pred 268 s2_disagree(w) := s2_tageTakens(w) =/= pred 269 // fit to always-taken condition 270 // io.out.resp.s2.full_pred.br_taken_mask(w) := pred 271 XSDebug(p"pc(${Hexadecimal(debug_pc)}) SC(${w.U}) overriden pred to ${pred}\n") 272 } 273 } 274 275 io.out.resp.s2.full_pred.br_taken_mask(w) := 276 Mux(s2_provideds(w) && s2_sumAboveThresholds(s2_chooseBit), 277 s2_scPreds(s2_chooseBit), s2_tageTakens(w)) 278 279 val updateSCMeta = updateSCMetas(w) 280 val updateTageMeta = updateMetas(w) 281 when (updateValids(w) && updateSCMeta.scUsed.asBool) { 282 val scPred = updateSCMeta.scPred 283 val tagePred = updateSCMeta.tageTaken 284 val taken = update.full_pred.br_taken_mask(w) 285 val scOldCtrs = updateSCMeta.ctrs 286 val pvdrCtr = updateTageMeta.providerCtr 287 val sum = ParallelSingedExpandingAdd(scOldCtrs.map(getCentered)) +& getPvdrCentered(pvdrCtr) 288 val sumAbs = sum.abs.asUInt 289 val sumAboveThreshold = aboveThreshold(sum, useThresholds(w)) 290 scUpdateTagePreds(w) := tagePred 291 scUpdateTakens(w) := taken 292 (scUpdateOldCtrs(w) zip scOldCtrs).foreach{case (t, c) => t := c} 293 294 update_sc_used(w) := true.B 295 update_unconf(w) := !sumAboveThreshold 296 update_conf(w) := sumAboveThreshold 297 update_agree(w) := scPred === tagePred 298 update_disagree(w) := scPred =/= tagePred 299 sc_corr_tage_misp(w) := scPred === taken && tagePred =/= taken && update_conf(w) 300 sc_misp_tage_corr(w) := scPred =/= taken && tagePred === taken && update_conf(w) 301 302 val thres = useThresholds(w) 303 when (scPred =/= tagePred && sumAbs >= thres - 4.U && sumAbs <= thres - 2.U) { 304 val newThres = scThresholds(w).update(scPred =/= taken) 305 scThresholds(w) := newThres 306 XSDebug(p"scThres $w update: old ${useThresholds(w)} --> new ${newThres.thres}\n") 307 } 308 309 val updateThres = updateThresholds(w) 310 when (scPred =/= taken || !sumAboveThreshold) { 311 scUpdateMask(w).foreach(_ := true.B) 312 XSDebug(sum < 0.S, 313 p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " + 314 p"scSum(-$sumAbs), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n" 315 ) 316 XSDebug(sum >= 0.S, 317 p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " + 318 p"scSum(+$sumAbs), mispred: sc(${scPred =/= taken}), tage(${updateMisPreds(w)})\n" 319 ) 320 XSDebug(p"bank(${w}), update: sc: ${updateSCMeta}\n") 321 update_on_mispred(w) := scPred =/= taken 322 update_on_unconf(w) := scPred === taken 323 } 324 } 325 } 326 327 328 for (b <- 0 until TageBanks) { 329 for (i <- 0 until BankSCNTables(b)) { 330 bank_scTables(b)(i).io.update.mask := RegNext(scUpdateMask(b)(i)) 331 bank_scTables(b)(i).io.update.tagePred := RegNext(scUpdateTagePreds(b)) 332 bank_scTables(b)(i).io.update.taken := RegNext(scUpdateTakens(b)) 333 bank_scTables(b)(i).io.update.oldCtr := RegNext(scUpdateOldCtrs(b)(i)) 334 bank_scTables(b)(i).io.update.pc := RegNext(update.pc) 335 bank_scTables(b)(i).io.update.folded_hist := RegNext(updateFHist) 336 } 337 } 338 339 tage_perf("sc_conf", PopCount(s2_conf), PopCount(update_conf)) 340 tage_perf("sc_unconf", PopCount(s2_unconf), PopCount(update_unconf)) 341 tage_perf("sc_agree", PopCount(s2_agree), PopCount(update_agree)) 342 tage_perf("sc_disagree", PopCount(s2_disagree), PopCount(update_disagree)) 343 tage_perf("sc_used", PopCount(s2_sc_used), PopCount(update_sc_used)) 344 XSPerfAccumulate("sc_update_on_mispred", PopCount(update_on_mispred)) 345 XSPerfAccumulate("sc_update_on_unconf", PopCount(update_on_unconf)) 346 XSPerfAccumulate("sc_mispred_but_tage_correct", PopCount(sc_misp_tage_corr)) 347 XSPerfAccumulate("sc_correct_and_tage_wrong", PopCount(sc_corr_tage_misp)) 348 349 } 350 351 override def getFoldedHistoryInfo = Some(tage_fh_info ++ sc_fh_info) 352 353 val perfEvents = Seq( 354 ("tage_tht_hit ", updateMetas(1).provider.valid + updateMetas(0).provider.valid), 355 ("sc_update_on_mispred ", PopCount(update_on_mispred) ), 356 ("sc_update_on_unconf ", PopCount(update_on_unconf) ), 357 ) 358 generatePerfEvent() 359} 360