xref: /XiangShan/src/main/scala/xiangshan/frontend/PreDecode.scala (revision a4e57ea3a91431261d57a58df4810c0d9f0366ef)
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
18
19import chipsalliance.rocketchip.config.Parameters
20import freechips.rocketchip.rocket.{RVCDecoder, ExpandedInstruction}
21import chisel3.{util, _}
22import chisel3.util._
23import utils._
24import xiangshan._
25import xiangshan.frontend.icache._
26import xiangshan.backend.decode.isa.predecode.PreDecodeInst
27
28trait HasPdConst extends HasXSParameter with HasICacheParameters with HasIFUConst{
29  def isRVC(inst: UInt) = (inst(1,0) =/= 3.U)
30  def isLink(reg:UInt) = reg === 1.U || reg === 5.U
31  def brInfo(instr: UInt) = {
32    val brType::Nil = ListLookup(instr, List(BrType.notCFI), PreDecodeInst.brTable)
33    val rd = Mux(isRVC(instr), instr(12), instr(11,7))
34    val rs = Mux(isRVC(instr), Mux(brType === BrType.jal, 0.U, instr(11, 7)), instr(19, 15))
35    val isCall = (brType === BrType.jal && !isRVC(instr) || brType === BrType.jalr) && isLink(rd) // Only for RV64
36    val isRet = brType === BrType.jalr && isLink(rs) && !isCall
37    List(brType, isCall, isRet)
38  }
39  def jal_offset(inst: UInt, rvc: Bool): UInt = {
40    val rvc_offset = Cat(inst(12), inst(8), inst(10, 9), inst(6), inst(7), inst(2), inst(11), inst(5, 3), 0.U(1.W))
41    val rvi_offset = Cat(inst(31), inst(19, 12), inst(20), inst(30, 21), 0.U(1.W))
42    val max_width = rvi_offset.getWidth
43    SignExt(Mux(rvc, SignExt(rvc_offset, max_width), SignExt(rvi_offset, max_width)), XLEN)
44  }
45  def br_offset(inst: UInt, rvc: Bool): UInt = {
46    val rvc_offset = Cat(inst(12), inst(6, 5), inst(2), inst(11, 10), inst(4, 3), 0.U(1.W))
47    val rvi_offset = Cat(inst(31), inst(7), inst(30, 25), inst(11, 8), 0.U(1.W))
48    val max_width = rvi_offset.getWidth
49    SignExt(Mux(rvc, SignExt(rvc_offset, max_width), SignExt(rvi_offset, max_width)), XLEN)
50  }
51
52  def NOP = "h4501".U(16.W)
53}
54
55object BrType {
56  def notCFI   = "b00".U
57  def branch  = "b01".U
58  def jal     = "b10".U
59  def jalr    = "b11".U
60  def apply() = UInt(2.W)
61}
62
63object ExcType {  //TODO:add exctype
64  def notExc = "b000".U
65  def apply() = UInt(3.W)
66}
67
68class PreDecodeInfo extends Bundle {  // 8 bit
69  val valid   = Bool()
70  val isRVC   = Bool()
71  val brType  = UInt(2.W)
72  val isCall  = Bool()
73  val isRet   = Bool()
74  //val excType = UInt(3.W)
75  def isBr    = brType === BrType.branch
76  def isJal   = brType === BrType.jal
77  def isJalr  = brType === BrType.jalr
78  def notCFI  = brType === BrType.notCFI
79}
80
81class PreDecodeResp(implicit p: Parameters) extends XSBundle with HasPdConst {
82  val pd = Vec(PredictWidth, new PreDecodeInfo)
83  val hasHalfValid = Vec(PredictWidth, Bool())
84  val expInstr = Vec(PredictWidth, UInt(32.W))
85  val jumpOffset = Vec(PredictWidth, UInt(XLEN.W))
86//  val hasLastHalf = Bool()
87  val triggered    = Vec(PredictWidth, new TriggerCf)
88}
89
90class PreDecode(implicit p: Parameters) extends XSModule with HasPdConst{
91  val io = IO(new Bundle() {
92    val in = Input(new IfuToPreDecode)
93    val out = Output(new PreDecodeResp)
94  })
95
96  val data          = io.in.data
97//  val lastHalfMatch = io.in.lastHalfMatch
98  val validStart, validEnd = Wire(Vec(PredictWidth, Bool()))
99  val h_validStart, h_validEnd = Wire(Vec(PredictWidth, Bool()))
100
101  val rawInsts = if (HasCExtension) VecInit((0 until PredictWidth).map(i => Cat(data(i+1), data(i))))
102  else         VecInit((0 until PredictWidth).map(i => data(i)))
103
104
105
106  for (i <- 0 until PredictWidth) {
107    val inst           =WireInit(rawInsts(i))
108    val expander       = Module(new RVCExpander)
109    val currentIsRVC   = isRVC(inst)
110    val currentPC      = io.in.pc(i)
111    expander.io.in             := inst
112
113    val brType::isCall::isRet::Nil = brInfo(inst)
114    val jalOffset = jal_offset(inst, currentIsRVC)
115    val brOffset  = br_offset(inst, currentIsRVC)
116
117    //val lastIsValidEnd =  if (i == 0) { !lastHalfMatch } else { validEnd(i-1) || !HasCExtension.B }
118    val lastIsValidEnd =   if (i == 0) { true.B } else { validEnd(i-1) || !HasCExtension.B }
119    validStart(i)   := (lastIsValidEnd || !HasCExtension.B)
120    validEnd(i)     := validStart(i) && currentIsRVC || !validStart(i) || !HasCExtension.B
121
122    //prepared for last half match
123    //TODO if HasCExtension
124    val h_lastIsValidEnd = if (i == 0) { false.B } else { h_validEnd(i-1) || !HasCExtension.B }
125    h_validStart(i)   := (h_lastIsValidEnd || !HasCExtension.B)
126    h_validEnd(i)     := h_validStart(i) && currentIsRVC || !h_validStart(i) || !HasCExtension.B
127
128    io.out.hasHalfValid(i)        := h_validStart(i)
129
130    io.out.triggered(i)   := DontCare//VecInit(Seq.fill(10)(false.B))
131
132
133    io.out.pd(i).valid         := validStart(i)
134    io.out.pd(i).isRVC         := currentIsRVC
135    io.out.pd(i).brType        := brType
136    io.out.pd(i).isCall        := isCall
137    io.out.pd(i).isRet         := isRet
138
139    io.out.expInstr(i)         := expander.io.out.bits
140    io.out.jumpOffset(i)       := Mux(io.out.pd(i).isBr, brOffset, jalOffset)
141  }
142
143//  io.out.hasLastHalf := !io.out.pd(PredictWidth - 1).isRVC && io.out.pd(PredictWidth - 1).valid
144
145  for (i <- 0 until PredictWidth) {
146    XSDebug(true.B,
147      p"instr ${Hexadecimal(io.out.expInstr(i))}, " +
148        p"validStart ${Binary(validStart(i))}, " +
149        p"validEnd ${Binary(validEnd(i))}, " +
150        p"isRVC ${Binary(io.out.pd(i).isRVC)}, " +
151        p"brType ${Binary(io.out.pd(i).brType)}, " +
152        p"isRet ${Binary(io.out.pd(i).isRet)}, " +
153        p"isCall ${Binary(io.out.pd(i).isCall)}\n"
154    )
155  }
156}
157
158class RVCExpander(implicit p: Parameters) extends XSModule {
159  val io = IO(new Bundle {
160    val in = Input(UInt(32.W))
161    val out = Output(new ExpandedInstruction)
162  })
163
164  if (HasCExtension) {
165    io.out := new RVCDecoder(io.in, XLEN).decode
166  } else {
167    io.out := new RVCDecoder(io.in, XLEN).passthrough
168  }
169}
170
171/* ---------------------------------------------------------------------
172 * Predict result check
173 *
174 * ---------------------------------------------------------------------
175 */
176
177object FaultType {
178  def noFault         = "b000".U
179  def jalFault        = "b001".U    //not CFI taken or invalid instruction taken
180  def retFault        = "b010".U    //not CFI taken or invalid instruction taken
181  def targetFault     = "b011".U
182  def faulsePred      = "b100".U    //not CFI taken or invalid instruction taken
183  def apply() = UInt(3.W)
184}
185
186class CheckInfo extends Bundle {  // 8 bit
187  val value  = UInt(3.W)
188  def isjalFault      = value === FaultType.jalFault
189  def isRetFault      = value === FaultType.retFault
190  def istargetFault   = value === FaultType.targetFault
191  def isfaulsePred    = value === FaultType.faulsePred
192}
193
194class PredCheckerResp(implicit p: Parameters) extends XSBundle with HasPdConst {
195  //to Ibuffer write port (timing critical)
196  val fixedRange  = Vec(PredictWidth, Bool())
197  val fixedTaken  = Vec(PredictWidth, Bool())
198  //to Ftq write back port (not timing critical)
199  val fixedTarget = Vec(PredictWidth, UInt(VAddrBits.W))
200  val fixedMissPred = Vec(PredictWidth,  Bool())
201  val faultType   = Vec(PredictWidth, new CheckInfo)
202}
203
204
205class PredChecker(implicit p: Parameters) extends XSModule with HasPdConst {
206  val io = IO( new Bundle{
207    val in = Input(new IfuToPredChecker)
208    val out = Output(new PredCheckerResp)
209  })
210
211  val (takenIdx, predTaken)     = (io.in.ftqOffset.bits, io.in.ftqOffset.valid)
212  val predTarget                = (io.in.target)
213  val (instrRange, instrValid)  = (io.in.instrRange, io.in.instrValid)
214  val (pds, pc, jumpOffset)     = (io.in.pds, io.in.pc, io.in.jumpOffset)
215
216  val jalFaultVec, retFaultVec, targetFault, notCFITaken, invalidTaken = Wire(Vec(PredictWidth, Bool()))
217
218  /** remask fault may appear together with other faults, but other faults are exclusive
219    * so other f ault mast use fixed mask to keep only one fault would be found and redirect to Ftq
220    * we first detecct remask fault and then use fixedRange to do second check
221    **/
222
223  /** first check: remask Fault */
224  jalFaultVec         := VecInit(pds.zipWithIndex.map{case(pd, i) => pd.isJal && instrRange(i) && instrValid(i) && (takenIdx > i.U && predTaken || !predTaken) })
225  retFaultVec         := VecInit(pds.zipWithIndex.map{case(pd, i) => pd.isRet && instrRange(i) && instrValid(i) && (takenIdx > i.U && predTaken || !predTaken) })
226  val remaskFault      = VecInit((0 until PredictWidth).map(i => jalFaultVec(i) || retFaultVec(i)))
227  val remaskIdx        = ParallelPriorityEncoder(remaskFault.asUInt)
228  val needRemask       = ParallelOR(remaskFault)
229  val fixedRange       = instrRange.asUInt & (Fill(PredictWidth, !needRemask) | Fill(PredictWidth, 1.U(1.W)) >> ~remaskIdx)
230
231  io.out.fixedRange := fixedRange.asTypeOf((Vec(PredictWidth, Bool())))
232
233  io.out.fixedTaken := VecInit(pds.zipWithIndex.map{case(pd, i) => instrValid (i) && fixedRange(i) && (pd.isRet || pd.isJal || takenIdx === i.U && predTaken && !pd.notCFI)  })
234
235  /** second check: faulse prediction fault and target fault */
236  notCFITaken  := VecInit(pds.zipWithIndex.map{case(pd, i) => fixedRange(i) && instrValid(i) && i.U === takenIdx && pd.notCFI && predTaken })
237  invalidTaken := VecInit(pds.zipWithIndex.map{case(pd, i) => fixedRange(i) && !instrValid(i)  && i.U === takenIdx  && predTaken })
238
239  /** target calculation  */
240  val jumpTargets          = VecInit(pds.zipWithIndex.map{case(pd,i) => pc(i) + jumpOffset(i)})
241  targetFault      := VecInit(pds.zipWithIndex.map{case(pd,i) => fixedRange(i) && instrValid(i) && (pd.isJal || pd.isBr) && takenIdx === i.U && predTaken  && (predTarget =/= jumpTargets(i))})
242
243  val seqTargets = VecInit((0 until PredictWidth).map(i => pc(i) + Mux(pds(i).isRVC || !instrValid(i), 2.U, 4.U ) ))
244
245  io.out.faultType.zipWithIndex.map{case(faultType, i) => faultType.value := Mux(jalFaultVec(i) , FaultType.jalFault ,
246                                                                             Mux(retFaultVec(i), FaultType.retFault ,
247                                                                             Mux(targetFault(i), FaultType.targetFault ,
248                                                                             Mux(notCFITaken(i) || invalidTaken(i) ,FaultType.faulsePred, FaultType.noFault))))}
249
250  io.out.fixedMissPred.zipWithIndex.map{case(missPred, i ) => missPred := jalFaultVec(i) || retFaultVec(i) || notCFITaken(i) || invalidTaken(i) || targetFault(i)}
251  io.out.fixedTarget.zipWithIndex.map{case(target, i) => target := Mux(jalFaultVec(i) || targetFault(i), jumpTargets(i),  seqTargets(i) )}
252
253}
254
255class FrontendTrigger(implicit p: Parameters) extends XSModule {
256  val io = IO(new Bundle(){
257    val frontendTrigger = Input(new FrontendTdataDistributeIO)
258    val csrTriggerEnable = Input(Vec(4, Bool()))
259    val triggered    = Output(Vec(PredictWidth, new TriggerCf))
260
261    val pds           = Input(Vec(PredictWidth, new PreDecodeInfo))
262    val pc            = Input(Vec(PredictWidth, UInt(VAddrBits.W)))
263    val data          = if(HasCExtension) Input(Vec(PredictWidth + 1, UInt(16.W)))
264                        else Input(Vec(PredictWidth, UInt(32.W)))
265  })
266
267  val data          = io.data
268
269  val rawInsts = if (HasCExtension) VecInit((0 until PredictWidth).map(i => Cat(data(i+1), data(i))))
270                        else         VecInit((0 until PredictWidth).map(i => data(i)))
271
272  val tdata = Reg(Vec(4, new MatchTriggerIO))
273  when(io.frontendTrigger.t.valid) {
274    tdata(io.frontendTrigger.t.bits.addr) := io.frontendTrigger.t.bits.tdata
275  }
276  io.triggered.map{i => i := 0.U.asTypeOf(new TriggerCf)}
277  val triggerEnable = RegInit(VecInit(Seq.fill(4)(false.B))) // From CSR, controlled by priv mode, etc.
278  triggerEnable := io.csrTriggerEnable
279  val triggerHitVec = Wire(Vec(4, Bool()))
280  XSDebug(triggerEnable.asUInt.orR, "Debug Mode: At least one frontend trigger is enabled\n")
281
282  for (i <- 0 until 4) {PrintTriggerInfo(triggerEnable(i), tdata(i))}
283
284  for (i <- 0 until PredictWidth) {
285    val currentPC = io.pc(i)
286    val currentIsRVC = io.pds(i).isRVC
287    val inst = WireInit(rawInsts(i))
288
289    for (j <- 0 until 4) {
290      triggerHitVec(j) := Mux(tdata(j).select, TriggerCmp(Mux(currentIsRVC, inst(15, 0), inst), tdata(j).tdata2, tdata(j).matchType, triggerEnable(j)),
291        TriggerCmp(currentPC, tdata(j).tdata2, tdata(j).matchType, triggerEnable(j)))
292    }
293
294    // fix chains this could be moved further into the pipeline
295    io.triggered(i).frontendHit := triggerHitVec
296    val enableChain = tdata(0).chain
297    when(enableChain){
298      io.triggered(i).frontendHit(0) := triggerHitVec(0) && triggerHitVec(1) && (tdata(0).timing === tdata(1).timing)
299      io.triggered(i).frontendHit(1) := triggerHitVec(0) && triggerHitVec(1) && (tdata(0).timing === tdata(1).timing)
300    }
301    for(j <- 0 until 2) {
302      io.triggered(i).backendEn(j) := Mux(tdata(j+2).chain, triggerHitVec(j+2), true.B)
303      io.triggered(i).frontendHit(j+2) := !tdata(j+2).chain && triggerHitVec(j+2) // temporary workaround
304    }
305    XSDebug(io.triggered(i).getHitFrontend, p"Debug Mode: Predecode Inst No. ${i} has trigger hit vec ${io.triggered(i).frontendHit}" +
306      p"and backend en ${io.triggered(i).backendEn}\n")
307  }
308}
309