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