ITTAGE.scala 28.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/***************************************************************************************
  * Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
  * Copyright (c) 2020-2021 Peng Cheng Laboratory
  *
  * XiangShan is licensed under Mulan PSL v2.
  * You can use this software according to the terms and conditions of the Mulan PSL v2.
  * You may obtain a copy of Mulan PSL v2 at:
  *          http://license.coscl.org.cn/MulanPSL2
  *
  * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
  * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
  * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
  *
  * See the Mulan PSL v2 for more details.
  ***************************************************************************************/

package xiangshan.frontend

import chipsalliance.rocketchip.config.Parameters
import chisel3._
import chisel3.util._
import xiangshan._
import utils._
import chisel3.experimental.chiselName
import chisel3.stage.{ChiselGeneratorAnnotation, ChiselStage}
import firrtl.stage.RunFirrtlTransformAnnotation
import firrtl.transforms.RenameModules
import freechips.rocketchip.transforms.naming.RenameDesiredNames

import scala.math.min
import scala.util.matching.Regex
32
import firrtl.passes.wiring.Wiring
33 34

trait ITTageParams extends HasXSParameter with HasBPUParameter {
35 36

  val ITTageNTables = ITTageTableInfos.size // Number of tage tables
37
  val UBitPeriod = 2048
38
  val ITTageCtrBits = 2
39
  val uFoldedWidth = 16
40
  val TickWidth = 8
41 42 43 44 45 46 47
  def ctr_null(ctr: UInt, ctrBits: Int = ITTageCtrBits) = {
    ctr === 0.U
  }
  def ctr_unconf(ctr: UInt, ctrBits: Int = ITTageCtrBits) = {
    ctr < (1 << (ctrBits-1)).U
  }
  val UAONA_bits = 4
48

49
  val TotalBits = ITTageTableInfos.map {
50
    case (s, h, t) => {
51
      s * (1+t+ITTageCtrBits+VAddrBits)
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
    }
  }.reduce(_+_)
}
// reuse TAGE implementation

trait ITTageHasFoldedHistory {
  val histLen: Int
  def compute_folded_hist(hist: UInt, l: Int) = {
    if (histLen > 0) {
      val nChunks = (histLen + l - 1) / l
      val hist_chunks = (0 until nChunks) map {i =>
        hist(min((i+1)*l, histLen)-1, i*l)
      }
      ParallelXOR(hist_chunks)
    }
    else 0.U
  }
}



abstract class ITTageBundle(implicit p: Parameters)
  extends XSBundle with ITTageParams with BPUUtils

abstract class ITTageModule(implicit p: Parameters)
  extends XSModule with ITTageParams with BPUUtils
{}


class ITTageReq(implicit p: Parameters) extends ITTageBundle {
  val pc = UInt(VAddrBits.W)
83
  val folded_hist = new AllFoldedHistories(foldedGHistInfos)
84 85 86 87 88 89 90 91 92 93
}

class ITTageResp(implicit p: Parameters) extends ITTageBundle {
  val ctr = UInt(ITTageCtrBits.W)
  val u = UInt(2.W)
  val target = UInt(VAddrBits.W)
}

class ITTageUpdate(implicit p: Parameters) extends ITTageBundle {
  val pc = UInt(VAddrBits.W)
94
  val folded_hist = new AllFoldedHistories(foldedGHistInfos)
95
  // update tag and ctr
96 97 98 99
  val valid = Bool()
  val correct = Bool()
  val alloc = Bool()
  val oldCtr = UInt(ITTageCtrBits.W)
100
  // update u
101
  val uValid = Bool()
102 103
  val u = Bool()
  val reset_u = Bool()
104 105 106
  // target
  val target = UInt(VAddrBits.W)
  val old_target = UInt(VAddrBits.W)
107 108 109 110 111 112
}

// reuse TAGE Implementation

class ITTageMeta(implicit p: Parameters) extends XSBundle with ITTageParams{
  val provider = ValidUndirectioned(UInt(log2Ceil(ITTageNTables).W))
113
  val altProvider = ValidUndirectioned(UInt(log2Ceil(ITTageNTables).W))
114
  val altDiffers = Bool()
115
  val providerU = Bool()
116 117
  val providerCtr = UInt(ITTageCtrBits.W)
  val altProviderCtr = UInt(ITTageCtrBits.W)
118 119
  val allocate = ValidUndirectioned(UInt(log2Ceil(ITTageNTables).W))
  val taken = Bool()
120 121
  val providerTarget = UInt(VAddrBits.W)
  val altProviderTarget = UInt(VAddrBits.W)
122 123
  // val scMeta = new SCMeta(EnableSC)
  // TODO: check if we need target info here
124
  val pred_cycle = if (!env.FPGAPlatform) Some(UInt(64.W)) else None
125

126 127 128
  override def toPrintable = {
    p"pvdr(v:${provider.valid} num:${provider.bits} ctr:$providerCtr u:$providerU tar:${Hexadecimal(providerTarget)}), " +
    p"altpvdr(v:${altProvider.valid} num:${altProvider.bits}, ctr:$altProviderCtr, tar:${Hexadecimal(altProviderTarget)}), " +
129
    p"altdiff:$altDiffers, alloc(v:${allocate.valid} num:${allocate.bits}), taken:$taken, cycle:${pred_cycle.getOrElse(0.U)}"
130
  }
131 132 133 134 135 136
}


class FakeITTageTable()(implicit p: Parameters) extends ITTageModule {
  val io = IO(new Bundle() {
    val req = Input(Valid(new ITTageReq))
137
    val resp = Output(Valid(new ITTageResp))
138 139 140 141 142 143 144 145 146 147 148 149
    val update = Input(new ITTageUpdate)
  })
  io.resp := DontCare

}
@chiselName
class ITTageTable
(
  val nRows: Int, val histLen: Int, val tagLen: Int, val uBitPeriod: Int, val tableIdx: Int
)(implicit p: Parameters)
  extends ITTageModule with HasFoldedHistory {
  val io = IO(new Bundle() {
150
    val req = Flipped(DecoupledIO(new ITTageReq))
151
    val resp = Output(Valid(new ITTageResp))
152 153 154
    val update = Input(new ITTageUpdate)
  })

155 156 157 158 159 160 161 162 163 164 165 166
  val SRAM_SIZE=128
  val nBanks = 2
  val bankSize = nRows / nBanks
  val bankFoldWidth = if (bankSize >= SRAM_SIZE) bankSize / SRAM_SIZE else 1

  if (bankSize < SRAM_SIZE) {
    println(f"warning: ittage table $tableIdx has small sram depth of $bankSize")
  }
  val bankIdxWidth = log2Ceil(nBanks)
  def get_bank_mask(idx: UInt) = VecInit((0 until nBanks).map(idx(bankIdxWidth-1, 0) === _.U))
  def get_bank_idx(idx: UInt) = idx >> bankIdxWidth

167 168 169 170
  // override val debug = true
  // bypass entries for tage update
  val wrBypassEntries = 4

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  require(histLen == 0 && tagLen == 0 || histLen != 0 && tagLen != 0)
  val idxFhInfo = (histLen, min(log2Ceil(nRows), histLen))
  val tagFhInfo = (histLen, min(histLen, tagLen))
  val altTagFhInfo = (histLen, min(histLen, tagLen-1))
  val allFhInfos = Seq(idxFhInfo, tagFhInfo, altTagFhInfo)

  def getFoldedHistoryInfo = allFhInfos.filter(_._1 >0).toSet

  def compute_tag_and_hash(unhashed_idx: UInt, allFh: AllFoldedHistories) = {
    if (histLen > 0) {
      val idx_fh = allFh.getHistWithInfo(idxFhInfo).folded_hist
      val tag_fh = allFh.getHistWithInfo(tagFhInfo).folded_hist
      val alt_tag_fh = allFh.getHistWithInfo(altTagFhInfo).folded_hist
      // require(idx_fh.getWidth == log2Ceil(nRows))
      val idx = (unhashed_idx ^ idx_fh)(log2Ceil(nRows)-1, 0)
      val tag = ((unhashed_idx >> log2Ceil(nRows)) ^ tag_fh ^ (alt_tag_fh << 1)) (tagLen - 1, 0)
      (idx, tag)
    }
    else {
      require(tagLen == 0)
      (unhashed_idx(log2Ceil(nRows)-1, 0), 0.U)
    }
193 194 195 196 197
  }

  def inc_ctr(ctr: UInt, taken: Bool): UInt = satUpdate(ctr, ITTageCtrBits, taken)

  class ITTageEntry() extends ITTageBundle {
198
    // val valid = Bool()
199 200 201 202 203
    val tag = UInt(tagLen.W)
    val ctr = UInt(ITTageCtrBits.W)
    val target = UInt(VAddrBits.W)
  }

204 205
  val validArray = RegInit(0.U(nRows.W))

206 207 208 209 210 211 212 213 214 215
  // Why need add instOffsetBits?
  val ittageEntrySz = 1 + tagLen + ITTageCtrBits + VAddrBits

  // pc is start address of basic block, most 2 branch inst in block
  // def getUnhashedIdx(pc: UInt) = pc >> (instOffsetBits+log2Ceil(TageBanks))
  def getUnhashedIdx(pc: UInt): UInt = pc >> instOffsetBits

  val s0_pc = io.req.bits.pc
  val s0_unhashed_idx = getUnhashedIdx(io.req.bits.pc)

216
  val (s0_idx, s0_tag) = compute_tag_and_hash(s0_unhashed_idx, io.req.bits.folded_hist)
217 218 219 220 221 222 223 224 225 226 227 228 229
  val (s1_idx, s1_tag) = (RegEnable(s0_idx, io.req.fire), RegEnable(s0_tag, io.req.fire))
  val s0_bank_req_1h = get_bank_mask(s0_idx)
  val s1_bank_req_1h = RegEnable(s0_bank_req_1h, io.req.fire)
  
  val us = Module(new Folded1WDataModuleTemplate(Bool(), nRows, 1, isSync=true, width=uFoldedWidth))
  // val table  = Module(new SRAMTemplate(new ITTageEntry, set=nRows, way=1, shouldReset=true, holdRead=true, singlePort=false))
  val table_banks = Seq.fill(nBanks)(
    Module(new FoldedSRAMTemplate(new ITTageEntry, set=nRows/nBanks, width=bankFoldWidth, shouldReset=false, holdRead=true, singlePort=true)))

  for (b <- 0 until nBanks) {
    table_banks(b).io.r.req.valid := io.req.fire && s0_bank_req_1h(b)
    table_banks(b).io.r.req.bits.setIdx := get_bank_idx(s0_idx)
  }
230

231
  us.io.raddr(0) := s0_idx
232

233
  val table_banks_r = table_banks.map(_.io.r.resp.data(0))
234

235 236
  val resp_selected = Mux1H(s1_bank_req_1h, table_banks_r)
  val s1_req_rhit = validArray(s1_idx) && resp_selected.tag === s1_tag
237 238

  io.resp.valid := (if (tagLen != 0) s1_req_rhit else true.B) // && s1_mask(b)
239
  io.resp.bits.ctr := resp_selected.ctr
240
  io.resp.bits.u := us.io.rdata(0)
241 242
  io.resp.bits.target := resp_selected.target

243 244 245


  // Use fetchpc to compute hash
246
  val (update_idx, update_tag) = compute_tag_and_hash(getUnhashedIdx(io.update.pc), io.update.folded_hist)
247 248
  val update_req_bank_1h = get_bank_mask(update_idx)
  val update_idx_in_bank = get_bank_idx(update_idx)
249
  val update_target = io.update.target
250
  val update_wdata = Wire(new ITTageEntry)
251 252 253 254 255 256 257 258 259
  
  for (b <- 0 until nBanks) {
    table_banks(b).io.w.apply(
      valid   = io.update.valid && update_req_bank_1h(b),
      data    = update_wdata,
      setIdx  = update_idx_in_bank,
      waymask = true.B
    )
  }
260

261
  val bank_conflict = (0 until nBanks).map(b => table_banks(b).io.w.req.valid && s0_bank_req_1h(b)).reduce(_||_)
262
  io.req.ready := !io.update.valid
L
Lingrui98 已提交
263
  // io.req.ready := !bank_conflict
264
  XSPerfAccumulate(f"ittage_table_bank_conflict", bank_conflict)
265

266 267 268
  us.io.wen := io.update.uValid
  us.io.waddr := update_idx
  us.io.wdata := io.update.u
269

L
Lingrui98 已提交
270
  val wrbypass = Module(new WrBypass(UInt(ITTageCtrBits.W), wrBypassEntries, log2Ceil(nRows), tagWidth=tagLen))
271

L
Lingrui98 已提交
272 273 274 275
  wrbypass.io.wen := io.update.valid
  wrbypass.io.write_idx := update_idx
  wrbypass.io.write_tag.map(_ := update_tag)
  wrbypass.io.write_data.map(_ := update_wdata.ctr)
276

L
Lingrui98 已提交
277
  val old_ctr = Mux(wrbypass.io.hit, wrbypass.io.hit_data(0).bits, io.update.oldCtr)
278 279 280 281
  update_wdata.ctr   := Mux(io.update.alloc, 2.U, inc_ctr(old_ctr, io.update.correct))
  update_wdata.tag   := update_tag
  // only when ctr is null
  update_wdata.target := Mux(ctr_null(old_ctr), update_target, io.update.old_target)
282 283 284 285 286 287
  
  val newValidArray = VecInit(validArray.asBools)
  when (io.update.valid) {
    newValidArray(update_idx) := true.B
    validArray := newValidArray.asUInt
  }
288

289 290 291 292
  // reset all us in 32 cycles
  us.io.resetEn.map(_ := io.update.reset_u)

  XSPerfAccumulate("ittage_table_updates", io.update.valid)
293
  XSPerfAccumulate("ittage_table_hits", io.resp.valid)
294 295 296 297 298

  if (BPUDebug && debug) {
    val u = io.update
    val idx = s0_idx
    val tag = s0_tag
299
    XSDebug(io.req.fire,
300
      p"ITTageTableReq: pc=0x${Hexadecimal(io.req.bits.pc)}, " +
301
      p"idx=$idx, tag=$tag\n")
302
    XSDebug(RegNext(io.req.fire) && s1_req_rhit,
303 304 305
      p"ITTageTableResp: idx=$s1_idx, hit:${s1_req_rhit}, " +
      p"ctr:${io.resp.bits.ctr}, u:${io.resp.bits.u}, tar:${Hexadecimal(io.resp.bits.target)}\n")
    XSDebug(io.update.valid,
306
      p"update ITTAGE Table: pc:${Hexadecimal(u.pc)}}, " +
307 308 309 310 311 312
      p"correct:${u.correct}, alloc:${u.alloc}, oldCtr:${u.oldCtr}, " +
      p"target:${Hexadecimal(u.target)}, old_target:${Hexadecimal(u.old_target)}\n")
    XSDebug(io.update.valid,
      p"update ITTAGE Table: writing tag:${update_tag}, " +
      p"ctr: ${update_wdata.ctr}, target:${Hexadecimal(update_wdata.target)}" +
      p" in idx $update_idx\n")
313
    XSDebug(RegNext(io.req.fire) && !s1_req_rhit, "TageTableResp: no hits!\n")
314 315 316


    // ------------------------------Debug-------------------------------------
317 318 319 320
    val valids = RegInit(0.U.asTypeOf(Vec(nRows, Bool())))
    when (io.update.valid) { valids(update_idx) := true.B }
    XSDebug("ITTAGE Table usage:------------------------\n")
    XSDebug("%d out of %d rows are valid\n", PopCount(valids), nRows.U)
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
  }

}

abstract class BaseITTage(implicit p: Parameters) extends BasePredictor with ITTageParams with BPUUtils {
  // class TAGEResp {
  //   val takens = Vec(PredictWidth, Bool())
  //   val hits = Vec(PredictWidth, Bool())
  // }
  // class TAGEMeta {
  // }
  // class FromBIM {
  //   val ctrs = Vec(PredictWidth, UInt(2.W))
  // }
  // class TageIO extends DefaultBasePredictorIO {
  //   val resp = Output(new TAGEResp)
  //   val meta = Output(Vec(PredictWidth, new TageMeta))
  //   val bim = Input(new FromBIM)
  //   val s2Fire = Input(Bool())
  // }

  // override val io = IO(new TageIO)
}

class FakeITTage(implicit p: Parameters) extends BaseITTage {
  io.out <> 0.U.asTypeOf(DecoupledIO(new BasePredictorOutput))

  // io.s0_ready := true.B
  io.s1_ready := true.B
  io.s2_ready := true.B
}
// TODO: check target related logics
@chiselName
class ITTage(implicit p: Parameters) extends BaseITTage {
355
  override val meta_size = 0.U.asTypeOf(new ITTageMeta).getWidth
356

357
  val tables = ITTageTableInfos.zipWithIndex.map {
358 359 360 361 362
    case ((nRows, histLen, tagLen), i) =>
      // val t = if(EnableBPD) Module(new TageTable(nRows, histLen, tagLen, UBitPeriod)) else Module(new FakeTageTable)
      val t = Module(new ITTageTable(nRows, histLen, tagLen, UBitPeriod, i))
      t.io.req.valid := io.s0_fire
      t.io.req.bits.pc := s0_pc
363
      t.io.req.bits.folded_hist := io.in.bits.folded_hist
364 365
      t
  }
366
  override def getFoldedHistoryInfo = Some(tables.map(_.getFoldedHistoryInfo).reduce(_++_))
367

368 369

  val useAltOnNa = RegInit((1 << (UAONA_bits-1)).U(UAONA_bits.W))
370
  val tickCtr = RegInit(0.U(TickWidth.W))
371

372 373 374
  // Keep the table responses to process in s2

  val s1_resps = VecInit(tables.map(t => t.io.resp))
375
  val base_table_resp = s1_resps(0)
376

377
  val s1_bim = io.in.bits.resp_in(0).s1.full_pred
378 379
  val s2_bim = RegEnable(s1_bim, enable=io.s1_fire)

380
  val debug_pc_s1 = RegEnable(s0_pc, enable=io.s0_fire)
381 382
  val debug_pc_s2 = RegEnable(debug_pc_s1, enable=io.s1_fire)

383 384 385 386 387 388 389 390 391
  val s1_tageTaken         = Wire(Bool())
  val s1_tageTarget        = Wire(UInt(VAddrBits.W))
  val s1_providerTarget    = Wire(UInt(VAddrBits.W))
  val s1_altProviderTarget = Wire(UInt(VAddrBits.W))
  val s1_provided          = Wire(Bool())
  val s1_provider          = Wire(UInt(log2Ceil(ITTageNTables).W))
  val s1_altProvided       = Wire(Bool())
  val s1_altProvider       = Wire(UInt(log2Ceil(ITTageNTables).W))
  val s1_finalAltPred      = Wire(Bool())
392
  val s1_providerU         = Wire(Bool())
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
  val s1_providerCtr       = Wire(UInt(ITTageCtrBits.W))
  val s1_altProviderCtr    = Wire(UInt(ITTageCtrBits.W))

  val s2_tageTaken         = RegEnable(s1_tageTaken, io.s1_fire)
  val s2_tageTarget        = RegEnable(s1_tageTarget, io.s1_fire)
  val s2_providerTarget    = RegEnable(s1_providerTarget, io.s1_fire)
  val s2_altProviderTarget = RegEnable(s1_altProviderTarget, io.s1_fire)
  val s2_provided          = RegEnable(s1_provided, io.s1_fire)
  val s2_provider          = RegEnable(s1_provider, io.s1_fire)
  val s2_altProvided       = RegEnable(s1_altProvided, io.s1_fire)
  val s2_altProvider       = RegEnable(s1_altProvider, io.s1_fire)
  val s2_finalAltPred      = RegEnable(s1_finalAltPred, io.s1_fire)
  val s2_providerU         = RegEnable(s1_providerU, io.s1_fire)
  val s2_providerCtr       = RegEnable(s1_providerCtr, io.s1_fire)
  val s2_altProviderCtr    = RegEnable(s1_altProviderCtr, io.s1_fire)
408 409

  // val updateBank = u.pc(log2Ceil(TageBanks)+instOffsetBits-1, instOffsetBits)
410
  val resp_meta = WireInit(0.U.asTypeOf(new ITTageMeta))
411 412

  io.out.resp := io.in.bits.resp_in(0)
L
Lingrui98 已提交
413
  io.out.last_stage_meta := RegEnable(resp_meta.asUInt, io.s2_fire)
414

415
  val ftb_hit = io.in.bits.resp_in(0).s2.full_pred.hit
416 417 418 419 420 421
  val ftb_entry = io.in.bits.resp_in(0).s2.ftb_entry
  val resp_s2 = io.out.resp.s2

  // Update logic
  val u_valid = io.update.valid
  val update = io.update.bits
422
  val updateValid =
423
    update.ftb_entry.isJalr && u_valid && update.ftb_entry.jmpValid &&
424
    !(update.full_pred.real_br_taken_mask().reduce(_||_))
425
  val updateFhist = update.folded_hist
426 427

  // meta is splited by composer
428 429 430 431
  val updateMeta = update.meta.asTypeOf(new ITTageMeta)

  val updateMask      = WireInit(0.U.asTypeOf(Vec(ITTageNTables, Bool())))
  val updateUMask     = WireInit(0.U.asTypeOf(Vec(ITTageNTables, Bool())))
432
  val updateResetU    = WireInit(false.B)
433 434 435 436 437
  val updateCorrect   = Wire(Vec(ITTageNTables, Bool()))
  val updateTarget    = Wire(Vec(ITTageNTables, UInt(VAddrBits.W)))
  val updateOldTarget = Wire(Vec(ITTageNTables, UInt(VAddrBits.W)))
  val updateAlloc     = Wire(Vec(ITTageNTables, Bool()))
  val updateOldCtr    = Wire(Vec(ITTageNTables, UInt(ITTageCtrBits.W)))
438
  val updateU         = Wire(Vec(ITTageNTables, Bool()))
439
  updateCorrect   := DontCare
440
  updateTarget  := DontCare
441
  updateOldTarget  := DontCare
442 443 444 445 446
  updateAlloc   := DontCare
  updateOldCtr  := DontCare
  updateU       := DontCare

  // val updateTageMisPreds = VecInit((0 until numBr).map(i => updateMetas(i).taken =/= u.takens(i)))
447
  val updateMisPred = update.mispred_mask(numBr) // the last one indicates jmp results
448
  // access tag tables and output meta info
L
Lingrui98 已提交
449 450
  class ITTageTableInfo(implicit p: Parameters) extends ITTageResp {
    val tableIdx = UInt(log2Ceil(ITTageNTables).W)
451
  }
L
Lingrui98 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
  val inputRes = VecInit(s1_resps.zipWithIndex.map{case (r, i) => {
    val tableInfo = Wire(new ITTageTableInfo)
    tableInfo.u := r.bits.u
    tableInfo.ctr := r.bits.ctr
    tableInfo.target := r.bits.target
    tableInfo.tableIdx := i.U(log2Ceil(ITTageNTables).W)
    SelectTwoInterRes(r.valid, tableInfo)
  }}.init)

  val selectedInfo = ParallelSelectTwo(inputRes.reverse)
  val provided = selectedInfo.hasOne
  val altProvided = selectedInfo.hasTwo
  val providerInfo = selectedInfo.first
  val altProviderInfo = selectedInfo.second
  val providerNull = providerInfo.ctr === 0.U
  
  val basePred   = base_table_resp.bits.ctr =/= 0.U
  val baseTarget = base_table_resp.bits.target
  
  s1_tageTaken := Mux1H(Seq(
    (provided && !providerNull, providerInfo.ctr(ITTageCtrBits-1)),
    (altProvided && providerNull, altProviderInfo.ctr(ITTageCtrBits-1)),
    (!provided, basePred)
  )) // TODO: reintroduce BIM
  s1_tageTarget := Mux1H(Seq(
    (provided && !providerNull, providerInfo.target),
    (altProvided && providerNull, altProviderInfo.target),
    (!provided, baseTarget)
  ))
  s1_finalAltPred := Mux(altProvided, altProviderInfo.ctr(ITTageCtrBits-1), basePred)
  s1_provided       := provided
  s1_provider       := providerInfo.tableIdx
  s1_altProvided    := altProvided
  s1_altProvider    := altProviderInfo.tableIdx
  s1_providerU      := providerInfo.u
  s1_providerCtr    := providerInfo.ctr
  s1_altProviderCtr := altProviderInfo.ctr
  s1_providerTarget := providerInfo.target
  s1_altProviderTarget := altProviderInfo.target
491 492

  XSDebug(io.s2_fire, p"hit_taken_jalr:")
L
Lingrui98 已提交
493
  when(s2_tageTaken) {
494
    io.out.resp.s2.full_pred.jalr_target := s2_tageTarget
L
Lingrui98 已提交
495 496 497 498 499 500
  }

  val s3_tageTaken = RegEnable(s2_tageTaken, io.s2_fire)
  val s3_tageTarget = RegEnable(s2_tageTarget, io.s2_fire)
  when(s3_tageTaken) {
    io.out.resp.s3.full_pred.jalr_target := s3_tageTarget
501
  }
L
Lingrui98 已提交
502
  // this is handled in RAS
503 504 505
  // val is_jalr = io.in.bits.resp_in(0).s2.full_pred.is_jalr
  // val last_target_in = io.in.bits.resp_in(0).s2.full_pred.targets.last
  // val last_target_out = io.out.resp.s2.full_pred.targets.last
L
Lingrui98 已提交
506
  // last_target_out := Mux(is_jalr, jalr_target, last_target_in)
507

508 509 510 511
  resp_meta.provider.valid    := s2_provided
  resp_meta.provider.bits     := s2_provider
  resp_meta.altProvider.valid := s2_altProvided
  resp_meta.altProvider.bits  := s2_altProvider
512
  resp_meta.altDiffers        := s2_finalAltPred =/= s2_tageTaken || s1_altProviderTarget =/= s2_providerTarget
513 514 515 516 517 518
  resp_meta.providerU         := s2_providerU
  resp_meta.providerCtr       := s2_providerCtr
  resp_meta.altProviderCtr    := s2_altProviderCtr
  resp_meta.taken             := s2_tageTaken
  resp_meta.providerTarget    := s2_providerTarget
  resp_meta.altProviderTarget := s2_altProviderTarget
519
  resp_meta.pred_cycle.map(_:= GTimer())
520 521 522
  // TODO: adjust for ITTAGE
  // Create a mask fo tables which did not hit our query, and also contain useless entries
  // and also uses a longer history than the provider
523
  val allocatableSlots = RegEnable(VecInit(s1_resps.map(r => !r.valid && !r.bits.u)).asUInt &
524 525 526 527 528 529 530 531 532 533 534 535 536 537
    ~(LowerMask(UIntToOH(s1_provider), ITTageNTables) & Fill(ITTageNTables, s1_provided.asUInt)), io.s1_fire
  )
  val allocLFSR   = LFSR64()(ITTageNTables - 1, 0)
  val firstEntry  = PriorityEncoder(allocatableSlots)
  val maskedEntry = PriorityEncoder(allocatableSlots & allocLFSR)
  val allocEntry  = Mux(allocatableSlots(maskedEntry), maskedEntry, firstEntry)
  resp_meta.allocate.valid := allocatableSlots =/= 0.U
  resp_meta.allocate.bits  := allocEntry

  // Update in loop
  val updateRealTarget = update.full_target
  when (updateValid) {
    when (updateMeta.provider.valid) {
      val provider = updateMeta.provider.bits
538
      XSDebug(true.B, p"update provider $provider, pred cycle ${updateMeta.pred_cycle.getOrElse(0.U)}\n")
539 540 541
      val altProvider = updateMeta.altProvider.bits
      val usedAltpred = updateMeta.altProvider.valid && updateMeta.providerCtr === 0.U
      when (usedAltpred && updateMisPred) { // update altpred if used as pred
542
        XSDebug(true.B, p"update altprovider $altProvider, pred cycle ${updateMeta.pred_cycle.getOrElse(0.U)}\n")
543 544 545 546 547 548 549 550

        updateMask(altProvider)    := true.B
        updateUMask(altProvider)   := false.B
        updateCorrect(altProvider) := false.B
        updateOldCtr(altProvider)  := updateMeta.altProviderCtr
        updateAlloc(altProvider)   := false.B
        updateTarget(altProvider)  := updateRealTarget
        updateOldTarget(altProvider) := updateMeta.altProviderTarget
551
      }
552 553 554 555 556


      updateMask(provider)   := true.B
      updateUMask(provider)  := true.B

557
      updateU(provider) := Mux(!updateMeta.altDiffers, updateMeta.providerU, !updateMisPred)
558 559 560 561 562
      updateCorrect(provider)  := updateMeta.providerTarget === updateRealTarget
      updateTarget(provider) := updateRealTarget
      updateOldTarget(provider) := updateMeta.providerTarget
      updateOldCtr(provider) := updateMeta.providerCtr
      updateAlloc(provider)  := false.B
563
    }
564 565 566 567 568 569
  }

  // update base table if used base table to predict
  when (updateValid) {
    val useBaseTableAsAltPred = updateMeta.provider.valid && !updateMeta.altProvider.valid && updateMeta.providerCtr === 0.U
    val usedBaseTable = !updateMeta.provider.valid || useBaseTableAsAltPred
570
    XSDebug(usedBaseTable, p"update base table, pred cycle ${updateMeta.pred_cycle.getOrElse(0.U)}\n")
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
    updateMask(0) := usedBaseTable
    updateCorrect(0) := !updateMisPred
    updateTarget(0) := updateRealTarget
    updateOldTarget(0) := Mux(useBaseTableAsAltPred,
      updateMeta.altProviderTarget, updateMeta.providerTarget)
    updateOldCtr(0) := Mux(useBaseTableAsAltPred,
      updateMeta.altProviderCtr, updateMeta.providerCtr)
    updateAlloc(0) := false.B
    updateUMask(0) := false.B
  }

  // if mispredicted and not the case that
  // provider offered correct target but used altpred due to unconfident
  val providerCorrect = updateMeta.provider.valid && updateMeta.providerTarget === updateRealTarget
  val providerUnconf = updateMeta.providerCtr === 0.U
  when (updateValid && updateMisPred && !(providerCorrect && providerUnconf)) {
    val allocate = updateMeta.allocate
588
    tickCtr := satUpdate(tickCtr, TickWidth, allocate.valid)
589
    when (allocate.valid) {
590
      XSDebug(true.B, p"allocate new table entry, pred cycle ${updateMeta.pred_cycle.getOrElse(0.U)}\n")
591 592 593 594 595
      updateMask(allocate.bits)  := true.B
      updateCorrect(allocate.bits) := true.B // useless for alloc
      updateTarget(allocate.bits) := updateRealTarget
      updateAlloc(allocate.bits) := true.B
      updateUMask(allocate.bits) := true.B
596
      updateU(allocate.bits) := false.B
597 598 599 600 601 602 603
    }.otherwise {

      val provider = updateMeta.provider
      val decrMask = Mux(provider.valid, ~LowerMask(UIntToOH(provider.bits), ITTageNTables), 0.U(ITTageNTables.W))
      for (i <- 0 until ITTageNTables) {
        when (decrMask(i)) {
          updateUMask(i) := true.B
604
          updateU(i) := false.B
605 606
        }
      }
607 608 609 610 611 612
    } 
  }

  when (tickCtr === ((1 << TickWidth) - 1).U) {
    tickCtr := 0.U
    updateResetU := true.B
613 614
  }

615 616
  XSPerfAccumulate(s"ittage_reset_u", updateResetU)
  
617 618 619
  /*
  val fallThruAddr = getFallThroughAddr(s2_pc, ftb_entry.carry, ftb_entry.pftAddr)
  when(ftb_hit) {
620 621
    io.out.resp.s2.full_pred.target := Mux(resp_s2.full_pred.is_jalr & ftb_entry.isJalr,
      resp_s2.full_pred.target,
622 623 624 625 626
      Mux(ftb_entry.jmpValid, ftb_entry.jmpTarget, fallThruAddr))
  }*/


  for (i <- 0 until ITTageNTables) {
627 628 629 630 631 632 633
    tables(i).io.update.valid := RegNext(updateMask(i))
    tables(i).io.update.correct := RegNext(updateCorrect(i))
    tables(i).io.update.target := RegNext(updateTarget(i))
    tables(i).io.update.old_target := RegNext(updateOldTarget(i))
    tables(i).io.update.alloc := RegNext(updateAlloc(i))
    tables(i).io.update.oldCtr := RegNext(updateOldCtr(i))

634
    tables(i).io.update.reset_u := RegNext(updateResetU)
635 636 637
    tables(i).io.update.uValid := RegNext(updateUMask(i))
    tables(i).io.update.u := RegNext(updateU(i))
    tables(i).io.update.pc := RegNext(update.pc)
638
    // use fetch pc instead of instruction pc
639
    tables(i).io.update.folded_hist := RegNext(updateFhist)
640 641
  }

642 643 644
  // all should be ready for req
  io.s1_ready := tables.map(_.io.req.ready).reduce(_&&_)
  XSPerfAccumulate(f"ittage_write_blocks_read", !io.s1_ready)
645 646
  // Debug and perf info

647 648 649 650 651
  def pred_perf(name: String, cond: Bool)   = XSPerfAccumulate(s"${name}_at_pred", cond && io.s2_fire)
  def commit_perf(name: String, cond: Bool) = XSPerfAccumulate(s"${name}_at_commit", cond && updateValid)
  def ittage_perf(name: String, pred_cond: Bool, commit_cond: Bool) = {
    pred_perf(s"ittage_${name}", pred_cond)
    commit_perf(s"ittage_${name}", commit_cond)
652
  }
653 654 655 656 657 658 659 660 661 662 663 664
  val pred_use_provider = s2_provided && !ctr_null(s2_providerCtr)
  val pred_use_altpred = s2_provided && ctr_null(s2_providerCtr)
  val pred_use_ht_as_altpred = pred_use_altpred && s2_altProvided
  val pred_use_bim_as_altpred = pred_use_altpred && !s2_altProvided
  val pred_use_bim_as_pred = !s2_provided

  val commit_use_provider = updateMeta.provider.valid && !ctr_null(updateMeta.providerCtr)
  val commit_use_altpred = updateMeta.provider.valid && ctr_null(updateMeta.providerCtr)
  val commit_use_ht_as_altpred = commit_use_altpred && updateMeta.altProvider.valid
  val commit_use_bim_as_altpred = commit_use_altpred && !updateMeta.altProvider.valid
  val commit_use_bim_as_pred = !updateMeta.provider.valid

665
  for (i <- 0 until ITTageNTables) {
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
    val pred_this_is_provider = s2_provider === i.U
    val pred_this_is_altpred  = s2_altProvider === i.U
    val commit_this_is_provider = updateMeta.provider.bits === i.U
    val commit_this_is_altpred  = updateMeta.altProvider.bits === i.U
    ittage_perf(s"table_${i}_final_provided",
      pred_use_provider && pred_this_is_provider,
      commit_use_provider && commit_this_is_provider
    )
    ittage_perf(s"table_${i}_provided_not_used",
      pred_use_altpred && pred_this_is_provider,
      commit_use_altpred && commit_this_is_provider
    )
    ittage_perf(s"table_${i}_alt_provider_as_final_pred",
      pred_use_ht_as_altpred && pred_this_is_altpred,
      commit_use_ht_as_altpred && commit_this_is_altpred
    )
    ittage_perf(s"table_${i}_alt_provider_not_used",
      pred_use_provider && pred_this_is_altpred,
      commit_use_provider && commit_this_is_altpred
    )
686
  }
687 688 689 690 691 692 693 694 695

  ittage_perf("provided", s2_provided, updateMeta.provider.valid)
  ittage_perf("use_provider", pred_use_provider, commit_use_provider)
  ittage_perf("use_altpred", pred_use_altpred, commit_use_altpred)
  ittage_perf("use_ht_as_altpred", pred_use_ht_as_altpred, commit_use_ht_as_altpred)
  ittage_perf("use_bim_when_no_provider", pred_use_bim_as_pred, commit_use_bim_as_pred)
  ittage_perf("use_bim_as_alt_provider", pred_use_bim_as_altpred, commit_use_bim_as_altpred)
  // XSPerfAccumulate("ittage_provider_right")
  XSPerfAccumulate("updated", updateValid)
696 697

  if (debug) {
698 699 700 701
    // for (b <- 0 until ITTageBanks) {
    //   val m = updateMetas(b)
    //   // val bri = u.metas(b)
    //   XSDebug(updateValids(b), "update(%d): pc=%x, cycle=%d, hist=%x, taken:%b, misPred:%d, bimctr:%d, pvdr(%d):%d, altDiff:%d, pvdrU:%d, pvdrCtr:%d, alloc(%d):%d\n",
702
    //     b.U, update.pc, 0.U, updateHist.predHist, update.full_pred.taken_mask(b), update.mispred_mask(b),
703 704 705
    //     0.U, m.provider.valid, m.provider.bits, m.altDiffers, m.providerU, m.providerCtr, m.allocate.valid, m.allocate.bits
    //   )
    // }
706
    val s2_resps = RegEnable(s1_resps, io.s1_fire)
707 708 709
    XSDebug("req: v=%d, pc=0x%x\n", io.s0_fire, s0_pc)
    XSDebug("s1_fire:%d, resp: pc=%x\n", io.s1_fire, debug_pc_s1)
    XSDebug("s2_fireOnLastCycle: resp: pc=%x, target=%x, hit=%b, taken=%b\n",
710
      debug_pc_s2, io.out.resp.s2.getTarget, s2_provided, s2_tageTaken)
711
    for (i <- 0 until ITTageNTables) {
712 713 714
      XSDebug("TageTable(%d): valids:%b, resp_ctrs:%b, resp_us:%b, target:%x\n",
        i.U, VecInit(s2_resps(i).valid).asUInt, s2_resps(i).bits.ctr,
        s2_resps(i).bits.u, s2_resps(i).bits.target)
715 716
    }
  }
717 718 719
  XSDebug(updateValid, p"pc: ${Hexadecimal(update.pc)}, target: ${Hexadecimal(update.full_target)}\n")
  XSDebug(updateValid, updateMeta.toPrintable+p"\n")
  XSDebug(updateValid, p"correct(${!updateMisPred})\n")
720 721

  generatePerfEvent()
722 723 724 725
}


// class Tage_SC(implicit p: Parameters) extends Tage with HasSC {}