xref: /XiangShan/src/main/scala/xiangshan/mem/vector/VecCommon.scala (revision c035529718e1497576294297592784096deeb73e)
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.mem
18
19import org.chipsalliance.cde.config.Parameters
20import chisel3._
21import chisel3.util._
22import utils._
23import utility._
24import xiangshan._
25import xiangshan.backend.rob.RobPtr
26import xiangshan.backend.Bundles._
27import xiangshan.backend.fu.FuType
28import xiangshan.backend.fu.vector.Bundles.VEew
29
30/**
31  * Common used parameters or functions in vlsu
32  */
33trait VLSUConstants {
34  val VLEN = 128
35  //for pack unit-stride flow
36  val AlignedNum = 4 // 1/2/4/8
37  def VLENB = VLEN/8
38  def vOffsetBits = log2Up(VLENB) // bits-width to index offset inside a vector reg
39  lazy val vlmBindexBits = 8 //will be overrided later
40  lazy val vsmBindexBits = 8 // will be overrided later
41
42  def alignTypes = 5 // eew/sew = 1/2/4/8, last indicate 128 bit element
43  def alignTypeBits = log2Up(alignTypes)
44  def maxMUL = 8
45  def maxFields = 8
46  /**
47    * In the most extreme cases like a segment indexed instruction, eew=64, emul=8, sew=8, lmul=1,
48    * and nf=8, each data reg is mapped with 8 index regs and there are 8 data regs in total,
49    * each for a field. Therefore an instruction can be divided into 64 uops at most.
50    */
51  def maxUopNum = maxMUL * maxFields // 64
52  def maxFlowNum = 16
53  def maxElemNum = maxMUL * maxFlowNum // 128
54  // def uopIdxBits = log2Up(maxUopNum) // to index uop inside an robIdx
55  def elemIdxBits = log2Up(maxElemNum) + 1 // to index which element in an instruction
56  def flowIdxBits = log2Up(maxFlowNum) + 1 // to index which flow in a uop
57  def fieldBits = log2Up(maxFields) + 1 // 4-bits to indicate 1~8
58
59  def ewBits = 3 // bits-width of EEW/SEW
60  def mulBits = 3 // bits-width of emul/lmul
61
62  def getSlice(data: UInt, i: Int, alignBits: Int): UInt = {
63    require(data.getWidth >= (i+1) * alignBits)
64    data((i+1) * alignBits - 1, i * alignBits)
65  }
66  def getNoAlignedSlice(data: UInt, i: Int, alignBits: Int): UInt = {
67    data(i * 8 + alignBits - 1, i * 8)
68  }
69
70  def getByte(data: UInt, i: Int = 0) = getSlice(data, i, 8)
71  def getHalfWord(data: UInt, i: Int = 0) = getSlice(data, i, 16)
72  def getWord(data: UInt, i: Int = 0) = getSlice(data, i, 32)
73  def getDoubleWord(data: UInt, i: Int = 0) = getSlice(data, i, 64)
74  def getDoubleDoubleWord(data: UInt, i: Int = 0) = getSlice(data, i, 128)
75}
76
77trait HasVLSUParameters extends HasXSParameter with VLSUConstants {
78  override val VLEN = coreParams.VLEN
79  override lazy val vlmBindexBits = log2Up(coreParams.VlMergeBufferSize)
80  override lazy val vsmBindexBits = log2Up(coreParams.VsMergeBufferSize)
81  lazy val maxMemByteNum = 16 // Maximum bytes for a single memory access
82  /**
83   * get addr aligned low bits
84   * @param addr Address to be check
85   * @param width Width for checking alignment
86   */
87  def getCheckAddrLowBits(addr: UInt, width: Int): UInt = addr(log2Up(width) - 1, 0)
88  def getOverflowBit(in: UInt, width: Int): UInt = in(log2Up(width))
89  def isUnitStride(instType: UInt) = instType(1, 0) === "b00".U
90  def isStrided(instType: UInt) = instType(1, 0) === "b10".U
91  def isIndexed(instType: UInt) = instType(0) === "b1".U
92  def isNotIndexed(instType: UInt) = instType(0) === "b0".U
93  def isSegment(instType: UInt) = instType(2) === "b1".U
94  def is128Bit(alignedType: UInt) = alignedType(2) === "b1".U
95
96  def mergeDataWithMask(oldData: UInt, newData: UInt, mask: UInt): Vec[UInt] = {
97    require(oldData.getWidth == newData.getWidth)
98    require(oldData.getWidth == mask.getWidth * 8)
99    VecInit(mask.asBools.zipWithIndex.map { case (en, i) =>
100      Mux(en, getByte(newData, i), getByte(oldData, i))
101    })
102  }
103
104  // def asBytes(data: UInt) = {
105  //   require(data.getWidth % 8 == 0)
106  //   (0 until data.getWidth/8).map(i => getByte(data, i))
107  // }
108
109  def mergeDataWithElemIdx(
110    oldData: UInt,
111    newData: Seq[UInt],
112    alignedType: UInt,
113    elemIdx: Seq[UInt],
114    valids: Seq[Bool]
115  ): UInt = {
116    require(newData.length == elemIdx.length)
117    require(newData.length == valids.length)
118    LookupTree(alignedType, List(
119      "b00".U -> VecInit(elemIdx.map(e => UIntToOH(e(3, 0)).asBools).transpose.zipWithIndex.map { case (selVec, i) =>
120        ParallelPosteriorityMux(
121          true.B +: selVec.zip(valids).map(x => x._1 && x._2),
122          getByte(oldData, i) +: newData.map(getByte(_))
123        )}).asUInt,
124      "b01".U -> VecInit(elemIdx.map(e => UIntToOH(e(2, 0)).asBools).transpose.zipWithIndex.map { case (selVec, i) =>
125        ParallelPosteriorityMux(
126          true.B +: selVec.zip(valids).map(x => x._1 && x._2),
127          getHalfWord(oldData, i) +: newData.map(getHalfWord(_))
128        )}).asUInt,
129      "b10".U -> VecInit(elemIdx.map(e => UIntToOH(e(1, 0)).asBools).transpose.zipWithIndex.map { case (selVec, i) =>
130        ParallelPosteriorityMux(
131          true.B +: selVec.zip(valids).map(x => x._1 && x._2),
132          getWord(oldData, i) +: newData.map(getWord(_))
133        )}).asUInt,
134      "b11".U -> VecInit(elemIdx.map(e => UIntToOH(e(0)).asBools).transpose.zipWithIndex.map { case (selVec, i) =>
135        ParallelPosteriorityMux(
136          true.B +: selVec.zip(valids).map(x => x._1 && x._2),
137          getDoubleWord(oldData, i) +: newData.map(getDoubleWord(_))
138        )}).asUInt
139    ))
140  }
141
142  def mergeDataWithElemIdx(oldData: UInt, newData: UInt, alignedType: UInt, elemIdx: UInt): UInt = {
143    mergeDataWithElemIdx(oldData, Seq(newData), alignedType, Seq(elemIdx), Seq(true.B))
144  }
145  /**
146    * for merge 128-bits data of unit-stride
147    */
148  object mergeDataByByte{
149    def apply(oldData: UInt, newData: UInt, mask: UInt): UInt = {
150      val selVec = Seq(mask).map(_.asBools).transpose
151      VecInit(selVec.zipWithIndex.map{ case (selV, i) =>
152        ParallelPosteriorityMux(
153          true.B +: selV.map(x => x),
154          getByte(oldData, i) +: Seq(getByte(newData, i))
155        )}).asUInt
156    }
157  }
158
159  /**
160    * for merge Unit-Stride data to 256-bits
161    * merge 128-bits data to 256-bits
162    * if have 3 port,
163    *   if is port0, it is 6 to 1 Multiplexer -> (128'b0, data) or (data, 128'b0) or (data, port2data) or (port2data, data) or (data, port3data) or (port3data, data)
164    *   if is port1, it is 4 to 1 Multiplexer -> (128'b0, data) or (data, 128'b0) or (data, port3data) or (port3data, data)
165    *   if is port3, it is 2 to 1 Multiplexer -> (128'b0, data) or (data, 128'b0)
166    *
167    */
168  object mergeDataByIndex{
169    def apply(data:  Seq[UInt], mask: Seq[UInt], index: UInt, valids: Seq[Bool]): (UInt, UInt) = {
170      require(data.length == valids.length)
171      require(data.length == mask.length)
172      val muxLength = data.length
173      val selDataMatrix = Wire(Vec(muxLength, Vec(2, UInt((VLEN * 2).W)))) // 3 * 2 * 256
174      val selMaskMatrix = Wire(Vec(muxLength, Vec(2, UInt((VLENB * 2).W)))) // 3 * 2 * 16
175      dontTouch(selDataMatrix)
176      dontTouch(selMaskMatrix)
177      for(i <- 0 until muxLength){
178        if(i == 0){
179          selDataMatrix(i)(0) := Cat(0.U(VLEN.W), data(i))
180          selDataMatrix(i)(1) := Cat(data(i), 0.U(VLEN.W))
181          selMaskMatrix(i)(0) := Cat(0.U(VLENB.W), mask(i))
182          selMaskMatrix(i)(1) := Cat(mask(i), 0.U(VLENB.W))
183        }
184        else{
185          selDataMatrix(i)(0) := Cat(data(i), data(0))
186          selDataMatrix(i)(1) := Cat(data(0), data(i))
187          selMaskMatrix(i)(0) := Cat(mask(i), mask(0))
188          selMaskMatrix(i)(1) := Cat(mask(0), mask(i))
189        }
190      }
191      val selIdxVec = (0 until muxLength).map(_.U)
192      val selIdx    = PriorityMux(valids.reverse, selIdxVec.reverse)
193
194      val selData = Mux(index === 0.U,
195                        selDataMatrix(selIdx)(0),
196                        selDataMatrix(selIdx)(1))
197      val selMask = Mux(index === 0.U,
198                        selMaskMatrix(selIdx)(0),
199                        selMaskMatrix(selIdx)(1))
200      (selData, selMask)
201    }
202  }
203  def mergeDataByIndex(data:  UInt, mask: UInt, index: UInt): (UInt, UInt) = {
204    mergeDataByIndex(Seq(data), Seq(mask), index, Seq(true.B))
205  }
206}
207abstract class VLSUModule(implicit p: Parameters) extends XSModule
208  with HasVLSUParameters
209  with HasCircularQueuePtrHelper
210abstract class VLSUBundle(implicit p: Parameters) extends XSBundle
211  with HasVLSUParameters
212
213class VLSUBundleWithMicroOp(implicit p: Parameters) extends VLSUBundle {
214  val uop = new DynInst
215}
216
217class OnlyVecExuOutput(implicit p: Parameters) extends VLSUBundle {
218  val isvec = Bool()
219  val vecdata = UInt(VLEN.W)
220  val mask = UInt(VLENB.W)
221  // val rob_idx_valid = Vec(2, Bool())
222  // val inner_idx = Vec(2, UInt(3.W))
223  // val rob_idx = Vec(2, new RobPtr)
224  // val offset = Vec(2, UInt(4.W))
225  val reg_offset = UInt(vOffsetBits.W)
226  val vecActive = Bool() // 1: vector active element, 0: vector not active element
227  val is_first_ele = Bool()
228  val elemIdx = UInt(elemIdxBits.W) // element index
229  val elemIdxInsideVd = UInt(elemIdxBits.W) // element index in scope of vd
230  val trigger = TriggerAction()
231  // val uopQueuePtr = new VluopPtr
232  // val flowPtr = new VlflowPtr
233}
234
235class VecExuOutput(implicit p: Parameters) extends MemExuOutput with HasVLSUParameters {
236  val vec = new OnlyVecExuOutput
237  val alignedType       = UInt(alignTypeBits.W)
238   // feedback
239  val vecFeedback       = Bool()
240}
241
242class VecUopBundle(implicit p: Parameters) extends VLSUBundleWithMicroOp {
243  val flowMask       = UInt(VLENB.W) // each bit for a flow
244  val byteMask       = UInt(VLENB.W) // each bit for a byte
245  val data           = UInt(VLEN.W)
246  // val fof            = Bool() // fof is only used for vector loads
247  val excp_eew_index = UInt(elemIdxBits.W)
248  // val exceptionVec   = ExceptionVec() // uop has exceptionVec
249  val baseAddr = UInt(VAddrBits.W)
250  val stride = UInt(VLEN.W)
251  val flow_counter = UInt(flowIdxBits.W)
252
253  // instruction decode result
254  val flowNum = UInt(flowIdxBits.W) // # of flows in a uop
255  // val flowNumLog2 = UInt(log2Up(flowIdxBits).W) // log2(flowNum), for better timing of multiplication
256  val nfields = UInt(fieldBits.W) // NFIELDS
257  val vm = Bool() // whether vector masking is enabled
258  val usWholeReg = Bool() // unit-stride, whole register load
259  val usMaskReg = Bool() // unit-stride, masked store/load
260  val eew = VEew() // size of memory elements
261  val sew = UInt(ewBits.W)
262  val emul = UInt(mulBits.W)
263  val lmul = UInt(mulBits.W)
264  val vlmax = UInt(elemIdxBits.W)
265  val instType = UInt(3.W)
266  val vd_last_uop = Bool()
267  val vd_first_uop = Bool()
268}
269
270class VecFlowBundle(implicit p: Parameters) extends VLSUBundleWithMicroOp {
271  val vaddr             = UInt(VAddrBits.W)
272  val mask              = UInt(VLENB.W)
273  val alignedType       = UInt(alignTypeBits.W)
274  val vecActive         = Bool()
275  val elemIdx           = UInt(elemIdxBits.W)
276  val is_first_ele      = Bool()
277
278  // pack
279  val isPackage         = Bool()
280  val packageNum        = UInt((log2Up(VLENB) + 1).W)
281  val originAlignedType = UInt(alignTypeBits.W)
282}
283
284class VecMemExuOutput(isVector: Boolean = false)(implicit p: Parameters) extends VLSUBundle{
285  val output = new MemExuOutput(isVector)
286  val vecFeedback = Bool()
287  val mmio = Bool()
288  val usSecondInv = Bool()
289  val elemIdx = UInt(elemIdxBits.W)
290  val alignedType = UInt(alignTypeBits.W)
291  val mbIndex     = UInt(vsmBindexBits.W)
292  val mask        = UInt(VLENB.W)
293  val vaddr       = UInt(XLEN.W)
294  val vaNeedExt   = Bool()
295  val gpaddr      = UInt(GPAddrBits.W)
296  val isForVSnonLeafPTE = Bool()
297  val vecVaddrOffset = UInt(VAddrBits.W)
298}
299
300object MulNum {
301  def apply (mul: UInt): UInt = { //mul means emul or lmul
302    (LookupTree(mul,List(
303      "b101".U -> 1.U , // 1/8
304      "b110".U -> 1.U , // 1/4
305      "b111".U -> 1.U , // 1/2
306      "b000".U -> 1.U , // 1
307      "b001".U -> 2.U , // 2
308      "b010".U -> 4.U , // 4
309      "b011".U -> 8.U   // 8
310    )))}
311}
312/**
313  * when emul is greater than or equal to 1, this means the entire register needs to be written;
314  * otherwise, only write the specified number of bytes */
315object MulDataSize {
316  def apply (mul: UInt): UInt = { //mul means emul or lmul
317    (LookupTree(mul,List(
318      "b101".U -> 2.U  , // 1/8
319      "b110".U -> 4.U  , // 1/4
320      "b111".U -> 8.U  , // 1/2
321      "b000".U -> 16.U , // 1
322      "b001".U -> 16.U , // 2
323      "b010".U -> 16.U , // 4
324      "b011".U -> 16.U   // 8
325    )))}
326}
327
328object OneRegNum {
329  def apply (eew: UInt): UInt = { //mul means emul or lmul
330    require(eew.getWidth == 2, "The eew width must be 2.")
331    (LookupTree(eew, List(
332      "b00".U -> 16.U , // 1
333      "b01".U ->  8.U , // 2
334      "b10".U ->  4.U , // 4
335      "b11".U ->  2.U   // 8
336    )))}
337}
338
339//index inst read data byte
340object SewDataSize {
341  def apply (sew: UInt): UInt = {
342    (LookupTree(sew,List(
343      "b000".U -> 1.U , // 1
344      "b001".U -> 2.U , // 2
345      "b010".U -> 4.U , // 4
346      "b011".U -> 8.U   // 8
347    )))}
348}
349
350// strided inst read data byte
351object EewDataSize {
352  def apply (eew: UInt): UInt = {
353    require(eew.getWidth == 2, "The eew width must be 2.")
354    (LookupTree(eew, List(
355      "b00".U -> 1.U , // 1
356      "b01".U -> 2.U , // 2
357      "b10".U -> 4.U , // 4
358      "b11".U -> 8.U   // 8
359    )))}
360}
361
362object loadDataSize {
363  def apply (instType: UInt, emul: UInt, eew: UInt, sew: UInt): UInt = {
364    (LookupTree(instType,List(
365      "b000".U ->  MulDataSize(emul), // unit-stride
366      "b010".U ->  EewDataSize(eew)  , // strided
367      "b001".U ->  SewDataSize(sew)  , // indexed-unordered
368      "b011".U ->  SewDataSize(sew)  , // indexed-ordered
369      "b100".U ->  EewDataSize(eew)  , // segment unit-stride
370      "b110".U ->  EewDataSize(eew)  , // segment strided
371      "b101".U ->  SewDataSize(sew)  , // segment indexed-unordered
372      "b111".U ->  SewDataSize(sew)    // segment indexed-ordered
373    )))}
374}
375
376object storeDataSize {
377  def apply (instType: UInt, eew: UInt, sew: UInt): UInt = {
378    (LookupTree(instType,List(
379      "b000".U ->  EewDataSize(eew)  , // unit-stride, do not use
380      "b010".U ->  EewDataSize(eew)  , // strided
381      "b001".U ->  SewDataSize(sew)  , // indexed-unordered
382      "b011".U ->  SewDataSize(sew)  , // indexed-ordered
383      "b100".U ->  EewDataSize(eew)  , // segment unit-stride
384      "b110".U ->  EewDataSize(eew)  , // segment strided
385      "b101".U ->  SewDataSize(sew)  , // segment indexed-unordered
386      "b111".U ->  SewDataSize(sew)    // segment indexed-ordered
387    )))}
388}
389
390/**
391  * these are used to obtain immediate addresses for  index instruction */
392object EewEq8 {
393  def apply(index:UInt, flow_inner_idx: UInt): UInt = {
394    (LookupTree(flow_inner_idx,List(
395      0.U  -> index(7 ,0   ),
396      1.U  -> index(15,8   ),
397      2.U  -> index(23,16  ),
398      3.U  -> index(31,24  ),
399      4.U  -> index(39,32  ),
400      5.U  -> index(47,40  ),
401      6.U  -> index(55,48  ),
402      7.U  -> index(63,56  ),
403      8.U  -> index(71,64  ),
404      9.U  -> index(79,72  ),
405      10.U -> index(87,80  ),
406      11.U -> index(95,88  ),
407      12.U -> index(103,96 ),
408      13.U -> index(111,104),
409      14.U -> index(119,112),
410      15.U -> index(127,120)
411    )))}
412}
413
414object EewEq16 {
415  def apply(index: UInt, flow_inner_idx: UInt): UInt = {
416    (LookupTree(flow_inner_idx, List(
417      0.U -> index(15, 0),
418      1.U -> index(31, 16),
419      2.U -> index(47, 32),
420      3.U -> index(63, 48),
421      4.U -> index(79, 64),
422      5.U -> index(95, 80),
423      6.U -> index(111, 96),
424      7.U -> index(127, 112)
425    )))}
426}
427
428object EewEq32 {
429  def apply(index: UInt, flow_inner_idx: UInt): UInt = {
430    (LookupTree(flow_inner_idx, List(
431      0.U -> index(31, 0),
432      1.U -> index(63, 32),
433      2.U -> index(95, 64),
434      3.U -> index(127, 96)
435    )))}
436}
437
438object EewEq64 {
439  def apply (index: UInt, flow_inner_idx: UInt): UInt = {
440    (LookupTree(flow_inner_idx, List(
441      0.U -> index(63, 0),
442      1.U -> index(127, 64)
443    )))}
444}
445
446object IndexAddr {
447  def apply (index: UInt, flow_inner_idx: UInt, eew: UInt): UInt = {
448    require(eew.getWidth == 2, "The eew width must be 2.")
449    (LookupTree(eew, List(
450      "b00".U -> EewEq8 (index = index, flow_inner_idx = flow_inner_idx ), // Imm is 1 Byte // TODO: index maybe cross register
451      "b01".U -> EewEq16(index = index, flow_inner_idx = flow_inner_idx ), // Imm is 2 Byte
452      "b10".U -> EewEq32(index = index, flow_inner_idx = flow_inner_idx ), // Imm is 4 Byte
453      "b11".U -> EewEq64(index = index, flow_inner_idx = flow_inner_idx )  // Imm is 8 Byte
454    )))}
455}
456
457object Log2Num {
458  def apply (num: UInt): UInt = {
459    (LookupTree(num,List(
460      16.U -> 4.U,
461      8.U  -> 3.U,
462      4.U  -> 2.U,
463      2.U  -> 1.U,
464      1.U  -> 0.U
465    )))}
466}
467
468object GenUopIdxInField {
469  /**
470   * Used in normal vector instruction
471   * */
472  def apply (instType: UInt, emul: UInt, lmul: UInt, uopIdx: UInt): UInt = {
473    val isIndexed = instType(0)
474    val mulInField = Mux(
475      isIndexed,
476      Mux(lmul.asSInt > emul.asSInt, lmul, emul),
477      emul
478    )
479    LookupTree(mulInField, List(
480      "b101".U -> 0.U,
481      "b110".U -> 0.U,
482      "b111".U -> 0.U,
483      "b000".U -> 0.U,
484      "b001".U -> uopIdx(0),
485      "b010".U -> uopIdx(1, 0),
486      "b011".U -> uopIdx(2, 0)
487    ))
488  }
489  /**
490   *  Only used in segment instruction.
491   * */
492  def apply (select: UInt, uopIdx: UInt): UInt = {
493    LookupTree(select, List(
494      "b101".U -> 0.U,
495      "b110".U -> 0.U,
496      "b111".U -> 0.U,
497      "b000".U -> 0.U,
498      "b001".U -> uopIdx(0),
499      "b010".U -> uopIdx(1, 0),
500      "b011".U -> uopIdx(2, 0)
501    ))
502  }
503}
504
505//eew decode
506object EewLog2 extends VLSUConstants {
507  // def apply (eew: UInt): UInt = {
508  //   (LookupTree(eew,List(
509  //     "b000".U -> "b000".U , // 1
510  //     "b101".U -> "b001".U , // 2
511  //     "b110".U -> "b010".U , // 4
512  //     "b111".U -> "b011".U   // 8
513  //   )))}
514  def apply(eew: UInt): UInt = {
515    require(eew.getWidth == 2, "The eew width must be 2.")
516    ZeroExt(eew, ewBits)
517  }
518}
519
520object GenRealFlowNum {
521  /**
522   * unit-stride instructions don't use this method;
523   * other instructions generate realFlowNum by EmulDataSize >> eew,
524   * EmulDataSize means the number of bytes that need to be written to the register,
525   * eew means the number of bytes written at once.
526   *
527   * @param instType As the name implies.
528   * @param emul As the name implies.
529   * @param lmul As the name implies.
530   * @param eew As the name implies.
531   * @param sew As the name implies.
532   * @param isSegment Only modules related to segment need to be set to true.
533   * @return FlowNum of instruction.
534   *
535   */
536  def apply (instType: UInt, emul: UInt, lmul: UInt, eew: UInt, sew: UInt, isSegment: Boolean = false): UInt = {
537    require(instType.getWidth == 3, "The instType width must be 3, (isSegment, mop)")
538    require(eew.getWidth == 2, "The eew width must be 2.")
539    // Because the new segmentunit is needed. But the previous implementation is retained for the time being in case of emergency.
540    val segmentIndexFlowNum =  if (isSegment) (MulDataSize(lmul) >> sew(1,0)).asUInt
541    else Mux(emul.asSInt > lmul.asSInt, (MulDataSize(emul) >> eew).asUInt, (MulDataSize(lmul) >> sew(1,0)).asUInt)
542    (LookupTree(instType,List(
543      "b000".U ->  (MulDataSize(emul) >> eew).asUInt, // store use, load do not use
544      "b010".U ->  (MulDataSize(emul) >> eew).asUInt, // strided
545      "b001".U ->  Mux(emul.asSInt > lmul.asSInt, (MulDataSize(emul) >> eew).asUInt, (MulDataSize(lmul) >> sew(1,0)).asUInt), // indexed-unordered
546      "b011".U ->  Mux(emul.asSInt > lmul.asSInt, (MulDataSize(emul) >> eew).asUInt, (MulDataSize(lmul) >> sew(1,0)).asUInt), // indexed-ordered
547      "b100".U ->  (MulDataSize(emul) >> eew).asUInt, // segment unit-stride
548      "b110".U ->  (MulDataSize(emul) >> eew).asUInt, // segment strided
549      "b101".U ->  segmentIndexFlowNum, // segment indexed-unordered
550      "b111".U ->  segmentIndexFlowNum  // segment indexed-ordered
551    )))}
552}
553
554object GenRealFlowLog2 extends VLSUConstants {
555  /**
556   * GenRealFlowLog2 = Log2(GenRealFlowNum)
557   *
558   * @param instType As the name implies.
559   * @param emul As the name implies.
560   * @param lmul As the name implies.
561   * @param eew As the name implies.
562   * @param sew As the name implies.
563   * @param isSegment Only modules related to segment need to be set to true.
564   * @return FlowNumLog2 of instruction.
565   */
566  def apply(instType: UInt, emul: UInt, lmul: UInt, eew: UInt, sew: UInt, isSegment: Boolean = false): UInt = {
567    require(instType.getWidth == 3, "The instType width must be 3, (isSegment, mop)")
568    require(eew.getWidth == 2, "The eew width must be 2.")
569    val emulLog2 = Mux(emul.asSInt >= 0.S, 0.U, emul)
570    val lmulLog2 = Mux(lmul.asSInt >= 0.S, 0.U, lmul)
571    val eewRealFlowLog2 = emulLog2 + log2Up(VLENB).U - eew
572    val sewRealFlowLog2 = lmulLog2 + log2Up(VLENB).U - sew(1, 0)
573    // Because the new segmentunit is needed. But the previous implementation is retained for the time being in case of emergency.
574    val segmentIndexFlowLog2 = if (isSegment) sewRealFlowLog2 else Mux(emul.asSInt > lmul.asSInt, eewRealFlowLog2, sewRealFlowLog2)
575    (LookupTree(instType, List(
576      "b000".U -> eewRealFlowLog2, // unit-stride
577      "b010".U -> eewRealFlowLog2, // strided
578      "b001".U -> Mux(emul.asSInt > lmul.asSInt, eewRealFlowLog2, sewRealFlowLog2), // indexed-unordered
579      "b011".U -> Mux(emul.asSInt > lmul.asSInt, eewRealFlowLog2, sewRealFlowLog2), // indexed-ordered
580      "b100".U -> eewRealFlowLog2, // segment unit-stride
581      "b110".U -> eewRealFlowLog2, // segment strided
582      "b101".U -> segmentIndexFlowLog2, // segment indexed-unordered
583      "b111".U -> segmentIndexFlowLog2, // segment indexed-ordered
584    )))
585  }
586}
587
588/**
589  * GenElemIdx generals an element index within an instruction, given a certain uopIdx and a known flowIdx
590  * inside the uop.
591  */
592object GenElemIdx extends VLSUConstants {
593  def apply(instType: UInt, emul: UInt, lmul: UInt, eew: UInt, sew: UInt,
594            uopIdx: UInt, flowIdx: UInt): UInt = {
595    require(eew.getWidth == 2, "The eew width must be 2.")
596    val isIndexed = instType(0).asBool
597    val eewUopFlowsLog2 = Mux(emul.asSInt > 0.S, 0.U, emul) + log2Up(VLENB).U - eew
598    val sewUopFlowsLog2 = Mux(lmul.asSInt > 0.S, 0.U, lmul) + log2Up(VLENB).U - sew(1, 0)
599    val uopFlowsLog2 = Mux(
600      isIndexed,
601      Mux(emul.asSInt > lmul.asSInt, eewUopFlowsLog2, sewUopFlowsLog2),
602      eewUopFlowsLog2
603    )
604    LookupTree(uopFlowsLog2, List(
605      0.U -> uopIdx,
606      1.U -> uopIdx ## flowIdx(0),
607      2.U -> uopIdx ## flowIdx(1, 0),
608      3.U -> uopIdx ## flowIdx(2, 0),
609      4.U -> uopIdx ## flowIdx(3, 0)
610    ))
611  }
612}
613
614/**
615  * GenVLMAX calculates VLMAX, which equals MUL * ew
616  */
617object GenVLMAXLog2 extends VLSUConstants {
618  def apply(lmul: UInt, sew: UInt): UInt = lmul + log2Up(VLENB).U - sew
619}
620object GenVLMAX {
621  def apply(lmul: UInt, sew: UInt): UInt = 1.U << GenVLMAXLog2(lmul, sew)
622}
623/**
624 * generate mask base on vlmax
625 * example: vlmax = b100, max = b011
626 * */
627object GenVlMaxMask{
628  def apply(vlmax: UInt, length: Int): UInt = (vlmax - 1.U)(length-1, 0)
629}
630
631object GenUSWholeRegVL extends VLSUConstants {
632  def apply(nfields: UInt, eew: UInt): UInt = {
633    require(eew.getWidth == 2, "The eew width must be 2.")
634    LookupTree(eew, List(
635      "b00".U -> (nfields << (log2Up(VLENB) - 0)),
636      "b01".U -> (nfields << (log2Up(VLENB) - 1)),
637      "b10".U -> (nfields << (log2Up(VLENB) - 2)),
638      "b11".U -> (nfields << (log2Up(VLENB) - 3))
639    ))
640  }
641}
642object GenUSWholeEmul extends VLSUConstants{
643  def apply(nf: UInt): UInt={
644    LookupTree(nf,List(
645      "b000".U -> "b000".U(mulBits.W),
646      "b001".U -> "b001".U(mulBits.W),
647      "b011".U -> "b010".U(mulBits.W),
648      "b111".U -> "b011".U(mulBits.W)
649    ))
650  }
651}
652
653
654object GenUSMaskRegVL extends VLSUConstants {
655  def apply(vl: UInt): UInt = {
656    Mux(vl(2,0) === 0.U , (vl >> 3.U), ((vl >> 3.U) + 1.U))
657  }
658}
659
660object GenUopByteMask {
661  def apply(flowMask: UInt, alignedType: UInt): UInt = {
662    LookupTree(alignedType, List(
663      "b000".U -> flowMask,
664      "b001".U -> FillInterleaved(2, flowMask),
665      "b010".U -> FillInterleaved(4, flowMask),
666      "b011".U -> FillInterleaved(8, flowMask),
667      "b100".U -> FillInterleaved(16, flowMask)
668    ))
669  }
670}
671
672object GenVdIdxInField extends VLSUConstants {
673  def apply(instType: UInt, emul: UInt, lmul: UInt, uopIdx: UInt): UInt = {
674    val vdIdx = Wire(UInt(log2Up(maxMUL).W))
675    when (instType(1,0) === "b00".U || instType(1,0) === "b10".U || lmul.asSInt > emul.asSInt) {
676      // Unit-stride or Strided, or indexed with lmul >= emul
677      vdIdx := uopIdx
678    }.otherwise {
679      // Indexed with lmul <= emul
680      val multiple = emul - lmul
681      val uopIdxWidth = uopIdx.getWidth
682      vdIdx := LookupTree(multiple, List(
683        0.U -> uopIdx,
684        1.U -> (uopIdx >> 1),
685        2.U -> (uopIdx >> 2),
686        3.U -> (uopIdx >> 3)
687      ))
688    }
689    vdIdx
690  }
691}
692/**
693* Use start and vl to generate flow activative mask
694* mod = true fill 0
695* mod = false fill 1
696*/
697object GenFlowMask extends VLSUConstants {
698  def apply(elementMask: UInt, start: UInt, vl: UInt , mod: Boolean): UInt = {
699    val startMask = ~UIntToMask(start, VLEN)
700    val vlMask = UIntToMask(vl, VLEN)
701    val maskVlStart = vlMask & startMask
702    if(mod){
703      elementMask & maskVlStart
704    }
705    else{
706      (~elementMask).asUInt & maskVlStart
707    }
708  }
709}
710
711object genVWmask128 {
712  def apply(addr: UInt, sizeEncode: UInt): UInt = {
713    (LookupTree(sizeEncode, List(
714      "b000".U -> 0x1.U, //0001 << addr(2:0)
715      "b001".U -> 0x3.U, //0011
716      "b010".U -> 0xf.U, //1111
717      "b011".U -> 0xff.U, //11111111
718      "b100".U -> 0xffff.U //1111111111111111
719    )) << addr(3, 0)).asUInt
720  }
721}
722/*
723* only use in max length is 128
724*/
725object genVWdata {
726  def apply(data: UInt, sizeEncode: UInt): UInt = {
727    LookupTree(sizeEncode, List(
728      "b000".U -> Fill(16, data(7, 0)),
729      "b001".U -> Fill(8, data(15, 0)),
730      "b010".U -> Fill(4, data(31, 0)),
731      "b011".U -> Fill(2, data(63,0)),
732      "b100".U -> data(127,0)
733    ))
734  }
735}
736
737object genUSSplitAddr{
738  def apply(addr: UInt, index: UInt, width: Int): UInt = {
739    val tmpAddr = Cat(addr(width - 1, 4), 0.U(4.W))
740    val nextCacheline = tmpAddr + 16.U
741    LookupTree(index, List(
742      0.U -> tmpAddr,
743      1.U -> nextCacheline
744    ))
745  }
746}
747
748object genUSSplitMask{
749  def apply(mask: UInt, index: UInt): UInt = {
750    require(mask.getWidth == 32) // need to be 32-bits
751    LookupTree(index, List(
752      0.U -> mask(15, 0),
753      1.U -> mask(31, 16),
754    ))
755  }
756}
757
758object genUSSplitData{
759  def apply(data: UInt, index: UInt, addrOffset: UInt): UInt = {
760    val tmpData = WireInit(0.U(256.W))
761    val lookupTable = (0 until 16).map{case i =>
762      if(i == 0){
763        i.U -> Cat(0.U(128.W), data)
764      }else{
765        i.U -> Cat(0.U(((16-i)*8).W), data, 0.U((i*8).W))
766      }
767    }
768    tmpData := LookupTree(addrOffset, lookupTable).asUInt
769
770    LookupTree(index, List(
771      0.U -> tmpData(127, 0),
772      1.U -> tmpData(255, 128)
773    ))
774  }
775}
776
777object genVSData extends VLSUConstants {
778  def apply(data: UInt, elemIdx: UInt, alignedType: UInt): UInt = {
779    LookupTree(alignedType, List(
780      "b000".U -> ZeroExt(LookupTree(elemIdx(3, 0), List.tabulate(VLEN/8)(i => i.U -> getByte(data, i))), VLEN),
781      "b001".U -> ZeroExt(LookupTree(elemIdx(2, 0), List.tabulate(VLEN/16)(i => i.U -> getHalfWord(data, i))), VLEN),
782      "b010".U -> ZeroExt(LookupTree(elemIdx(1, 0), List.tabulate(VLEN/32)(i => i.U -> getWord(data, i))), VLEN),
783      "b011".U -> ZeroExt(LookupTree(elemIdx(0), List.tabulate(VLEN/64)(i => i.U -> getDoubleWord(data, i))), VLEN),
784      "b100".U -> data // if have wider element, it will broken
785    ))
786  }
787}
788
789// TODO: more elegant
790object genVStride extends VLSUConstants {
791  def apply(uopIdx: UInt, stride: UInt): UInt = {
792    LookupTree(uopIdx, List(
793      0.U -> 0.U,
794      1.U -> stride,
795      2.U -> (stride << 1),
796      3.U -> ((stride << 1).asUInt + stride),
797      4.U -> (stride << 2),
798      5.U -> ((stride << 2).asUInt + stride),
799      6.U -> ((stride << 2).asUInt + (stride << 1)),
800      7.U -> ((stride << 2).asUInt + (stride << 1) + stride)
801    ))
802  }
803}
804/**
805 * generate uopOffset, not used in segment instruction
806 * */
807object genVUopOffset extends VLSUConstants {
808  def apply(instType: UInt, isfof: Bool, uopidx: UInt, nf: UInt, eew: UInt, stride: UInt, alignedType: UInt): UInt = {
809    val uopInsidefield = (uopidx >> nf).asUInt // when nf == 0, is uopidx
810
811    val fofVUopOffset = (LookupTree(instType,List(
812      "b000".U -> ( genVStride(uopInsidefield, stride) << (log2Up(VLENB).U - eew)   ) , // unit-stride fof
813      "b100".U -> ( genVStride(uopInsidefield, stride) << (log2Up(VLENB).U - eew)   ) , // segment unit-stride fof
814    ))).asUInt
815
816    val otherVUopOffset = (LookupTree(instType,List(
817      "b000".U -> ( uopInsidefield << alignedType                                   ) , // unit-stride
818      "b010".U -> ( genVStride(uopInsidefield, stride) << (log2Up(VLENB).U - eew)   ) , // strided
819      "b001".U -> ( 0.U                                                             ) , // indexed-unordered
820      "b011".U -> ( 0.U                                                             ) , // indexed-ordered
821      "b100".U -> ( uopInsidefield << alignedType                                   ) , // segment unit-stride
822      "b110".U -> ( genVStride(uopInsidefield, stride) << (log2Up(VLENB).U - eew)   ) , // segment strided
823      "b101".U -> ( 0.U                                                             ) , // segment indexed-unordered
824      "b111".U -> ( 0.U                                                             )   // segment indexed-ordered
825    ))).asUInt
826
827    Mux(isfof, fofVUopOffset, otherVUopOffset)
828  }
829}
830
831
832
833object genVFirstUnmask extends VLSUConstants {
834  /**
835   * Find the lowest unmasked number of bits.
836   * example:
837   *   mask = 16'b1111_1111_1110_0000
838   *   return 5
839   * @param mask 16bits of mask.
840   * @return lowest unmasked number of bits.
841   */
842  def apply(mask: UInt): UInt = {
843    require(mask.getWidth == 16, "The mask width must be 16")
844    val select = (0 until 16).zip(mask.asBools).map{case (i, v) =>
845      (v, i.U)
846    }
847    PriorityMuxDefault(select, 0.U)
848  }
849
850  def apply(mask: UInt, regOffset: UInt): UInt = {
851    require(mask.getWidth == 16, "The mask width must be 16")
852    val realMask = (mask >> regOffset).asUInt
853    val select = (0 until 16).zip(realMask.asBools).map{case (i, v) =>
854      (v, i.U)
855    }
856    PriorityMuxDefault(select, 0.U)
857  }
858}
859
860class skidBufferConnect[T <: Data](gen: T) extends Module {
861  val io = IO(new Bundle() {
862    val in = Flipped(DecoupledIO(gen.cloneType))
863    val flush = Input(Bool())
864    val out = DecoupledIO(gen.cloneType)
865  })
866
867  skidBuffer.connect(io.in, io.out, io.flush)
868}
869
870object skidBuffer{
871  /*
872  * Skid Buffer used to break timing path of ready
873  * */
874  def connect[T <: Data](
875                          in: DecoupledIO[T],
876                          out: DecoupledIO[T],
877                          flush: Bool
878                        ): T = {
879    val empty :: skid :: Nil = Enum(2)
880    val state      = RegInit(empty)
881    val stateNext  = WireInit(empty)
882    val dataBuffer = RegEnable(in.bits, (!out.ready && in.fire))
883
884    when(state === empty){
885      stateNext := Mux(!out.ready && in.fire && !flush, skid, empty)
886    }.elsewhen(state === skid){
887      stateNext := Mux(out.ready || flush, empty, skid)
888    }
889    state     := stateNext
890
891    in.ready  := state === empty
892    out.bits  := Mux(state === skid, dataBuffer, in.bits)
893    out.valid := in.valid || (state === skid)
894
895    dataBuffer
896  }
897  def apply[T <: Data](
898                        in: DecoupledIO[T],
899                        out: DecoupledIO[T],
900                        flush: Bool,
901                        moduleName: String
902                      ): Unit = {
903    val buffer = Module(new skidBufferConnect(in.bits))
904    buffer.suggestName(moduleName)
905    buffer.io.in <> in
906    buffer.io.flush := flush
907    out <> buffer.io.out
908  }
909}
910
911