xref: /XiangShan/src/main/scala/xiangshan/frontend/SC.scala (revision 2225d46ebbe2fd16b9b29963c27a7d0385a42709)
1package xiangshan.frontend
2
3import chipsalliance.rocketchip.config.Parameters
4import chisel3._
5import chisel3.util._
6import xiangshan._
7import utils._
8import chisel3.experimental.chiselName
9
10import scala.math.min
11
12trait HasSCParameter extends HasTageParameter {
13  val SCHistLens = 0 :: TableInfo.map{ case (_,h,_) => h}.toList
14  val SCNTables = 6
15  val SCCtrBits = 6
16  val SCNRows = 1024
17  val SCTableInfo = Seq.fill(SCNTables)((SCNRows, SCCtrBits)) zip SCHistLens map {case ((n, cb), h) => (n, cb, h)}
18}
19
20class SCReq(implicit p: Parameters) extends TageReq
21
22abstract class SCBundle(implicit p: Parameters) extends TageBundle with HasSCParameter {}
23abstract class SCModule(implicit p: Parameters) extends TageModule with HasSCParameter {}
24
25class SCResp(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
26  val ctr = Vec(2, SInt(ctrBits.W))
27}
28
29class SCUpdate(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
30  val pc = UInt(VAddrBits.W)
31  val hist = UInt(HistoryLength.W)
32  val mask = Vec(TageBanks, Bool())
33  val oldCtrs = Vec(TageBanks, SInt(ctrBits.W))
34  val tagePreds = Vec(TageBanks, Bool())
35  val takens = Vec(TageBanks, Bool())
36}
37
38class SCTableIO(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
39  val req = Input(Valid(new SCReq))
40  val resp = Output(Vec(TageBanks, new SCResp(ctrBits)))
41  val update = Input(new SCUpdate(ctrBits))
42}
43
44@chiselName
45class SCTable(val nRows: Int, val ctrBits: Int, val histLen: Int)(implicit p: Parameters)
46  extends SCModule with HasFoldedHistory {
47  val io = IO(new SCTableIO(ctrBits))
48
49  val table = Module(new SRAMTemplate(SInt(ctrBits.W), set=nRows, way=2*TageBanks, shouldReset=true, holdRead=true, singlePort=false))
50
51  def getIdx(hist: UInt, pc: UInt) = {
52    (compute_folded_hist(hist, log2Ceil(nRows)) ^ (pc >> (instOffsetBits+log2Ceil(TageBanks))))(log2Ceil(nRows)-1,0)
53  }
54
55  def ctrUpdate(ctr: SInt, cond: Bool): SInt = signedSatUpdate(ctr, ctrBits, cond)
56
57  val if2_idx = getIdx(io.req.bits.hist, io.req.bits.pc)
58  val if3_idx = RegEnable(if2_idx, enable=io.req.valid)
59
60  val table_r =
61    VecInit((0 until TageBanks).map(b => VecInit((0 to 1).map(i => table.io.r.resp.data(b*2+i)))))
62
63
64  val if2_mask = io.req.bits.mask
65  val if3_mask = RegEnable(if2_mask, enable=io.req.valid)
66
67  val update_idx = getIdx(io.update.hist, io.update.pc)
68  val update_wdatas =
69    VecInit((0 until TageBanks).map(w =>
70      ctrUpdate(io.update.oldCtrs(w), io.update.takens(w))))
71
72  table.io.r.req.valid := io.req.valid
73  table.io.r.req.bits.setIdx := if2_idx
74
75  val updateWayMask =
76    VecInit((0 until TageBanks).map(b =>
77      VecInit((0 to 1).map(i =>
78        (io.update.mask(b) && i.U === io.update.tagePreds(b).asUInt))))).asUInt
79
80  table.io.w.apply(
81    valid = io.update.mask.asUInt.orR,
82    data = VecInit((0 until TageBanks*2).map(i => update_wdatas(i/2))),
83    setIdx = update_idx,
84    waymask = updateWayMask
85  )
86
87  (0 until TageBanks).map(b => {
88    io.resp(b).ctr := table_r(b)
89  })
90
91  val wrBypassEntries = 4
92
93  val wrbypass_idxs = RegInit(0.U.asTypeOf(Vec(wrBypassEntries, UInt(log2Ceil(nRows).W))))
94  val wrbypass_ctrs = RegInit(0.U.asTypeOf(Vec(wrBypassEntries, Vec(2*TageBanks, SInt(ctrBits.W)))))
95  val wrbypass_ctr_valids = RegInit(0.U.asTypeOf(Vec(wrBypassEntries, Vec(2*TageBanks, Bool()))))
96  val wrbypass_enq_idx = RegInit(0.U(log2Ceil(wrBypassEntries).W))
97
98  when (reset.asBool) {
99    wrbypass_ctr_valids := 0.U.asTypeOf(Vec(wrBypassEntries, Vec(2*TageBanks, Bool())))
100  }
101
102  val wrbypass_hits = VecInit((0 until wrBypassEntries) map (i => wrbypass_idxs(i) === update_idx))
103  val wrbypass_hit = wrbypass_hits.asUInt.orR
104  val wrbypass_hit_idx = ParallelPriorityEncoder(wrbypass_hits)
105
106  for (w <- 0 until TageBanks) {
107    val ctrPos = (w << 1).U | io.update.tagePreds(w).asUInt
108    val altPos = (w << 1).U | ~io.update.tagePreds(w).asUInt
109    val bypass_ctr = wrbypass_ctrs(wrbypass_hit_idx)(ctrPos)
110    val hit_and_valid = wrbypass_hit && wrbypass_ctr_valids(wrbypass_hit_idx)(ctrPos)
111    val oldCtr = Mux(hit_and_valid, wrbypass_ctrs(wrbypass_hit_idx)(ctrPos), io.update.oldCtrs(w))
112    update_wdatas(w) := ctrUpdate(oldCtr, io.update.takens(w))
113
114    when (io.update.mask.reduce(_||_)) {
115      when (wrbypass_hit) {
116        when (io.update.mask(w)) {
117          wrbypass_ctrs(wrbypass_hit_idx)(ctrPos) := update_wdatas(w)
118          wrbypass_ctr_valids(wrbypass_hit_idx)(ctrPos) := true.B
119        }
120      }.otherwise {
121        // reset valid bit first
122        wrbypass_ctr_valids(wrbypass_enq_idx)(ctrPos) := false.B
123        wrbypass_ctr_valids(wrbypass_enq_idx)(altPos) := false.B
124        when (io.update.mask(w)) {
125          wrbypass_ctr_valids(wrbypass_enq_idx)(ctrPos) := true.B
126          wrbypass_ctrs(wrbypass_enq_idx)(w) := update_wdatas(w)
127        }
128      }
129    }
130  }
131
132  when (io.update.mask.reduce(_||_) && !wrbypass_hit) {
133    wrbypass_idxs(wrbypass_enq_idx) := update_idx
134    wrbypass_enq_idx := (wrbypass_enq_idx + 1.U)(log2Ceil(wrBypassEntries)-1,0)
135  }
136
137
138  if (BPUDebug && debug) {
139    val u = io.update
140    XSDebug(io.req.valid,
141      p"scTableReq: pc=0x${Hexadecimal(io.req.bits.pc)}, " +
142      p"if2_idx=${if2_idx}, hist=${Hexadecimal(io.req.bits.hist)}, " +
143      p"if2_mask=${Binary(if2_mask)}\n")
144    for (i <- 0 until TageBanks) {
145      XSDebug(RegNext(io.req.valid),
146        p"scTableResp[${i.U}]: if3_idx=${if3_idx}," +
147        p"ctr:${io.resp(i).ctr}, if3_mask=${Binary(if3_mask)}\n")
148      XSDebug(io.update.mask(i),
149        p"update Table: pc:${Hexadecimal(u.pc)}, hist:${Hexadecimal(u.hist)}, " +
150        p"bank:${i}, tageTaken:${u.tagePreds(i)}, taken:${u.takens(i)}, oldCtr:${u.oldCtrs(i)}\n")
151      val ctrPos = (i << 1).U | io.update.tagePreds(i).asUInt
152      val hitCtr = wrbypass_ctrs(wrbypass_hit_idx)(ctrPos)
153      XSDebug(wrbypass_hit && wrbypass_ctr_valids(wrbypass_hit_idx)(ctrPos) && io.update.mask(i),
154        p"bank $i wrbypass hit wridx:$wrbypass_hit_idx, idx:$update_idx, ctr:$hitCtr" +
155        p"taken:${io.update.takens(i)} newCtr:${update_wdatas(i)}\n")
156    }
157  }
158
159}
160
161class SCThreshold(val ctrBits: Int = 6)(implicit p: Parameters) extends SCBundle {
162  val ctr = UInt(ctrBits.W)
163  def satPos(ctr: UInt = this.ctr) = ctr === ((1.U << ctrBits) - 1.U)
164  def satNeg(ctr: UInt = this.ctr) = ctr === 0.U
165  def neutralVal = (1.U << (ctrBits - 1))
166  val thres = UInt(8.W)
167  def initVal = 6.U
168  def minThres = 6.U
169  def maxThres = 31.U
170  def update(cause: Bool): SCThreshold = {
171    val res = Wire(new SCThreshold(this.ctrBits))
172    val newCtr = satUpdate(this.ctr, this.ctrBits, cause)
173    val newThres = Mux(res.satPos(newCtr) && this.thres <= maxThres, this.thres + 2.U,
174                      Mux(res.satNeg(newCtr) && this.thres >= minThres, this.thres - 2.U,
175                      this.thres))
176    res.thres := newThres
177    res.ctr := Mux(res.satPos(newCtr) || res.satNeg(newCtr), res.neutralVal, newCtr)
178    // XSDebug(true.B, p"scThres Update: cause${cause} newCtr ${newCtr} newThres ${newThres}\n")
179    res
180  }
181}
182
183object SCThreshold {
184  def apply(bits: Int)(implicit p: Parameters) = {
185    val t = Wire(new SCThreshold(ctrBits=bits))
186    t.ctr := t.neutralVal
187    t.thres := t.initVal
188    t
189  }
190}
191
192
193trait HasSC extends HasSCParameter { this: Tage =>
194  val scTables = SCTableInfo.map {
195    case (nRows, ctrBits, histLen) => {
196      val t = Module(new SCTable(nRows/TageBanks, ctrBits, histLen))
197      val req = t.io.req
198      req.valid := io.pc.valid
199      req.bits.pc := io.pc.bits
200      req.bits.hist := io.hist
201      req.bits.mask := io.inMask
202      if (!EnableSC) {t.io.update := DontCare}
203      t
204    }
205  }
206
207  val scThresholds = List.fill(TageBanks)(RegInit(SCThreshold(5)))
208  val useThresholds = VecInit(scThresholds map (_.thres))
209  val updateThresholds = VecInit(useThresholds map (t => (t << 3) +& 21.U))
210
211  val if3_scResps = VecInit(scTables.map(t => t.io.resp))
212
213  val scUpdateMask = WireInit(0.U.asTypeOf(Vec(SCNTables, Vec(TageBanks, Bool()))))
214  val scUpdateTagePreds = Wire(Vec(TageBanks, Bool()))
215  val scUpdateTakens = Wire(Vec(TageBanks, Bool()))
216  val scUpdateOldCtrs = Wire(Vec(TageBanks, Vec(SCNTables, SInt(SCCtrBits.W))))
217  scUpdateTagePreds := DontCare
218  scUpdateTakens := DontCare
219  scUpdateOldCtrs := DontCare
220
221  val updateSCMetas = VecInit(u.metas.map(_.tageMeta.scMeta))
222
223  val if4_sc_used, if4_conf, if4_unconf, if4_agree, if4_disagree =
224    0.U.asTypeOf(Vec(TageBanks, Bool()))
225  val update_sc_used, update_conf, update_unconf, update_agree, update_disagree =
226    0.U.asTypeOf(Vec(TageBanks, Bool()))
227  val update_on_mispred, update_on_unconf, sc_misp_tage_corr, sc_corr_tage_misp =
228    0.U.asTypeOf(Vec(TageBanks, Bool()))
229
230  // for sc ctrs
231  def getCentered(ctr: SInt): SInt = (ctr << 1).asSInt + 1.S
232  // for tage ctrs
233  def getPvdrCentered(ctr: UInt): SInt = ((((ctr.zext -& 4.S) << 1).asSInt + 1.S) << 3).asSInt
234
235  for (w <- 0 until TageBanks) {
236    val scMeta = io.meta(w).scMeta
237    scMeta := DontCare
238    // do summation in if3
239    val if3_scTableSums = VecInit(
240      (0 to 1) map { i =>
241        ParallelSingedExpandingAdd(if3_scResps map (r => getCentered(r(w).ctr(i)))) // TODO: rewrite with wallace tree
242      }
243    )
244
245    val providerCtr = if3_providerCtrs(w)
246    val if3_pvdrCtrCentered = getPvdrCentered(providerCtr)
247    val if3_totalSums = VecInit(if3_scTableSums.map(_  +& if3_pvdrCtrCentered))
248    val if3_sumAbs = VecInit(if3_totalSums.map(_.abs.asUInt))
249    val if3_sumBelowThresholds = VecInit(if3_sumAbs map (_ <= useThresholds(w)))
250    val if3_scPreds = VecInit(if3_totalSums.map (_ >= 0.S))
251
252    val if4_sumBelowThresholds = RegEnable(if3_sumBelowThresholds, s3_fire)
253    val if4_scPreds = RegEnable(if3_scPreds, s3_fire)
254    val if4_sumAbs = RegEnable(if3_sumAbs, s3_fire)
255
256    val if4_scCtrs = RegEnable(VecInit(if3_scResps.map(r => r(w).ctr(if3_tageTakens(w).asUInt))), s3_fire)
257    val if4_chooseBit = if4_tageTakens(w)
258    scMeta.tageTaken := if4_tageTakens(w)
259    scMeta.scUsed := if4_provideds(w)
260    scMeta.scPred := if4_scPreds(if4_chooseBit)
261    scMeta.ctrs   := if4_scCtrs
262
263    when (if4_provideds(w)) {
264      if4_sc_used(w) := true.B
265      if4_unconf(w) := if4_sumBelowThresholds(if4_chooseBit)
266      if4_conf(w) := !if4_sumBelowThresholds(if4_chooseBit)
267      // Use prediction from Statistical Corrector
268      XSDebug(p"---------tage${w} provided so that sc used---------\n")
269      XSDebug(p"scCtrs:$if4_scCtrs, prdrCtr:${if4_providerCtrs(w)}, sumAbs:$if4_sumAbs, tageTaken:${if4_chooseBit}\n")
270      when (!if4_sumBelowThresholds(if4_chooseBit)) {
271        when (ctrl.sc_enable) {
272          val pred = if4_scPreds(if4_chooseBit)
273          val debug_pc = Cat(packetIdx(debug_pc_s3), w.U, 0.U(instOffsetBits.W))
274          XSDebug(p"pc(${Hexadecimal(debug_pc)}) SC(${w.U}) overriden pred to ${pred}\n")
275          if4_agree(w) := if4_tageTakens(w) === pred
276          if4_disagree(w) := if4_tageTakens(w) =/= pred
277          io.resp.takens(w) := pred
278        }
279      }
280    }
281
282    val updateSCMeta = updateSCMetas(w)
283    val updateTageMeta = updateMetas(w)
284    when (updateValids(w) && updateSCMeta.scUsed.asBool) {
285      val scPred = updateSCMeta.scPred
286      val tagePred = updateSCMeta.tageTaken
287      val taken = u.takens(w)
288      val scOldCtrs = updateSCMeta.ctrs
289      val pvdrCtr = updateTageMeta.providerCtr
290      val sum = ParallelSingedExpandingAdd(scOldCtrs.map(getCentered)) +& getPvdrCentered(pvdrCtr)
291      val sumAbs = sum.abs.asUInt
292      scUpdateTagePreds(w) := tagePred
293      scUpdateTakens(w) := taken
294      (scUpdateOldCtrs(w) zip scOldCtrs).foreach{case (t, c) => t := c}
295
296      update_sc_used(w) := true.B
297      update_unconf(w) := sumAbs < useThresholds(w)
298      update_conf(w) := sumAbs >= useThresholds(w)
299      update_agree(w) := scPred === tagePred
300      update_disagree(w) := scPred =/= tagePred
301      sc_corr_tage_misp(w) := scPred === taken && tagePred =/= taken && update_conf(w)
302      sc_misp_tage_corr(w) := scPred =/= taken && tagePred === taken && update_conf(w)
303
304      val thres = useThresholds(w)
305      when (scPred =/= tagePred && sumAbs >= thres - 4.U && sumAbs <= thres - 2.U) {
306        val newThres = scThresholds(w).update(scPred =/= taken)
307        scThresholds(w) := newThres
308        XSDebug(p"scThres $w update: old ${useThresholds(w)} --> new ${newThres.thres}\n")
309      }
310
311      val updateThres = updateThresholds(w)
312      when (scPred =/= taken || sumAbs < updateThres) {
313        scUpdateMask.foreach(t => t(w) := true.B)
314        XSDebug(sum < 0.S,
315        p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " +
316        p"scSum(-$sumAbs), mispred: sc(${scPred =/= taken}), tage(${updateTageMisPreds(w)})\n"
317        )
318        XSDebug(sum >= 0.S,
319        p"scUpdate: bank(${w}), scPred(${scPred}), tagePred(${tagePred}), " +
320        p"scSum(+$sumAbs), mispred: sc(${scPred =/= taken}), tage(${updateTageMisPreds(w)})\n"
321        )
322        XSDebug(p"bank(${w}), update: sc: ${updateSCMeta}\n")
323        update_on_mispred(w) := scPred =/= taken
324        update_on_unconf(w) := scPred === taken
325      }
326    }
327  }
328
329  tage_perf("sc_conf", PopCount(if4_conf), PopCount(update_conf))
330  tage_perf("sc_unconf", PopCount(if4_unconf), PopCount(update_unconf))
331  tage_perf("sc_agree", PopCount(if4_agree), PopCount(update_agree))
332  tage_perf("sc_disagree", PopCount(if4_disagree), PopCount(update_disagree))
333  tage_perf("sc_used", PopCount(if4_sc_used), PopCount(update_sc_used))
334  XSPerfAccumulate("sc_update_on_mispred", PopCount(update_on_mispred))
335  XSPerfAccumulate("sc_update_on_unconf", PopCount(update_on_unconf))
336  XSPerfAccumulate("sc_mispred_but_tage_correct", PopCount(sc_misp_tage_corr))
337  XSPerfAccumulate("sc_correct_and_tage_wrong", PopCount(sc_corr_tage_misp))
338
339  for (i <- 0 until SCNTables) {
340    scTables(i).io.update.mask := RegNext(scUpdateMask(i))
341    scTables(i).io.update.tagePreds := RegNext(scUpdateTagePreds)
342    scTables(i).io.update.takens    := RegNext(scUpdateTakens)
343    scTables(i).io.update.oldCtrs   := RegNext(VecInit(scUpdateOldCtrs.map(_(i))))
344    scTables(i).io.update.pc := RegNext(u.ftqPC)
345    scTables(i).io.update.hist := RegNext(updateHist)
346  }
347}
348