xref: /XiangShan/src/main/scala/xiangshan/mem/vector/VSegmentUnit.scala (revision 3088616cbf0793407bb68460b2db89b7de80c12a)
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.mem._
28import xiangshan.backend.fu.FuType
29import freechips.rocketchip.diplomacy.BufferParams
30import xiangshan.cache.mmu._
31import xiangshan.cache._
32import xiangshan.cache.wpu.ReplayCarry
33import xiangshan.backend.fu.util.SdtrigExt
34import xiangshan.ExceptionNO._
35import xiangshan.backend.fu.vector.Bundles.VConfig
36import xiangshan.backend.datapath.NewPipelineConnect
37import xiangshan.backend.fu.vector.Utils.VecDataToMaskDataVec
38
39class VSegmentBundle(implicit p: Parameters) extends VLSUBundle
40{
41  val baseVaddr        = UInt(VAddrBits.W)
42  val uop              = new DynInst
43  val paddr            = UInt(PAddrBits.W)
44  val mask             = UInt(VLEN.W)
45  val alignedType      = UInt(alignTypeBits.W)
46  val vl               = UInt(elemIdxBits.W)
47  val uopFlowNum       = UInt(elemIdxBits.W)
48  val uopFlowNumMask   = UInt(elemIdxBits.W)
49  // for exception
50  val vstart           = UInt(elemIdxBits.W)
51  val exceptionVaddr   = UInt(VAddrBits.W)
52  val exception_va     = Bool()
53  val exception_pa     = Bool()
54  val exceptionVstart  = UInt(elemIdxBits.W)
55  val exceptionVl      = UInt(elemIdxBits.W)
56  val isFof            = Bool()
57}
58
59// latch each uop's VecWen, pdest, v0Wen, uopIdx
60class VSegmentUop(implicit p: Parameters) extends VLSUBundle{
61  val uop              = new DynInst
62}
63
64class VSegmentUnit (implicit p: Parameters) extends VLSUModule
65  with HasDCacheParameters
66  with MemoryOpConstants
67  with SdtrigExt
68  with HasLoadHelper
69{
70  val io               = IO(new VSegmentUnitIO)
71
72  val maxSize          = VSegmentBufferSize
73
74  class VSegUPtr(implicit p: Parameters) extends CircularQueuePtr[VSegUPtr](maxSize){
75  }
76
77  object VSegUPtr {
78    def apply(f: Bool, v: UInt)(implicit p: Parameters): VSegUPtr = {
79      val ptr           = Wire(new VSegUPtr)
80      ptr.flag         := f
81      ptr.value        := v
82      ptr
83    }
84  }
85
86
87  /**
88  ********************************************************************************************************
89  *  Use an example to illustrate the working logic of a segmentunit:                                    *
90  *    For:                                                                                              *
91  *      lmul=2 sew=32 emul=2 eew=32  vl=16                                                              *
92  *    Then:                                                                                             *
93  *      Access memory in the order:                                                                     *
94  *        (V2,S0),(V4,S0),(V6,S0),(V8,S0),                                                              *
95  *        (V2,S1),(V4,S1),(V6,S1),(V8,S1),                                                              *
96  *        (V2,S2),(V4,S2),(V6,S2),(V8,S2),                                                              *
97  *        (V2,S3),(V4,S3),(V6,S3),(V8,S3),                                                              *
98  *        (V3,S4),(V5,S4),(V7,S4),(V9,S4),                                                              *
99  *        (V3,S5),(V5,S5),(V7,S5),(V9,S5),                                                              *
100  *        (V3,S6),(V5,S6),(V7,S6),(V9,S6),                                                              *
101  *        (V3,S7),(V5,S7),(V7,S7),(V9,S7),                                                              *
102  *                                                                                                      *
103  *                                                                                                      *
104  *    [[data]] saves the data generated by the access and corresponds to the register.                  *
105  *    [[splitPtr]] controls the destination register written to.                                        *
106  *                                                                                                      *
107  *    splitptr offset can be seen in [[splitPtrNext]] is assignment logic,                              *
108  *    which is mainly calculated in terms of [[fieldIdx]] and [[segmentIdx]]                            *
109  *    First access different fields of the same segment, and then visit different segments.             *
110  *    For the case of 'emul' greater than 1, such as the following example,                             *
111  *    although 'v2' and 'v3' are different vd and the same field, they are still different segments,    *
112  *    so they should be accessed sequentially.Just like the 'Access memory in the order' above.         *
113  *                                                                                                      *
114  *                         [[segmentIdx]]                                                               *
115  *                               |                                                                      *
116  *                               |                                                                      *
117  *                               V                                                                      *
118  *                                                                                                      *
119  *                               S0               S1                S2                 S3               *
120  *                      ----------------------------------------------------------------------------    *
121  *  [[splitPtr]]--> v2  |     field0     |      field0     |      field0     |      field0         |    *
122  *                      ----------------------------------------------------------------------------    *
123  *                               S4               S5                S6                 S7               *
124  *                      ----------------------------------------------------------------------------    *
125  *                  v3  |     field0     |      field0     |      field0     |      field0         |    *
126  *                      ----------------------------------------------------------------------------    *
127  *                               S0               S1                S2                 S3               *
128  *                      ----------------------------------------------------------------------------    *
129  *                  v4  |     field1     |      field1     |      field1     |      field1         |    *
130  *                      ----------------------------------------------------------------------------    *
131  *                               S4               S5                S6                 S7               *
132  *                      ----------------------------------------------------------------------------    *
133  *                  v5  |     field1     |      field1     |      field1     |      field1         |    *
134  *                      ----------------------------------------------------------------------------    *
135  *                               S0               S1                S2                 S3               *
136  *                      ----------------------------------------------------------------------------    *
137  *                  v6  |     field2     |      field2     |      field2     |      field2         |    *
138  *                      ----------------------------------------------------------------------------    *
139  *                               S4               S5                S6                 S7               *
140  *                      ----------------------------------------------------------------------------    *
141  *                  v7  |     field2     |      field2     |      field2     |      field2         |    *
142  *                      ----------------------------------------------------------------------------    *
143  *                               S0               S1                S2                 S3               *
144  *                      ----------------------------------------------------------------------------    *
145  *                  v8  |     field3     |      field3     |      field3     |      field3         |    *
146  *                      ----------------------------------------------------------------------------    *
147  *                               S4               S5                S6                 S7               *
148  *                      ----------------------------------------------------------------------------    *
149  *                  v9  |     field3     |      field3     |      field3     |      field3         |    *
150  *                      ----------------------------------------------------------------------------    *                                                                                    *
151  *                                                                                                      *                                                                                    *
152  *                                                                                                      *                                                                                    *
153  ********************************************************************************************************
154  **/
155
156
157  // buffer uop
158  val instMicroOp       = Reg(new VSegmentBundle)
159  val instMicroOpValid  = RegInit(false.B)
160  val data              = Reg(Vec(maxSize, UInt(VLEN.W)))
161  val uopq              = Reg(Vec(maxSize, new VSegmentUop))
162  val stride            = Reg(Vec(maxSize, UInt(VLEN.W)))
163  val allocated         = RegInit(VecInit(Seq.fill(maxSize)(false.B)))
164  val enqPtr            = RegInit(0.U.asTypeOf(new VSegUPtr))
165  val deqPtr            = RegInit(0.U.asTypeOf(new VSegUPtr))
166  val stridePtr         = WireInit(0.U.asTypeOf(new VSegUPtr)) // for select stride/index
167
168  val segmentIdx        = RegInit(0.U(elemIdxBits.W))
169  val fieldIdx          = RegInit(0.U(fieldBits.W))
170  val segmentOffset     = RegInit(0.U(VAddrBits.W))
171  val splitPtr          = RegInit(0.U.asTypeOf(new VSegUPtr)) // for select load/store data
172  val splitPtrNext      = WireInit(0.U.asTypeOf(new VSegUPtr))
173
174  val exception_va      = WireInit(false.B)
175  val exception_pa      = WireInit(false.B)
176
177  val maxSegIdx         = instMicroOp.vl - 1.U
178  val maxNfields        = instMicroOp.uop.vpu.nf
179  val latchVaddr        = RegInit(0.U(VAddrBits.W))
180
181  XSError((segmentIdx > maxSegIdx) && instMicroOpValid, s"segmentIdx > vl, something error!\n")
182  XSError((fieldIdx > maxNfields) &&  instMicroOpValid, s"fieldIdx > nfields, something error!\n")
183
184  // MicroOp
185  val baseVaddr                       = instMicroOp.baseVaddr
186  val alignedType                     = instMicroOp.alignedType
187  val fuType                          = instMicroOp.uop.fuType
188  val mask                            = instMicroOp.mask
189  val exceptionVec                    = instMicroOp.uop.exceptionVec
190  val issueEew                        = instMicroOp.uop.vpu.veew
191  val issueLmul                       = instMicroOp.uop.vpu.vtype.vlmul
192  val issueSew                        = instMicroOp.uop.vpu.vtype.vsew
193  val issueEmul                       = EewLog2(issueEew) - issueSew + issueLmul
194  val elemIdxInVd                     = segmentIdx & instMicroOp.uopFlowNumMask
195  val issueInstType                   = Cat(true.B, instMicroOp.uop.fuOpType(6, 5)) // always segment instruction
196  val issueUopFlowNumLog2             = GenRealFlowLog2(issueInstType, issueEmul, issueLmul, issueEew, issueSew, true) // max element number log2 in vd
197  val issueVlMax                      = instMicroOp.uopFlowNum // max elementIdx in vd
198  val issueMaxIdxInIndex              = GenVLMAX(Mux(issueEmul.asSInt > 0.S, 0.U, issueEmul), issueEew(1, 0)) // index element index in index register
199  val issueMaxIdxInIndexMask          = GenVlMaxMask(issueMaxIdxInIndex, elemIdxBits)
200  val issueMaxIdxInIndexLog2          = GenVLMAXLog2(Mux(issueEmul.asSInt > 0.S, 0.U, issueEmul), issueEew(1, 0))
201  val issueIndexIdx                   = segmentIdx & issueMaxIdxInIndexMask
202  val segmentActive                   = (mask & UIntToOH(segmentIdx)).orR
203
204  // sbuffer write interface
205  val sbufferOut                      = Wire(Decoupled(new DCacheWordReqWithVaddrAndPfFlag))
206
207  // Segment instruction's FSM
208  /*
209  * s_idle: wait request
210  * s_flush_sbuffer_req: flush sbuffer
211  * s_wait_flush_sbuffer_resp: wait sbuffer empty
212  * s_tlb_req: request tlb
213  * s_wait_tlb_resp: wait tlb resp
214  * s_pm: check pmp
215  * s_cache_req: request cache
216  * s_cache_resp: wait cache resp
217  * s_latch_and_merge_data: for read data
218  * s_send_data: for send write data
219  * s_finish:
220  * */
221  val s_idle :: s_flush_sbuffer_req :: s_wait_flush_sbuffer_resp :: s_tlb_req :: s_wait_tlb_resp :: s_pm ::s_cache_req :: s_cache_resp :: s_latch_and_merge_data :: s_send_data :: s_finish :: Nil = Enum(11)
222  val state             = RegInit(s_idle)
223  val stateNext         = WireInit(s_idle)
224  val sbufferEmpty      = io.flush_sbuffer.empty
225
226  /**
227   * state update
228   */
229  state  := stateNext
230
231  /**
232   * state transfer
233   */
234  when(state === s_idle){
235    stateNext := Mux(isAfter(enqPtr, deqPtr), s_flush_sbuffer_req, s_idle)
236  }.elsewhen(state === s_flush_sbuffer_req){
237    stateNext := Mux(sbufferEmpty, s_tlb_req, s_wait_flush_sbuffer_resp) // if sbuffer is empty, go to query tlb
238
239  }.elsewhen(state === s_wait_flush_sbuffer_resp){
240    stateNext := Mux(sbufferEmpty, s_tlb_req, s_wait_flush_sbuffer_resp)
241
242  }.elsewhen(state === s_tlb_req){
243    stateNext := Mux(segmentActive, s_wait_tlb_resp, Mux(FuType.isVLoad(instMicroOp.uop.fuType), s_latch_and_merge_data, s_send_data))
244
245  }.elsewhen(state === s_wait_tlb_resp){
246    stateNext := Mux(io.dtlb.resp.fire,
247                      Mux(!io.dtlb.resp.bits.miss,
248                          s_pm,
249                          s_tlb_req),
250                      s_wait_tlb_resp)
251
252  }.elsewhen(state === s_pm){
253    /* if is vStore, send data to sbuffer, so don't need query dcache */
254    stateNext := Mux(exception_pa || exception_va,
255                     s_finish,
256                     Mux(FuType.isVLoad(instMicroOp.uop.fuType), s_cache_req, s_send_data))
257
258  }.elsewhen(state === s_cache_req){
259    stateNext := Mux(io.rdcache.req.fire, s_cache_resp, s_cache_req)
260
261  }.elsewhen(state === s_cache_resp){
262    when(io.rdcache.resp.fire) {
263      when(io.rdcache.resp.bits.miss || io.rdcache.s2_bank_conflict) {
264        stateNext := s_cache_req
265      }.otherwise {
266        stateNext := Mux(FuType.isVLoad(instMicroOp.uop.fuType), s_latch_and_merge_data, s_send_data)
267      }
268    }.otherwise{
269      stateNext := s_cache_resp
270    }
271    /* if segment is inactive, don't need to wait access all of the field */
272  }.elsewhen(state === s_latch_and_merge_data) {
273    when((segmentIdx === maxSegIdx) && (fieldIdx === maxNfields) ||
274      ((segmentIdx === maxSegIdx) && !segmentActive)) {
275
276      stateNext := s_finish // segment instruction finish
277    }.otherwise {
278      stateNext := s_tlb_req // need continue
279    }
280    /* if segment is inactive, don't need to wait access all of the field */
281  }.elsewhen(state === s_send_data) { // when sbuffer accept data
282    when(!sbufferOut.fire && segmentActive) {
283      stateNext := s_send_data
284    }.elsewhen((segmentIdx === maxSegIdx) && (fieldIdx === maxNfields || !segmentActive)) {
285      stateNext := s_finish // segment instruction finish
286    }.otherwise {
287      stateNext := s_tlb_req // need continue
288    }
289  }.elsewhen(state === s_finish){ // writeback uop
290    stateNext := Mux(distanceBetween(enqPtr, deqPtr) === 0.U, s_idle, s_finish)
291
292  }.otherwise{
293    stateNext := s_idle
294    XSError(true.B, s"Unknown state!\n")
295  }
296
297  /*************************************************************************
298   *                            enqueue logic
299   *************************************************************************/
300  io.in.ready                         := true.B
301  val fuOpType                         = io.in.bits.uop.fuOpType
302  val vtype                            = io.in.bits.uop.vpu.vtype
303  val mop                              = fuOpType(6, 5)
304  val instType                         = Cat(true.B, mop)
305  val eew                              = io.in.bits.uop.vpu.veew
306  val sew                              = vtype.vsew
307  val lmul                             = vtype.vlmul
308  val emul                             = EewLog2(eew) - sew + lmul
309  val vl                               = instMicroOp.vl
310  val vm                               = instMicroOp.uop.vpu.vm
311  val vstart                           = instMicroOp.uop.vpu.vstart
312  val srcMask                          = GenFlowMask(Mux(vm, Fill(VLEN, 1.U(1.W)), io.in.bits.src_mask), vstart, vl, true)
313  // first uop enqueue, we need to latch microOp of segment instruction
314  when(io.in.fire && !instMicroOpValid){
315    // element number in a vd
316    // TODO Rewrite it in a more elegant way.
317    val uopFlowNum                    = ZeroExt(GenRealFlowNum(instType, emul, lmul, eew, sew, true), elemIdxBits)
318    instMicroOp.baseVaddr             := io.in.bits.src_rs1(VAddrBits - 1, 0)
319    instMicroOpValid                  := true.B // if is first uop
320    instMicroOp.alignedType           := Mux(isIndexed(instType), sew(1, 0), eew)
321    instMicroOp.uop                   := io.in.bits.uop
322    instMicroOp.mask                  := srcMask
323    instMicroOp.vstart                := 0.U
324    instMicroOp.uopFlowNum            := uopFlowNum
325    instMicroOp.uopFlowNumMask        := GenVlMaxMask(uopFlowNum, elemIdxBits) // for merge data
326    instMicroOp.vl                    := io.in.bits.src_vl.asTypeOf(VConfig()).vl
327    segmentOffset                     := 0.U
328    instMicroOp.isFof                 := (fuOpType === VlduType.vleff) && FuType.isVLoad(fuType)
329  }
330  // latch data
331  when(io.in.fire){
332    data(enqPtr.value)                := io.in.bits.src_vs3
333    stride(enqPtr.value)              := io.in.bits.src_stride
334    uopq(enqPtr.value).uop            := io.in.bits.uop
335  }
336
337  // update enqptr, only 1 port
338  when(io.in.fire){
339    enqPtr                            := enqPtr + 1.U
340  }
341
342  /*************************************************************************
343   *                            output logic
344   *************************************************************************/
345
346  val indexStride                     = IndexAddr( // index for indexed instruction
347                                                    index = stride(stridePtr.value),
348                                                    flow_inner_idx = issueIndexIdx,
349                                                    eew = issueEew
350                                                  )
351  val realSegmentOffset               = Mux(isIndexed(issueInstType),
352                                            indexStride,
353                                            segmentOffset)
354  val vaddr                           = baseVaddr + (fieldIdx << alignedType).asUInt + realSegmentOffset
355
356  //latch vaddr
357  when(state === s_tlb_req){
358    latchVaddr := vaddr
359  }
360  /**
361   * tlb req and tlb resq
362   */
363
364  // query DTLB IO Assign
365  io.dtlb.req                         := DontCare
366  io.dtlb.resp.ready                  := true.B
367  io.dtlb.req.valid                   := state === s_tlb_req && segmentActive
368  io.dtlb.req.bits.cmd                := Mux(FuType.isVLoad(fuType), TlbCmd.read, TlbCmd.write)
369  io.dtlb.req.bits.vaddr              := vaddr
370  io.dtlb.req.bits.size               := instMicroOp.alignedType(2,0)
371  io.dtlb.req.bits.memidx.is_ld       := FuType.isVLoad(fuType)
372  io.dtlb.req.bits.memidx.is_st       := FuType.isVStore(fuType)
373  io.dtlb.req.bits.debug.robIdx       := instMicroOp.uop.robIdx
374  io.dtlb.req.bits.no_translate       := false.B
375  io.dtlb.req.bits.debug.pc           := instMicroOp.uop.pc
376  io.dtlb.req.bits.debug.isFirstIssue := DontCare
377  io.dtlb.req_kill                    := false.B
378
379  val canTriggerException              = segmentIdx === 0.U || !instMicroOp.isFof // only elementIdx = 0 or is not fof can trigger
380  // tlb resp
381  when(io.dtlb.resp.fire && state === s_wait_tlb_resp){
382      exceptionVec(storePageFault)    := io.dtlb.resp.bits.excp(0).pf.st && canTriggerException
383      exceptionVec(loadPageFault)     := io.dtlb.resp.bits.excp(0).pf.ld && canTriggerException
384      exceptionVec(storeAccessFault)  := io.dtlb.resp.bits.excp(0).af.st && canTriggerException
385      exceptionVec(loadAccessFault)   := io.dtlb.resp.bits.excp(0).af.ld && canTriggerException
386      when(!io.dtlb.resp.bits.miss){
387        instMicroOp.paddr             := io.dtlb.resp.bits.paddr(0)
388      }
389  }
390  // pmp
391  // NOTE: only handle load/store exception here, if other exception happens, don't send here
392  val pmp = WireInit(io.pmpResp)
393  when(state === s_pm) {
394    val addr_aligned = LookupTree(Mux(isIndexed(issueInstType), issueSew(1, 0), issueEew(1, 0)), List(
395      "b00".U   -> true.B,                   //b
396      "b01".U   -> (vaddr(0)    === 0.U), //h
397      "b10".U   -> (vaddr(1, 0) === 0.U), //w
398      "b11".U   -> (vaddr(2, 0) === 0.U)  //d
399    ))
400    val missAligned = !addr_aligned
401    exceptionVec(loadAddrMisaligned)  := missAligned && FuType.isVLoad(fuType)  && canTriggerException
402    exceptionVec(storeAddrMisaligned) := missAligned && FuType.isVStore(fuType) && canTriggerException
403
404    exception_va := exceptionVec(storePageFault) || exceptionVec(loadPageFault) ||
405      exceptionVec(storeAccessFault) || exceptionVec(loadAccessFault) || (missAligned && canTriggerException)
406    exception_pa := (pmp.st || pmp.ld || pmp.mmio) && canTriggerException
407
408    instMicroOp.exception_pa := exception_pa
409    instMicroOp.exception_va := exception_va
410    // update storeAccessFault bit. Currently, we don't support vector MMIO
411    exceptionVec(loadAccessFault)  := (exceptionVec(loadAccessFault) || pmp.ld || pmp.mmio) && canTriggerException
412    exceptionVec(storeAccessFault) := (exceptionVec(storeAccessFault) || pmp.st || pmp.mmio) && canTriggerException
413
414    when(exception_va || exception_pa) {
415      when(canTriggerException) {
416        instMicroOp.exceptionVaddr  := vaddr
417        instMicroOp.exceptionVl     := segmentIdx // for exception
418        instMicroOp.exceptionVstart := segmentIdx // for exception
419      }.otherwise {
420        instMicroOp.exceptionVl     := segmentIdx
421      }
422    }
423  }
424
425  /**
426   * flush sbuffer IO Assign
427   */
428  io.flush_sbuffer.valid           := !sbufferEmpty && (state === s_flush_sbuffer_req)
429
430
431  /**
432   * merge data for load
433   */
434  val cacheData = LookupTree(latchVaddr(3,0), List(
435    "b0000".U -> io.rdcache.resp.bits.data_delayed(63,    0),
436    "b0001".U -> io.rdcache.resp.bits.data_delayed(63,    8),
437    "b0010".U -> io.rdcache.resp.bits.data_delayed(63,   16),
438    "b0011".U -> io.rdcache.resp.bits.data_delayed(63,   24),
439    "b0100".U -> io.rdcache.resp.bits.data_delayed(63,   32),
440    "b0101".U -> io.rdcache.resp.bits.data_delayed(63,   40),
441    "b0110".U -> io.rdcache.resp.bits.data_delayed(63,   48),
442    "b0111".U -> io.rdcache.resp.bits.data_delayed(63,   56),
443    "b1000".U -> io.rdcache.resp.bits.data_delayed(127,  64),
444    "b1001".U -> io.rdcache.resp.bits.data_delayed(127,  72),
445    "b1010".U -> io.rdcache.resp.bits.data_delayed(127,  80),
446    "b1011".U -> io.rdcache.resp.bits.data_delayed(127,  88),
447    "b1100".U -> io.rdcache.resp.bits.data_delayed(127,  96),
448    "b1101".U -> io.rdcache.resp.bits.data_delayed(127, 104),
449    "b1110".U -> io.rdcache.resp.bits.data_delayed(127, 112),
450    "b1111".U -> io.rdcache.resp.bits.data_delayed(127, 120)
451  ))
452  val pickData  = rdataVecHelper(alignedType(1,0), cacheData)
453  val mergedData = mergeDataWithElemIdx(
454    oldData = data(splitPtr.value),
455    newData = Seq(pickData),
456    alignedType = alignedType(1,0),
457    elemIdx = Seq(elemIdxInVd),
458    valids = Seq(true.B)
459  )
460  when(state === s_latch_and_merge_data && segmentActive){
461    data(splitPtr.value) := mergedData
462  }
463  /**
464   * split data for store
465   * */
466  val splitData = genVSData(
467    data = data(splitPtr.value),
468    elemIdx = elemIdxInVd,
469    alignedType = alignedType
470  )
471  val flowData  = genVWdata(splitData, alignedType) // TODO: connect vstd, pass vector data
472  val wmask     = genVWmask(latchVaddr, alignedType(1, 0)) & Fill(VLENB, segmentActive)
473
474  /**
475   * rdcache req, write request don't need to query dcache, because we write element to sbuffer
476   */
477  io.rdcache.req                    := DontCare
478  io.rdcache.req.valid              := state === s_cache_req && FuType.isVLoad(fuType)
479  io.rdcache.req.bits.cmd           := MemoryOpConstants.M_XRD
480  io.rdcache.req.bits.vaddr         := latchVaddr
481  io.rdcache.req.bits.mask          := mask
482  io.rdcache.req.bits.data          := flowData
483  io.rdcache.pf_source              := LOAD_SOURCE.U
484  io.rdcache.req.bits.id            := DontCare
485  io.rdcache.resp.ready             := true.B
486  io.rdcache.s1_paddr_dup_lsu       := instMicroOp.paddr
487  io.rdcache.s1_paddr_dup_dcache    := instMicroOp.paddr
488  io.rdcache.s1_kill                := false.B
489  io.rdcache.s1_kill_data_read      := false.B
490  io.rdcache.s2_kill                := false.B
491  if (env.FPGAPlatform){
492    io.rdcache.s0_pc                := DontCare
493    io.rdcache.s1_pc                := DontCare
494    io.rdcache.s2_pc                := DontCare
495  }else{
496    io.rdcache.s0_pc                := instMicroOp.uop.pc
497    io.rdcache.s1_pc                := instMicroOp.uop.pc
498    io.rdcache.s2_pc                := instMicroOp.uop.pc
499  }
500  io.rdcache.replacementUpdated     := false.B
501  io.rdcache.is128Req               := false.B
502
503
504  /**
505   * write data to sbuffer
506   * */
507  sbufferOut.bits                  := DontCare
508  sbufferOut.valid                 := state === s_send_data && segmentActive
509  sbufferOut.bits.vecValid         := state === s_send_data && segmentActive
510  sbufferOut.bits.mask             := wmask
511  sbufferOut.bits.data             := flowData
512  sbufferOut.bits.vaddr            := latchVaddr
513  sbufferOut.bits.cmd              := MemoryOpConstants.M_XWR
514  sbufferOut.bits.id               := DontCare
515  sbufferOut.bits.addr             := instMicroOp.paddr
516
517  NewPipelineConnect(
518    sbufferOut, io.sbuffer, io.sbuffer.fire,
519    false.B,
520    Option(s"VSegmentUnitPipelineConnect")
521  )
522
523  io.vecDifftestInfo.valid         := io.sbuffer.valid
524  io.vecDifftestInfo.bits          := uopq(deqPtr.value).uop
525
526  /**
527   * update ptr
528   * */
529  private val fieldActiveWirteFinish = sbufferOut.fire && segmentActive // writedata finish and is a active segment
530  XSError(sbufferOut.fire && !segmentActive, "Attempt write inactive segment to sbuffer, something wrong!\n")
531
532  private val segmentInactiveFinish = ((state === s_latch_and_merge_data) || (state === s_send_data)) && !segmentActive
533
534  val splitPtrOffset = Mux(
535    isIndexed(instType),
536    Mux(lmul.asSInt < 0.S, 1.U, (1.U << lmul).asUInt),
537    Mux(emul.asSInt < 0.S, 1.U, (1.U << emul).asUInt)
538  )
539  splitPtrNext :=
540    Mux(fieldIdx === maxNfields || !segmentActive, // if segment is active, need to complete this segment, otherwise jump to next segment
541      // segment finish, By shifting 'issueUopFlowNumLog2' to the right to ensure that emul != 1 can correctly generate lateral offset.
542     (deqPtr + ((segmentIdx +& 1.U) >> issueUopFlowNumLog2).asUInt),
543      // next field.
544     (splitPtr + splitPtrOffset)
545    )
546
547  dontTouch(issueUopFlowNumLog2)
548  dontTouch(issueEmul)
549  dontTouch(splitPtrNext)
550  dontTouch(stridePtr)
551  dontTouch(segmentActive)
552
553  // update splitPtr
554  when(state === s_latch_and_merge_data || (state === s_send_data && (fieldActiveWirteFinish || !segmentActive))){
555    splitPtr := splitPtrNext
556  }.elsewhen(io.in.fire && !instMicroOpValid){
557    splitPtr := deqPtr // initial splitPtr
558  }
559
560  // update stridePtr, only use in index
561  val strideOffset = Mux(isIndexed(issueInstType), segmentIdx >> issueMaxIdxInIndexLog2, 0.U)
562  stridePtr       := deqPtr + strideOffset
563
564  // update fieldIdx
565  when(io.in.fire && !instMicroOpValid){ // init
566    fieldIdx := 0.U
567  }.elsewhen(state === s_latch_and_merge_data && segmentActive ||
568            (state === s_send_data && fieldActiveWirteFinish)){ // only if segment is active
569
570    /* next segment, only if segment complete */
571    fieldIdx := Mux(fieldIdx === maxNfields, 0.U, fieldIdx + 1.U)
572  }.elsewhen(segmentInactiveFinish){ // segment is inactive, go to next segment
573    fieldIdx := 0.U
574  }
575  //update segmentIdx
576  when(io.in.fire && !instMicroOpValid){
577    segmentIdx := 0.U
578  }.elsewhen(fieldIdx === maxNfields && (state === s_latch_and_merge_data || (state === s_send_data && fieldActiveWirteFinish)) &&
579             segmentIdx =/= maxSegIdx){ // next segment, only if segment is active
580
581    segmentIdx := segmentIdx + 1.U
582  }.elsewhen(segmentInactiveFinish && segmentIdx =/= maxSegIdx){ // if segment is inactive, go to next segment
583    segmentIdx := segmentIdx + 1.U
584  }
585
586  //update segmentOffset
587  /* when segment is active or segment is inactive, increase segmentOffset */
588  when((fieldIdx === maxNfields && (state === s_latch_and_merge_data || (state === s_send_data && fieldActiveWirteFinish))) ||
589       segmentInactiveFinish){
590
591    segmentOffset := segmentOffset + Mux(isUnitStride(issueInstType), (maxNfields +& 1.U) << issueEew(1, 0), stride(stridePtr.value))
592  }
593
594  //update deqPtr
595  when((state === s_finish) && !isEmpty(enqPtr, deqPtr)){
596    deqPtr := deqPtr + 1.U
597  }
598
599  /*************************************************************************
600   *                            dequeue logic
601   *************************************************************************/
602  val vdIdxInField = GenUopIdxInField(Mux(isIndexed(instType), issueLmul, issueEmul), uopq(deqPtr.value).uop.vpu.vuopIdx)
603  /*select mask of vd, maybe remove in feature*/
604  val realEw        = Mux(isIndexed(issueInstType), issueSew(1, 0), issueEew(1, 0))
605  val maskDataVec: Vec[UInt] = VecDataToMaskDataVec(instMicroOp.mask, realEw)
606  val maskUsed      = maskDataVec(vdIdxInField)
607
608  when(stateNext === s_idle){
609    instMicroOpValid := false.B
610  }
611  // writeback to backend
612  val writebackOut                     = WireInit(io.uopwriteback.bits)
613  val writebackValid                   = (state === s_finish) && !isEmpty(enqPtr, deqPtr)
614  writebackOut.uop                    := uopq(deqPtr.value).uop
615  writebackOut.uop.vpu                := instMicroOp.uop.vpu
616  writebackOut.uop.exceptionVec       := instMicroOp.uop.exceptionVec
617  writebackOut.mask.get               := instMicroOp.mask
618  writebackOut.data                   := data(deqPtr.value)
619  writebackOut.vdIdx.get              := vdIdxInField
620  writebackOut.uop.vpu.vl             := instMicroOp.vl
621  writebackOut.uop.vpu.vstart         := instMicroOp.vstart
622  writebackOut.uop.vpu.vmask          := maskUsed
623  writebackOut.uop.vpu.vuopIdx        := uopq(deqPtr.value).uop.vpu.vuopIdx
624  writebackOut.debug                  := DontCare
625  writebackOut.vdIdxInField.get       := vdIdxInField
626  writebackOut.uop.robIdx             := instMicroOp.uop.robIdx
627  writebackOut.uop.fuOpType           := instMicroOp.uop.fuOpType
628
629  io.uopwriteback.valid               := RegNext(writebackValid)
630  io.uopwriteback.bits                := RegEnable(writebackOut, writebackValid)
631
632  dontTouch(writebackValid)
633
634  //to RS
635  val feedbackOut                      = WireInit(0.U.asTypeOf(io.feedback.bits))
636  val feedbackValid                    = state === s_finish && !isEmpty(enqPtr, deqPtr)
637  feedbackOut.hit                     := true.B
638  feedbackOut.robIdx                  := instMicroOp.uop.robIdx
639  feedbackOut.sourceType              := DontCare
640  feedbackOut.flushState              := DontCare
641  feedbackOut.dataInvalidSqIdx        := DontCare
642  feedbackOut.sqIdx                   := uopq(deqPtr.value).uop.sqIdx
643  feedbackOut.lqIdx                   := uopq(deqPtr.value).uop.lqIdx
644
645  io.feedback.valid                   := RegNext(feedbackValid)
646  io.feedback.bits                    := RegEnable(feedbackOut, feedbackValid)
647
648  dontTouch(feedbackValid)
649
650  // exception
651  io.exceptionInfo                    := DontCare
652  io.exceptionInfo.bits.robidx        := instMicroOp.uop.robIdx
653  io.exceptionInfo.bits.uopidx        := uopq(deqPtr.value).uop.vpu.vuopIdx
654  io.exceptionInfo.bits.vstart        := instMicroOp.exceptionVstart
655  io.exceptionInfo.bits.vaddr         := instMicroOp.exceptionVaddr
656  io.exceptionInfo.bits.vl            := instMicroOp.exceptionVl
657  io.exceptionInfo.valid              := (state === s_finish) && instMicroOp.uop.exceptionVec.asUInt.orR && !isEmpty(enqPtr, deqPtr)
658}
659
660