xref: /XiangShan/src/main/scala/xiangshan/backend/rename/Rename.scala (revision c3abb8b6b92c14ec0f3dbbac60a8caa531994a95)
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.backend.rename
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import xiangshan._
23import utils._
24import xiangshan.backend.rob.RobPtr
25import xiangshan.backend.dispatch.PreDispatchInfo
26import xiangshan.backend.rename.freelist._
27
28class Rename(implicit p: Parameters) extends XSModule {
29  val io = IO(new Bundle() {
30    val redirect = Flipped(ValidIO(new Redirect))
31    val robCommits = Flipped(new RobCommitIO)
32    // from decode
33    val in = Vec(RenameWidth, Flipped(DecoupledIO(new CfCtrl)))
34    // to rename table
35    val intReadPorts = Vec(RenameWidth, Vec(3, Input(UInt(PhyRegIdxWidth.W))))
36    val fpReadPorts = Vec(RenameWidth, Vec(4, Input(UInt(PhyRegIdxWidth.W))))
37    val intRenamePorts = Vec(RenameWidth, Output(new RatWritePort))
38    val fpRenamePorts = Vec(RenameWidth, Output(new RatWritePort))
39    // to dispatch1
40    val out = Vec(RenameWidth, DecoupledIO(new MicroOp))
41    val dispatchInfo = Output(new PreDispatchInfo)
42  })
43
44  // create free list and rat
45  val intFreeList = Module(new MEFreeList(MEFreeListSize))
46  val intRefCounter = Module(new RefCounter(MEFreeListSize))
47  val fpFreeList = Module(new StdFreeList(StdFreeListSize))
48
49  // decide if given instruction needs allocating a new physical register (CfCtrl: from decode; RobCommitInfo: from rob)
50  def needDestReg[T <: CfCtrl](fp: Boolean, x: T): Bool = {
51    {if(fp) x.ctrl.fpWen else x.ctrl.rfWen && (x.ctrl.ldest =/= 0.U)}
52  }
53  def needDestRegCommit[T <: RobCommitInfo](fp: Boolean, x: T): Bool = {
54    if(fp) x.fpWen else x.rfWen
55  }
56
57  // connect [redirect + walk] ports for __float point__ & __integer__ free list
58  Seq((fpFreeList, true), (intFreeList, false)).foreach{ case (fl, isFp) =>
59    fl.io.redirect := io.redirect.valid
60    fl.io.walk := io.robCommits.isWalk
61    // when isWalk, use stepBack to restore head pointer of free list
62    // (if ME enabled, stepBack of intFreeList should be useless thus optimized out)
63    fl.io.stepBack := PopCount(io.robCommits.valid.zip(io.robCommits.info).map{case (v, i) => v && needDestRegCommit(isFp, i)})
64  }
65  // walk has higher priority than allocation and thus we don't use isWalk here
66  // only when both fp and int free list and dispatch1 has enough space can we do allocation
67  intFreeList.io.doAllocate := fpFreeList.io.canAllocate && io.out(0).ready
68  fpFreeList.io.doAllocate := intFreeList.io.canAllocate && io.out(0).ready
69
70  //           dispatch1 ready ++ float point free list ready ++ int free list ready      ++ not walk
71  val canOut = io.out(0).ready && fpFreeList.io.canAllocate && intFreeList.io.canAllocate && !io.robCommits.isWalk
72
73
74  // speculatively assign the instruction with an robIdx
75  val validCount = PopCount(io.in.map(_.valid)) // number of instructions waiting to enter rob (from decode)
76  val robIdxHead = RegInit(0.U.asTypeOf(new RobPtr))
77  val lastCycleMisprediction = RegNext(io.redirect.valid && !io.redirect.bits.flushItself())
78  val robIdxHeadNext = Mux(io.redirect.valid, io.redirect.bits.robIdx, // redirect: move ptr to given rob index
79         Mux(lastCycleMisprediction, robIdxHead + 1.U, // mis-predict: not flush robIdx itself
80                         Mux(canOut, robIdxHead + validCount, // instructions successfully entered next stage: increase robIdx
81                      /* default */  robIdxHead))) // no instructions passed by this cycle: stick to old value
82  robIdxHead := robIdxHeadNext
83
84  /**
85    * Rename: allocate free physical register and update rename table
86    */
87  val uops = Wire(Vec(RenameWidth, new MicroOp))
88  uops.foreach( uop => {
89    uop.srcState(0) := DontCare
90    uop.srcState(1) := DontCare
91    uop.srcState(2) := DontCare
92    uop.robIdx := DontCare
93    uop.diffTestDebugLrScValid := DontCare
94    uop.debugInfo := DontCare
95    uop.lqIdx := DontCare
96    uop.sqIdx := DontCare
97  })
98
99  val needFpDest = Wire(Vec(RenameWidth, Bool()))
100  val needIntDest = Wire(Vec(RenameWidth, Bool()))
101  val hasValid = Cat(io.in.map(_.valid)).orR
102
103  val isMove = io.in.map(_.bits.ctrl.isMove)
104  val intPsrc = Wire(Vec(RenameWidth, UInt()))
105
106  val intSpecWen = Wire(Vec(RenameWidth, Bool()))
107  val fpSpecWen = Wire(Vec(RenameWidth, Bool()))
108
109  // uop calculation
110  for (i <- 0 until RenameWidth) {
111    uops(i).cf := io.in(i).bits.cf
112    uops(i).ctrl := io.in(i).bits.ctrl
113
114    val inValid = io.in(i).valid
115
116    // alloc a new phy reg
117    needFpDest(i) := inValid && needDestReg(fp = true, io.in(i).bits)
118    needIntDest(i) := inValid && needDestReg(fp = false, io.in(i).bits)
119    fpFreeList.io.allocateReq(i) := needFpDest(i)
120    intFreeList.io.allocateReq(i) := needIntDest(i) && !isMove(i)
121
122    // no valid instruction from decode stage || all resources (dispatch1 + both free lists) ready
123    io.in(i).ready := !hasValid || canOut
124
125    uops(i).robIdx := robIdxHead + PopCount(io.in.take(i).map(_.valid))
126
127    val intPhySrcVec = io.intReadPorts(i).take(2)
128    val intOldPdest = io.intReadPorts(i).last
129    intPsrc(i) := intPhySrcVec(0)
130    val fpPhySrcVec = io.fpReadPorts(i).take(3)
131    val fpOldPdest = io.fpReadPorts(i).last
132    uops(i).psrc(0) := Mux(uops(i).ctrl.srcType(0) === SrcType.reg, intPhySrcVec(0), fpPhySrcVec(0))
133    uops(i).psrc(1) := Mux(uops(i).ctrl.srcType(1) === SrcType.reg, intPhySrcVec(1), fpPhySrcVec(1))
134    uops(i).psrc(2) := fpPhySrcVec(2)
135    uops(i).old_pdest := Mux(uops(i).ctrl.rfWen, intOldPdest, fpOldPdest)
136    uops(i).eliminatedMove := isMove(i)
137
138    // update pdest
139    uops(i).pdest := Mux(needIntDest(i), intFreeList.io.allocatePhyReg(i), // normal int inst
140      // normal fp inst
141      Mux(needFpDest(i), fpFreeList.io.allocatePhyReg(i),
142        /* default */0.U))
143
144    // Assign performance counters
145    uops(i).debugInfo.renameTime := GTimer()
146
147    io.out(i).valid := io.in(i).valid && intFreeList.io.canAllocate && fpFreeList.io.canAllocate && !io.robCommits.isWalk
148    io.out(i).bits := uops(i)
149    when (io.out(i).bits.ctrl.fuType === FuType.fence) {
150      io.out(i).bits.ctrl.imm := Cat(io.in(i).bits.ctrl.lsrc(1), io.in(i).bits.ctrl.lsrc(0))
151    }
152
153    // write speculative rename table
154    // we update rat later inside commit code
155    intSpecWen(i) := needIntDest(i) && intFreeList.io.canAllocate && intFreeList.io.doAllocate && !io.robCommits.isWalk && !io.redirect.valid
156    fpSpecWen(i) := needFpDest(i) && fpFreeList.io.canAllocate && fpFreeList.io.doAllocate && !io.robCommits.isWalk && !io.redirect.valid
157
158    intRefCounter.io.allocate(i).valid := intSpecWen(i)
159    intRefCounter.io.allocate(i).bits := io.out(i).bits.pdest
160  }
161
162  /**
163    * How to set psrc:
164    * - bypass the pdest to psrc if previous instructions write to the same ldest as lsrc
165    * - default: psrc from RAT
166    * How to set pdest:
167    * - Mux(isMove, psrc, pdest_from_freelist).
168    *
169    * The critical path of rename lies here:
170    * When move elimination is enabled, we need to update the rat with psrc.
171    * However, psrc maybe comes from previous instructions' pdest, which comes from freelist.
172    *
173    * If we expand these logic for pdest(N):
174    * pdest(N) = Mux(isMove(N), psrc(N), freelist_out(N))
175    *          = Mux(isMove(N), Mux(bypass(N, N - 1), pdest(N - 1),
176    *                           Mux(bypass(N, N - 2), pdest(N - 2),
177    *                           ...
178    *                           Mux(bypass(N, 0),     pdest(0),
179    *                                                 rat_out(N))...)),
180    *                           freelist_out(N))
181    */
182  // a simple functional model for now
183  io.out(0).bits.pdest := Mux(isMove(0), uops(0).psrc.head, uops(0).pdest)
184  val bypassCond = Wire(Vec(4, MixedVec(List.tabulate(RenameWidth-1)(i => UInt((i+1).W)))))
185  for (i <- 1 until RenameWidth) {
186    val fpCond = io.in(i).bits.ctrl.srcType.map(_ === SrcType.fp) :+ needFpDest(i)
187    val intCond = io.in(i).bits.ctrl.srcType.map(_ === SrcType.reg) :+ needIntDest(i)
188    val target = io.in(i).bits.ctrl.lsrc :+ io.in(i).bits.ctrl.ldest
189    for ((((cond1, cond2), t), j) <- fpCond.zip(intCond).zip(target).zipWithIndex) {
190      val destToSrc = io.in.take(i).zipWithIndex.map { case (in, j) =>
191        val indexMatch = in.bits.ctrl.ldest === t
192        val writeMatch =  cond2 && needIntDest(j) || cond1 && needFpDest(j)
193        indexMatch && writeMatch
194      }
195      bypassCond(j)(i - 1) := VecInit(destToSrc).asUInt
196    }
197    io.out(i).bits.psrc(0) := io.out.take(i).map(_.bits.pdest).zip(bypassCond(0)(i-1).asBools).foldLeft(uops(i).psrc(0)) {
198      (z, next) => Mux(next._2, next._1, z)
199    }
200    io.out(i).bits.psrc(1) := io.out.take(i).map(_.bits.pdest).zip(bypassCond(1)(i-1).asBools).foldLeft(uops(i).psrc(1)) {
201      (z, next) => Mux(next._2, next._1, z)
202    }
203    io.out(i).bits.psrc(2) := io.out.take(i).map(_.bits.pdest).zip(bypassCond(2)(i-1).asBools).foldLeft(uops(i).psrc(2)) {
204      (z, next) => Mux(next._2, next._1, z)
205    }
206    io.out(i).bits.old_pdest := io.out.take(i).map(_.bits.pdest).zip(bypassCond(3)(i-1).asBools).foldLeft(uops(i).old_pdest) {
207      (z, next) => Mux(next._2, next._1, z)
208    }
209    io.out(i).bits.pdest := Mux(isMove(i), io.out(i).bits.psrc(0), uops(i).pdest)
210  }
211
212  // calculate lsq space requirement
213  val isLs    = VecInit(uops.map(uop => FuType.isLoadStore(uop.ctrl.fuType)))
214  val isStore = VecInit(uops.map(uop => FuType.isStoreExu(uop.ctrl.fuType)))
215  val isAMO   = VecInit(uops.map(uop => FuType.isAMO(uop.ctrl.fuType)))
216  io.dispatchInfo.lsqNeedAlloc := VecInit((0 until RenameWidth).map(i =>
217    Mux(isLs(i), Mux(isStore(i) && !isAMO(i), 2.U, 1.U), 0.U)))
218
219  /**
220    * Instructions commit: update freelist and rename table
221    */
222  for (i <- 0 until CommitWidth) {
223
224    Seq((io.intRenamePorts, false), (io.fpRenamePorts, true)) foreach { case (rat, fp) =>
225      // is valid commit req and given instruction has destination register
226      val commitDestValid = io.robCommits.valid(i) && needDestRegCommit(fp, io.robCommits.info(i))
227      XSDebug(p"isFp[${fp}]index[$i]-commitDestValid:$commitDestValid,isWalk:${io.robCommits.isWalk}\n")
228
229      /*
230      I. RAT Update
231       */
232
233      // walk back write - restore spec state : ldest => old_pdest
234      if (fp && i < RenameWidth) {
235        // When redirect happens (mis-prediction), don't update the rename table
236        rat(i).wen := fpSpecWen(i)
237        rat(i).addr := uops(i).ctrl.ldest
238        rat(i).data := fpFreeList.io.allocatePhyReg(i)
239      } else if (!fp && i < RenameWidth) {
240        rat(i).wen := intSpecWen(i)
241        rat(i).addr := uops(i).ctrl.ldest
242        rat(i).data := io.out(i).bits.pdest
243      }
244
245      /*
246      II. Free List Update
247       */
248      if (fp) { // Float Point free list
249        fpFreeList.io.freeReq(i)  := commitDestValid && !io.robCommits.isWalk
250        fpFreeList.io.freePhyReg(i) := io.robCommits.info(i).old_pdest
251      } else { // Integer free list
252        intFreeList.io.freeReq(i) := intRefCounter.io.freeRegs(i).valid
253        intFreeList.io.freePhyReg(i) := intRefCounter.io.freeRegs(i).bits
254      }
255    }
256    intRefCounter.io.deallocate(i).valid := io.robCommits.valid(i) && needDestRegCommit(false, io.robCommits.info(i))
257    intRefCounter.io.deallocate(i).bits := Mux(io.robCommits.isWalk, io.robCommits.info(i).pdest, io.robCommits.info(i).old_pdest)
258  }
259
260  /*
261  Debug and performance counters
262   */
263  def printRenameInfo(in: DecoupledIO[CfCtrl], out: DecoupledIO[MicroOp]) = {
264    XSInfo(out.fire, p"pc:${Hexadecimal(in.bits.cf.pc)} in(${in.valid},${in.ready}) " +
265      p"lsrc(0):${in.bits.ctrl.lsrc(0)} -> psrc(0):${out.bits.psrc(0)} " +
266      p"lsrc(1):${in.bits.ctrl.lsrc(1)} -> psrc(1):${out.bits.psrc(1)} " +
267      p"lsrc(2):${in.bits.ctrl.lsrc(2)} -> psrc(2):${out.bits.psrc(2)} " +
268      p"ldest:${in.bits.ctrl.ldest} -> pdest:${out.bits.pdest} " +
269      p"old_pdest:${out.bits.old_pdest}\n"
270    )
271  }
272
273  for((x,y) <- io.in.zip(io.out)){
274    printRenameInfo(x, y)
275  }
276
277  XSDebug(io.robCommits.isWalk, p"Walk Recovery Enabled\n")
278  XSDebug(io.robCommits.isWalk, p"validVec:${Binary(io.robCommits.valid.asUInt)}\n")
279  for (i <- 0 until CommitWidth) {
280    val info = io.robCommits.info(i)
281    XSDebug(io.robCommits.isWalk && io.robCommits.valid(i), p"[#$i walk info] pc:${Hexadecimal(info.pc)} " +
282      p"ldest:${info.ldest} rfWen:${info.rfWen} fpWen:${info.fpWen} " + p"eliminatedMove:${info.eliminatedMove} " +
283      p"pdest:${info.pdest} old_pdest:${info.old_pdest}\n")
284  }
285
286  XSDebug(p"inValidVec: ${Binary(Cat(io.in.map(_.valid)))}\n")
287
288  XSPerfAccumulate("in", Mux(RegNext(io.in(0).ready), PopCount(io.in.map(_.valid)), 0.U))
289  XSPerfAccumulate("utilization", PopCount(io.in.map(_.valid)))
290  XSPerfAccumulate("waitInstr", PopCount((0 until RenameWidth).map(i => io.in(i).valid && !io.in(i).ready)))
291  XSPerfAccumulate("stall_cycle_dispatch", hasValid && !io.out(0).ready && fpFreeList.io.canAllocate && intFreeList.io.canAllocate && !io.robCommits.isWalk)
292  XSPerfAccumulate("stall_cycle_fp", hasValid && io.out(0).ready && !fpFreeList.io.canAllocate && intFreeList.io.canAllocate && !io.robCommits.isWalk)
293  XSPerfAccumulate("stall_cycle_int", hasValid && io.out(0).ready && fpFreeList.io.canAllocate && !intFreeList.io.canAllocate && !io.robCommits.isWalk)
294  XSPerfAccumulate("stall_cycle_walk", hasValid && io.out(0).ready && fpFreeList.io.canAllocate && intFreeList.io.canAllocate && io.robCommits.isWalk)
295
296  XSPerfAccumulate("move_instr_count", PopCount(io.out.map(out => out.fire() && out.bits.ctrl.isMove)))
297}
298