xref: /XiangShan/src/main/scala/xiangshan/frontend/Frontend.scala (revision 211d620b07edb797ba35b635d24fef4e7294bae2)
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
18import chisel3._
19import chisel3.util._
20import freechips.rocketchip.diplomacy.LazyModule
21import freechips.rocketchip.diplomacy.LazyModuleImp
22import org.chipsalliance.cde.config.Parameters
23import utility._
24import xiangshan._
25import xiangshan.backend.fu.PFEvent
26import xiangshan.backend.fu.PMP
27import xiangshan.backend.fu.PMPChecker
28import xiangshan.backend.fu.PMPReqBundle
29import xiangshan.cache.mmu._
30import xiangshan.frontend.icache._
31
32class Frontend()(implicit p: Parameters) extends LazyModule with HasXSParameter {
33  override def shouldBeInlined: Boolean = false
34  val inner       = LazyModule(new FrontendInlined)
35  lazy val module = new FrontendImp(this)
36}
37
38class FrontendImp(wrapper: Frontend)(implicit p: Parameters) extends LazyModuleImp(wrapper) {
39  val io      = IO(wrapper.inner.module.io.cloneType)
40  val io_perf = IO(wrapper.inner.module.io_perf.cloneType)
41  io <> wrapper.inner.module.io
42  io_perf <> wrapper.inner.module.io_perf
43  if (p(DebugOptionsKey).ResetGen) {
44    ResetGen(ResetGenNode(Seq(ModuleNode(wrapper.inner.module))), reset, sim = false)
45  }
46}
47
48class FrontendInlined()(implicit p: Parameters) extends LazyModule with HasXSParameter {
49  override def shouldBeInlined: Boolean = true
50
51  val instrUncache = LazyModule(new InstrUncache())
52  val icache       = LazyModule(new ICache())
53
54  lazy val module = new FrontendInlinedImp(this)
55}
56
57class FrontendInlinedImp(outer: FrontendInlined) extends LazyModuleImp(outer)
58    with HasXSParameter
59    with HasPerfEvents {
60  val io = IO(new Bundle() {
61    val hartId       = Input(UInt(hartIdLen.W))
62    val reset_vector = Input(UInt(PAddrBits.W))
63    val fencei       = Input(Bool())
64    val ptw          = new TlbPtwIO()
65    val backend      = new FrontendToCtrlIO
66    val softPrefetch = Vec(backendParams.LduCnt, Flipped(Valid(new SoftIfetchPrefetchBundle)))
67    val sfence       = Input(new SfenceBundle)
68    val tlbCsr       = Input(new TlbCsrBundle)
69    val csrCtrl      = Input(new CustomCSRCtrlIO)
70    val error        = ValidIO(new L1CacheErrorInfo)
71    val frontendInfo = new Bundle {
72      val ibufFull = Output(Bool())
73      val bpuInfo = new Bundle {
74        val bpRight = Output(UInt(XLEN.W))
75        val bpWrong = Output(UInt(XLEN.W))
76      }
77    }
78    val resetInFrontend = Output(Bool())
79    val debugTopDown = new Bundle {
80      val robHeadVaddr = Flipped(Valid(UInt(VAddrBits.W)))
81    }
82  })
83
84  // decouped-frontend modules
85  val instrUncache = outer.instrUncache.module
86  val icache       = outer.icache.module
87  val bpu          = Module(new Predictor)
88  val ifu          = Module(new NewIFU)
89  val ibuffer      = Module(new IBuffer)
90  val ftq          = Module(new Ftq)
91
92  val needFlush            = RegNext(io.backend.toFtq.redirect.valid)
93  val FlushControlRedirect = RegNext(io.backend.toFtq.redirect.bits.debugIsCtrl)
94  val FlushMemVioRedirect  = RegNext(io.backend.toFtq.redirect.bits.debugIsMemVio)
95  val FlushControlBTBMiss  = Wire(Bool())
96  val FlushTAGEMiss        = Wire(Bool())
97  val FlushSCMiss          = Wire(Bool())
98  val FlushITTAGEMiss      = Wire(Bool())
99  val FlushRASMiss         = Wire(Bool())
100
101  val tlbCsr  = DelayN(io.tlbCsr, 2)
102  val csrCtrl = DelayN(io.csrCtrl, 2)
103  val sfence  = RegNext(RegNext(io.sfence))
104
105  // trigger
106  ifu.io.frontendTrigger := csrCtrl.frontend_trigger
107
108  // bpu ctrl
109  bpu.io.ctrl         := csrCtrl.bp_ctrl
110  bpu.io.reset_vector := io.reset_vector
111
112// pmp
113  val PortNumber = ICacheParameters().PortNumber
114  val pmp        = Module(new PMP())
115  val pmp_check  = VecInit(Seq.fill(coreParams.ipmpPortNum)(Module(new PMPChecker(3, sameCycle = true)).io))
116  pmp.io.distribute_csr := csrCtrl.distribute_csr
117  val pmp_req_vec = Wire(Vec(coreParams.ipmpPortNum, Valid(new PMPReqBundle())))
118  (0 until 2 * PortNumber).foreach(i => pmp_req_vec(i) <> icache.io.pmp(i).req)
119  pmp_req_vec.last <> ifu.io.pmp.req
120
121  for (i <- pmp_check.indices) {
122    pmp_check(i).apply(tlbCsr.priv.imode, pmp.io.pmp, pmp.io.pma, pmp_req_vec(i))
123  }
124  (0 until 2 * PortNumber).foreach(i => icache.io.pmp(i).resp <> pmp_check(i).resp)
125  ifu.io.pmp.resp <> pmp_check.last.resp
126
127  val itlb =
128    Module(new TLB(coreParams.itlbPortNum, nRespDups = 1, Seq.fill(PortNumber)(false) ++ Seq(true), itlbParams))
129  itlb.io.requestor.take(PortNumber) zip icache.io.itlb foreach { case (a, b) => a <> b }
130  itlb.io.requestor.last <> ifu.io.iTLBInter // mmio may need re-tlb, blocked
131  itlb.io.hartId := io.hartId
132  itlb.io.base_connect(sfence, tlbCsr)
133  itlb.io.flushPipe.map(_ := needFlush)
134  itlb.io.redirect := DontCare // itlb has flushpipe, don't need redirect signal
135
136  val itlb_ptw = Wire(new VectorTlbPtwIO(coreParams.itlbPortNum))
137  itlb_ptw.connect(itlb.io.ptw)
138  val itlbRepeater1 = PTWFilter(itlbParams.fenceDelay, itlb_ptw, sfence, tlbCsr, l2tlbParams.ifilterSize)
139  val itlbRepeater2 =
140    PTWRepeaterNB(passReady = false, itlbParams.fenceDelay, itlbRepeater1.io.ptw, io.ptw, sfence, tlbCsr)
141
142  icache.io.ftqPrefetch <> ftq.io.toPrefetch
143  icache.io.softPrefetch <> io.softPrefetch
144
145  // IFU-Ftq
146  ifu.io.ftqInter.fromFtq <> ftq.io.toIfu
147  ftq.io.toIfu.req.ready := ifu.io.ftqInter.fromFtq.req.ready && icache.io.fetch.req.ready
148
149  ftq.io.fromIfu <> ifu.io.ftqInter.toFtq
150  bpu.io.ftq_to_bpu <> ftq.io.toBpu
151  ftq.io.fromBpu <> bpu.io.bpu_to_ftq
152
153  ftq.io.mmioCommitRead <> ifu.io.mmioCommitRead
154  // IFU-ICache
155
156  icache.io.fetch.req <> ftq.io.toICache.req
157  ftq.io.toICache.req.ready := ifu.io.ftqInter.fromFtq.req.ready && icache.io.fetch.req.ready
158
159  ifu.io.icacheInter.resp <> icache.io.fetch.resp
160  ifu.io.icacheInter.icacheReady       := icache.io.toIFU
161  ifu.io.icacheInter.topdownIcacheMiss := icache.io.fetch.topdownIcacheMiss
162  ifu.io.icacheInter.topdownItlbMiss   := icache.io.fetch.topdownItlbMiss
163  icache.io.stop                       := ifu.io.icacheStop
164  icache.io.flush                      := ftq.io.icacheFlush
165
166  ifu.io.icachePerfInfo := icache.io.perfInfo
167
168  icache.io.csr_pf_enable     := RegNext(csrCtrl.l1I_pf_enable)
169  icache.io.csr_parity_enable := RegNext(csrCtrl.icache_parity_enable)
170
171  icache.io.fencei := RegNext(io.fencei)
172
173  // IFU-Ibuffer
174  ifu.io.toIbuffer <> ibuffer.io.in
175
176  ftq.io.fromBackend <> io.backend.toFtq
177  io.backend.fromFtq := ftq.io.toBackend
178  io.backend.fromIfu := ifu.io.toBackend
179  io.frontendInfo.bpuInfo <> ftq.io.bpuInfo
180
181  val checkPcMem = Reg(Vec(FtqSize, new Ftq_RF_Components))
182  when(ftq.io.toBackend.pc_mem_wen) {
183    checkPcMem(ftq.io.toBackend.pc_mem_waddr) := ftq.io.toBackend.pc_mem_wdata
184  }
185
186  val checkTargetIdx = Wire(Vec(DecodeWidth, UInt(log2Up(FtqSize).W)))
187  val checkTarget    = Wire(Vec(DecodeWidth, UInt(VAddrBits.W)))
188
189  for (i <- 0 until DecodeWidth) {
190    checkTargetIdx(i) := ibuffer.io.out(i).bits.ftqPtr.value
191    checkTarget(i) := Mux(
192      ftq.io.toBackend.newest_entry_ptr.value === checkTargetIdx(i),
193      ftq.io.toBackend.newest_entry_target,
194      checkPcMem(checkTargetIdx(i) + 1.U).startAddr
195    )
196  }
197
198  // commented out for this br could be the last instruction in the fetch block
199  def checkNotTakenConsecutive = {
200    val prevNotTakenValid  = RegInit(0.B)
201    val prevNotTakenFtqIdx = Reg(UInt(log2Up(FtqSize).W))
202    for (i <- 0 until DecodeWidth - 1) {
203      // for instrs that is not the last, if a not-taken br, the next instr should have the same ftqPtr
204      // for instrs that is the last, record and check next request
205      when(ibuffer.io.out(i).fire && ibuffer.io.out(i).bits.pd.isBr) {
206        when(ibuffer.io.out(i + 1).fire) {
207          // not last br, check now
208          XSError(checkTargetIdx(i) =/= checkTargetIdx(i + 1), "not-taken br should have same ftqPtr\n")
209        }.otherwise {
210          // last br, record its info
211          prevNotTakenValid  := true.B
212          prevNotTakenFtqIdx := checkTargetIdx(i)
213        }
214      }
215    }
216    when(ibuffer.io.out(DecodeWidth - 1).fire && ibuffer.io.out(DecodeWidth - 1).bits.pd.isBr) {
217      // last instr is a br, record its info
218      prevNotTakenValid  := true.B
219      prevNotTakenFtqIdx := checkTargetIdx(DecodeWidth - 1)
220    }
221    when(prevNotTakenValid && ibuffer.io.out(0).fire) {
222      XSError(prevNotTakenFtqIdx =/= checkTargetIdx(0), "not-taken br should have same ftqPtr\n")
223      prevNotTakenValid := false.B
224    }
225    when(needFlush) {
226      prevNotTakenValid := false.B
227    }
228  }
229
230  def checkTakenNotConsecutive = {
231    val prevTakenValid  = RegInit(0.B)
232    val prevTakenFtqIdx = Reg(UInt(log2Up(FtqSize).W))
233    for (i <- 0 until DecodeWidth - 1) {
234      // for instrs that is not the last, if a taken br, the next instr should not have the same ftqPtr
235      // for instrs that is the last, record and check next request
236      when(ibuffer.io.out(i).fire && ibuffer.io.out(i).bits.pd.isBr && ibuffer.io.out(i).bits.pred_taken) {
237        when(ibuffer.io.out(i + 1).fire) {
238          // not last br, check now
239          XSError(checkTargetIdx(i) + 1.U =/= checkTargetIdx(i + 1), "taken br should have consecutive ftqPtr\n")
240        }.otherwise {
241          // last br, record its info
242          prevTakenValid  := true.B
243          prevTakenFtqIdx := checkTargetIdx(i)
244        }
245      }
246    }
247    when(ibuffer.io.out(DecodeWidth - 1).fire && ibuffer.io.out(DecodeWidth - 1).bits.pd.isBr && ibuffer.io.out(
248      DecodeWidth - 1
249    ).bits.pred_taken) {
250      // last instr is a br, record its info
251      prevTakenValid  := true.B
252      prevTakenFtqIdx := checkTargetIdx(DecodeWidth - 1)
253    }
254    when(prevTakenValid && ibuffer.io.out(0).fire) {
255      XSError(prevTakenFtqIdx + 1.U =/= checkTargetIdx(0), "taken br should have consecutive ftqPtr\n")
256      prevTakenValid := false.B
257    }
258    when(needFlush) {
259      prevTakenValid := false.B
260    }
261  }
262
263  def checkNotTakenPC = {
264    val prevNotTakenPC    = Reg(UInt(VAddrBits.W))
265    val prevIsRVC         = Reg(Bool())
266    val prevNotTakenValid = RegInit(0.B)
267
268    for (i <- 0 until DecodeWidth - 1) {
269      when(ibuffer.io.out(i).fire && ibuffer.io.out(i).bits.pd.isBr && !ibuffer.io.out(i).bits.pred_taken) {
270        when(ibuffer.io.out(i + 1).fire) {
271          XSError(
272            ibuffer.io.out(i).bits.pc + Mux(ibuffer.io.out(i).bits.pd.isRVC, 2.U, 4.U) =/= ibuffer.io.out(
273              i + 1
274            ).bits.pc,
275            "not-taken br should have consecutive pc\n"
276          )
277        }.otherwise {
278          prevNotTakenValid := true.B
279          prevIsRVC         := ibuffer.io.out(i).bits.pd.isRVC
280          prevNotTakenPC    := ibuffer.io.out(i).bits.pc
281        }
282      }
283    }
284    when(ibuffer.io.out(DecodeWidth - 1).fire && ibuffer.io.out(DecodeWidth - 1).bits.pd.isBr && !ibuffer.io.out(
285      DecodeWidth - 1
286    ).bits.pred_taken) {
287      prevNotTakenValid := true.B
288      prevIsRVC         := ibuffer.io.out(DecodeWidth - 1).bits.pd.isRVC
289      prevNotTakenPC    := ibuffer.io.out(DecodeWidth - 1).bits.pc
290    }
291    when(prevNotTakenValid && ibuffer.io.out(0).fire) {
292      XSError(
293        prevNotTakenPC + Mux(prevIsRVC, 2.U, 4.U) =/= ibuffer.io.out(0).bits.pc,
294        "not-taken br should have same pc\n"
295      )
296      prevNotTakenValid := false.B
297    }
298    when(needFlush) {
299      prevNotTakenValid := false.B
300    }
301  }
302
303  def checkTakenPC = {
304    val prevTakenFtqIdx = Reg(UInt(log2Up(FtqSize).W))
305    val prevTakenValid  = RegInit(0.B)
306    val prevTakenTarget = Wire(UInt(VAddrBits.W))
307    prevTakenTarget := checkPcMem(prevTakenFtqIdx + 1.U).startAddr
308
309    for (i <- 0 until DecodeWidth - 1) {
310      when(ibuffer.io.out(i).fire && !ibuffer.io.out(i).bits.pd.notCFI && ibuffer.io.out(i).bits.pred_taken) {
311        when(ibuffer.io.out(i + 1).fire) {
312          XSError(checkTarget(i) =/= ibuffer.io.out(i + 1).bits.pc, "taken instr should follow target pc\n")
313        }.otherwise {
314          prevTakenValid  := true.B
315          prevTakenFtqIdx := checkTargetIdx(i)
316        }
317      }
318    }
319    when(ibuffer.io.out(DecodeWidth - 1).fire && !ibuffer.io.out(DecodeWidth - 1).bits.pd.notCFI && ibuffer.io.out(
320      DecodeWidth - 1
321    ).bits.pred_taken) {
322      prevTakenValid  := true.B
323      prevTakenFtqIdx := checkTargetIdx(DecodeWidth - 1)
324    }
325    when(prevTakenValid && ibuffer.io.out(0).fire) {
326      XSError(prevTakenTarget =/= ibuffer.io.out(0).bits.pc, "taken instr should follow target pc\n")
327      prevTakenValid := false.B
328    }
329    when(needFlush) {
330      prevTakenValid := false.B
331    }
332  }
333
334  // checkNotTakenConsecutive
335  checkTakenNotConsecutive
336  checkTakenPC
337  checkNotTakenPC
338
339  ifu.io.rob_commits <> io.backend.toFtq.rob_commits
340
341  ibuffer.io.flush                := needFlush
342  ibuffer.io.ControlRedirect      := FlushControlRedirect
343  ibuffer.io.MemVioRedirect       := FlushMemVioRedirect
344  ibuffer.io.ControlBTBMissBubble := FlushControlBTBMiss
345  ibuffer.io.TAGEMissBubble       := FlushTAGEMiss
346  ibuffer.io.SCMissBubble         := FlushSCMiss
347  ibuffer.io.ITTAGEMissBubble     := FlushITTAGEMiss
348  ibuffer.io.RASMissBubble        := FlushRASMiss
349  ibuffer.io.decodeCanAccept      := io.backend.canAccept
350
351  FlushControlBTBMiss := ftq.io.ControlBTBMissBubble
352  FlushTAGEMiss       := ftq.io.TAGEMissBubble
353  FlushSCMiss         := ftq.io.SCMissBubble
354  FlushITTAGEMiss     := ftq.io.ITTAGEMissBubble
355  FlushRASMiss        := ftq.io.RASMissBubble
356
357  io.backend.cfVec <> ibuffer.io.out
358  io.backend.stallReason <> ibuffer.io.stallReason
359
360  instrUncache.io.req <> ifu.io.uncacheInter.toUncache
361  ifu.io.uncacheInter.fromUncache <> instrUncache.io.resp
362  instrUncache.io.flush := false.B
363  io.error <> RegNext(RegNext(icache.io.error))
364
365  icache.io.hartId := io.hartId
366
367  itlbRepeater1.io.debugTopDown.robHeadVaddr := io.debugTopDown.robHeadVaddr
368
369  val frontendBubble = Mux(io.backend.canAccept, DecodeWidth.U - PopCount(ibuffer.io.out.map(_.valid)), 0.U)
370  XSPerfAccumulate("FrontendBubble", frontendBubble)
371  io.frontendInfo.ibufFull := RegNext(ibuffer.io.full)
372  io.resetInFrontend       := reset.asBool
373
374  // PFEvent
375  val pfevent = Module(new PFEvent)
376  pfevent.io.distribute_csr := io.csrCtrl.distribute_csr
377  val csrevents = pfevent.io.hpmevent.take(8)
378
379  val perfFromUnits = Seq(ifu, ibuffer, icache, ftq, bpu).flatMap(_.getPerfEvents)
380  val perfFromIO    = Seq()
381  val perfBlock     = Seq()
382  // let index = 0 be no event
383  val allPerfEvents = Seq(("noEvent", 0.U)) ++ perfFromUnits ++ perfFromIO ++ perfBlock
384
385  if (printEventCoding) {
386    for (((name, inc), i) <- allPerfEvents.zipWithIndex) {
387      println("Frontend perfEvents Set", name, inc, i)
388    }
389  }
390
391  val allPerfInc          = allPerfEvents.map(_._2.asTypeOf(new PerfEvent))
392  override val perfEvents = HPerfMonitor(csrevents, allPerfInc).getPerfEvents
393  generatePerfEvent()
394}
395