xref: /XiangShan/src/main/scala/xiangshan/frontend/IFU.scala (revision cde9280d25efc101d8b0845edca84c1a95dea6e9)
1package xiangshan.frontend
2
3import chisel3._
4import chisel3.util._
5import device.RAMHelper
6import xiangshan._
7import utils._
8import xiangshan.cache._
9import chisel3.experimental.chiselName
10import freechips.rocketchip.tile.HasLazyRoCC
11import chisel3.ExcitingUtils._
12
13trait HasInstrMMIOConst extends HasXSParameter with HasIFUConst{
14  def mmioBusWidth = 64
15  def mmioBusBytes = mmioBusWidth /8
16  def mmioBeats = FetchWidth * 4 * 8 / mmioBusWidth
17  def mmioMask  = VecInit(List.fill(PredictWidth)(true.B)).asUInt
18  def mmioBusAligned(pc :UInt): UInt = align(pc, mmioBusBytes)
19}
20
21trait HasIFUConst extends HasXSParameter {
22  val resetVector = 0x10000000L//TODO: set reset vec
23  def align(pc: UInt, bytes: Int): UInt = Cat(pc(VAddrBits-1, log2Ceil(bytes)), 0.U(log2Ceil(bytes).W))
24  val groupBytes = 64 // correspond to cache line size
25  val groupOffsetBits = log2Ceil(groupBytes)
26  val groupWidth = groupBytes / instBytes
27  val packetBytes = PredictWidth * instBytes
28  val packetOffsetBits = log2Ceil(packetBytes)
29  def offsetInPacket(pc: UInt) = pc(packetOffsetBits-1, instOffsetBits)
30  def packetIdx(pc: UInt) = pc(VAddrBits-1, log2Ceil(packetBytes))
31  def groupAligned(pc: UInt)  = align(pc, groupBytes)
32  def packetAligned(pc: UInt) = align(pc, packetBytes)
33  def mask(pc: UInt): UInt = ((~(0.U(PredictWidth.W))) << offsetInPacket(pc))(PredictWidth-1,0)
34  def snpc(pc: UInt): UInt = packetAligned(pc) + packetBytes.U
35
36  val enableGhistRepair = true
37  val IFUDebug = true
38}
39
40class GlobalHistory extends XSBundle {
41  val predHist = UInt(HistoryLength.W)
42  def update(sawNTBr: Bool, takenOnBr: Bool, hist: UInt = predHist): GlobalHistory = {
43    val g = Wire(new GlobalHistory)
44    val shifted = takenOnBr || sawNTBr
45    g.predHist := Mux(shifted, (hist << 1) | takenOnBr.asUInt, hist)
46    g
47  }
48
49  final def === (that: GlobalHistory): Bool = {
50    predHist === that.predHist
51  }
52
53  final def =/= (that: GlobalHistory): Bool = !(this === that)
54
55  implicit val name = "IFU"
56  def debug(where: String) = XSDebug(p"[${where}_GlobalHistory] hist=${Binary(predHist)}\n")
57  // override def toString(): String = "histPtr=%d, sawNTBr=%d, takenOnBr=%d, saveHalfRVI=%d".format(histPtr, sawNTBr, takenOnBr, saveHalfRVI)
58}
59
60
61class IFUIO extends XSBundle
62{
63  // to ibuffer
64  val fetchPacket = DecoupledIO(new FetchPacket)
65  // from backend
66  val redirect = Flipped(ValidIO(UInt(VAddrBits.W)))
67  val cfiUpdateInfo = Flipped(ValidIO(new CfiUpdateInfo))
68  // to icache
69  val icacheMemGrant = Flipped(DecoupledIO(new L1plusCacheResp))
70  val fencei = Input(Bool())
71  // from icache
72  val icacheMemAcq = DecoupledIO(new L1plusCacheReq)
73  val l1plusFlush = Output(Bool())
74  val prefetchTrainReq = ValidIO(new IcacheMissReq)
75  // to tlb
76  val sfence = Input(new SfenceBundle)
77  val tlbCsr = Input(new TlbCsrBundle)
78  // from tlb
79  val ptw = new TlbPtwIO
80  // icache uncache
81  val mmio_acquire = DecoupledIO(new InsUncacheReq)
82  val mmio_grant  = Flipped(DecoupledIO(new InsUncacheResp))
83  val mmio_flush = Output(Bool())
84}
85
86class PrevHalfInstr extends XSBundle {
87  val taken = Bool()
88  val ghInfo = new GlobalHistory()
89  val fetchpc = UInt(VAddrBits.W) // only for debug
90  val idx = UInt(VAddrBits.W) // only for debug
91  val pc = UInt(VAddrBits.W)
92  val npc = UInt(VAddrBits.W)
93  val target = UInt(VAddrBits.W)
94  val instr = UInt(16.W)
95  val ipf = Bool()
96  val meta = new BpuMeta
97}
98
99@chiselName
100class IFU extends XSModule with HasIFUConst
101{
102  val io = IO(new IFUIO)
103  val bpu = BPU(EnableBPU)
104  val icache = Module(new ICache)
105
106  io.ptw <> TLB(
107    in = Seq(icache.io.tlb),
108    sfence = io.sfence,
109    csr = io.tlbCsr,
110    width = 1,
111    isDtlb = false,
112    shouldBlock = true
113  )
114
115  val if2_redirect, if3_redirect, if4_redirect = WireInit(false.B)
116  val if1_flush, if2_flush, if3_flush, if4_flush = WireInit(false.B)
117
118  val icacheResp = icache.io.resp.bits
119
120  if4_flush := io.redirect.valid
121  if3_flush := if4_flush || if4_redirect
122  if2_flush := if3_flush || if3_redirect
123  if1_flush := if2_flush || if2_redirect
124
125  //********************** IF1 ****************************//
126  val if1_valid = !reset.asBool && GTimer() > 500.U
127  val if1_npc = WireInit(0.U(VAddrBits.W))
128  val if2_ready = WireInit(false.B)
129  val if2_valid = RegInit(init = false.B)
130  val if2_allReady = WireInit(if2_ready && icache.io.req.ready)
131  val if1_fire = (if1_valid &&  if2_allReady) && (icache.io.tlb.resp.valid || !if2_valid)
132  val if1_can_go = if1_fire || if2_flush
133
134  val if1_gh, if2_gh, if3_gh, if4_gh = Wire(new GlobalHistory)
135  val if2_predicted_gh, if3_predicted_gh, if4_predicted_gh = Wire(new GlobalHistory)
136  val final_gh = RegInit(0.U.asTypeOf(new GlobalHistory))
137  val final_gh_bypass = WireInit(0.U.asTypeOf(new GlobalHistory))
138  val flush_final_gh = WireInit(false.B)
139
140  //********************** IF2 ****************************//
141  val if2_allValid = if2_valid && icache.io.tlb.resp.valid
142  val if3_ready = WireInit(false.B)
143  val if2_fire = (if2_valid && if3_ready) && icache.io.tlb.resp.valid
144  val if2_pc = RegEnable(next = if1_npc, init = resetVector.U, enable = if1_can_go)
145  val if2_snpc = snpc(if2_pc)
146  val if2_predHist = RegEnable(if1_gh.predHist, enable=if1_can_go)
147  if2_ready := if3_ready || !if2_valid
148  when (if1_can_go)       { if2_valid := true.B }
149  .elsewhen (if2_flush) { if2_valid := false.B }
150  .elsewhen (if2_fire)  { if2_valid := false.B }
151
152  val npcGen = new PriorityMuxGenerator[UInt]
153  npcGen.register(true.B, RegNext(if1_npc), Some("stallPC"))
154  val if2_bp = bpu.io.out(0)
155
156  // if taken, bp_redirect should be true
157  // when taken on half RVI, we suppress this redirect signal
158
159  npcGen.register(if2_valid, Mux(if2_bp.taken, if2_bp.target, if2_snpc), Some("if2_target"))
160
161  if2_predicted_gh := if2_gh.update(if2_bp.hasNotTakenBrs, if2_bp.takenOnBr)
162
163  //********************** IF3 ****************************//
164  // if3 should wait for instructions resp to arrive
165  val if3_valid = RegInit(init = false.B)
166  val if4_ready = WireInit(false.B)
167  val if3_allValid = if3_valid && icache.io.resp.valid
168  val if3_fire = if3_allValid && if4_ready
169  val if3_pc = RegEnable(if2_pc, if2_fire)
170  val if3_snpc = RegEnable(if2_snpc, if2_fire)
171  val if3_predHist = RegEnable(if2_predHist, enable=if2_fire)
172  if3_ready := if4_ready && icache.io.resp.valid || !if3_valid
173  when (if3_flush) {
174    if3_valid := false.B
175  }.elsewhen (if2_fire && !if2_flush) {
176    if3_valid := true.B
177  }.elsewhen (if3_fire) {
178    if3_valid := false.B
179  }
180
181  val if3_bp = bpu.io.out(1)
182  if3_predicted_gh := if3_gh.update(if3_bp.hasNotTakenBrs, if3_bp.takenOnBr)
183
184
185  val prevHalfInstrReq = WireInit(0.U.asTypeOf(ValidUndirectioned(new PrevHalfInstr)))
186  // only valid when if4_fire
187  val hasPrevHalfInstrReq = prevHalfInstrReq.valid && HasCExtension.B
188
189  val if3_prevHalfInstr = RegInit(0.U.asTypeOf(ValidUndirectioned(new PrevHalfInstr)))
190
191  // 32-bit instr crosses 2 pages, and the higher 16-bit triggers page fault
192  val crossPageIPF = WireInit(false.B)
193
194  val if3_pendingPrevHalfInstr = if3_prevHalfInstr.valid && HasCExtension.B
195
196  // the previous half of RVI instruction waits until it meets its last half
197  val if3_prevHalfInstrMet = if3_pendingPrevHalfInstr && if3_prevHalfInstr.bits.npc === if3_pc && if3_valid
198  // set to invalid once consumed or redirect from backend
199  val if3_prevHalfConsumed = if3_prevHalfInstrMet && if3_fire
200  val if3_prevHalfFlush = if4_flush
201  when (if3_prevHalfFlush) {
202    if3_prevHalfInstr.valid := false.B
203  }.elsewhen (hasPrevHalfInstrReq) {
204    if3_prevHalfInstr.valid := true.B
205  }.elsewhen (if3_prevHalfConsumed) {
206    if3_prevHalfInstr.valid := false.B
207  }
208  when (hasPrevHalfInstrReq) {
209    if3_prevHalfInstr.bits := prevHalfInstrReq.bits
210  }
211  // when bp signal a redirect, we distinguish between taken and not taken
212  // if taken and saveHalfRVI is true, we do not redirect to the target
213
214  class IF3_PC_COMP extends XSModule {
215    val io = IO(new Bundle {
216      val if2_pc = Input(UInt(VAddrBits.W))
217      val pc     = Input(UInt(VAddrBits.W))
218      val if2_valid = Input(Bool())
219      val res = Output(Bool())
220    })
221    io.res := !io.if2_valid || io.if2_valid && io.if2_pc =/= io.pc
222  }
223  def if3_nextValidPCNotEquals(pc: UInt) = {
224    val comp = Module(new IF3_PC_COMP)
225    comp.io.if2_pc := if2_pc
226    comp.io.pc     := pc
227    comp.io.if2_valid := if2_valid
228    comp.io.res
229  }
230
231  val if3_predTakenRedirectVec = VecInit((0 until PredictWidth).map(i => !if3_pendingPrevHalfInstr && if3_bp.realTakens(i) && if3_nextValidPCNotEquals(if3_bp.targets(i))))
232  val if3_prevHalfMetRedirect    = if3_pendingPrevHalfInstr && if3_prevHalfInstrMet && if3_prevHalfInstr.bits.taken && if3_nextValidPCNotEquals(if3_prevHalfInstr.bits.target)
233  val if3_prevHalfNotMetRedirect = if3_pendingPrevHalfInstr && !if3_prevHalfInstrMet && if3_nextValidPCNotEquals(if3_prevHalfInstr.bits.npc)
234  val if3_predTakenRedirect    = ParallelOR(if3_predTakenRedirectVec)
235  val if3_predNotTakenRedirect = !if3_pendingPrevHalfInstr && !if3_bp.taken && if3_nextValidPCNotEquals(if3_snpc)
236  // when pendingPrevHalfInstr, if3_GHInfo is set to the info of last prev half instr
237  // val if3_ghInfoNotIdenticalRedirect = !if3_pendingPrevHalfInstr && if3_GHInfo =/= if3_lastGHInfo && enableGhistRepair.B
238
239  if3_redirect := if3_valid && (
240                    // prevHalf is consumed but the next packet is not where it meant to be
241                    // we do not handle this condition because of the burden of building a correct GHInfo
242                    // prevHalfMetRedirect ||
243                    // prevHalf does not match if3_pc and the next fetch packet is not snpc
244                    if3_prevHalfNotMetRedirect && HasCExtension.B ||
245                    // pred taken and next fetch packet is not the predicted target
246                    if3_predTakenRedirect ||
247                    // pred not taken and next fetch packet is not snpc
248                    if3_predNotTakenRedirect
249                    // GHInfo from last pred does not corresponds with this packet
250                    // if3_ghInfoNotIdenticalRedirect
251                  )
252
253  val if3_target = WireInit(if3_snpc)
254
255  if3_target := Mux1H(Seq((if3_prevHalfNotMetRedirect -> if3_prevHalfInstr.bits.npc),
256                          (if3_predTakenRedirect      -> if3_bp.target),
257                          (if3_predNotTakenRedirect   -> if3_snpc)))
258
259  npcGen.register(if3_redirect, if3_target, Some("if3_target"))
260
261
262  //********************** IF4 ****************************//
263  val if4_pd = RegEnable(icache.io.pd_out, if3_fire)
264  val if4_ipf = RegEnable(icacheResp.ipf || if3_prevHalfInstrMet && if3_prevHalfInstr.bits.ipf, if3_fire)
265  val if4_acf = RegEnable(icacheResp.acf, if3_fire)
266  val if4_crossPageIPF = RegEnable(crossPageIPF, if3_fire)
267  val if4_valid = RegInit(false.B)
268  val if4_fire = if4_valid && io.fetchPacket.ready
269  val if4_pc = RegEnable(if3_pc, if3_fire)
270  val if4_snpc = RegEnable(if3_snpc, if3_fire)
271  // This is the real mask given from icache
272  val if4_mask = RegEnable(icacheResp.mask, if3_fire)
273
274
275  val if4_predHist = RegEnable(if3_predHist, enable=if3_fire)
276  // wait until prevHalfInstr written into reg
277  if4_ready := (io.fetchPacket.ready && !hasPrevHalfInstrReq || !if4_valid) && GTimer() > 500.U
278  when (if4_flush) {
279    if4_valid := false.B
280  }.elsewhen (if3_fire && !if3_flush) {
281    if4_valid := Mux(if3_pendingPrevHalfInstr, if3_prevHalfInstrMet, true.B)
282  }.elsewhen (if4_fire) {
283    if4_valid := false.B
284  }
285
286  val if4_bp = Wire(new BranchPrediction)
287  if4_bp := bpu.io.out(2)
288
289  if4_predicted_gh := if4_gh.update(if4_bp.hasNotTakenBrs, if4_bp.takenOnBr)
290
291  def jal_offset(inst: UInt, rvc: Bool): SInt = {
292    Mux(rvc,
293      Cat(inst(12), inst(8), inst(10, 9), inst(6), inst(7), inst(2), inst(11), inst(5, 3), 0.U(1.W)).asSInt(),
294      Cat(inst(31), inst(19, 12), inst(20), inst(30, 21), 0.U(1.W)).asSInt()
295    )
296  }
297  val if4_instrs = if4_pd.instrs
298  val if4_jals = if4_bp.jalMask
299  val if4_jal_tgts = VecInit((0 until PredictWidth).map(i => (if4_pd.pc(i).asSInt + jal_offset(if4_instrs(i), if4_pd.pd(i).isRVC)).asUInt))
300
301  (0 until PredictWidth).foreach {i =>
302    when (if4_jals(i)) {
303      if4_bp.targets(i) := if4_jal_tgts(i)
304    }
305  }
306
307  // we need this to tell BPU the prediction of prev half
308  // because the prediction is with the start of each inst
309  val if4_prevHalfInstr = RegInit(0.U.asTypeOf(ValidUndirectioned(new PrevHalfInstr)))
310  val if4_pendingPrevHalfInstr = if4_prevHalfInstr.valid && HasCExtension.B
311  val if4_prevHalfInstrMet = if4_pendingPrevHalfInstr && if4_valid
312  val if4_prevHalfConsumed = if4_prevHalfInstrMet && if4_fire
313  val if4_prevHalfFlush = if4_flush
314
315  val if4_takenPrevHalf = WireInit(if4_prevHalfInstrMet && if4_prevHalfInstr.bits.taken)
316  when (if4_prevHalfFlush) {
317    if4_prevHalfInstr.valid := false.B
318  }.elsewhen (if3_prevHalfConsumed) {
319    if4_prevHalfInstr.valid := if3_prevHalfInstr.valid
320  }.elsewhen (if4_prevHalfConsumed) {
321    if4_prevHalfInstr.valid := false.B
322  }
323
324  when (if3_prevHalfConsumed) {
325    if4_prevHalfInstr.bits := if3_prevHalfInstr.bits
326  }
327
328  prevHalfInstrReq.valid := if4_fire && if4_bp.saveHalfRVI && HasCExtension.B
329  val idx = if4_bp.lastHalfRVIIdx
330
331  // // this is result of the last half RVI
332  prevHalfInstrReq.bits.taken := if4_bp.lastHalfRVITaken
333  prevHalfInstrReq.bits.ghInfo := if4_gh
334  prevHalfInstrReq.bits.fetchpc := if4_pc
335  prevHalfInstrReq.bits.idx := idx
336  prevHalfInstrReq.bits.pc := if4_pd.pc(idx)
337  prevHalfInstrReq.bits.npc := if4_pd.pc(idx) + 2.U
338  prevHalfInstrReq.bits.target := if4_bp.lastHalfRVITarget
339  prevHalfInstrReq.bits.instr := if4_pd.instrs(idx)(15, 0)
340  prevHalfInstrReq.bits.ipf := if4_ipf
341  prevHalfInstrReq.bits.meta := bpu.io.bpuMeta(idx)
342
343  class IF4_PC_COMP extends XSModule {
344    val io = IO(new Bundle {
345      val if2_pc = Input(UInt(VAddrBits.W))
346      val if3_pc = Input(UInt(VAddrBits.W))
347      val pc     = Input(UInt(VAddrBits.W))
348      val if2_valid = Input(Bool())
349      val if3_valid = Input(Bool())
350      val res = Output(Bool())
351    })
352    io.res := io.if3_valid  && io.if3_pc =/= io.pc ||
353              !io.if3_valid && (io.if2_valid && io.if2_pc =/= io.pc) ||
354              !io.if3_valid && !io.if2_valid
355  }
356  def if4_nextValidPCNotEquals(pc: UInt) = {
357    val comp = Module(new IF4_PC_COMP)
358    comp.io.if2_pc := if2_pc
359    comp.io.if3_pc := if3_pc
360    comp.io.pc     := pc
361    comp.io.if2_valid := if2_valid
362    comp.io.if3_valid := if3_valid
363    comp.io.res
364  }
365
366  val if4_predTakenRedirectVec = VecInit((0 until PredictWidth).map(i => if4_bp.realTakens(i) && if4_nextValidPCNotEquals(if4_bp.targets(i))))
367
368  val if4_prevHalfNextNotMet = hasPrevHalfInstrReq && if4_nextValidPCNotEquals(prevHalfInstrReq.bits.pc+2.U)
369  val if4_predTakenRedirect = ParallelORR(if4_predTakenRedirectVec)
370  val if4_predNotTakenRedirect = !if4_bp.taken && if4_nextValidPCNotEquals(if4_snpc)
371  // val if4_ghInfoNotIdenticalRedirect = if4_GHInfo =/= if4_lastGHInfo && enableGhistRepair.B
372
373  if4_redirect := if4_valid && (
374                    // when if4 has a lastHalfRVI, but the next fetch packet is not snpc
375                    // if4_prevHalfNextNotMet ||
376                    // when if4 preds taken, but the pc of next fetch packet is not the target
377                    if4_predTakenRedirect ||
378                    // when if4 preds not taken, but the pc of next fetch packet is not snpc
379                    if4_predNotTakenRedirect
380                    // GHInfo from last pred does not corresponds with this packet
381                    // if4_ghInfoNotIdenticalRedirect
382                  )
383
384  val if4_target = WireInit(if4_snpc)
385
386  if4_target := Mux(if4_bp.taken, if4_bp.target, if4_snpc)
387
388  npcGen.register(if4_redirect, if4_target, Some("if4_target"))
389
390  when (if4_fire) {
391    final_gh := if4_predicted_gh
392  }
393  if4_gh := Mux(flush_final_gh, final_gh_bypass, final_gh)
394  if3_gh := Mux(if4_valid && !if4_flush, if4_predicted_gh, if4_gh)
395  if2_gh := Mux(if3_valid && !if3_flush, if3_predicted_gh, if3_gh)
396  if1_gh := Mux(if2_valid && !if2_flush, if2_predicted_gh, if2_gh)
397
398
399
400
401  val cfiUpdate = io.cfiUpdateInfo
402  when (cfiUpdate.valid && (cfiUpdate.bits.isMisPred || cfiUpdate.bits.isReplay)) {
403    val b = cfiUpdate.bits
404    val oldGh = b.bpuMeta.hist
405    val sawNTBr = b.bpuMeta.sawNotTakenBranch
406    val isBr = b.pd.isBr
407    val taken = Mux(cfiUpdate.bits.isReplay, b.bpuMeta.predTaken, b.taken)
408    val updatedGh = oldGh.update(sawNTBr, isBr && taken)
409    final_gh := updatedGh
410    final_gh_bypass := updatedGh
411    flush_final_gh := true.B
412  }
413
414  npcGen.register(io.redirect.valid, io.redirect.bits, Some("backend_redirect"))
415  npcGen.register(RegNext(reset.asBool) && !reset.asBool, resetVector.U(VAddrBits.W), Some("reset_vector"))
416
417  if1_npc := npcGen()
418
419
420  icache.io.req.valid := if1_can_go
421  icache.io.resp.ready := if4_ready
422  icache.io.req.bits.addr := if1_npc
423  icache.io.req.bits.mask := mask(if1_npc)
424  icache.io.flush := Cat(if3_flush, if2_flush)
425  icache.io.mem_grant <> io.icacheMemGrant
426  icache.io.fencei := io.fencei
427  icache.io.prev.valid := if3_prevHalfInstrMet
428  icache.io.prev.bits := if3_prevHalfInstr.bits.instr
429  icache.io.prev_ipf := if3_prevHalfInstr.bits.ipf
430  icache.io.prev_pc := if3_prevHalfInstr.bits.pc
431  icache.io.mmio_acquire <> io.mmio_acquire
432  icache.io.mmio_grant <> io.mmio_grant
433  icache.io.mmio_flush <> io.mmio_flush
434  io.icacheMemAcq <> icache.io.mem_acquire
435  io.l1plusFlush := icache.io.l1plusflush
436  io.prefetchTrainReq := icache.io.prefetchTrainReq
437
438  bpu.io.cfiUpdateInfo <> io.cfiUpdateInfo
439
440  bpu.io.inFire(0) := if1_can_go
441  bpu.io.inFire(1) := if2_fire
442  bpu.io.inFire(2) := if3_fire
443  bpu.io.inFire(3) := if4_fire
444  bpu.io.in.pc := if1_npc
445  bpu.io.in.hist := if1_gh.asUInt
446  bpu.io.in.inMask := mask(if1_npc)
447  bpu.io.predecode.mask := if4_pd.mask
448  bpu.io.predecode.lastHalf := if4_pd.lastHalf
449  bpu.io.predecode.pd := if4_pd.pd
450  bpu.io.predecode.hasLastHalfRVI := if4_prevHalfInstrMet
451  bpu.io.realMask := if4_mask
452  bpu.io.prevHalf := if4_prevHalfInstr
453
454
455  when (if3_prevHalfInstrMet && icacheResp.ipf && !if3_prevHalfInstr.bits.ipf) {
456    crossPageIPF := true.B // higher 16 bits page fault
457  }
458
459  val fetchPacketValid = if4_valid && !io.redirect.valid
460  val fetchPacketWire = Wire(new FetchPacket)
461
462  fetchPacketWire.instrs := if4_pd.instrs
463  fetchPacketWire.mask := if4_pd.mask & (Fill(PredictWidth, !if4_bp.taken) | (Fill(PredictWidth, 1.U(1.W)) >> (~if4_bp.jmpIdx)))
464  fetchPacketWire.pdmask := if4_pd.mask
465
466  fetchPacketWire.pc := if4_pd.pc
467  (0 until PredictWidth).foreach(i => fetchPacketWire.pnpc(i) := if4_pd.pc(i) + Mux(if4_pd.pd(i).isRVC, 2.U, 4.U))
468  when (if4_bp.taken) {
469    fetchPacketWire.pnpc(if4_bp.jmpIdx) := if4_bp.target
470  }
471  fetchPacketWire.bpuMeta := bpu.io.bpuMeta
472  // save it for update
473  when (if4_pendingPrevHalfInstr) {
474    fetchPacketWire.bpuMeta(0) := if4_prevHalfInstr.bits.meta
475  }
476  (0 until PredictWidth).foreach(i => {
477    val meta = fetchPacketWire.bpuMeta(i)
478    meta.hist := final_gh
479    meta.predHist := if4_predHist.asTypeOf(new GlobalHistory)
480    meta.predTaken := if4_bp.takens(i)
481  })
482  fetchPacketWire.pd := if4_pd.pd
483  fetchPacketWire.ipf := if4_ipf
484  fetchPacketWire.acf := if4_acf
485  fetchPacketWire.crossPageIPFFix := if4_crossPageIPF
486
487  // predTaken Vec
488  fetchPacketWire.predTaken := if4_bp.taken
489
490  io.fetchPacket.bits := fetchPacketWire
491  io.fetchPacket.valid := fetchPacketValid
492
493//  if(IFUDebug) {
494    val predictor_s3 = RegEnable(Mux(if3_redirect, 1.U(log2Up(4).W), 0.U(log2Up(4).W)), if3_fire)
495    val predictor_s4 = Mux(if4_redirect, 2.U, predictor_s3)
496    val predictor = predictor_s4
497
498    fetchPacketWire.bpuMeta.map(_.predictor := predictor)
499 // }
500
501  // val predRight = cfiUpdate.valid && !cfiUpdate.bits.isMisPred && !cfiUpdate.bits.isReplay
502  // val predWrong = cfiUpdate.valid && cfiUpdate.bits.isMisPred && !cfiUpdate.bits.isReplay
503
504  // val ubtbRight = predRight && cfiUpdate.bits.bpuMeta.predictor === 0.U
505  // val ubtbWrong = predWrong && cfiUpdate.bits.bpuMeta.predictor === 0.U
506  // val btbRight  = predRight && cfiUpdate.bits.bpuMeta.predictor === 1.U
507  // val btbWrong  = predWrong && cfiUpdate.bits.bpuMeta.predictor === 1.U
508  // val tageRight = predRight && cfiUpdate.bits.bpuMeta.predictor === 2.U
509  // val tageWrong = predWrong && cfiUpdate.bits.bpuMeta.predictor === 2.U
510  // val loopRight = predRight && cfiUpdate.bits.bpuMeta.predictor === 3.U
511  // val loopWrong = predWrong && cfiUpdate.bits.bpuMeta.predictor === 3.U
512
513  // ExcitingUtils.addSource(ubtbRight, "perfCntubtbRight", Perf)
514  // ExcitingUtils.addSource(ubtbWrong, "perfCntubtbWrong", Perf)
515  // ExcitingUtils.addSource(btbRight, "perfCntbtbRight", Perf)
516  // ExcitingUtils.addSource(btbWrong, "perfCntbtbWrong", Perf)
517  // ExcitingUtils.addSource(tageRight, "perfCnttageRight", Perf)
518  // ExcitingUtils.addSource(tageWrong, "perfCnttageWrong", Perf)
519  // ExcitingUtils.addSource(loopRight, "perfCntloopRight", Perf)
520  // ExcitingUtils.addSource(loopWrong, "perfCntloopWrong", Perf)
521
522  // debug info
523  if (IFUDebug) {
524    XSDebug(RegNext(reset.asBool) && !reset.asBool, "Reseting...\n")
525    XSDebug(icache.io.flush(0).asBool, "Flush icache stage2...\n")
526    XSDebug(icache.io.flush(1).asBool, "Flush icache stage3...\n")
527    XSDebug(io.redirect.valid, p"Redirect from backend! target=${Hexadecimal(io.redirect.bits)}\n")
528
529    XSDebug("[IF1] v=%d     fire=%d  cango=%d          flush=%d pc=%x mask=%b\n", if1_valid, if1_fire,if1_can_go, if1_flush, if1_npc, mask(if1_npc))
530    XSDebug("[IF2] v=%d r=%d fire=%d redirect=%d flush=%d pc=%x snpc=%x\n", if2_valid, if2_ready, if2_fire, if2_redirect, if2_flush, if2_pc, if2_snpc)
531    XSDebug("[IF3] v=%d r=%d fire=%d redirect=%d flush=%d pc=%x crossPageIPF=%d sawNTBrs=%d\n", if3_valid, if3_ready, if3_fire, if3_redirect, if3_flush, if3_pc, crossPageIPF, if3_bp.hasNotTakenBrs)
532    XSDebug("[IF4] v=%d r=%d fire=%d redirect=%d flush=%d pc=%x crossPageIPF=%d sawNTBrs=%d\n", if4_valid, if4_ready, if4_fire, if4_redirect, if4_flush, if4_pc, if4_crossPageIPF, if4_bp.hasNotTakenBrs)
533    XSDebug("[predictor] predictor_s3=%d, predictor_s4=%d, predictor=%d\n", predictor_s3, predictor_s4, predictor)
534    XSDebug("[IF1][icacheReq] v=%d r=%d addr=%x\n", icache.io.req.valid, icache.io.req.ready, icache.io.req.bits.addr)
535    XSDebug("[IF1][ghr] hist=%b\n", if1_gh.asUInt)
536    XSDebug("[IF1][ghr] extHist=%b\n\n", if1_gh.asUInt)
537
538    XSDebug("[IF2][bp] taken=%d jmpIdx=%d hasNTBrs=%d target=%x saveHalfRVI=%d\n\n", if2_bp.taken, if2_bp.jmpIdx, if2_bp.hasNotTakenBrs, if2_bp.target, if2_bp.saveHalfRVI)
539    if2_gh.debug("if2")
540
541    XSDebug("[IF3][icacheResp] v=%d r=%d pc=%x mask=%b\n", icache.io.resp.valid, icache.io.resp.ready, icache.io.resp.bits.pc, icache.io.resp.bits.mask)
542    XSDebug("[IF3][bp] taken=%d jmpIdx=%d hasNTBrs=%d target=%x saveHalfRVI=%d\n", if3_bp.taken, if3_bp.jmpIdx, if3_bp.hasNotTakenBrs, if3_bp.target, if3_bp.saveHalfRVI)
543    XSDebug("[IF3][redirect]: v=%d, prevMet=%d, prevNMet=%d, predT=%d, predNT=%d\n", if3_redirect, if3_prevHalfMetRedirect, if3_prevHalfNotMetRedirect, if3_predTakenRedirect, if3_predNotTakenRedirect)
544    // XSDebug("[IF3][prevHalfInstr] v=%d redirect=%d fetchpc=%x idx=%d tgt=%x taken=%d instr=%x\n\n",
545    //   prev_half_valid, prev_half_redirect, prev_half_fetchpc, prev_half_idx, prev_half_tgt, prev_half_taken, prev_half_instr)
546    XSDebug("[IF3][if3_prevHalfInstr] v=%d taken=%d fetchpc=%x idx=%d pc=%x npc=%x tgt=%x instr=%x ipf=%d\n\n",
547    if3_prevHalfInstr.valid, if3_prevHalfInstr.bits.taken, if3_prevHalfInstr.bits.fetchpc, if3_prevHalfInstr.bits.idx, if3_prevHalfInstr.bits.pc, if3_prevHalfInstr.bits.npc, if3_prevHalfInstr.bits.target, if3_prevHalfInstr.bits.instr, if3_prevHalfInstr.bits.ipf)
548    if3_gh.debug("if3")
549
550    XSDebug("[IF4][predecode] mask=%b\n", if4_pd.mask)
551    XSDebug("[IF4][snpc]: %x, realMask=%b\n", if4_snpc, if4_mask)
552    XSDebug("[IF4][bp] taken=%d jmpIdx=%d hasNTBrs=%d target=%x saveHalfRVI=%d\n", if4_bp.taken, if4_bp.jmpIdx, if4_bp.hasNotTakenBrs, if4_bp.target, if4_bp.saveHalfRVI)
553    XSDebug("[IF4][redirect]: v=%d, prevNotMet=%d, predT=%d, predNT=%d\n", if4_redirect, if4_prevHalfNextNotMet, if4_predTakenRedirect, if4_predNotTakenRedirect)
554    XSDebug(if4_pd.pd(if4_bp.jmpIdx).isJal && if4_bp.taken, "[IF4] cfi is jal!  instr=%x target=%x\n", if4_instrs(if4_bp.jmpIdx), if4_jal_tgts(if4_bp.jmpIdx))
555    XSDebug("[IF4][ prevHalfInstrReq] v=%d taken=%d fetchpc=%x idx=%d pc=%x npc=%x tgt=%x instr=%x ipf=%d\n",
556      prevHalfInstrReq.valid, prevHalfInstrReq.bits.taken, prevHalfInstrReq.bits.fetchpc, prevHalfInstrReq.bits.idx, prevHalfInstrReq.bits.pc, prevHalfInstrReq.bits.npc, prevHalfInstrReq.bits.target, prevHalfInstrReq.bits.instr, prevHalfInstrReq.bits.ipf)
557    XSDebug("[IF4][if4_prevHalfInstr] v=%d taken=%d fetchpc=%x idx=%d pc=%x npc=%x tgt=%x instr=%x ipf=%d\n",
558      if4_prevHalfInstr.valid, if4_prevHalfInstr.bits.taken, if4_prevHalfInstr.bits.fetchpc, if4_prevHalfInstr.bits.idx, if4_prevHalfInstr.bits.pc, if4_prevHalfInstr.bits.npc, if4_prevHalfInstr.bits.target, if4_prevHalfInstr.bits.instr, if4_prevHalfInstr.bits.ipf)
559    if4_gh.debug("if4")
560    XSDebug(io.fetchPacket.fire(), "[IF4][fetchPacket] v=%d r=%d mask=%b ipf=%d acf=%d crossPageIPF=%d\n",
561      io.fetchPacket.valid, io.fetchPacket.ready, io.fetchPacket.bits.mask, io.fetchPacket.bits.ipf, io.fetchPacket.bits.acf, io.fetchPacket.bits.crossPageIPFFix)
562    for (i <- 0 until PredictWidth) {
563      XSDebug(io.fetchPacket.fire(), "[IF4][fetchPacket] %b %x pc=%x pnpc=%x pd: rvc=%d brType=%b call=%d ret=%d\n",
564        io.fetchPacket.bits.mask(i),
565        io.fetchPacket.bits.instrs(i),
566        io.fetchPacket.bits.pc(i),
567        io.fetchPacket.bits.pnpc(i),
568        io.fetchPacket.bits.pd(i).isRVC,
569        io.fetchPacket.bits.pd(i).brType,
570        io.fetchPacket.bits.pd(i).isCall,
571        io.fetchPacket.bits.pd(i).isRet
572      )
573    }
574  }
575}
576