No public description PiperOrigin-RevId: 1018526001 Change-Id: I846f35f9a9f3c2ff7c357710358401542ef2a3a9
diff --git a/riscv/riscv_csr.h b/riscv/riscv_csr.h index eacf424..25f9481 100644 --- a/riscv/riscv_csr.h +++ b/riscv/riscv_csr.h
@@ -179,6 +179,18 @@ kPmpCfg1 = 0x3a1, // PMP configuration register 1 (only for RV32). kPmpCfg2 = 0x3a2, // PMP configuration register 2. kPmpCfg3 = 0x3a3, // PMP configuration register 3 (only for RV32). + kPmpCfg4 = 0x3a4, // PMP configuration register 4. + kPmpCfg5 = 0x3a5, // PMP configuration register 5 (only for RV32). + kPmpCfg6 = 0x3a6, // PMP configuration register 6. + kPmpCfg7 = 0x3a7, // PMP configuration register 7 (only for RV32). + kPmpCfg8 = 0x3a8, // PMP configuration register 8. + kPmpCfg9 = 0x3a9, // PMP configuration register 9 (only for RV32). + kPmpCfg10 = 0x3aa, // PMP configuration register 10. + kPmpCfg11 = 0x3ab, // PMP configuration register 11 (only for RV32). + kPmpCfg12 = 0x3ac, // PMP configuration register 12. + kPmpCfg13 = 0x3ad, // PMP configuration register 13 (only for RV32). + kPmpCfg14 = 0x3ae, // PMP configuration register 14. + kPmpCfg15 = 0x3af, // PMP configuration register 15 (only for RV32). kPmpAddr0 = 0x3b0, // PMP address register 0. kPmpAddr1 = 0x3b1, // PMP address register 1. kPmpAddr2 = 0x3b2, // PMP address register 2. @@ -195,6 +207,54 @@ kPmpAddr13 = 0x3bd, // PMP address register 13. kPmpAddr14 = 0x3be, // PMP address register 14. kPmpAddr15 = 0x3bf, // PMP address register 15. + kPmpAddr16 = 0x3c0, // PMP address register 16. + kPmpAddr17 = 0x3c1, // PMP address register 17. + kPmpAddr18 = 0x3c2, // PMP address register 18. + kPmpAddr19 = 0x3c3, // PMP address register 19. + kPmpAddr20 = 0x3c4, // PMP address register 20. + kPmpAddr21 = 0x3c5, // PMP address register 21. + kPmpAddr22 = 0x3c6, // PMP address register 22. + kPmpAddr23 = 0x3c7, // PMP address register 23. + kPmpAddr24 = 0x3c8, // PMP address register 24. + kPmpAddr25 = 0x3c9, // PMP address register 25. + kPmpAddr26 = 0x3ca, // PMP address register 26. + kPmpAddr27 = 0x3cb, // PMP address register 27. + kPmpAddr28 = 0x3cc, // PMP address register 28. + kPmpAddr29 = 0x3cd, // PMP address register 29. + kPmpAddr30 = 0x3ce, // PMP address register 30. + kPmpAddr31 = 0x3cf, // PMP address register 31. + kPmpAddr32 = 0x3d0, // PMP address register 32. + kPmpAddr33 = 0x3d1, // PMP address register 33. + kPmpAddr34 = 0x3d2, // PMP address register 34. + kPmpAddr35 = 0x3d3, // PMP address register 35. + kPmpAddr36 = 0x3d4, // PMP address register 36. + kPmpAddr37 = 0x3d5, // PMP address register 37. + kPmpAddr38 = 0x3d6, // PMP address register 38. + kPmpAddr39 = 0x3d7, // PMP address register 39. + kPmpAddr40 = 0x3d8, // PMP address register 40. + kPmpAddr41 = 0x3d9, // PMP address register 41. + kPmpAddr42 = 0x3da, // PMP address register 42. + kPmpAddr43 = 0x3db, // PMP address register 43. + kPmpAddr44 = 0x3dc, // PMP address register 44. + kPmpAddr45 = 0x3dd, // PMP address register 45. + kPmpAddr46 = 0x3de, // PMP address register 46. + kPmpAddr47 = 0x3df, // PMP address register 47. + kPmpAddr48 = 0x3e0, // PMP address register 48. + kPmpAddr49 = 0x3e1, // PMP address register 49. + kPmpAddr50 = 0x3e2, // PMP address register 50. + kPmpAddr51 = 0x3e3, // PMP address register 51. + kPmpAddr52 = 0x3e4, // PMP address register 52. + kPmpAddr53 = 0x3e5, // PMP address register 53. + kPmpAddr54 = 0x3e6, // PMP address register 54. + kPmpAddr55 = 0x3e7, // PMP address register 55. + kPmpAddr56 = 0x3e8, // PMP address register 56. + kPmpAddr57 = 0x3e9, // PMP address register 57. + kPmpAddr58 = 0x3ea, // PMP address register 58. + kPmpAddr59 = 0x3eb, // PMP address register 59. + kPmpAddr60 = 0x3ec, // PMP address register 60. + kPmpAddr61 = 0x3ed, // PMP address register 61. + kPmpAddr62 = 0x3ee, // PMP address register 62. + kPmpAddr63 = 0x3ef, // PMP address register 63. // Hypervisor level CSRs. kHenvcfg = 0x60A, // Hypervisor environment configuration register.
diff --git a/riscv/riscv_f_instructions.cc b/riscv/riscv_f_instructions.cc index 27d7726..1d718f1 100644 --- a/riscv/riscv_f_instructions.cc +++ b/riscv/riscv_f_instructions.cc
@@ -458,9 +458,9 @@ // Single precision fp class instruction. void RiscVFClass(const Instruction* instruction) { - RiscVUnaryOp<XRegister, uint32_t, float>( - instruction, - [](float a) -> uint32_t { return static_cast<uint32_t>(ClassifyFP(a)); }); + RiscVUnaryOp<XRegister, XUint, float>(instruction, [](float a) -> XUint { + return static_cast<XUint>(ClassifyFP(a)); + }); } } // namespace RV32 @@ -535,9 +535,9 @@ // Single precision fp class instruction. void RiscVFClass(const Instruction* instruction) { - RiscVUnaryOp<XRegister, uint32_t, float>( - instruction, - [](float a) -> uint32_t { return static_cast<uint32_t>(ClassifyFP(a)); }); + RiscVUnaryOp<XRegister, XUint, float>(instruction, [](float a) -> XUint { + return static_cast<XUint>(ClassifyFP(a)); + }); } } // namespace RV64
diff --git a/riscv/riscv_pmp.h b/riscv/riscv_pmp.h index fd09220..4a17127 100644 --- a/riscv/riscv_pmp.h +++ b/riscv/riscv_pmp.h
@@ -61,54 +61,37 @@ private: ArchState* state_; - RiscVCsrInterface* pmp_addr_[16]; - RiscVCsrInterface* pmp_cfg_[4]; + RiscVCsrInterface* pmp_addr_[64] = {}; + RiscVCsrInterface* pmp_cfg_[16] = {}; }; template <typename T, typename E> void RiscVPmp::CreatePmpCsrs(RiscVCsrSet* csr_set) { // Create the PMP configuration registers. Each configuration register - // contains XLEN/8 configuration entries for a total of 16 configuration - // entries. In the case of XLEN=64, there are only two configuration registers - // pmp_cfg_[0] and pmp_cfg_[2]. - pmp_cfg_[0] = new RiscVSimpleCsr<T>("pmpcfg0", *E::kPmpCfg0, state_); - pmp_cfg_[1] = sizeof(T) == 8 - ? nullptr - : new RiscVSimpleCsr<T>("pmpcfg1", *E::kPmpCfg1, state_); - pmp_cfg_[2] = new RiscVSimpleCsr<T>("pmpcfg2", *E::kPmpCfg2, state_); - pmp_cfg_[3] = sizeof(T) == 8 - ? nullptr - : new RiscVSimpleCsr<T>("pmpcfg3", *E::kPmpCfg3, state_); - for (auto* pmp_cfg : pmp_cfg_) { - if (pmp_cfg == nullptr) continue; - auto status = csr_set->AddCsr(pmp_cfg); + // contains XLEN/8 configuration entries for a total of 64 configuration + // entries. In the case of XLEN=64, only even-numbered configuration registers + // are created. + for (int i = 0; i < 16; ++i) { + if (sizeof(T) == 8 && (i % 2 != 0)) { + pmp_cfg_[i] = nullptr; + continue; + } + pmp_cfg_[i] = new RiscVSimpleCsr<T>(absl::StrCat("pmpcfg", i), + *E::kPmpCfg0 + i, state_); + auto status = csr_set->AddCsr(pmp_cfg_[i]); if (!status.ok()) { LOG(ERROR) << absl::StrCat("Failed to add PMP configuration register: '", - pmp_cfg->name(), "': ", status.message()); + pmp_cfg_[i]->name(), "': ", status.message()); } } - // Create the 16 PMP address registers. - pmp_addr_[0] = new RiscVSimpleCsr<T>("pmpaddr0", *E::kPmpAddr0, state_); - pmp_addr_[1] = new RiscVSimpleCsr<T>("pmpaddr1", *E::kPmpAddr1, state_); - pmp_addr_[2] = new RiscVSimpleCsr<T>("pmpaddr2", *E::kPmpAddr2, state_); - pmp_addr_[3] = new RiscVSimpleCsr<T>("pmpaddr3", *E::kPmpAddr3, state_); - pmp_addr_[4] = new RiscVSimpleCsr<T>("pmpaddr4", *E::kPmpAddr4, state_); - pmp_addr_[5] = new RiscVSimpleCsr<T>("pmpaddr5", *E::kPmpAddr5, state_); - pmp_addr_[6] = new RiscVSimpleCsr<T>("pmpaddr6", *E::kPmpAddr6, state_); - pmp_addr_[7] = new RiscVSimpleCsr<T>("pmpaddr7", *E::kPmpAddr7, state_); - pmp_addr_[8] = new RiscVSimpleCsr<T>("pmpaddr8", *E::kPmpAddr8, state_); - pmp_addr_[9] = new RiscVSimpleCsr<T>("pmpaddr9", *E::kPmpAddr9, state_); - pmp_addr_[10] = new RiscVSimpleCsr<T>("pmpaddr10", *E::kPmpAddr10, state_); - pmp_addr_[11] = new RiscVSimpleCsr<T>("pmpaddr11", *E::kPmpAddr11, state_); - pmp_addr_[12] = new RiscVSimpleCsr<T>("pmpaddr12", *E::kPmpAddr12, state_); - pmp_addr_[13] = new RiscVSimpleCsr<T>("pmpaddr13", *E::kPmpAddr13, state_); - pmp_addr_[14] = new RiscVSimpleCsr<T>("pmpaddr14", *E::kPmpAddr14, state_); - pmp_addr_[15] = new RiscVSimpleCsr<T>("pmpaddr15", *E::kPmpAddr15, state_); - for (auto* pmp_addr : pmp_addr_) { - auto status = csr_set->AddCsr(pmp_addr); + // Create the 64 PMP address registers. + for (int i = 0; i < 64; ++i) { + pmp_addr_[i] = new RiscVSimpleCsr<T>(absl::StrCat("pmpaddr", i), + *E::kPmpAddr0 + i, state_); + auto status = csr_set->AddCsr(pmp_addr_[i]); if (!status.ok()) { LOG(ERROR) << absl::StrCat("Failed to add PMP address register: '", - pmp_addr->name(), "': ", status.message()); + pmp_addr_[i]->name(), "': ", status.message()); } } }
diff --git a/riscv/riscv_vector.isa b/riscv/riscv_vector.isa index ee9ae36..3e375b2 100644 --- a/riscv/riscv_vector.isa +++ b/riscv/riscv_vector.isa
@@ -1107,8 +1107,8 @@ vfmv_vf{: fs1, vmask : vd}, disasm: "vfmv.vf", "%vd, %fs1, %vmask", semfunc: "&Vfmvvf"; - vfmerge_vf{: vs2, vs1, vmask : vd}, - disasm: "vfmerge.vf", "%vd, %vs2, %vs1, %vmask", + vfmerge_vf{: vs2, fs1, vmask : vd}, + disasm: "vfmerge.vf", "%vd, %vs2, %fs1, %vmask", semfunc: "&Vfmerge"; vmfeq_vv{: vs2, vs1, vmask : vd}, disasm: "vmfeq.vv", "%vd, %vs2, %vs1, %vmask",
diff --git a/riscv/riscv_zvt_instructions.cc b/riscv/riscv_zvt_instructions.cc index 8b62189..473a32e 100644 --- a/riscv/riscv_zvt_instructions.cc +++ b/riscv/riscv_zvt_instructions.cc
@@ -34,8 +34,16 @@ namespace mpact::sim::riscv { +using ::mpact::sim::generic::Bfloat16; +using ::mpact::sim::generic::ConvertBf16ToSingle; +using ::mpact::sim::generic::ConvertFp8E4m3ToSingle; +using ::mpact::sim::generic::ConvertFp8E5m2ToSingle; +using ::mpact::sim::generic::ConvertHalfToSingle; using ::mpact::sim::generic::DataBuffer; +using ::mpact::sim::generic::Fp8E4m3; +using ::mpact::sim::generic::Fp8E5m2; using ::mpact::sim::generic::GetInstructionSource; +using ::mpact::sim::generic::HalfFP; using ::mpact::sim::generic::operator*; // NOLINT(misc-unused-using-decls) using ::mpact::sim::riscv::RiscVVectorState; @@ -49,15 +57,14 @@ // is held at bit XLEN-1 (bit 31 for RV32, bit 63 for RV64). In // RiscVVectorState, vtype is currently stored as a 32-bit integer with // kVillBitMask = 1U << 31. -inline bool GetVtypeVill( - const ::mpact::sim::riscv::RiscVVectorState* vector_state) { - constexpr uint32_t kVillBitMask = 1U << 31; +constexpr uint32_t kVillBitMask = 1U << 31; + +inline bool GetVtypeVill(const RiscVVectorState* vector_state) { return (vector_state->vtype() & kVillBitMask) != 0; } // Returns the vector selected element width (SEW) in bits. -inline int GetSewBits( - const ::mpact::sim::riscv::RiscVVectorState* vector_state) { +inline int GetSewBits(const RiscVVectorState* vector_state) { switch (vector_state->selected_element_width()) { case 1: return 8; @@ -72,6 +79,12 @@ } } +// Returns the alternate format (altfmt) bit from vtype. +inline uint32_t GetVtypeAltfmt(const RiscVVectorState* vector_state) { + constexpr uint32_t kVtypeAltfmtShift = 8; + return ((vector_state->vtype() >> kVtypeAltfmtShift) & 1U); +} + // Calculates the tile element width (TEW) in bits from 'sew_bits' and 'twiden'. inline int CalculateTew(int sew_bits, int twiden) { switch (twiden) { @@ -96,37 +109,34 @@ uint32_t index; // bits[23:0]. }; +// TSS bitfield shifts and masks per Zvt spec 15.1.1.5. +constexpr uint32_t kTssIndexMask = 0xFFFFFF; +constexpr uint32_t kTssPatternShift = 24; +constexpr uint32_t kTssPatternMask = 0x7; +constexpr uint32_t kTssTileShift = 27; +constexpr uint32_t kTssTileMask = 0xF; +constexpr int kTssPatternCol = 1; + // Decodes a 32-bit Tile Subset Specifier ('tss') for element width 'tew'. Tss DecodeTss(const RiscVZvtMatrixState* matrix_state, uint32_t tss, int tew) { return Tss{ - .tile = - matrix_state->MaskTssTile(static_cast<int>((tss >> 27) & 0xF), tew), - .pattern = static_cast<int>((tss >> 24) & 0x7), - .index = tss & 0xFFFFFF, + .tile = matrix_state->MaskTssTile( + static_cast<int>((tss >> kTssTileShift) & kTssTileMask), tew), + .pattern = static_cast<int>((tss >> kTssPatternShift) & kTssPatternMask), + .index = tss & kTssIndexMask, }; } -constexpr int kTssPatternCol = 1; - // Updates vector and matrix geometry (vtype, vl, mtype) based on the // current configuration. -void UpdateVectorMatrixGeometry( - ::mpact::sim::riscv::RiscVVectorState* vector_state, - ::mpact::sim::riscv::RiscVZvtMatrixState* matrix_state) { - const int vill_shift = sizeof(vector_state->vtype()) * 8 - 1; +void UpdateVectorMatrixGeometry(RiscVVectorState* vector_state, + RiscVZvtMatrixState* matrix_state) { const int sew_bits = GetSewBits(vector_state); - if ((vector_state->vtype() >> vill_shift) || sew_bits == 0) { + if (GetVtypeVill(vector_state) || sew_bits == 0) { matrix_state->set_mtype(0); return; } const int twiden = matrix_state->twiden(); - if (twiden == 0) { - vector_state->set_vector_exception(); - vector_state->SetVectorType(1ull << vill_shift); - vector_state->set_vector_length(0); - matrix_state->set_mtype(0); - return; - } const int tew = CalculateTew(sew_bits, twiden); const int effective_tile_elements = matrix_state->effective_tile_edge(tew); const int max_k = RiscVZvtKmax(sew_bits); @@ -186,7 +196,7 @@ const bool vill = tew > kElen; if (vill) { vector_state->set_vector_exception(); - vector_state->SetVectorType(1ull << vill_shift); + vector_state->SetVectorType(kVillBitMask); matrix_state->set_mtype(0); return; } @@ -266,16 +276,10 @@ const Instruction* inst) { auto* state = matrix_state->riscv_state(); - bool trap = false; - if ((state->mstatus()->GetUint32() & 0x60000000U) == 0) { - trap = true; - } - - if (trap) { + if ((state->mstatus()->GetUint32() & kMstatusMsMask) == 0) { state->Trap( /*is_interrupt=*/false, /*trap_value=*/0, - *::mpact::sim::riscv::ExceptionCode::kIllegalInstruction, - inst->address(), inst); + *ExceptionCode::kIllegalInstruction, inst->address(), inst); return true; } return false; @@ -285,16 +289,10 @@ bool TrapIfFpStateOff(const Instruction* inst) { auto* state = static_cast<RiscVState*>(inst->state()); - bool trap = false; - if (state->mstatus()->fs() == 0) { - trap = true; - } - - if (trap) { + if (state->mstatus()->fs() == kMstatusStateOff) { state->Trap( /*is_interrupt=*/false, /*trap_value=*/0, - *::mpact::sim::riscv::ExceptionCode::kIllegalInstruction, - inst->address(), inst); + *ExceptionCode::kIllegalInstruction, inst->address(), inst); return true; } return false; @@ -305,7 +303,7 @@ auto* state = matrix_state->riscv_state(); if (auto mstatus_csr_or = state->csr_set()->GetCsr("mstatus"); mstatus_csr_or.ok()) { - auto* csr = mstatus_csr_or.value(); + auto* csr = *mstatus_csr_or; uint64_t val = (csr->GetUint64() & ~kMstatusMsMask) | (static_cast<uint64_t>(kMstatusStateInitial) << kMstatusMsShift); @@ -318,7 +316,7 @@ auto* state = matrix_state->riscv_state(); if (auto mstatus_csr_or = state->csr_set()->GetCsr("mstatus"); mstatus_csr_or.ok()) { - auto* csr = mstatus_csr_or.value(); + auto* csr = *mstatus_csr_or; uint64_t sd_mask = (state->xlen() == RiscVXlen::RV32) ? kMstatusSdMaskRv32 : kMstatusSdMaskRv64; uint64_t val = @@ -334,7 +332,7 @@ auto* state = matrix_state->riscv_state(); if (auto mstatus_csr_or = state->csr_set()->GetCsr("mstatus"); mstatus_csr_or.ok()) { - auto* csr = mstatus_csr_or.value(); + auto* csr = *mstatus_csr_or; uint64_t sd_mask = (state->xlen() == RiscVXlen::RV32) ? kMstatusSdMaskRv32 : kMstatusSdMaskRv64; uint64_t val = @@ -348,7 +346,7 @@ // Returns true and raises an IllegalInstruction exception if 'tss' is invalid. bool TrapIfTssInvalid(RiscVZvtMatrixState* matrix_state, const Tss& tss, int tew, const Instruction* inst) { - if (tss.pattern > 1) { + if (tss.pattern > kTssPatternCol) { matrix_state->riscv_state()->Trap( /*is_interrupt=*/false, /*trap_value=*/0, *ExceptionCode::kIllegalInstruction, inst->address(), inst); @@ -491,9 +489,9 @@ const uint32_t rs1 = GetInstructionSource<uint32_t>(inst, 0); if (matrix_state->mtwiden() == 0) { - matrix_state->set_tile_m(0); - WriteScalar(inst, 0, 0); - SetVectorStateDirty(matrix_state); + auto* rv_state = matrix_state->riscv_state(); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); return; } @@ -522,9 +520,9 @@ const uint32_t rs1 = GetInstructionSource<uint32_t>(inst, 0); if (matrix_state->mtwiden() == 0) { - matrix_state->set_tile_k(0); - WriteScalar(inst, 0, 0); - SetVectorStateDirty(matrix_state); + auto* rv_state = matrix_state->riscv_state(); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); return; } @@ -950,28 +948,24 @@ if (kind == RiscVZvtMatmulKind::kBf16) { uint16_t u; std::memcpy(&u, &span[e * sew_bytes], sizeof(u)); - return ::mpact::sim::generic::ConvertBf16ToSingle( - ::mpact::sim::generic::Bfloat16{u}); + return ConvertBf16ToSingle(Bfloat16{u}); } if (kind == RiscVZvtMatmulKind::kFp16) { uint16_t u; std::memcpy(&u, &span[e * sew_bytes], sizeof(u)); - return ::mpact::sim::generic::ConvertHalfToSingle( - ::mpact::sim::generic::HalfFP{u}); + return ConvertHalfToSingle(HalfFP{u}); } if (kind == RiscVZvtMatmulKind::kFp8E4M3 || kind == RiscVZvtMatmulKind::kFp8E4M3E5M2) { uint8_t u; std::memcpy(&u, &span[e * sew_bytes], sizeof(u)); - return ::mpact::sim::generic::ConvertFp8E4m3ToSingle( - ::mpact::sim::generic::Fp8E4m3{u}); + return ConvertFp8E4m3ToSingle(Fp8E4m3{u}); } if (kind == RiscVZvtMatmulKind::kFp8E5M2E4M3 || kind == RiscVZvtMatmulKind::kFp8E5M2) { uint8_t u; std::memcpy(&u, &span[e * sew_bytes], sizeof(u)); - return ::mpact::sim::generic::ConvertFp8E5m2ToSingle( - ::mpact::sim::generic::Fp8E5m2{u}); + return ConvertFp8E5m2ToSingle(Fp8E5m2{u}); } float f; std::memcpy(&f, &span[e * sew_bytes], sizeof(f)); @@ -988,28 +982,24 @@ if (kind == RiscVZvtMatmulKind::kBf16) { uint16_t u; std::memcpy(&u, &span[e * sew_bytes], sizeof(u)); - return ::mpact::sim::generic::ConvertBf16ToSingle( - ::mpact::sim::generic::Bfloat16{u}); + return ConvertBf16ToSingle(Bfloat16{u}); } if (kind == RiscVZvtMatmulKind::kFp16) { uint16_t u; std::memcpy(&u, &span[e * sew_bytes], sizeof(u)); - return ::mpact::sim::generic::ConvertHalfToSingle( - ::mpact::sim::generic::HalfFP{u}); + return ConvertHalfToSingle(HalfFP{u}); } if (kind == RiscVZvtMatmulKind::kFp8E4M3 || kind == RiscVZvtMatmulKind::kFp8E5M2E4M3) { uint8_t u; std::memcpy(&u, &span[e * sew_bytes], sizeof(u)); - return ::mpact::sim::generic::ConvertFp8E4m3ToSingle( - ::mpact::sim::generic::Fp8E4m3{u}); + return ConvertFp8E4m3ToSingle(Fp8E4m3{u}); } if (kind == RiscVZvtMatmulKind::kFp8E4M3E5M2 || kind == RiscVZvtMatmulKind::kFp8E5M2) { uint8_t u; std::memcpy(&u, &span[e * sew_bytes], sizeof(u)); - return ::mpact::sim::generic::ConvertFp8E5m2ToSingle( - ::mpact::sim::generic::Fp8E5m2{u}); + return ConvertFp8E5m2ToSingle(Fp8E5m2{u}); } float f; std::memcpy(&f, &span[e * sew_bytes], sizeof(f)); @@ -1147,7 +1137,7 @@ (tile_m > 0 && tile_n > 0 && tile_k > 0)) { auto* mstatus = matrix_state->riscv_state()->mstatus(); if (mstatus != nullptr) { - mstatus->set_fs(3); + mstatus->set_fs(kMstatusStateDirty); mstatus->Submit(); } } @@ -1175,7 +1165,7 @@ *ExceptionCode::kIllegalInstruction, inst->address(), inst); return; } - const uint32_t altfmt = (vector_state->vtype() >> 8) & 1; + const uint32_t altfmt = GetVtypeAltfmt(vector_state); RiscVZvtMatmul(altfmt ? RiscVZvtMatmulKind::kInt8Signed : RiscVZvtMatmulKind::kInt8SignedUnsigned, inst); @@ -1200,7 +1190,7 @@ *ExceptionCode::kIllegalInstruction, inst->address(), inst); return; } - const uint32_t altfmt = (vector_state->vtype() >> 8) & 1; + const uint32_t altfmt = GetVtypeAltfmt(vector_state); RiscVZvtMatmul(altfmt ? RiscVZvtMatmulKind::kInt8UnsignedSigned : RiscVZvtMatmulKind::kInt8Unsigned, inst); @@ -1220,7 +1210,7 @@ } auto* matrix_state = *m_result; auto* vector_state = matrix_state->riscv_state()->rv_vector(); - const uint32_t altfmt = (vector_state->vtype() >> 8) & 1; + const uint32_t altfmt = GetVtypeAltfmt(vector_state); const int sew_bits = GetSewBits(vector_state); const uint32_t twiden = matrix_state->twiden(); @@ -1235,7 +1225,7 @@ } else if (sew_bits == 64 && twiden == 1 && altfmt == 0) { kind = RiscVZvtMatmulKind::kFp64; } else { - auto* rv_state = static_cast<RiscVState*>(inst->state()); + auto* rv_state = matrix_state->riscv_state(); rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, *ExceptionCode::kIllegalInstruction, inst->address(), inst); return; @@ -1257,7 +1247,7 @@ } auto* matrix_state = *m_result; auto* vector_state = matrix_state->riscv_state()->rv_vector(); - const uint32_t altfmt = (vector_state->vtype() >> 8) & 1; + const uint32_t altfmt = GetVtypeAltfmt(vector_state); const int sew_bits = GetSewBits(vector_state); const uint32_t twiden = matrix_state->twiden(); @@ -1265,10 +1255,10 @@ if (sew_bits == 8 && twiden == 4) { kind = altfmt ? RiscVZvtMatmulKind::kFp8E5M2 : RiscVZvtMatmulKind::kFp8E5M2E4M3; - } else if (sew_bits == 16 && twiden == 2 && altfmt == 0) { + } else if (sew_bits == 16 && twiden == 2) { kind = RiscVZvtMatmulKind::kBf16; } else { - auto* rv_state = static_cast<RiscVState*>(inst->state()); + auto* rv_state = matrix_state->riscv_state(); rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, *ExceptionCode::kIllegalInstruction, inst->address(), inst); return;
diff --git a/riscv/test/BUILD b/riscv/test/BUILD index 7c61ae6..9cf2504 100644 --- a/riscv/test/BUILD +++ b/riscv/test/BUILD
@@ -208,6 +208,7 @@ "//riscv:riscv_fp_state", "//riscv:riscv_g", "//riscv:riscv_state", + "@abseil-cpp//absl/base", "@com_google_googletest//:gtest_main", "@mpact-sim//mpact/sim/generic:instruction", "@mpact-sim//mpact/sim/generic:type_helpers", @@ -1072,6 +1073,20 @@ ) cc_test( + name = "riscv_vector_state_test", + size = "small", + srcs = [ + "riscv_vector_state_test.cc", + ], + deps = [ + "//riscv:riscv_state", + "//riscv:riscv_v", + "@com_google_googletest//:gtest_main", + "@mpact-sim//mpact/sim/util/memory", + ], +) + +cc_test( name = "riscv_zvt_instructions_test", size = "small", srcs = ["riscv_zvt_instructions_test.cc"], @@ -1082,27 +1097,15 @@ "//riscv:riscv_zvt_instructions", "//riscv:riscv_zvt_state", "@abseil-cpp//absl/base", - "@abseil-cpp//absl/log:check", + "@abseil-cpp//absl/status", "@abseil-cpp//absl/status:statusor", + "@abseil-cpp//absl/strings", "@abseil-cpp//absl/types:span", "@com_google_googletest//:gtest_main", "@mpact-sim//mpact/sim/generic:arch_state", "@mpact-sim//mpact/sim/generic:core", "@mpact-sim//mpact/sim/generic:instruction", - "@mpact-sim//mpact/sim/util/memory", - ], -) - -cc_test( - name = "riscv_vector_state_test", - size = "small", - srcs = [ - "riscv_vector_state_test.cc", - ], - deps = [ - "//riscv:riscv_state", - "//riscv:riscv_v", - "@com_google_googletest//:gtest_main", + "@mpact-sim//mpact/sim/generic:type_helpers", "@mpact-sim//mpact/sim/util/memory", ], )
diff --git a/riscv/test/riscv_f_instructions_test.cc b/riscv/test/riscv_f_instructions_test.cc index 88b63a6..d2c6ef8 100644 --- a/riscv/test/riscv_f_instructions_test.cc +++ b/riscv/test/riscv_f_instructions_test.cc
@@ -19,6 +19,7 @@ #include <tuple> #include <vector> +#include "absl/base/casts.h" #include "googlemock/include/gmock/gmock.h" // IWYU pragma: keep #include "googletest/include/gtest/gtest.h" #include "mpact/sim/generic/instruction.h" @@ -32,6 +33,7 @@ using ::mpact::sim::generic::Instruction; using ::mpact::sim::riscv::FPExceptions; using ::mpact::sim::riscv::RV32Register; +using ::mpact::sim::riscv::RV64Register; using ::mpact::sim::riscv::RVFpRegister; using ::mpact::sim::riscv::test::FPTypeInfo; using ::mpact::sim::riscv::test::RiscVFPInstructionTestBase; @@ -451,4 +453,38 @@ } } +class RV64FInstructionTest : public RiscVFPInstructionTestBase<RV64Register> {}; + +TEST_F(RV64FInstructionTest, RiscVFClassZeroExtendsRd) { + SetSemanticFunction(&::mpact::sim::riscv::RV64::RiscVFClass); + AppendRegisterOperands<RVFpRegister>({"f1"}, {}); + AppendRegisterOperands<RV64Register>({}, {"x5"}); + + struct FClassCase { + uint32_t fp_bits; + uint64_t initial_rd; + uint64_t expected_rd; + }; + const std::vector<FClassCase> test_cases = { + {FPTypeInfo<float>::kNegInf, 0xdead'beef'aaaa'5555ULL, 1ULL << 0}, + {FPTypeInfo<float>::kNegZero, 0xcafe'babe'ffff'ffffULL, 1ULL << 3}, + {absl::bit_cast<uint32_t>(1.0f), 0x0123'4567'89ab'cdefULL, 1ULL << 6}, + {FPTypeInfo<float>::kSNaN, 0xffff'ffff'ffff'ffffULL, 1ULL << 8}, + {FPTypeInfo<float>::kQNaN, 0x8000'0000'ffff'ffffULL, 1ULL << 9}, + }; + + for (const auto& tc : test_cases) { + SetNaNBoxedRegisterValues<float, RVFpRegister>( + {{"f1", absl::bit_cast<float>(tc.fp_bits)}}); + SetRegisterValues<uint64_t, RV64Register>({{"x5", tc.initial_rd}}); + + instruction_->Execute(nullptr); + + uint64_t rd = state_->GetRegister<RV64Register>("x5") + .first->data_buffer() + ->template Get<uint64_t>(0); + EXPECT_EQ(rd, tc.expected_rd); + } +} + } // namespace
diff --git a/riscv/test/riscv_pmp_test.cc b/riscv/test/riscv_pmp_test.cc index 6406bf5..7991729 100644 --- a/riscv/test/riscv_pmp_test.cc +++ b/riscv/test/riscv_pmp_test.cc
@@ -22,18 +22,25 @@ RiscVState state("test", RiscVXlen::RV32, nullptr, nullptr); RiscVPmp pmp(&state); pmp.CreatePmpCsrs<uint32_t, RiscVCsrEnum>(state.csr_set()); - for (int i = 0; i < 4; ++i) { + for (int i = 0; i < 16; ++i) { EXPECT_TRUE( state.csr_set()->GetCsr(absl::StrCat("pmpcfg", i)).status().ok()); EXPECT_TRUE( state.csr_set()->GetCsr(*RiscVCsrEnum::kPmpCfg0 + i).status().ok()); } - for (int i = 0; i < 16; ++i) { + for (int i = 0; i < 64; ++i) { EXPECT_TRUE( state.csr_set()->GetCsr(absl::StrCat("pmpaddr", i)).status().ok()); EXPECT_TRUE( state.csr_set()->GetCsr(*RiscVCsrEnum::kPmpAddr0 + i).status().ok()); } + // Verify specific RV32 standard CSR addresses. + EXPECT_EQ(*RiscVCsrEnum::kPmpCfg0, 0x3a0); + EXPECT_EQ(*RiscVCsrEnum::kPmpCfg15, 0x3af); + EXPECT_EQ(*RiscVCsrEnum::kPmpAddr0, 0x3b0); + EXPECT_EQ(*RiscVCsrEnum::kPmpAddr16, 0x3c0); + EXPECT_EQ(*RiscVCsrEnum::kPmpAddr31, 0x3cf); + EXPECT_EQ(*RiscVCsrEnum::kPmpAddr63, 0x3ef); } // Test that the expected PMP CSRs are created. @@ -41,7 +48,7 @@ RiscVState state("test", RiscVXlen::RV64, nullptr, nullptr); RiscVPmp pmp(&state); pmp.CreatePmpCsrs<uint64_t, RiscVCsrEnum>(state.csr_set()); - for (int i = 0; i < 4; ++i) { + for (int i = 0; i < 16; ++i) { // For RV64, only the even numbered PMP configuration registers are created. if (i & 0x1) { EXPECT_FALSE( @@ -55,7 +62,7 @@ state.csr_set()->GetCsr(*RiscVCsrEnum::kPmpCfg0 + i).status().ok()); } } - for (int i = 0; i < 16; ++i) { + for (int i = 0; i < 64; ++i) { EXPECT_TRUE( state.csr_set()->GetCsr(absl::StrCat("pmpaddr", i)).status().ok()); EXPECT_TRUE(
diff --git a/riscv/test/riscv_zvt_instructions_test.cc b/riscv/test/riscv_zvt_instructions_test.cc index eda9d5a..3da26b8 100644 --- a/riscv/test/riscv_zvt_instructions_test.cc +++ b/riscv/test/riscv_zvt_instructions_test.cc
@@ -12,21 +12,61 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Functional and regression unit tests for RISC-V Vector Matrix Extension -// (Zvt v0.4) instruction semantics, configuration, state transitions, and CSR -// dirty status updates. +// Functional and regression unit tests for the RISC-V Vector Matrix Extension +// (Zvt v0.4) specification in the MPACT simulator. +// +// This test suite verifies architectural compliance and functional correctness +// across the following instruction and subsystem categories: +// +// 1. Matrix Configuration Instructions: +// - msetmtype, msetmtypei: dynamic tile element width (TEW), widening factor +// (TWIDEN), vector length (VL) zeroing, tail/mask policy mapping, and +// vill invalidation state machine. +// - msettn, msettm, msettk: dimension configuration, bound clamping (KMAX, +// MMAX, NMAX), and illegal instruction traps on invalid TWIDEN/SEW. +// +// 2. Tile Movement Instructions: +// - vtmv.v.t, vtmv.t.v: bidirectional register transfers between vector +// register groups and matrix tiles across SEW=8/16/32/64 and LMUL=1/2/4/8. +// - vtzero, vtdiscard: tile clearing, canonical tile ID validation, and +// status transitions (MS downgrade to Initial). +// +// 3. Tile Memory Instructions: +// - vtle*, vtse*: strided and unit-stride tile loads/stores, row/column TSS +// patterns, address alignment, exception prioritization (reserved TSS +// trap priority over misaligned address trap), and vstart restart bounds. +// +// 4. Matrix Multiplication Instructions: +// - vtmmu.tvv, vtmms.tvv: integer unsigned and signed matrix multiplication +// across valid/invalid tile topologies. +// - vtfmm.tvv, vtfmm.alt.tvv: floating-point matrix multiplication +// supporting FP8 (E4M3, E5M2), FP16, BF16, FP32, and FP64 arithmetic, +// tile alignment rules, and status tracking (FS dirtied on execution). +// +// 5. Architectural Context & Status Tracking: +// - mstatus.MS (Matrix Status), mstatus.VS (Vector Status), and mstatus.FS +// (Floating-Point Status) dirty/initial/off lifecycle state tracking, +// vsstatus virtualization, and SD bit calculation across RV32 and RV64. #include "riscv/riscv_zvt_instructions.h" #include <algorithm> +#include <cmath> +#include <cstddef> #include <cstdint> +#include <initializer_list> +#include <limits> // IWYU pragma: keep #include <memory> +#include <numeric> #include <string> #include <utility> #include <vector> #include "absl/base/casts.h" +#include "absl/status/status.h" #include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" // IWYU pragma: keep +#include "absl/strings/string_view.h" #include "absl/types/span.h" #include "googlemock/include/gmock/gmock.h" #include "googletest/include/gtest/gtest.h" @@ -34,12 +74,19 @@ #include "mpact/sim/generic/instruction.h" #include "mpact/sim/generic/operand_interface.h" #include "mpact/sim/generic/register.h" +#include "mpact/sim/generic/type_helpers.h" #include "mpact/sim/util/memory/flat_demand_memory.h" +#include "mpact/sim/util/memory/memory_interface.h" +#include "riscv/riscv_csr.h" +#include "riscv/riscv_fp_info.h" #include "riscv/riscv_fp_state.h" #include "riscv/riscv_instruction_helpers.h" +#include "riscv/riscv_misa.h" #include "riscv/riscv_register.h" #include "riscv/riscv_state.h" +#include "riscv/riscv_vector_memory_instructions.h" #include "riscv/riscv_vector_state.h" +#include "riscv/riscv_xstatus.h" #include "riscv/riscv_zvt_state.h" /* start - helper test macro */ @@ -54,13 +101,24 @@ namespace { +using ::mpact::sim::generic::ArchState; +using ::mpact::sim::generic::operator*; // NOLINT(misc-unused-using-decls) +using ::mpact::sim::generic::Bfloat16; +using ::mpact::sim::generic::ConvertFp8E4m3ToSingle; +using ::mpact::sim::generic::ConvertFp8E5m2ToSingle; using ::mpact::sim::generic::DestinationOperandInterface; +using ::mpact::sim::generic::Fp8E4m3; +using ::mpact::sim::generic::Fp8E5m2; using ::mpact::sim::generic::ImmediateOperand; using ::mpact::sim::generic::Instruction; using ::mpact::sim::generic::RegisterBase; using ::mpact::sim::generic::SourceOperandInterface; using ::mpact::sim::riscv::DoubleToFloatROD; using ::mpact::sim::riscv::ExceptionCode; +using ::mpact::sim::riscv::FPExceptions; +using ::mpact::sim::riscv::FPRoundingMode; +using ::mpact::sim::riscv::kMstatusFsMask; +using ::mpact::sim::riscv::kMstatusFsShift; using ::mpact::sim::riscv::kMstatusMsMask; using ::mpact::sim::riscv::kMstatusMsShift; using ::mpact::sim::riscv::kMstatusSdMaskRv32; @@ -77,7 +135,12 @@ using ::mpact::sim::riscv::kMtypeTkShift; using ::mpact::sim::riscv::kMtypeTmMask; using ::mpact::sim::riscv::kMtypeTmShift; +using ::mpact::sim::riscv::kRiscVMtypeCsrIndex; +using ::mpact::sim::riscv::RiscVCsrEnum; using ::mpact::sim::riscv::RiscVFPState; +using ::mpact::sim::riscv::RiscVMIsa; +using ::mpact::sim::riscv::RiscVMStatus; +using ::mpact::sim::riscv::RiscVSimpleCsr; using ::mpact::sim::riscv::RiscVState; using ::mpact::sim::riscv::RiscVVectorState; using ::mpact::sim::riscv::RiscVXlen; @@ -88,15 +151,125 @@ using ::mpact::sim::riscv::RiscVZvtMsetTm; using ::mpact::sim::riscv::RiscVZvtMsetTn; using ::mpact::sim::riscv::RiscVZvtVtDiscard; +using ::mpact::sim::riscv::RiscVZvtVtfmm; +using ::mpact::sim::riscv::RiscVZvtVtfmmAlt; +using ::mpact::sim::riscv::RiscVZvtVtle; +using ::mpact::sim::riscv::RiscVZvtVtmms; +using ::mpact::sim::riscv::RiscVZvtVtmmu; using ::mpact::sim::riscv::RiscVZvtVtmvTv; using ::mpact::sim::riscv::RiscVZvtVtmvVt; +using ::mpact::sim::riscv::RiscVZvtVtse; using ::mpact::sim::riscv::RiscVZvtVtZero; using ::mpact::sim::riscv::RV32Register; using ::mpact::sim::riscv::RV32VectorDestinationOperand; using ::mpact::sim::riscv::RV32VectorSourceOperand; using ::mpact::sim::riscv::RV64Register; using ::mpact::sim::riscv::RVVectorRegister; +using ::mpact::sim::riscv::Vsetvl; using ::mpact::sim::util::FlatDemandMemory; +using ::mpact::sim::util::MemoryInterface; + +// mstatus.XS (user extension state) field constants. +inline constexpr uint32_t kMstatusXsShift = 15; +inline constexpr uint32_t kMstatusXsMask = 0b11U << kMstatusXsShift; + +class TestMStatus : public RiscVMStatus { + public: + TestMStatus(uint64_t initial_value, ArchState* state, RiscVMIsa* misa) + : RiscVMStatus(initial_value, state, misa, ~0ULL, ~0ULL) {} + uint32_t vs() { return (GetUint32() & kMstatusVsMask) >> kMstatusVsShift; } + void set_vs(uint32_t value) { + uint32_t v = + (GetUint32() & ~kMstatusVsMask) | ((value & 0b11U) << kMstatusVsShift); + UpdateSdAndSet(v); + } + uint32_t ms() { return (GetUint32() & kMstatusMsMask) >> kMstatusMsShift; } + void set_ms(uint32_t value) { + uint32_t v = + (GetUint32() & ~kMstatusMsMask) | ((value & 0b11U) << kMstatusMsShift); + UpdateSdAndSet(v); + } + uint32_t fs() { return (GetUint32() & kMstatusFsMask) >> kMstatusFsShift; } + void set_fs(uint32_t value) { + uint32_t v = + (GetUint32() & ~kMstatusFsMask) | ((value & 0b11U) << kMstatusFsShift); + UpdateSdAndSet(v); + } + uint32_t sd() { + return ((vs() == kMstatusStateDirty) || (fs() == kMstatusStateDirty) || + (ms() == kMstatusStateDirty) || + (((GetUint32() & kMstatusXsMask) >> kMstatusXsShift) == + kMstatusStateDirty)) + ? 1 + : 0; + } + void Submit() {} + + private: + void UpdateSdAndSet(uint32_t v) { + bool is_sd = + (((v & kMstatusMsMask) >> kMstatusMsShift) == kMstatusStateDirty) || + (((v & kMstatusVsMask) >> kMstatusVsShift) == kMstatusStateDirty) || + (((v & kMstatusFsMask) >> kMstatusFsShift) == kMstatusStateDirty) || + (((v & kMstatusXsMask) >> kMstatusXsShift) == kMstatusStateDirty); + if (is_sd) { + v |= kMstatusSdMaskRv32; + } else { + v &= ~kMstatusSdMaskRv32; + } + Set(v); + } +}; + +// CSR index for vsstatus (virtual supervisor status). +inline constexpr uint32_t kVsstatusCsrIndex = 0x200; + +class RiscVVSStatus : public RiscVSimpleCsr<uint64_t> { + public: + RiscVVSStatus(std::string name, RiscVCsrEnum csr_enum, uint64_t initial_value, + ArchState* state, TestMStatus* mstatus) + : RiscVSimpleCsr<uint64_t>(std::move(name), csr_enum, initial_value, + ~0ULL, ~0ULL, state), + mstatus_(mstatus) {} + uint32_t vs() { return mstatus_->vs(); } + void set_vs(uint32_t value) { mstatus_->set_vs(value); } + uint32_t fs() { return mstatus_->fs(); } + void set_fs(uint32_t value) { mstatus_->set_fs(value); } + uint32_t ms() { return (GetUint32() & kMstatusMsMask) >> kMstatusMsShift; } + void set_ms(uint32_t value) { + Set((GetUint32() & ~kMstatusMsMask) | ((value & 0b11U) << kMstatusMsShift)); + } + uint32_t sd() { return mstatus_->sd(); } + void Submit() {} + + private: + TestMStatus* mstatus_; +}; + +class TestRiscVState : public RiscVState { + public: + TestRiscVState(absl::string_view id, RiscVXlen xlen, MemoryInterface* memory) + : RiscVState(id, xlen, memory) { + uint64_t old_val = mstatus_->GetUint64(); + csr_set()->RemoveCsr(*RiscVCsrEnum::kMStatus).IgnoreError(); + test_mstatus_ = std::make_unique<TestMStatus>(old_val, this, misa()); + mstatus_ = test_mstatus_.get(); + csr_set()->AddCsr(mstatus_).IgnoreError(); + vsstatus_ = std::make_unique<RiscVVSStatus>( + "vsstatus", static_cast<RiscVCsrEnum>(kVsstatusCsrIndex), 0, this, + test_mstatus_.get()); + csr_set()->AddCsr(vsstatus_.get()).IgnoreError(); + } + TestMStatus* mstatus() const { return test_mstatus_.get(); } + RiscVVSStatus* vsstatus() const { return vsstatus_.get(); } + bool v() const { return v_; } + void set_v(bool v) { v_ = v; } + + private: + bool v_ = false; + std::unique_ptr<TestMStatus> test_mstatus_; + std::unique_ptr<RiscVVSStatus> vsstatus_; +}; // Architectural mstatus SD bit states. inline constexpr uint64_t kMstatusSdSet = 1ULL; @@ -123,6 +296,11 @@ inline constexpr uint32_t kVtypeAltfmtShift = 8; inline constexpr uint32_t kVillMask = 1U << 31; +// Returns the alternate format (altfmt) bit from vtype. +inline uint32_t GetVtypeAltfmt(const RiscVVectorState* vector_state) { + return (vector_state->vtype() >> kVtypeAltfmtShift) & 1U; +} + // Assembles an RVV / Zvt vtype configuration value from individual fields. constexpr uint32_t EncodeVtype(uint32_t vsew, uint32_t vlmul, bool vta = false, bool vma = false, bool altfmt = false) { @@ -136,6 +314,7 @@ inline constexpr uint32_t kMtwidenUnconfigured = 0; inline constexpr uint32_t kMtwiden1 = 1; // TWIDEN = 1 (no widening, TEW = SEW) inline constexpr uint32_t kMtwiden2 = 2; // TWIDEN = 2 (2x, TEW = 2 * SEW) +inline constexpr uint32_t kMtwiden4 = 3; // TWIDEN = 4 (4x, TEW = 4 * SEW) // Zvt msetmtypei altfmt encodings. inline constexpr uint32_t kAltfmtStandard = 0; @@ -152,9 +331,13 @@ // Zvt Tile Subset Specifier (TSS) encodings (spec 15.1.1.5). inline constexpr uint32_t kTssPatternRow = 0; inline constexpr uint32_t kTssPatternCol = 1; +inline constexpr uint32_t kTssPatternInvalid = 2; inline constexpr uint32_t kTssPatternShift = 24; inline constexpr uint32_t kTssTileShift = 27; +// FCSR rounding-mode bitfield offset. +inline constexpr uint32_t kFcsrFrmShift = 5; + // Assembles a 32-bit Tile Subset Specifier (TSS) value. constexpr uint32_t EncodeTss(uint32_t tile, uint32_t pattern, uint32_t index) { return ((tile & 0xF) << kTssTileShift) | @@ -237,21 +420,33 @@ class ScopedTrapCapture { public: explicit ScopedTrapCapture(RiscVState* state) : state_(state) { - state_->set_on_trap( - [this](bool, uint64_t, uint64_t code, uint64_t, const Instruction*) { - trap_taken_ = true; - trap_code_ = code; - return true; - }); + state_->set_on_trap([this](bool, uint64_t trap_value, uint64_t code, + uint64_t, const Instruction*) { + trap_taken_ = true; + trap_code_ = code; + trap_value_ = trap_value; + return true; + }); } + ~ScopedTrapCapture() { + if (state_ != nullptr) { + state_->set_on_trap(nullptr); + } + } + + ScopedTrapCapture(const ScopedTrapCapture&) = delete; + ScopedTrapCapture& operator=(const ScopedTrapCapture&) = delete; + bool trap_taken() const { return trap_taken_; } uint64_t trap_code() const { return trap_code_; } + uint64_t trap_value() const { return trap_value_; } private: RiscVState* state_; bool trap_taken_ = false; uint64_t trap_code_ = 0; + uint64_t trap_value_ = 0; }; // Encapsulates a localized 64-bit RISC-V state, vector state, and matrix @@ -263,18 +458,18 @@ RiscVVectorState vector_state; std::unique_ptr<RiscVZvtMatrixState> matrix_state; - explicit Rv64TestContext(const std::string& name) + explicit Rv64TestContext(absl::string_view name) : state(name, RiscVXlen::RV64, &memory), vector_state(&state, 128) { state.set_rv_vector(&vector_state); vector_state.SetVectorType(EncodeVtype(kVsew8, kVlmul1)); } static absl::StatusOr<std::unique_ptr<Rv64TestContext>> Create( - const std::string& name, int tile_elements = 32) { + absl::string_view name, int tile_elements = 32) { auto ctx = std::make_unique<Rv64TestContext>(name); auto ms_or = RiscVZvtMatrixState::Create(&ctx->state, tile_elements); if (!ms_or.ok()) return ms_or.status(); - ctx->matrix_state = std::move(ms_or.value()); + ctx->matrix_state = *std::move(ms_or); return ctx; } @@ -307,44 +502,68 @@ class RiscVZvtInstructionsTest : public testing::Test { protected: - RiscVZvtInstructionsTest() { - state_ = new RiscVState("test", RiscVXlen::RV32, &memory_); - vector_state_ = new RiscVVectorState(state_, 128); // 128 bytes - state_->set_rv_vector(vector_state_); + void SetUp() override { + state_ = + std::make_unique<TestRiscVState>("test", RiscVXlen::RV32, &memory_); + fp_state_ = std::make_unique<RiscVFPState>(state_->csr_set(), state_.get()); + state_->set_rv_fp(fp_state_.get()); + state_->mstatus()->set_fs(kMstatusStateInitial); - instruction_ = new Instruction(0x1000, state_); + vector_state_ = + std::make_unique<RiscVVectorState>(state_.get(), 128); // 128 bytes + state_->set_rv_vector(vector_state_.get()); + + ASSERT_OK_AND_ASSIGN(matrix_state_, + RiscVZvtMatrixState::Create(state_.get(), 32)); + + instruction_.reset(new Instruction(0x1000, state_.get())); instruction_->set_size(4); } - void SetUp() override { - ASSERT_OK_AND_ASSIGN(auto matrix_state, - RiscVZvtMatrixState::Create(state_, 32)); - matrix_state_ = matrix_state.release(); - } - - ~RiscVZvtInstructionsTest() override { - instruction_->DecRef(); - delete matrix_state_; - delete vector_state_; - delete state_; - } + ~RiscVZvtInstructionsTest() override = default; void ResetInstruction() { - if (instruction_ != nullptr) { - instruction_->DecRef(); - } - instruction_ = new Instruction(0x1000, state_); + instruction_.reset(new Instruction(0x1000, state_.get())); instruction_->set_size(4); } + // Appends a vector group source operand constructed from 'count' consecutive + // vector registers starting at 'base_reg'. + void AppendVectorGroupSource(int base_reg, int count = 8) { + std::vector<RegisterBase*> reg_vec; + reg_vec.reserve(count); + for (int i = 0; i < count; ++i) { + reg_vec.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", base_reg + i)) + .first); + } + instruction_->AppendSource(new RV32VectorSourceOperand( + absl::MakeSpan(reg_vec), absl::StrCat("v", base_reg))); + } + + // Appends a vector group destination operand constructed from 'count' + // consecutive vector registers starting at 'base_reg'. + void AppendVectorGroupDestination(int base_reg, int latency = 0, + int count = 8) { + std::vector<RegisterBase*> reg_vec; + reg_vec.reserve(count); + for (int i = 0; i < count; ++i) { + reg_vec.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", base_reg + i)) + .first); + } + instruction_->AppendDestination(new RV32VectorDestinationOperand( + absl::MakeSpan(reg_vec), latency, absl::StrCat("v", base_reg))); + } + // Sets the value of scalar register 'name' to 'value'. - void SetRegisterValue(const std::string& name, uint32_t value) { + void SetRegisterValue(absl::string_view name, uint32_t value) { auto* reg = state_->GetRegister<RV32Register>(name).first; reg->data_buffer()->Set<uint32_t>(0, value); } // Returns the value of scalar register 'name'. - uint32_t GetRegisterValue(const std::string& name) const { + uint32_t GetRegisterValue(absl::string_view name) const { return state_->GetRegister<RV32Register>(name) .first->data_buffer() ->Get<uint32_t>(0); @@ -382,38 +601,70 @@ return (state_->mstatus()->GetUint64() >> shift) & 1ULL; } + // Returns the vsstatus CSR pointer. + RiscVVSStatus* vsstatus() const { return state_->vsstatus(); } + // Creates a scalar source operand for register 'name'. - SourceOperandInterface* CreateScalarSource(const std::string& name) { + SourceOperandInterface* CreateScalarSource(absl::string_view name) { return state_->GetRegister<RV32Register>(name).first->CreateSourceOperand(); } // Creates a scalar destination operand for register 'name'. - DestinationOperandInterface* CreateScalarDest(const std::string& name) { + DestinationOperandInterface* CreateScalarDest(absl::string_view name) { return state_->GetRegister<RV32Register>(name) .first->CreateDestinationOperand(0); } // Creates a vector destination operand for vector register group 'reg_name'. RV32VectorDestinationOperand* CreateVectorDestOperand( - const std::string& reg_name) { + absl::string_view reg_name) { auto* reg = state_->GetRegister<RVVectorRegister>(reg_name).first; - std::vector<RegisterBase*> group = {reg}; - return new RV32VectorDestinationOperand(absl::Span<RegisterBase*>(group), 0, - reg_name); + RegisterBase* regs[] = {reg}; + return new RV32VectorDestinationOperand(absl::MakeSpan(regs), 0, + std::string(reg_name)); } // Creates a vector source operand for vector register group 'reg_name'. RV32VectorSourceOperand* CreateVectorSourceOperand( - const std::string& reg_name) { + absl::string_view reg_name) { auto* reg = state_->GetRegister<RVVectorRegister>(reg_name).first; - std::vector<RegisterBase*> group = {reg}; - return new RV32VectorSourceOperand(absl::Span<RegisterBase*>(group), - reg_name); + RegisterBase* regs[] = {reg}; + return new RV32VectorSourceOperand(absl::MakeSpan(regs), + std::string(reg_name)); } - // Verifies that 'semantic_function' triggers an IllegalInstruction trap - // when called on a state lacking matrix extension support. - void ExpectTrapWithoutMatrixState( + // Appends all 5 ISA source operands (matA, matB, mtile, vs2_idx, vs1_idx) + // for Zvt matrix-multiply instructions. + void AppendMatmulSources(uint32_t reg_a, uint32_t reg_b, + uint32_t dest_tile = 0) { + std::vector<RegisterBase*> reg_vec_a; + reg_vec_a.reserve(std::min<size_t>(8, 32 - reg_a)); + for (int i = 0; i < 8 && (reg_a + i) < 32; ++i) { + reg_vec_a.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", reg_a + i)) + .first); + } + instruction_->AppendSource(new RV32VectorSourceOperand( + absl::MakeSpan(reg_vec_a), absl::StrCat("v", reg_a))); + + std::vector<RegisterBase*> reg_vec_b; + reg_vec_b.reserve(std::min<size_t>(8, 32 - reg_b)); + for (int i = 0; i < 8 && (reg_b + i) < 32; ++i) { + reg_vec_b.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", reg_b + i)) + .first); + } + instruction_->AppendSource(new RV32VectorSourceOperand( + absl::MakeSpan(reg_vec_b), absl::StrCat("v", reg_b))); + + instruction_->AppendSource(new ImmediateOperand<uint32_t>(dest_tile)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(reg_a)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(reg_b)); + } + + // Executes 'semantic_function' on a state lacking matrix extension support + // and returns the captured trap code, or an error if no trap occurred. + absl::StatusOr<uint64_t> ExecuteWithoutMatrixStateExpectTrap( void (*semantic_function)(const Instruction*)) { FlatDemandMemory memory; RiscVState rv_state("test_no_matrix", RiscVXlen::RV32, &memory); @@ -425,9 +676,263 @@ inst->Execute(nullptr); inst->DecRef(); - EXPECT_TRUE(trap_capture.trap_taken()); - EXPECT_EQ(trap_capture.trap_code(), - static_cast<uint64_t>(ExceptionCode::kIllegalInstruction)); + if (!trap_capture.trap_taken()) { + return absl::FailedPreconditionError("Expected trap was not taken"); + } + return trap_capture.trap_code(); + } + + // Enables matrix, vector, and floating-point extensions in mstatus/vsstatus + // and configures mtype, vtype, vl, and vstart for a test scenario. + void ConfigureMatrixUnit(uint32_t mtwiden, uint32_t vsew, uint32_t vlmul, + uint32_t vl, uint32_t tk = 0, uint32_t tm = 0, + uint32_t vstart = 0, bool vta = false, + bool vma = false, bool altfmt = false) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->set_fs(kMstatusStateInitial); + state_->mstatus()->Submit(); + vsstatus()->set_ms(kMstatusStateInitial); + vsstatus()->set_fs(kMstatusStateInitial); + + matrix_state_->set_mtype(EncodeMtype(mtwiden, tk, tm)); + vector_state_->SetVectorType(EncodeVtype(vsew, vlmul, vta, vma, altfmt)); + vector_state_->set_vector_length(vl); + vector_state_->set_vstart(vstart); + } + + // Reads a single element at (tile, row, col) from the active matrix state. + template <typename T> + absl::StatusOr<T> GetTileElem(uint32_t tile, uint32_t row, uint32_t col, + int elem_bits = sizeof(T) * 8) { + return matrix_state_->GetElem<T>(tile, row, col, elem_bits); + } + + // Writes 'values' into row 'row' of 'tile' starting at column 0. + template <typename T> + absl::Status SetTileRow(uint32_t tile, uint32_t row, + absl::Span<const T> values, + int elem_bits = sizeof(T) * 8) { + for (int c = 0; c < static_cast<int>(values.size()); ++c) { + absl::Status status = + matrix_state_->SetElem<T>(tile, row, c, elem_bits, values[c]); + if (!status.ok()) return status; + } + return absl::OkStatus(); + } + + template <typename T> + absl::Status SetTileRow(uint32_t tile, uint32_t row, + std::initializer_list<T> values, + int elem_bits = sizeof(T) * 8) { + return SetTileRow(tile, row, absl::Span<const T>(values), elem_bits); + } + + // Populates 'count' columns of 'row' in 'tile' using 'generator(col)'. + template <typename T, typename GeneratorFn> + absl::Status SetTileRowPattern(uint32_t tile, uint32_t row, int count, + GeneratorFn generator, + int elem_bits = sizeof(T) * 8) { + for (int c = 0; c < count; ++c) { + absl::Status status = matrix_state_->SetElem<T>( + tile, row, c, elem_bits, static_cast<T>(generator(c))); + if (!status.ok()) return status; + } + return absl::OkStatus(); + } + + // Populates a small 2D matrix literal starting at (0, 0) in 'tile'. + template <typename T> + absl::Status SetTileMatrix( + uint32_t tile, std::initializer_list<std::initializer_list<T>> rows, + int elem_bits = sizeof(T) * 8) { + int r = 0; + for (const auto& row : rows) { + absl::Status status = SetTileRow<T>(tile, r++, row, elem_bits); + if (!status.ok()) return status; + } + return absl::OkStatus(); + } + + // Writes 'values' into column 'col' of 'tile' starting at row 0. + template <typename T> + absl::Status SetTileColumn(uint32_t tile, uint32_t col, + absl::Span<const T> values, + int elem_bits = sizeof(T) * 8) { + for (int r = 0; r < static_cast<int>(values.size()); ++r) { + absl::Status status = + matrix_state_->SetElem<T>(tile, r, col, elem_bits, values[r]); + if (!status.ok()) return status; + } + return absl::OkStatus(); + } + + template <typename T> + absl::Status SetTileColumn(uint32_t tile, uint32_t col, + std::initializer_list<T> values, + int elem_bits = sizeof(T) * 8) { + return SetTileColumn(tile, col, absl::Span<const T>(values), elem_bits); + } + + // Populates a rows x cols region of 'tile' using 'generator(row, col)'. + template <typename T, typename GeneratorFn> + absl::Status FillTilePattern(uint32_t tile, int rows, int cols, + GeneratorFn generator, + int elem_bits = sizeof(T) * 8) { + for (int r = 0; r < rows; ++r) { + for (int c = 0; c < cols; ++c) { + absl::Status status = matrix_state_->SetElem<T>( + tile, r, c, elem_bits, static_cast<T>(generator(r, c))); + if (!status.ok()) return status; + } + } + return absl::OkStatus(); + } + + // Populates a rows x cols region of 'tile' with a constant value. + template <typename T> + absl::Status FillTileConstant(uint32_t tile, int rows, int cols, T value, + int elem_bits = sizeof(T) * 8) { + return FillTilePattern<T>( + tile, rows, cols, [value](int, int) { return value; }, elem_bits); + } + + // Writes 'values' into the front of vector register 'reg_name'. + template <typename T> + void WriteVectorRegister(absl::string_view reg_name, + absl::Span<const T> values) { + auto* reg = state_->GetRegister<RVVectorRegister>(reg_name).first; + auto* db = state_->db_factory()->MakeCopyOf(reg->data_buffer()); + auto span = db->template Get<T>(); + std::copy(values.begin(), values.end(), span.begin()); + reg->SetDataBuffer(db); + db->DecRef(); + } + + template <typename T> + void WriteVectorRegister(absl::string_view reg_name, + std::initializer_list<T> values) { + WriteVectorRegister(reg_name, absl::Span<const T>(values)); + } + + // Fills all elements of type T in vector register 'reg_name' with 'value'. + template <typename T> + void FillVectorRegister(absl::string_view reg_name, T value) { + auto* reg = state_->GetRegister<RVVectorRegister>(reg_name).first; + auto* db = state_->db_factory()->MakeCopyOf(reg->data_buffer()); + auto span = db->template Get<T>(); + std::fill(span.begin(), span.end(), value); + reg->SetDataBuffer(db); + db->DecRef(); + } + + // Returns a read-only view of the first 'count' elements in 'reg_name'. + template <typename T> + absl::Span<const T> ReadVectorRegister(absl::string_view reg_name, + size_t count) const { + auto* reg = state_->GetRegister<RVVectorRegister>(reg_name).first; + return reg->data_buffer()->template Get<T>().subspan(0, count); + } + + // Writes 'values' to 'memory_' starting at byte address 'addr'. + template <typename T> + void WriteMemory(uint64_t addr, absl::Span<const T> values) { + auto* db = state_->db_factory()->Allocate(values.size() * sizeof(T)); + auto span = db->template Get<T>(); + std::copy(values.begin(), values.end(), span.begin()); + memory_.Store(addr, db); + db->DecRef(); + } + + template <typename T> + void WriteMemory(uint64_t addr, std::initializer_list<T> values) { + WriteMemory(addr, absl::Span<const T>(values)); + } + + // Writes 'count' elements generated by 'generator(index)' to 'memory_'. + template <typename T, typename GeneratorFn> + void WriteMemoryPattern(uint64_t addr, size_t count, GeneratorFn generator) { + auto* db = state_->db_factory()->Allocate(count * sizeof(T)); + auto span = db->template Get<T>(); + for (size_t i = 0; i < count; ++i) { + span[i] = static_cast<T>(generator(i)); + } + memory_.Store(addr, db); + db->DecRef(); + } + + // Writes 'count' copies of 'value' to 'memory_' starting at 'addr'. + template <typename T> + void WriteMemoryConstant(uint64_t addr, size_t count, T value) { + WriteMemoryPattern<T>(addr, count, [value](size_t) { return value; }); + } + + // Reads 'count' elements of type T from 'memory_' starting at 'addr'. + template <typename T> + std::vector<T> ReadMemory(uint64_t addr, size_t count) { + auto* db = state_->db_factory()->Allocate(count * sizeof(T)); + memory_.Load(addr, db, nullptr, nullptr); + auto span = db->template Get<T>(); + std::vector<T> result(span.begin(), span.begin() + count); + db->DecRef(); + return result; + } + + // Executes vtmv.v.t with encoded 'tss' into vector register group 'vd_reg'. + void ExecuteVtmvVt(uint32_t tss, int vd_reg = 8) { + instruction_->AppendSource(new ImmediateOperand<uint32_t>(tss)); + AppendVectorGroupDestination(vd_reg); + instruction_->set_semantic_function(&RiscVZvtVtmvVt); + instruction_->Execute(nullptr); + } + + // Executes vtmv.t.v from vector register group 'vs_reg' into tile slice + // 'tss'. + void ExecuteVtmvTv(int vs_reg, uint32_t tss) { + AppendVectorGroupSource(vs_reg); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(tss)); + instruction_->set_semantic_function(&RiscVZvtVtmvTv); + instruction_->Execute(nullptr); + } + + // Executes a Zvt tile memory semantic function (vtle or vtse) with EEW 'eew', + // base address 'base_addr', and encoded TSS 'tss'. + void ExecuteTileMemoryOp(void (*semantic_fn)(int, const Instruction*), + int eew, uint64_t base_addr, uint32_t tss) { + instruction_->AppendSource(new ImmediateOperand<uint64_t>(base_addr)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(tss)); + instruction_->set_semantic_function( + [semantic_fn, eew](const Instruction* inst) { + semantic_fn(eew, inst); + }); + instruction_->Execute(nullptr); + } + + // Executes a Zvt matrix-multiply semantic function with source register + // groups 'reg_a' and 'reg_b' accumulating into 'dest_tile'. + void ExecuteMatmul(void (*semantic_fn)(const Instruction*), + uint32_t reg_a = 8, uint32_t reg_b = 16, + uint32_t dest_tile = 0) { + AppendMatmulSources(reg_a, reg_b, dest_tile); + instruction_->set_semantic_function(semantic_fn); + instruction_->Execute(nullptr); + } + + // Reads a rows x cols region of 'tile' in row-major order into a vector. + template <typename T> + absl::StatusOr<std::vector<T>> GetTileRegion(uint32_t tile, int rows, + int cols, + int elem_bits = sizeof(T) * 8) { + std::vector<T> elements; + elements.reserve(rows * cols); + for (int r = 0; r < rows; ++r) { + for (int c = 0; c < cols; ++c) { + auto elem_or = matrix_state_->GetElem<T>(tile, r, c, elem_bits); + if (!elem_or.ok()) return elem_or.status(); + elements.push_back(*elem_or); + } + } + return elements; } // Reads 'count' elements from row 'row' of tile 'tile' into a vector. @@ -461,10 +966,16 @@ } FlatDemandMemory memory_; - RiscVState* state_; - RiscVVectorState* vector_state_; - RiscVZvtMatrixState* matrix_state_; - Instruction* instruction_; + std::unique_ptr<TestRiscVState> state_; + std::unique_ptr<RiscVFPState> fp_state_; + std::unique_ptr<RiscVVectorState> vector_state_; + std::unique_ptr<RiscVZvtMatrixState> matrix_state_; + struct InstructionDeleter { + void operator()(Instruction* ptr) const { + if (ptr) ptr->DecRef(); + } + }; + std::unique_ptr<Instruction, InstructionDeleter> instruction_; }; TEST_F(RiscVZvtInstructionsTest, MsetmtypeFunctionalDecoding) { @@ -509,9 +1020,11 @@ TEST_F(RiscVZvtInstructionsTest, MsetmtypeiFunctionalDecoding) { // mtwiden = 1 (TWIDEN = 1), vsew = 0 (SEW = 8 bits), altfmt = 0 (standard). - instruction_->AppendSource(new ImmediateOperand<uint32_t>(kMtwiden1)); - instruction_->AppendSource(new ImmediateOperand<uint32_t>(kVsew8)); - instruction_->AppendSource(new ImmediateOperand<uint32_t>(kAltfmtStandard)); + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(/*mtwiden=*/kMtwiden1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vsew=*/kVsew8)); + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(/*altfmt=*/kAltfmtStandard)); instruction_->set_semantic_function(&RiscVZvtMsetMtypei); instruction_->Execute(nullptr); @@ -520,6 +1033,7 @@ EXPECT_EQ(matrix_state_->mtwiden(), kMtwiden1); EXPECT_EQ(state_->rv_vector()->vector_length(), 0); EXPECT_EQ(state_->rv_vector()->selected_element_width(), 1); + EXPECT_EQ(GetVtypeAltfmt(state_->rv_vector()), 0); } TEST_F(RiscVZvtInstructionsTest, MsetmtypeiImmediateDecoding) { @@ -534,8 +1048,9 @@ EXPECT_EQ(matrix_state_->mtwiden(), kMtwiden1); EXPECT_EQ(state_->rv_vector()->vector_length(), 0); EXPECT_EQ(state_->rv_vector()->selected_element_width(), 4); - EXPECT_EQ(state_->rv_vector()->vtype() & 0x7, kVlmul1); + EXPECT_EQ(state_->rv_vector()->vtype() & kVlmulMask, kVlmul1); EXPECT_EQ(state_->rv_vector()->max_vector_length(), 32); + EXPECT_EQ(GetVtypeAltfmt(state_->rv_vector()), 1); } TEST_F(RiscVZvtInstructionsTest, MsettnFunctionalDecoding) { @@ -590,14 +1105,18 @@ SetMstatusVs(kMstatusStateInitial); EXPECT_EQ(GetMstatusVs(), kMstatusStateInitial); - // mtwiden = 0, but retain active TM in mtype to ensure msettm resets it. + // mtwiden = 0, but retain active TM in mtype to ensure msettm traps + // with kIllegalInstruction and leaves state unchanged. matrix_state_->set_mtype( EncodeMtype(kMtwidenUnconfigured, /*tk=*/0, /*tm=*/32)); ASSERT_EQ(matrix_state_->tile_m(), 32); + ScopedTrapCapture trap_capture(state_.get()); instruction_->Execute(nullptr); - EXPECT_EQ(matrix_state_->tile_m(), 0); - EXPECT_EQ(GetRegisterValue("x2"), 0); - EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); + EXPECT_EQ(matrix_state_->tile_m(), 32); + EXPECT_EQ(GetRegisterValue("x2"), 32); + EXPECT_EQ(GetMstatusVs(), kMstatusStateInitial); } TEST_F(RiscVZvtInstructionsTest, MsettkFunctionalDecoding) { @@ -621,14 +1140,1655 @@ SetMstatusVs(kMstatusStateInitial); EXPECT_EQ(GetMstatusVs(), kMstatusStateInitial); - // mtwiden = 0, but retain active TK in mtype to ensure msettk resets it. + // mtwiden = 0, but retain active TK in mtype to ensure msettk traps + // with kIllegalInstruction and leaves state unchanged. matrix_state_->set_mtype( EncodeMtype(kMtwidenUnconfigured, /*tk=*/4, /*tm=*/0)); ASSERT_EQ(matrix_state_->tile_k(), 4); + ScopedTrapCapture trap_capture(state_.get()); instruction_->Execute(nullptr); + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); + EXPECT_EQ(matrix_state_->tile_k(), 4); + EXPECT_EQ(GetRegisterValue("x2"), 4); + EXPECT_EQ(GetMstatusVs(), kMstatusStateInitial); +} + +TEST_F(RiscVZvtInstructionsTest, DynamicVlmulResolution) { + // mtwiden = 1 -> TWIDEN = 1 + uint32_t rs1_val = EncodeMtype(kMtwiden1); + // overridden. + uint32_t rs2_val = EncodeVtype(kVsew16, kVlmul8); + + SetRegisterValue("x1", rs1_val); + SetRegisterValue("x2", rs2_val); + + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* reg2 = state_->GetRegister<RV32Register>("x2").first; + + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendSource(reg2->CreateSourceOperand()); + + instruction_->set_semantic_function(&RiscVZvtMsetMtype); + + instruction_->Execute(nullptr); + + // EXPECT_EQ LMUL=1 (represented internally as 8). + EXPECT_EQ(state_->rv_vector()->vector_length_multiplier(), 8); +} + +TEST_F(RiscVZvtInstructionsTest, MtypeTkKmaxBoundsClamping) { + // tk=7, mtwiden=1 + uint32_t rs1_val = EncodeMtype(kMtwiden1, /*tk=*/7); + uint32_t rs2_val = 0; + + SetRegisterValue("x1", rs1_val); + SetRegisterValue("x2", rs2_val); + + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* reg2 = state_->GetRegister<RV32Register>("x2").first; + + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendSource(reg2->CreateSourceOperand()); + + instruction_->set_semantic_function(&RiscVZvtMsetMtype); + instruction_->Execute(nullptr); + + // Assert clamped K to KMAX=4 + EXPECT_EQ(matrix_state_->tile_k(), 4); +} + +TEST_F(RiscVZvtInstructionsTest, MtypeTmCapacityLayoutClamping) { + // tm=500, mtwiden=1 + uint32_t rs1_val = EncodeMtype(kMtwiden1, /*tk=*/0, /*tm=*/500); + uint32_t rs2_val = 0; + + SetRegisterValue("x1", rs1_val); + SetRegisterValue("x2", rs2_val); + + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* reg2 = state_->GetRegister<RV32Register>("x2").first; + + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendSource(reg2->CreateSourceOperand()); + + instruction_->set_semantic_function(&RiscVZvtMsetMtype); + instruction_->Execute(nullptr); + + // ETE for 8-bit * TWIDEN=1 is tile_elements(), which is 32. + // LMUL=1 -> kLmulElements = 128 (max_vector_length in elements). + // min(tmpl_m=500, kLmulElements=128, kEffectiveTileElements=32) = 32. + EXPECT_EQ(matrix_state_->tile_m(), 32); +} + +TEST_F(RiscVZvtInstructionsTest, MsetmtypeVmaTailMapping) { + SetRegisterValue("x1", EncodeMtype(kMtwiden1)); + SetRegisterValue("x2", + EncodeVtype(kVsew8, kVlmul1, /*vta=*/false, /*vma=*/true)); + + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* reg2 = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendSource(reg2->CreateSourceOperand()); + + instruction_->set_semantic_function(&RiscVZvtMsetMtype); + instruction_->Execute(nullptr); + + EXPECT_TRUE(state_->rv_vector()->vector_mask_agnostic()); +} + +TEST_F(RiscVZvtInstructionsTest, MsetmtypeVtaMaskMapping) { + SetRegisterValue("x1", EncodeMtype(kMtwiden1)); + SetRegisterValue("x2", EncodeVtype(kVsew8, kVlmul1, /*vta=*/true)); + + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* reg2 = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendSource(reg2->CreateSourceOperand()); + + instruction_->set_semantic_function(&RiscVZvtMsetMtype); + instruction_->Execute(nullptr); + + EXPECT_TRUE(state_->rv_vector()->vector_tail_agnostic()); +} + +TEST_F(RiscVZvtInstructionsTest, MsetmtypeUnconditionalVlZeroing) { + vector_state_->set_vector_length(100); + + SetRegisterValue("x1", 1); + SetRegisterValue("x2", 0); + + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* reg2 = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendSource(reg2->CreateSourceOperand()); + + instruction_->set_semantic_function(&RiscVZvtMsetMtype); + instruction_->Execute(nullptr); + + EXPECT_EQ(state_->rv_vector()->vector_length(), 0); +} + +TEST_F(RiscVZvtInstructionsTest, MsetmtypeiUnconditionalVlZeroing) { + vector_state_->set_vector_length(100); + + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(/*mtwiden=*/kMtwiden1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vsew=*/kVsew8)); + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(/*altfmt=*/kAltfmtStandard)); + instruction_->set_semantic_function(&RiscVZvtMsetMtypei); + instruction_->Execute(nullptr); + + EXPECT_EQ(state_->rv_vector()->vector_length(), 0); +} + +TEST_F(RiscVZvtInstructionsTest, MstatusVsDirtyTrackingOnMsetmtype) { + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + SetRegisterValue("x1", EncodeMtype(kMtwiden1)); + SetRegisterValue("x2", 0); + + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* reg2 = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendSource(reg2->CreateSourceOperand()); + + instruction_->set_semantic_function(&RiscVZvtMsetMtype); + instruction_->Execute(nullptr); + + EXPECT_EQ(state_->mstatus()->vs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, MstatusVsDirtyTrackingOnMsetmtypei) { + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + vsstatus()->set_vs(kMstatusStateInitial); + + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(/*mtwiden=*/kMtwiden1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vsew=*/kVsew8)); + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(/*altfmt=*/kAltfmtStandard)); + instruction_->set_semantic_function(&RiscVZvtMsetMtypei); + instruction_->Execute(nullptr); + + EXPECT_EQ(state_->mstatus()->vs(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->vs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, MsetExecuteWithoutTrapWhenMsOff) { + state_->mstatus()->set_ms(kMstatusStateOff); + + ScopedTrapCapture trap_capture(state_.get()); + + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(/*mtwiden=*/kMtwiden1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vsew=*/kVsew8)); + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(/*altfmt=*/kAltfmtStandard)); + instruction_->set_semantic_function(&RiscVZvtMsetMtypei); + instruction_->Execute(nullptr); + + EXPECT_FALSE(trap_capture.trap_taken()); +} + +TEST_F(RiscVZvtInstructionsTest, MstatusVsDirtyTrackingOnMsettn) { + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + vsstatus()->set_vs(kMstatusStateInitial); + + // Configure matrix state first + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + + SetRegisterValue("x1", 16); + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* dest = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendDestination(dest->CreateDestinationOperand(0)); + + instruction_->set_semantic_function(&RiscVZvtMsetTn); + instruction_->Execute(nullptr); + + EXPECT_EQ(state_->mstatus()->vs(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->vs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, MstatusVsDirtyTrackingOnMsettm) { + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + vsstatus()->set_vs(kMstatusStateInitial); + + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + + SetRegisterValue("x1", 16); + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* dest = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendDestination(dest->CreateDestinationOperand(0)); + + instruction_->set_semantic_function(&RiscVZvtMsetTm); + instruction_->Execute(nullptr); + + EXPECT_EQ(state_->mstatus()->vs(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->vs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, MstatusVsDirtyTrackingOnMsettk) { + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + vsstatus()->set_vs(kMstatusStateInitial); + + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + + SetRegisterValue("x1", 16); + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* dest = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendDestination(dest->CreateDestinationOperand(0)); + + instruction_->set_semantic_function(&RiscVZvtMsetTk); + instruction_->Execute(nullptr); + + EXPECT_EQ(state_->mstatus()->vs(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->vs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, MsettmIllegalInstructionException) { + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + matrix_state_->set_mtype(kMtwidenUnconfigured); + + ScopedTrapCapture trap_capture(state_.get()); + + SetRegisterValue("x1", 500); + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* dest = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendDestination(dest->CreateDestinationOperand(0)); + + instruction_->set_semantic_function(&RiscVZvtMsetTm); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); + EXPECT_EQ(state_->mstatus()->vs(), kMstatusStateInitial); +} + +TEST_F(RiscVZvtInstructionsTest, GetMatrixStateIllegalInstruction) { + // Remove the CSR to simulate GetMatrixState failure. + ASSERT_OK(state_->csr_set()->RemoveCsr(kRiscVMtypeCsrIndex)); + + ScopedTrapCapture trap_capture(state_.get()); + + instruction_->set_semantic_function(&RiscVZvtMsetMtypei); + instruction_->Execute(nullptr); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, MsettkIllegalInstructionException) { + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + matrix_state_->set_mtype(kMtwidenUnconfigured); + + ScopedTrapCapture trap_capture(state_.get()); + + SetRegisterValue("x1", 500); + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* dest = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendDestination(dest->CreateDestinationOperand(0)); + + instruction_->set_semantic_function(&RiscVZvtMsetTk); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); + EXPECT_EQ(state_->mstatus()->vs(), kMstatusStateInitial); +} + +TEST_F(RiscVZvtInstructionsTest, MsettnVsetvlDegeneration) { + matrix_state_->set_mtype(kMtwidenUnconfigured); + vector_state_->SetVectorType( + EncodeVtype(kVsew8, kVlmul1)); // vlmax = 128 elements + + SetRegisterValue("x1", 500); // Greater than vlmax + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* dest = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendDestination(dest->CreateDestinationOperand(0)); + + instruction_->set_semantic_function(&RiscVZvtMsetTn); + instruction_->Execute(nullptr); + + EXPECT_EQ(state_->rv_vector()->vector_length(), + 128); // Degenerates to min(500, current vlmax) +} + +TEST_F(RiscVZvtInstructionsTest, MsettnX0RegisterHandling) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + + SetRegisterValue("x0", 0); + auto* reg0 = state_->GetRegister<RV32Register>("x0").first; + auto* dest = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg0->CreateSourceOperand()); + instruction_->AppendDestination(dest->CreateDestinationOperand(0)); + + instruction_->set_semantic_function(&RiscVZvtMsetTn); + instruction_->Execute(nullptr); + + EXPECT_EQ(state_->rv_vector()->vector_length(), 0); +} + +TEST_F(RiscVZvtInstructionsTest, MsettmX0RegisterHandling) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + + SetRegisterValue("x0", 0); + auto* reg0 = state_->GetRegister<RV32Register>("x0").first; + auto* dest = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg0->CreateSourceOperand()); + instruction_->AppendDestination(dest->CreateDestinationOperand(0)); + + instruction_->set_semantic_function(&RiscVZvtMsetTm); + instruction_->Execute(nullptr); + + EXPECT_EQ(matrix_state_->tile_m(), 0); +} + +TEST_F(RiscVZvtInstructionsTest, MsettkX0RegisterHandling) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + + SetRegisterValue("x0", 0); + auto* reg0 = state_->GetRegister<RV32Register>("x0").first; + auto* dest = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg0->CreateSourceOperand()); + instruction_->AppendDestination(dest->CreateDestinationOperand(0)); + + instruction_->set_semantic_function(&RiscVZvtMsetTk); + instruction_->Execute(nullptr); + EXPECT_EQ(matrix_state_->tile_k(), 0); - EXPECT_EQ(GetRegisterValue("x2"), 0); - EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, VtypeVillInvalidationStateMachine) { + // ELEN is 32. mtwiden = 1. SEW = 64bit -> 64 * 1 > 32 -> triggers vill + // (exception). + SetRegisterValue("x1", EncodeMtype(kMtwiden1)); + SetRegisterValue("x2", EncodeVtype(kVsew64, kVlmul1)); + + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* reg2 = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendSource(reg2->CreateSourceOperand()); + + instruction_->set_semantic_function(&RiscVZvtMsetMtype); + instruction_->Execute(nullptr); + + // Assert vtype.vill escalation + EXPECT_TRUE(state_->rv_vector()->vector_exception()); + EXPECT_EQ(state_->rv_vector()->vtype(), kVillMask); + EXPECT_EQ(state_->rv_vector()->vector_length(), 0u); + // Assert mtype zeroing + EXPECT_EQ(matrix_state_->mtype(), 0u); + // Assert vtype remaining fields zeroing + EXPECT_EQ(state_->rv_vector()->vector_length_multiplier(), 0); + EXPECT_EQ(state_->rv_vector()->selected_element_width(), 0); + EXPECT_FALSE(state_->rv_vector()->vector_tail_agnostic()); + EXPECT_FALSE(state_->rv_vector()->vector_mask_agnostic()); +} + +TEST_F(RiscVZvtInstructionsTest, VillEscalationWhenSewTwidenExceedsElen) { + // ELEN is 32. + // mtwiden = 1. SEW = 64bit -> 64 * 1 > 32 -> triggers vill (exception). + SetRegisterValue("x1", EncodeMtype(kMtwiden1)); + SetRegisterValue("x2", EncodeVtype(kVsew64, kVlmul1)); + + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* reg2 = state_->GetRegister<RV32Register>("x2").first; + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendSource(reg2->CreateSourceOperand()); + + instruction_->set_semantic_function(&RiscVZvtMsetMtype); + instruction_->Execute(nullptr); + + EXPECT_TRUE(state_->rv_vector()->vector_exception()); + EXPECT_EQ(state_->rv_vector()->vtype(), kVillMask); + EXPECT_EQ(state_->rv_vector()->vector_length(), 0u); + EXPECT_EQ(matrix_state_->mtype(), 0u); +} + +TEST_F(RiscVZvtInstructionsTest, MatrixExceptionTrapWhenMsOff) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + + state_->mstatus()->set_ms(kMstatusStateOff); // MS off + state_->mstatus()->Submit(); + + ScopedTrapCapture trap_capture(state_.get()); + + instruction_->set_semantic_function(&RiscVZvtVtZero); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtDiscardTrapWhenMatrixStateOff) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + + state_->mstatus()->set_ms(kMstatusStateOff); // MS off + state_->mstatus()->Submit(); + + ScopedTrapCapture trap_capture(state_.get()); + + instruction_->set_semantic_function(&RiscVZvtVtDiscard); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtDiscardTrapWhenVill) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(kVillMask); + + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->Submit(); + ScopedTrapCapture trap_capture(state_.get()); + + instruction_->set_semantic_function(&RiscVZvtVtDiscard); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtDiscardTrapWhenVillAndMtwidenZero) { + matrix_state_->set_mtype(0); // mtwiden = 0 + + // Set vill = 1 (vector unconfigured) + vector_state_->SetVectorType(kVillMask); + + state_->mstatus()->set_ms(kMstatusStateDirty); + state_->mstatus()->Submit(); + + ScopedTrapCapture trap_capture(state_.get()); + + instruction_->set_semantic_function(&RiscVZvtVtDiscard); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtDiscardNoTrapWhenMtwidenZero) { + matrix_state_->set_mtype(0); // mtwiden = 0 + // Assert valid vector state (vill = 0) to avoid precondition trap + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + + state_->mstatus()->set_ms(kMstatusStateDirty); + state_->mstatus()->Submit(); + ScopedTrapCapture trap_capture(state_.get()); + + instruction_->set_semantic_function(&RiscVZvtVtDiscard); + instruction_->Execute(nullptr); + + EXPECT_FALSE(trap_capture.trap_taken()); + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateInitial); // Initial +} + +TEST_F(RiscVZvtInstructionsTest, MstatusMsDirtyTrackingOnDirectTileUpdate) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + + state_->mstatus()->set_ms(kMstatusStateInitial); // Initial + state_->mstatus()->Submit(); + + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*mtd=*/0)); + instruction_->set_semantic_function(&RiscVZvtVtZero); + instruction_->Execute(nullptr); + + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateDirty); // Dirty +} + +TEST_F(RiscVZvtInstructionsTest, MstatusVsDirtyTrackingOnGeneralInstruction) { + state_->mstatus()->set_ms(kMstatusStateInitial); // Initial + state_->mstatus()->set_vs(kMstatusStateInitial); // Initial + state_->mstatus()->Submit(); + + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*mtd=*/0)); + instruction_->set_semantic_function(&RiscVZvtVtZero); + instruction_->Execute(nullptr); + + EXPECT_EQ(state_->mstatus()->vs(), kMstatusStateDirty); // Dirty +} + +TEST_F(RiscVZvtInstructionsTest, VsetvlDoesNotTrapWhenMatrixStateIsOff) { + // mstatus.MS = Off + state_->mstatus()->set_ms(kMstatusStateOff); + state_->mstatus()->Submit(); + + // Test vsetvl execution + SetRegisterValue("x1", 10); + SetRegisterValue("x2", 0x15); + auto* reg1 = state_->GetRegister<RV32Register>("x1").first; + auto* reg2 = state_->GetRegister<RV32Register>("x2").first; + auto* dest = state_->GetRegister<RV32Register>("x3").first; + + instruction_->AppendSource(reg1->CreateSourceOperand()); + instruction_->AppendSource(reg2->CreateSourceOperand()); + instruction_->AppendDestination(dest->CreateDestinationOperand(0)); + + ScopedTrapCapture trap_capture(state_.get()); + + instruction_->set_semantic_function([](Instruction* inst) { + Vsetvl(/*rd_zero=*/false, /*rs1_zero=*/false, inst); + }); + + instruction_->Execute(nullptr); + + // Expect no exception to be generated + // Matrix state Off shouldn't cause kIllegalInstruction in vsetvl! + EXPECT_FALSE(trap_capture.trap_taken()); +} + +TEST_F(RiscVZvtInstructionsTest, VtzeroStateZeroingLoop) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/0, + /*tm=*/4); + constexpr uint32_t kTileId = 0; + ScopedTrapCapture trap_capture(state_.get()); + + // Populate tile 0 with non-zero values to verify zeroing. + ASSERT_OK(FillTileConstant<uint32_t>(kTileId, 4, 4, 0xDEADC0DE)); + + // Create `vtzero` instruction testing `mtd` = 0. + instruction_->AppendSource(new ImmediateOperand<uint32_t>(kTileId)); // mtd + instruction_->set_semantic_function(&RiscVZvtVtZero); + instruction_->Execute(nullptr); + + EXPECT_FALSE(trap_capture.trap_taken()); + ASSERT_OK_AND_ASSIGN( + auto tile_vals, GetTileRegion<uint32_t>(kTileId, /*rows=*/4, /*cols=*/4)); + EXPECT_THAT(tile_vals, testing::Each(0)); +} + +TEST_F(RiscVZvtInstructionsTest, VtzeroTrapOnIllegalTile) { + // mstatus.MS and mstatus.VS must be enabled + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + vsstatus()->set_ms(kMstatusStateInitial); + + // Set up mtype (mtwiden = 1) -> TWIDEN = 1 + uint32_t mtype = EncodeMtype(kMtwiden1, /*tk=*/0, /*tm=*/4); + matrix_state_->set_mtype(mtype); + + // Set up vector state: vl = 4, sew = 32 bits (0b10 == 2, shifted by 3) + vector_state_->set_vector_length(4); + vector_state_->SetVectorType(EncodeVtype(kVsew32, kVlmul1)); + + const int tile_id = 7; + ScopedTrapCapture trap_capture(state_.get()); + + // Create `vtzero` instruction testing `mtd` = 7. + instruction_->AppendSource(new ImmediateOperand<uint32_t>(tile_id)); // mtd + instruction_->set_semantic_function(&RiscVZvtVtZero); + instruction_->Execute(nullptr); + + // Expect trap since tile_id=7 is unaligned for TEW=32 + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtzeroNoTrapWhenMtwidenZero) { + // mstatus.MS and mstatus.VS must be enabled + state_->mstatus()->set_ms(kMstatusStateDirty); + state_->mstatus()->set_vs(kMstatusStateDirty); + state_->mstatus()->Submit(); + + // Set up mtype (mtwiden = 0) + matrix_state_->set_mtype(0); + + ScopedTrapCapture trap_capture(state_.get()); + + const int tile_id = + 1; // Unaligned tile index (e.g., usually would be mod 16/NTiles) + + instruction_->AppendSource(new ImmediateOperand<uint32_t>(tile_id)); // mtd + instruction_->set_semantic_function(&RiscVZvtVtZero); + instruction_->Execute(nullptr); + + // Must not trap when mtwiden == 0, even if the tile is otherwise unaligned. + EXPECT_FALSE(trap_capture.trap_taken()); +} + +TEST_F(RiscVZvtInstructionsTest, VtzeroTrapWhenMtwidenNotZeroAndUnaligned) { + state_->mstatus()->set_ms(kMstatusStateDirty); + state_->mstatus()->set_vs(kMstatusStateDirty); + state_->mstatus()->Submit(); + + // Set up mtype (mtwiden = 1) -> TWIDEN = 1, NTiles = 8, tile align = 2 + uint32_t mtype = EncodeMtype(kMtwiden1, /*tk=*/0, /*tm=*/4); + matrix_state_->set_mtype(mtype); + + vector_state_->set_vector_length(4); + vector_state_->SetVectorType(EncodeVtype(kVsew32, kVlmul1)); + + ScopedTrapCapture trap_capture(state_.get()); + + const int tile_id = 1; // Unaligned since align is 16/NTiles = 16/8 = 2 + + instruction_->AppendSource(new ImmediateOperand<uint32_t>(tile_id)); // mtd + instruction_->set_semantic_function(&RiscVZvtVtZero); + instruction_->Execute(nullptr); + + // Must trap when mtwiden != 0 and tile is unaligned. + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvVtGeneralizedRowElementExtraction) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/0, + /*tm=*/4); + constexpr uint32_t kTileId = 4; + const int te = matrix_state_->tile_elements(); + ASSERT_OK(FillTilePattern<uint32_t>(kTileId, te, te, [](int row, int col) { + return 0xDEADC0DE + row * 10 + col; + })); + + ExecuteVtmvVt(EncodeTss(kTileId, kTssPatternRow, /*index=*/2)); + + EXPECT_THAT(ReadVectorRegister<uint32_t>("v8", 4), + testing::ElementsAre(0xDEADC0DE + 20, 0xDEADC0DE + 21, + 0xDEADC0DE + 22, 0xDEADC0DE + 23)); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvVtGeneralizedColumnElementExtraction) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/0, + /*tm=*/4); + constexpr uint32_t kTileId = 4; + const int te = matrix_state_->tile_elements(); + ASSERT_OK(FillTilePattern<uint32_t>(kTileId, te, te, [](int row, int col) { + return 0xDEADC0DE + row * 10 + col; + })); + + ExecuteVtmvVt(EncodeTss(kTileId, kTssPatternCol, /*index=*/2)); + + EXPECT_THAT(ReadVectorRegister<uint32_t>("v8", 4), + testing::ElementsAre(0xDEADC0DE + 2, 0xDEADC0DE + 12, + 0xDEADC0DE + 22, 0xDEADC0DE + 32)); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvTvPatternDirectedRowVectorInsertion) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/0, + /*tm=*/4); + constexpr uint32_t kTileId = 4; + const int te = matrix_state_->tile_elements(); + ASSERT_OK(FillTileConstant<uint32_t>(kTileId, te, te, 0)); + WriteVectorRegister<uint32_t>( + "v8", {0xBEAF0000, 0xBEAF0001, 0xBEAF0002, 0xBEAF0003}); + + ExecuteVtmvTv(/*vs_reg=*/8, EncodeTss(kTileId, kTssPatternRow, /*index=*/2)); + + ASSERT_OK_AND_ASSIGN(auto row_vals, + GetTileRow<uint32_t>(kTileId, /*row=*/2, /*count=*/4)); + EXPECT_THAT(row_vals, testing::ElementsAre(0xBEAF0000, 0xBEAF0001, 0xBEAF0002, + 0xBEAF0003)); + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvTvPatternDirectedColumnVectorInsertion) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/0, + /*tm=*/4); + constexpr uint32_t kTileId = 4; + const int te = matrix_state_->tile_elements(); + ASSERT_OK(FillTileConstant<uint32_t>(kTileId, te, te, 0)); + WriteVectorRegister<uint32_t>( + "v8", {0xBEAF0000, 0xBEAF0001, 0xBEAF0002, 0xBEAF0003}); + + ExecuteVtmvTv(/*vs_reg=*/8, EncodeTss(kTileId, kTssPatternCol, /*index=*/2)); + + ASSERT_OK_AND_ASSIGN( + auto col_vals, GetTileColumn<uint32_t>(kTileId, /*col=*/2, /*count=*/4)); + EXPECT_THAT(col_vals, testing::ElementsAre(0xBEAF0000, 0xBEAF0001, 0xBEAF0002, + 0xBEAF0003)); + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvTssPatternExceedsBoundsTrap) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteVtmvVt(EncodeTss(/*tile=*/4, kTssPatternInvalid, /*index=*/2)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvTssIndexOverflowTrap) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + // Max tile elements for SEW=32 and TWIDEN=1 is 128 / 4 = 32; index 32 is out + // of bounds (0..31). + ExecuteVtmvVt(EncodeTss(/*tile=*/4, kTssPatternRow, /*index=*/32)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvTssMisalignedTileMasking) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + // Mock data in tile 0 so we can observe that misaligned tile 1 masks to tile + // 0. + ASSERT_OK(SetTileRow<uint32_t>( + /*tile=*/0, /*row=*/0, {0xFACEBEEF, 0xDEADC0DE, 0xBAADF00D, 0xCAFEBABE})); + + ExecuteVtmvVt(EncodeTss(/*tile=*/1, kTssPatternRow, /*index=*/0)); + + EXPECT_FALSE(trap_capture.trap_taken()); + EXPECT_THAT( + ReadVectorRegister<uint32_t>("v8", 4), + testing::ElementsAre(0xFACEBEEF, 0xDEADC0DE, 0xBAADF00D, 0xCAFEBABE)); +} + +TEST_F(RiscVZvtInstructionsTest, VtleUnconfiguredTrap) { + ConfigureMatrixUnit(kMtwidenUnconfigured, kVsew8, kVlmul1, /*vl=*/0); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/32, /*base_addr=*/0, /*tss=*/0); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtseUnconfiguredTrap) { + ConfigureMatrixUnit(kMtwidenUnconfigured, kVsew8, kVlmul1, /*vl=*/0); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/32, /*base_addr=*/0, /*tss=*/0); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvVtVstartLowerBoundEnforcement) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/0, + /*tm=*/4, /*vstart=*/2); + constexpr uint32_t kTileId = 4; + const int te = matrix_state_->tile_elements(); + ASSERT_OK(FillTilePattern<uint32_t>(kTileId, te, te, [](int row, int col) { + return 0xDEADC0DE + row * 10 + col; + })); + + // Pre-fill v8 to verify elements < vstart are unchanged. + WriteVectorRegister<uint32_t>( + "v8", {0x11111111, 0x11111111, 0x11111111, 0x11111111}); + + ExecuteVtmvVt(EncodeTss(kTileId, kTssPatternRow, /*index=*/2)); + + // Elements < vstart remain untouched; elements [vstart..vl) are extracted. + EXPECT_THAT(ReadVectorRegister<uint32_t>("v8", 4), + testing::ElementsAre(0x11111111, 0x11111111, 0xDEADC0DE + 22, + 0xDEADC0DE + 23)); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvTvVstartLowerBoundEnforcement) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/0, + /*tm=*/4, /*vstart=*/2); + constexpr uint32_t kTileId = 4; + const int te = matrix_state_->tile_elements(); + ASSERT_OK(FillTileConstant<uint32_t>(kTileId, te, te, 0x0)); + WriteVectorRegister<uint32_t>( + "v8", {0x11111110, 0x11111111, 0x11111112, 0x11111113}); + + ExecuteVtmvTv(/*vs_reg=*/8, EncodeTss(kTileId, kTssPatternRow, /*index=*/2)); + + // Elements < vstart remain untouched (0x0); elements [vstart..vl) are + // inserted. + ASSERT_OK_AND_ASSIGN(auto row_vals, + GetTileRow<uint32_t>(kTileId, /*row=*/2, /*count=*/4)); + EXPECT_THAT(row_vals, testing::ElementsAre(0x0, 0x0, 0x11111112, 0x11111113)); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvVtUnconfiguredTrap) { + ConfigureMatrixUnit(kMtwidenUnconfigured, kVsew32, kVlmul1, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteVtmvVt(/*tss=*/0); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvTvUnconfiguredTrap) { + ConfigureMatrixUnit(kMtwidenUnconfigured, kVsew32, kVlmul1, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteVtmvTv(/*vs_reg=*/8, /*tss=*/0); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtleVstartLowerBoundLimitation) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4, /*tk=*/0, /*tm=*/0, + /*vstart=*/2); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemory<uint8_t>(kBaseAddr, {0x11, 0x22, 0x33, 0x44}); + + constexpr uint32_t kTileId = 1; + constexpr uint32_t kRowIndex = 2; + // Pre-fill tile row to verify elements < vstart remain unchanged. + ASSERT_OK(SetTileRowPattern<uint8_t>(kTileId, kRowIndex, /*count=*/4, + [](int) { return 0xAA; })); + + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/8, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + // Elements < vstart remain untouched (0xAA); elements [vstart..vl) are + // loaded. + ASSERT_OK_AND_ASSIGN(auto row_vals, + GetTileRow<uint8_t>(kTileId, kRowIndex, /*count=*/4)); + EXPECT_THAT(row_vals, testing::ElementsAre(0xAA, 0xAA, 0x33, 0x44)); + EXPECT_EQ(vector_state_->vstart(), 0); +} + +TEST_F(RiscVZvtInstructionsTest, Vtle8UnitStrideRow) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemory<uint8_t>(kBaseAddr, {0x11, 0x22, 0x33, 0x44}); + + constexpr uint32_t kTileId = 1; + constexpr uint32_t kRowIndex = 2; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/8, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + ASSERT_OK_AND_ASSIGN(auto row_vals, + GetTileRow<uint8_t>(kTileId, kRowIndex, /*count=*/4)); + EXPECT_THAT(row_vals, testing::ElementsAre(0x11, 0x22, 0x33, 0x44)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtle16UnitStrideRow) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemory<uint16_t>(kBaseAddr, {0x1111, 0x2222, 0x3333, 0x4444}); + + constexpr uint32_t kTileId = 2; + constexpr uint32_t kRowIndex = 2; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/16, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + ASSERT_OK_AND_ASSIGN(auto row_vals, + GetTileRow<uint16_t>(kTileId, kRowIndex, /*count=*/4)); + EXPECT_THAT(row_vals, testing::ElementsAre(0x1111, 0x2222, 0x3333, 0x4444)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtle32UnitStrideRow) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemory<uint32_t>(kBaseAddr, + {0x11111111, 0x22222222, 0x33333333, 0x44444444}); + + constexpr uint32_t kTileId = 4; + constexpr uint32_t kRowIndex = 2; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/32, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + ASSERT_OK_AND_ASSIGN(auto row_vals, + GetTileRow<uint32_t>(kTileId, kRowIndex, /*count=*/4)); + EXPECT_THAT(row_vals, testing::ElementsAre(0x11111111, 0x22222222, 0x33333333, + 0x44444444)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtle64UnitStrideRow) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/2); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemory<uint64_t>(kBaseAddr, + {0x1111111122222222ULL, 0x3333333344444444ULL}); + + constexpr uint32_t kTileId = 8; + constexpr uint32_t kRowIndex = 2; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/64, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + ASSERT_OK_AND_ASSIGN(auto row_vals, + GetTileRow<uint64_t>(kTileId, kRowIndex, /*count=*/2)); + EXPECT_THAT(row_vals, testing::ElementsAre(0x1111111122222222ULL, + 0x3333333344444444ULL)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtle8UnitStrideCol) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemory<uint8_t>(kBaseAddr, {0x11, 0x22, 0x33, 0x44}); + + constexpr uint32_t kTileId = 1; + constexpr uint32_t kColIndex = 2; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/8, kBaseAddr, + EncodeTss(kTileId, kTssPatternCol, kColIndex)); + + ASSERT_OK_AND_ASSIGN(auto col_vals, + GetTileColumn<uint8_t>(kTileId, kColIndex, /*count=*/4)); + EXPECT_THAT(col_vals, testing::ElementsAre(0x11, 0x22, 0x33, 0x44)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtse8UnitStrideRow) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4); + + constexpr uint32_t kTileId = 1; + constexpr uint32_t kRowIndex = 2; + ASSERT_OK(SetTileRow<uint8_t>(kTileId, kRowIndex, {0x11, 0x22, 0x33, 0x44})); + + constexpr uint64_t kBaseAddr = 0x2000; + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/8, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + EXPECT_THAT(ReadMemory<uint8_t>(kBaseAddr, 4), + testing::ElementsAre(0x11, 0x22, 0x33, 0x44)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtse8UnitStrideCol) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4); + + constexpr uint32_t kTileId = 1; + constexpr uint32_t kColIndex = 2; + ASSERT_OK( + SetTileColumn<uint8_t>(kTileId, kColIndex, {0x11, 0x22, 0x33, 0x44})); + + constexpr uint64_t kBaseAddr = 0x2000; + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/8, kBaseAddr, + EncodeTss(kTileId, kTssPatternCol, kColIndex)); + + EXPECT_THAT(ReadMemory<uint8_t>(kBaseAddr, 4), + testing::ElementsAre(0x11, 0x22, 0x33, 0x44)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtle16UnitStrideCol) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemory<uint16_t>(kBaseAddr, {0x1111, 0x2222, 0x3333, 0x4444}); + + constexpr uint32_t kTileId = 2; + constexpr uint32_t kColIndex = 2; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/16, kBaseAddr, + EncodeTss(kTileId, kTssPatternCol, kColIndex)); + + ASSERT_OK_AND_ASSIGN( + auto col_vals, GetTileColumn<uint16_t>(kTileId, kColIndex, /*count=*/4)); + EXPECT_THAT(col_vals, testing::ElementsAre(0x1111, 0x2222, 0x3333, 0x4444)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtse16UnitStrideRow) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4); + + constexpr uint32_t kTileId = 2; + constexpr uint32_t kRowIndex = 2; + ASSERT_OK(SetTileRow<uint16_t>(kTileId, kRowIndex, + {0x1111, 0x2222, 0x3333, 0x4444})); + + constexpr uint64_t kBaseAddr = 0x2000; + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/16, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + EXPECT_THAT(ReadMemory<uint16_t>(kBaseAddr, 4), + testing::ElementsAre(0x1111, 0x2222, 0x3333, 0x4444)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtse16UnitStrideCol) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4); + + constexpr uint32_t kTileId = 2; + constexpr uint32_t kColIndex = 2; + ASSERT_OK(SetTileColumn<uint16_t>(kTileId, kColIndex, + {0x1111, 0x2222, 0x3333, 0x4444})); + + constexpr uint64_t kBaseAddr = 0x2000; + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/16, kBaseAddr, + EncodeTss(kTileId, kTssPatternCol, kColIndex)); + + EXPECT_THAT(ReadMemory<uint16_t>(kBaseAddr, 4), + testing::ElementsAre(0x1111, 0x2222, 0x3333, 0x4444)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtle32UnitStrideCol) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemory<uint32_t>(kBaseAddr, + {0x11111111, 0x22222222, 0x33333333, 0x44444444}); + + constexpr uint32_t kTileId = 4; + constexpr uint32_t kColIndex = 2; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/32, kBaseAddr, + EncodeTss(kTileId, kTssPatternCol, kColIndex)); + + ASSERT_OK_AND_ASSIGN( + auto col_vals, GetTileColumn<uint32_t>(kTileId, kColIndex, /*count=*/4)); + EXPECT_THAT(col_vals, testing::ElementsAre(0x11111111, 0x22222222, 0x33333333, + 0x44444444)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtse32UnitStrideRow) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4); + + constexpr uint32_t kTileId = 4; + constexpr uint32_t kRowIndex = 2; + ASSERT_OK(SetTileRow<uint32_t>( + kTileId, kRowIndex, {0x11111111, 0x22222222, 0x33333333, 0x44444444})); + + constexpr uint64_t kBaseAddr = 0x2000; + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/32, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + EXPECT_THAT( + ReadMemory<uint32_t>(kBaseAddr, 4), + testing::ElementsAre(0x11111111, 0x22222222, 0x33333333, 0x44444444)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtse32UnitStrideCol) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4); + + constexpr uint32_t kTileId = 4; + constexpr uint32_t kColIndex = 2; + ASSERT_OK(SetTileColumn<uint32_t>( + kTileId, kColIndex, {0x11111111, 0x22222222, 0x33333333, 0x44444444})); + + constexpr uint64_t kBaseAddr = 0x2000; + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/32, kBaseAddr, + EncodeTss(kTileId, kTssPatternCol, kColIndex)); + + EXPECT_THAT( + ReadMemory<uint32_t>(kBaseAddr, 4), + testing::ElementsAre(0x11111111, 0x22222222, 0x33333333, 0x44444444)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtle64UnitStrideCol) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/2); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemory<uint64_t>(kBaseAddr, + {0x1111111122222222ULL, 0x3333333344444444ULL}); + + constexpr uint32_t kTileId = 8; + constexpr uint32_t kColIndex = 2; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/64, kBaseAddr, + EncodeTss(kTileId, kTssPatternCol, kColIndex)); + + ASSERT_OK_AND_ASSIGN( + auto col_vals, GetTileColumn<uint64_t>(kTileId, kColIndex, /*count=*/2)); + EXPECT_THAT(col_vals, testing::ElementsAre(0x1111111122222222ULL, + 0x3333333344444444ULL)); +} + +TEST_F(RiscVZvtInstructionsTest, VtleActiveBodyBounds) { + // Test that vtle loads min(vl, ETE) elements (EEW=8 => ETE=32, vl=40 => 32). + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/40); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemoryPattern<uint8_t>(kBaseAddr, /*count=*/40, + [](size_t i) { return i; }); + + constexpr uint32_t kTileId = 0; + constexpr uint32_t kRowIndex = 0; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/8, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + ASSERT_OK_AND_ASSIGN(auto row_vals, + GetTileRow<uint8_t>(kTileId, kRowIndex, /*count=*/32)); + std::vector<uint8_t> expected(32); + std::iota(expected.begin(), expected.end(), 0); + EXPECT_THAT(row_vals, testing::ElementsAreArray(expected)); +} + +TEST_F(RiscVZvtInstructionsTest, VtleActiveBodyBounds64) { + // Test that vtle loads min(vl, ETE) elements for 64-bit + // (EEW=64 => ETE=16, vl=20 => 16). + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/20); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemoryPattern<uint64_t>(kBaseAddr, /*count=*/20, + [](size_t i) { return i; }); + + constexpr uint32_t kTileId = 8; + constexpr uint32_t kRowIndex = 0; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/64, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + ASSERT_OK_AND_ASSIGN(auto row_vals, + GetTileRow<uint64_t>(kTileId, kRowIndex, /*count=*/16)); + std::vector<uint64_t> expected(16); + std::iota(expected.begin(), expected.end(), 0); + EXPECT_THAT(row_vals, testing::ElementsAreArray(expected)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtse64UnitStrideRow) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/2); + + constexpr uint32_t kTileId = 8; + constexpr uint32_t kRowIndex = 2; + ASSERT_OK(SetTileRow<uint64_t>( + kTileId, kRowIndex, {0x1111111122222222ULL, 0x3333333344444444ULL})); + + constexpr uint64_t kBaseAddr = 0x2000; + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/64, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + EXPECT_THAT( + ReadMemory<uint64_t>(kBaseAddr, 2), + testing::ElementsAre(0x1111111122222222ULL, 0x3333333344444444ULL)); +} + +TEST_F(RiscVZvtInstructionsTest, Vtse64UnitStrideCol) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/2); + + constexpr uint32_t kTileId = 8; + constexpr uint32_t kColIndex = 2; + ASSERT_OK(SetTileColumn<uint64_t>( + kTileId, kColIndex, {0x1111111122222222ULL, 0x3333333344444444ULL})); + + constexpr uint64_t kBaseAddr = 0x2000; + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/64, kBaseAddr, + EncodeTss(kTileId, kTssPatternCol, kColIndex)); + + EXPECT_THAT( + ReadMemory<uint64_t>(kBaseAddr, 2), + testing::ElementsAre(0x1111111122222222ULL, 0x3333333344444444ULL)); +} + +TEST_F(RiscVZvtInstructionsTest, VtseActiveBodyBounds) { + // Test that vtse stores min(vl, ETE) elements (EEW=8 => ETE=32, vl=40 => 32). + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/40); + + constexpr uint32_t kTileId = 0; + constexpr uint32_t kRowIndex = 0; + ASSERT_OK(SetTileRowPattern<uint8_t>(kTileId, kRowIndex, /*count=*/40, + [](int i) { return i; })); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemoryConstant<uint8_t>(kBaseAddr, /*count=*/40, 0xFF); + + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/8, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + std::vector<uint8_t> expected(40, 0xFF); + std::iota(expected.begin(), expected.begin() + 32, 0); + EXPECT_THAT(ReadMemory<uint8_t>(kBaseAddr, 40), + testing::ElementsAreArray(expected)); +} + +TEST_F(RiscVZvtInstructionsTest, VtseActiveBodyBounds64) { + // Test that vtse stores min(vl, ETE) elements for 64-bit + // (EEW=64 => ETE=16, vl=20 => 16). + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/20); + + constexpr uint32_t kTileId = 8; + constexpr uint32_t kRowIndex = 0; + ASSERT_OK(SetTileRowPattern<uint64_t>(kTileId, kRowIndex, /*count=*/20, + [](int i) { return i; })); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemoryConstant<uint64_t>(kBaseAddr, /*count=*/20, 0xFFFFFFFFFFFFFFFFULL); + + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/64, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + std::vector<uint64_t> expected(20, 0xFFFFFFFFFFFFFFFFULL); + std::iota(expected.begin(), expected.begin() + 16, 0); + EXPECT_THAT(ReadMemory<uint64_t>(kBaseAddr, 20), + testing::ElementsAreArray(expected)); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulOperandLmulDivisibilityTrap) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul2, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + // Misaligned register group v9 for LMUL=2! + ExecuteMatmul(&RiscVZvtVtfmm, /*reg_a=*/8, /*reg_b=*/9, /*dest_tile=*/0); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulOperandKmaxBoundsTrap) { + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteMatmul(&RiscVZvtVtfmm, /*reg_a=*/10, /*reg_b=*/8, /*dest_tile=*/0); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulUint8ByUint8) { + // Zvt spec v0.4: vtmmu.tvv (altfmt=0) uint8 x uint8 -> int32. + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/2, + /*tm=*/2); + + // Pre-populate destination tile 0 with initial accumulator values. + ASSERT_OK(SetTileMatrix<int32_t>(/*tile=*/0, {{50, 0}, {0, 0}})); + + // KMAX(8) = 4, kStride = 8 / 4 = 2. + // Matrix A: kk=0 -> v8: [200, 10]; kk=1 -> v10: [150, 20]. + WriteVectorRegister<uint8_t>("v8", {200, 10}); + WriteVectorRegister<uint8_t>("v10", {150, 20}); + + // Matrix B: kk=0 -> v16: [130, 5]; kk=1 -> v18: [140, 7]. + WriteVectorRegister<uint8_t>("v16", {130, 5}); + WriteVectorRegister<uint8_t>("v18", {140, 7}); + + ExecuteMatmul(&RiscVZvtVtmmu); + + // C[0,0] = 50 + 200*130 + 150*140 = 47050, C[0,1] = 0 + 200*5 + 150*7 = 2050 + // C[1,0] = 0 + 10*130 + 20*140 = 4100, C[1,1] = 0 + 10*5 + 20*7 = 190 + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<int32_t>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(47050, 2050, 4100, 190)); + + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->ms(), + state_->v() ? kMstatusStateDirty : kMstatusStateInitial); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmuDynamicDispatchAltfmt0) { + // Zvt spec v0.4: vtmmu.tvv (altfmt=0) uint8 x uint8 -> int32. + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/2, + /*tm=*/2); + + ASSERT_OK(SetTileMatrix<int32_t>(/*tile=*/0, {{50, 0}, {0, 0}})); + WriteVectorRegister<uint8_t>("v8", {200, 10}); + WriteVectorRegister<uint8_t>("v10", {150, 20}); + WriteVectorRegister<uint8_t>("v16", {130, 5}); + WriteVectorRegister<uint8_t>("v18", {140, 7}); + + ExecuteMatmul(&RiscVZvtVtmmu); + + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<int32_t>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(47050, 2050, 4100, 190)); + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->ms(), + state_->v() ? kMstatusStateDirty : kMstatusStateInitial); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmuDynamicDispatchAltfmt1) { + // Zvt spec v0.4: vtmmu.tvv (altfmt=1) uint8 x int8 -> int32. + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/2, + /*tm=*/2, /*vstart=*/0, /*vta=*/false, /*vma=*/false, + /*altfmt=*/true); + + ASSERT_OK(SetTileMatrix<int32_t>(/*tile=*/0, {{50, 0}, {0, 0}})); + WriteVectorRegister<uint8_t>("v8", {200, 10}); + WriteVectorRegister<uint8_t>("v10", {150, 20}); + WriteVectorRegister<uint8_t>("v16", {static_cast<uint8_t>(-126), 5}); + WriteVectorRegister<uint8_t>("v18", {static_cast<uint8_t>(-116), 7}); + + ExecuteMatmul(&RiscVZvtVtmmu); + + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<int32_t>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(-42550, 2050, -3580, 190)); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmsDynamicDispatchAltfmt0) { + // Zvt spec v0.4: vtmms.tvv (altfmt=0) int8 x uint8 -> int32. + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/2, + /*tm=*/2); + + ASSERT_OK(SetTileMatrix<int32_t>(/*tile=*/0, {{100, -20}, {30, 40}})); + WriteVectorRegister<uint8_t>("v8", {static_cast<uint8_t>(-50), 5}); + WriteVectorRegister<uint8_t>("v10", {40, static_cast<uint8_t>(-10)}); + WriteVectorRegister<uint8_t>("v16", {200, 10}); + WriteVectorRegister<uint8_t>("v18", {150, 20}); + + ExecuteMatmul(&RiscVZvtVtmms); + + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<int32_t>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(-3900, 280, -470, -110)); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulUint8ByInt8) { + // Zvt spec v0.4: vtmmu.tvv (altfmt=1) uint8 x int8 -> int32. + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/2, + /*tm=*/2, /*vstart=*/0, /*vta=*/false, /*vma=*/false, + /*altfmt=*/true); + + ASSERT_OK(SetTileMatrix<int32_t>(/*tile=*/0, {{100, -20}, {30, 40}})); + WriteVectorRegister<uint8_t>("v8", {200, 10}); + WriteVectorRegister<uint8_t>("v10", {150, 20}); + WriteVectorRegister<uint8_t>("v16", {static_cast<uint8_t>(-50), 5}); + WriteVectorRegister<uint8_t>("v18", {40, static_cast<uint8_t>(-10)}); + + ExecuteMatmul(&RiscVZvtVtmmu); + + // C[0,0] = 100 + 200*(-50) + 150*40 = -3900 + // C[0,1] = -20 + 200*5 + 150*(-10) = -520 + // C[1,0] = 30 + 10*(-50) + 20*40 = 330 + // C[1,1] = 40 + 10*5 + 20*(-10) = -110 + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<int32_t>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(-3900, -520, 330, -110)); + + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->ms(), + state_->v() ? kMstatusStateDirty : kMstatusStateInitial); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmsTvvSignedUnsignedMatmul) { + // Zvt spec v0.4: vtmms.tvv (altfmt=0) int8 x uint8 -> int32. + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/2, + /*tm=*/2); + + ASSERT_OK(SetTileMatrix<int32_t>(/*tile=*/0, {{100, -20}, {30, 40}})); + WriteVectorRegister<uint8_t>("v8", {static_cast<uint8_t>(-50), 5}); + WriteVectorRegister<uint8_t>("v10", {40, static_cast<uint8_t>(-10)}); + WriteVectorRegister<uint8_t>("v16", {200, 10}); + WriteVectorRegister<uint8_t>("v18", {150, 20}); + + ExecuteMatmul(&RiscVZvtVtmms); + + // C[0,0] = 100 + (-50)*200 + 40*150 = -3900 + // C[0,1] = -20 + (-50)*10 + 40*20 = 280 + // C[1,0] = 30 + 5*200 + (-10)*150 = -470 + // C[1,1] = 40 + 5*10 + (-10)*20 = -110 + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<int32_t>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(-3900, 280, -470, -110)); + + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->ms(), + state_->v() ? kMstatusStateDirty : kMstatusStateInitial); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmsTvvSignedSignedMatmul) { + // Zvt spec v0.4: vtmms.tvv (altfmt=1) int8 x int8 -> int32. + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/2, + /*tm=*/2, /*vstart=*/0, /*vta=*/false, /*vma=*/false, + /*altfmt=*/true); + + ASSERT_OK(SetTileMatrix<int32_t>(/*tile=*/0, {{100, -20}, {30, 40}})); + WriteVectorRegister<uint8_t>("v8", {static_cast<uint8_t>(-50), 5}); + WriteVectorRegister<uint8_t>("v10", {40, static_cast<uint8_t>(-10)}); + WriteVectorRegister<uint8_t>("v16", {static_cast<uint8_t>(-30), 10}); + WriteVectorRegister<uint8_t>("v18", {20, static_cast<uint8_t>(-15)}); + + ExecuteMatmul(&RiscVZvtVtmms); + + // C[0,0] = 100 + (-50)*(-30) + 40*20 = 2400 + // C[0,1] = -20 + (-50)*10 + 40*(-15) = -1120 + // C[1,0] = 30 + 5*(-30) + (-10)*20 = -320 + // C[1,1] = 40 + 5*10 + (-10)*(-15) = 240 + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<int32_t>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(2400, -1120, -320, 240)); + + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->ms(), + state_->v() ? kMstatusStateDirty : kMstatusStateInitial); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmTvvFp32Matmul) { + // Zvt spec v0.4: vtfmm.tvv FP32 x FP32 -> FP32. + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{1.5f, -0.5f}, {0.0f, 2.25f}})); + WriteVectorRegister<float>("v8", {2.0f, 0.5f}); + WriteVectorRegister<float>("v16", {3.0f, 1.0f}); + + ExecuteMatmul(&RiscVZvtVtfmm); + + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<float>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(7.5f, 1.5f, 1.5f, 2.75f)); + + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->ms(), + state_->v() ? kMstatusStateDirty : kMstatusStateInitial); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmTvvFp32DynamicRoundingMode) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/1, /*tk=*/1, + /*tm=*/1); + // Set FCSR frm to RUP - Round Up (towards +inf). + fp_state_->fcsr()->Write(*FPRoundingMode::kRoundUp << kFcsrFrmShift); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{1.0f}})); + WriteVectorRegister<uint32_t>("v8", {0x3f800000}); // 1.0f + WriteVectorRegister<uint32_t>("v16", {0x33800000}); // 2^-24 + + ExecuteMatmul(&RiscVZvtVtfmm); + + // In RUP, 1.0 + 2^-24 rounds up to 1.0 + 2^-23 (0x3f800001). + ASSERT_OK_AND_ASSIGN(float result_rup, + GetTileElem<float>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_EQ(absl::bit_cast<uint32_t>(result_rup), 0x3f800001U); + + // Re-run with RDN - Round Down (towards -inf). + fp_state_->fcsr()->Write(*FPRoundingMode::kRoundDown << kFcsrFrmShift); + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{1.0f}})); + instruction_->Execute(nullptr); + + ASSERT_OK_AND_ASSIGN(float result_rdn, + GetTileElem<float>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_EQ(absl::bit_cast<uint32_t>(result_rdn), 0x3f800000U); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmTvvFp64Matmul) { + // Zvt spec v0.4: vtfmm.tvv FP64 x FP64 -> FP64. + ConfigureMatrixUnit(kMtwiden1, kVsew64, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + + ASSERT_OK(SetTileMatrix<double>(/*tile=*/0, {{1.5, -0.5}, {0.0, 2.25}})); + WriteVectorRegister<double>("v8", {2.0, 0.5}); + WriteVectorRegister<double>("v16", {3.0, 1.0}); + + ExecuteMatmul(&RiscVZvtVtfmm); + + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<double>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(7.5, 1.5, 1.5, 2.75)); + + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->ms(), + state_->v() ? kMstatusStateDirty : kMstatusStateInitial); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmTvvFp16BulkNormalization) { + // Zvt spec v0.4: vtfmm.tvv FP16 x FP16 -> FP32. + ConfigureMatrixUnit(kMtwiden2, kVsew16, kVlmul1, /*vl=*/1, /*tk=*/2, + /*tm=*/1); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{1.0f}})); + WriteVectorRegister<uint16_t>("v8", {0x7800}); // 2^15 + WriteVectorRegister<uint16_t>("v12", {0xF800}); // -2^15 + WriteVectorRegister<uint16_t>("v16", {0x7800}); // 2^15 + WriteVectorRegister<uint16_t>("v20", {0x7800}); // 2^15 + + ExecuteMatmul(&RiscVZvtVtfmm); + + // With sequential FP32 addition: (1.0 + 2^30) - 2^30 = 0.0 + // With RVBNA bulk normalization: 1.0 + (2^30 - 2^30) = 1.0 + ASSERT_OK_AND_ASSIGN(float result, + GetTileElem<float>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_EQ(result, 1.0f); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmTvvFp16RoundToOddConversion) { + // Zvt spec v0.4: vtfmm.tvv FP16 x FP16 -> FP32. + ConfigureMatrixUnit(kMtwiden2, kVsew16, kVlmul1, /*vl=*/1, /*tk=*/2, + /*tm=*/1); + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + // Inputs yielding sum of products = 1.0 * 1.0 + 2^-24 * 2^-24. + WriteVectorRegister<uint16_t>("v8", {0x3C00}); // 1.0 + WriteVectorRegister<uint16_t>("v12", {0x0001}); // 2^-24 (min subnormal) + WriteVectorRegister<uint16_t>("v16", {0x3C00}); // 1.0 + WriteVectorRegister<uint16_t>("v20", {0x0001}); // 2^-24 + + ExecuteMatmul(&RiscVZvtVtfmm); + + ASSERT_OK_AND_ASSIGN(float result, + GetTileElem<float>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_EQ(absl::bit_cast<uint32_t>(result), + 0x3F800001u); // 1.0 + 2^-23 (ROD) +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmTvvFp16RoundToOddAddition) { + // Zvt spec v0.4: vtfmm.tvv FP16 x FP16 -> FP32. + ConfigureMatrixUnit(kMtwiden2, kVsew16, kVlmul1, /*vl=*/1, /*tk=*/2, + /*tm=*/1); + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{1.0f}})); + WriteVectorRegister<uint16_t>("v8", {0x0000}); // 0.0 + WriteVectorRegister<uint16_t>("v12", {0x0C00}); // 2^-12 + WriteVectorRegister<uint16_t>("v16", {0x0000}); // 0.0 + WriteVectorRegister<uint16_t>("v20", {0x0C00}); // 2^-12 + + ExecuteMatmul(&RiscVZvtVtfmm); + + ASSERT_OK_AND_ASSIGN(float result, + GetTileElem<float>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_EQ(absl::bit_cast<uint32_t>(result), + 0x3F800001u); // 1.0 + 2^-23 (ROD) +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmAltTvvBf16Matmul) { + // Zvt spec v0.4: vtfmm.alt.tvv BF16 x BF16 -> FP32. + ConfigureMatrixUnit(kMtwiden2, kVsew16, kVlmul1, /*vl=*/2, /*tk=*/2, + /*tm=*/2, /*vstart=*/0, /*vta=*/false, /*vma=*/false, + /*altfmt=*/true); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{1.5f, -0.5f}, {0.0f, 2.25f}})); + WriteVectorRegister<uint16_t>("v8", {0x4000, 0x3F00}); // 2.0f, 0.5f + WriteVectorRegister<uint16_t>("v12", {0x4100, 0x3E80}); // 8.0f, 0.25f + WriteVectorRegister<uint16_t>("v16", {0x4040, 0x3F80}); // 3.0f, 1.0f + WriteVectorRegister<uint16_t>("v20", {0x4080, 0x40C0}); // 4.0f, 6.0f + + ExecuteMatmul(&RiscVZvtVtfmmAlt); + + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<float>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(39.5f, 49.5f, 2.5f, 4.25f)); + + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->ms(), + state_->v() ? kMstatusStateDirty : kMstatusStateInitial); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmAltTvvSew32Trap) { + ConfigureMatrixUnit(kMtwiden2, kVsew32, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + ScopedTrapCapture trap_capture(state_.get()); + + // SEW=32 is invalid for vtfmm.alt.tvv. + ExecuteMatmul(&RiscVZvtVtfmmAlt); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmAltTvvSew64Trap) { + ConfigureMatrixUnit(kMtwiden2, kVsew64, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + ScopedTrapCapture trap_capture(state_.get()); + + // SEW=64 is invalid for vtfmm.alt.tvv. + ExecuteMatmul(&RiscVZvtVtfmmAlt); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmTvvFp16Matmul) { + // Zvt spec v0.4: vtfmm.tvv FP16 x FP16 -> FP32. + ConfigureMatrixUnit(kMtwiden2, kVsew16, kVlmul1, /*vl=*/2, /*tk=*/2, + /*tm=*/2); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{1.5f, -0.5f}, {0.0f, 2.25f}})); + WriteVectorRegister<uint16_t>("v8", {0x4000, 0x3800}); // 2.0f, 0.5f + WriteVectorRegister<uint16_t>("v12", {0x4800, 0x3400}); // 8.0f, 0.25f + WriteVectorRegister<uint16_t>("v16", {0x4200, 0x3c00}); // 3.0f, 1.0f + WriteVectorRegister<uint16_t>("v20", {0x4400, 0x4600}); // 4.0f, 6.0f + + ExecuteMatmul(&RiscVZvtVtfmm); + + // C = [[1.5, -0.5], [0.0, 2.25]] + [[38.0, 50.0], [2.5, 2.0]] + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<float>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(39.5f, 49.5f, 2.5f, 4.25f)); + + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->ms(), + state_->v() ? kMstatusStateDirty : kMstatusStateInitial); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulDestTileModuloReservationTrap) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + // Invalid tile 1 since alignment is 4 (NTiles=4 when TEW=32, Align=16/4=4). + ExecuteMatmul(&RiscVZvtVtfmm, /*reg_a=*/0, /*reg_b=*/8, /*dest_tile=*/1); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulDestTileModuloReservationTrapTEW64) { + ConfigureMatrixUnit(kMtwiden1, kVsew64, kVlmul1, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + // Invalid tile 3 since alignment is 2 (NTiles=8 when TEW=64, Align=16/8=2). + ExecuteMatmul(&RiscVZvtVtfmm, /*reg_a=*/0, /*reg_b=*/8, /*dest_tile=*/3); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulVstartNonZeroTrap) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/0, + /*tm=*/0, /*vstart=*/1); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteMatmul(&RiscVZvtVtfmm, /*reg_a=*/0, /*reg_b=*/8, /*dest_tile=*/0); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulZeroDimBypass) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/4, + /*tm=*/0); + + ExecuteMatmul(&RiscVZvtVtfmm, /*reg_a=*/0, /*reg_b=*/8, /*dest_tile=*/0); + + // Status should remain 1 (initial), not 3 (dirty), due to bypass. + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateInitial); } TEST_F(RiscVZvtInstructionsTest, CeilEteEveScalesVlmulCorrectly) { @@ -778,9 +2938,11 @@ // Execute msetmtypei, which calls SetVectorStateDirty. ResetInstruction(); - instruction_->AppendSource(new ImmediateOperand<uint32_t>(kMtwiden1)); - instruction_->AppendSource(new ImmediateOperand<uint32_t>(kVsew8)); - instruction_->AppendSource(new ImmediateOperand<uint32_t>(kAltfmtStandard)); + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(/*mtwiden=*/kMtwiden1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vsew=*/kVsew8)); + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(/*altfmt=*/kAltfmtStandard)); instruction_->set_semantic_function(&RiscVZvtMsetMtypei); instruction_->Execute(nullptr); @@ -794,18 +2956,17 @@ } TEST_F(RiscVZvtInstructionsTest, SetVectorStateDirtyRv64UpdatesMstatusVsAndSd) { - auto rv64 = Rv64TestContext::Create("rv64_test"); - ASSERT_OK(rv64); + ASSERT_OK_AND_ASSIGN(auto rv64, Rv64TestContext::Create("rv64_test")); // Clear VS and SD (bit 63 on RV64). - (*rv64)->SetMstatusVs(kMstatusStateInitial); - (*rv64)->state.mstatus()->Set((*rv64)->state.mstatus()->GetUint64() & - ~kMstatusSdMaskRv64); + rv64->SetMstatusVs(kMstatusStateInitial); + rv64->state.mstatus()->Set(rv64->state.mstatus()->GetUint64() & + ~kMstatusSdMaskRv64); - EXPECT_EQ((*rv64)->GetMstatusVs(), kMstatusStateInitial); - EXPECT_EQ((*rv64)->GetMstatusSd(), kMstatusSdClean); + EXPECT_EQ(rv64->GetMstatusVs(), kMstatusStateInitial); + EXPECT_EQ(rv64->GetMstatusSd(), kMstatusSdClean); - auto* inst = new Instruction(0x1000, &(*rv64)->state); + auto* inst = new Instruction(0x1000, &rv64->state); inst->set_size(4); inst->AppendSource(new ImmediateOperand<uint32_t>(kMtwiden1)); inst->AppendSource(new ImmediateOperand<uint32_t>(kVsew8)); @@ -817,8 +2978,8 @@ // Must set VS to Dirty (3) and SD (bit 63 on RV64) to 1. // If sd_bit was mutated to 31 on RV64, bit 63 is not set. - EXPECT_EQ((*rv64)->GetMstatusVs(), kMstatusStateDirty); - EXPECT_EQ((*rv64)->GetMstatusSd(), kMstatusSdSet); + EXPECT_EQ(rv64->GetMstatusVs(), kMstatusStateDirty); + EXPECT_EQ(rv64->GetMstatusSd(), kMstatusSdSet); } TEST_F(RiscVZvtInstructionsTest, MsetmtypeInvalidSewSetsVill) { @@ -845,31 +3006,25 @@ vector_state_->set_vector_length(4); // Populate tile 0 with non-zero bytes. - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - ASSERT_OK(matrix_state_->SetElem<uint8_t>(0, r, c, 8, 0xAB)); - ASSERT_OK_AND_ASSIGN(auto elem, - matrix_state_->GetElem<uint8_t>(0, r, c, 8)); - EXPECT_EQ(elem, 0xAB); - } - } + ASSERT_OK( + FillTileConstant<uint8_t>(/*tile=*/0, /*rows=*/4, /*cols=*/4, 0xAB)); // Clear mstatus MS and VS. SetMstatusMs(kMstatusStateInitial); SetMstatusVs(kMstatusStateInitial); ResetInstruction(); - instruction_->AppendSource(new ImmediateOperand<uint32_t>(0)); // tile 0 + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile=*/0)); + instruction_->set_semantic_function(&RiscVZvtVtZero); instruction_->Execute(nullptr); // All active elements in tile 0 must be 0. - for (int r = 0; r < 4; ++r) { - ASSERT_OK_AND_ASSIGN(auto row_elements, - GetTileRow<uint8_t>(/*tile=*/0, r, /*count=*/4)); - EXPECT_THAT(row_elements, testing::Each(testing::Eq(0))); - } + ASSERT_OK_AND_ASSIGN( + auto tile_elements, + GetTileRegion<uint8_t>(/*tile=*/0, /*rows=*/4, /*cols=*/4)); + EXPECT_THAT(tile_elements, testing::Each(0)); // MS and VS must both be Dirty. EXPECT_EQ(GetMstatusMs(), kMstatusStateDirty); @@ -907,15 +3062,14 @@ SetMstatusVs(kMstatusStateInitial); SetMstatusMs(kMstatusStateInitial); - ScopedTrapCapture trap_capture(state_); + ScopedTrapCapture trap_capture(state_.get()); ResetInstruction(); instruction_->set_semantic_function(&RiscVZvtVtDiscard); instruction_->Execute(nullptr); EXPECT_TRUE(trap_capture.trap_taken()); - EXPECT_EQ(trap_capture.trap_code(), - static_cast<uint64_t>(ExceptionCode::kIllegalInstruction)); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); } TEST_F(RiscVZvtInstructionsTest, VtmvVtTransfersTileSliceToVectorRegister) { @@ -928,10 +3082,9 @@ SetMstatusMs(kMstatusStateInitial); // Populate row 1 of tile 0: elements at (0, 1, c) = c + 0x10. - for (int c = 0; c < 4; ++c) { - ASSERT_OK(matrix_state_->SetElem<uint8_t>(0, 1, c, 8, - static_cast<uint8_t>(c + 0x10))); - } + ASSERT_OK(SetTileRowPattern<uint8_t>( + /*tile=*/0, /*row=*/1, /*count=*/4, + [](int c) { return static_cast<uint8_t>(c + 0x10); })); // TSS for row 1 of tile 0: pattern = row, tile = 0, index = 1. SetRegisterValue("x1", EncodeTss(/*tile=*/0, kTssPatternRow, /*index=*/1)); @@ -998,10 +3151,9 @@ SetMstatusMs(kMstatusStateInitial); // Populate row 1 of tile 0. - for (int c = 0; c < 4; ++c) { - ASSERT_OK(matrix_state_->SetElem<uint8_t>(0, 1, c, 8, - static_cast<uint8_t>(c + 0x10))); - } + ASSERT_OK(SetTileRowPattern<uint8_t>( + /*tile=*/0, /*row=*/1, /*count=*/4, + [](int c) { return static_cast<uint8_t>(c + 0x10); })); // TSS for row 1 of tile 0: pattern = row, tile = 0, index = 1. SetRegisterValue("x1", EncodeTss(/*tile=*/0, kTssPatternRow, /*index=*/1)); @@ -1040,7 +3192,8 @@ span[3] = 0x54; // Pre-populate tile 0, row 2, element 0 with 0xEE to verify undisturbed. - ASSERT_OK(matrix_state_->SetElem<uint8_t>(0, 2, 0, 8, 0xEE)); + ASSERT_OK(matrix_state_->SetElem<uint8_t>(/*tile=*/0, /*row=*/2, /*col=*/0, + /*element_width_in_bits=*/8, 0xEE)); // TSS for row 2 of tile 0: pattern = row, tile = 0, index = 2. SetRegisterValue("x1", EncodeTss(/*tile=*/0, kTssPatternRow, /*index=*/2)); @@ -1061,30 +3214,28 @@ TEST_F(RiscVZvtInstructionsTest, WriteScalarRv64ClearsUpperBits) { // Test WriteScalar on RV64: writes a 32-bit scalar value to an 8-byte // destination register operand, ensuring the upper 32 bits are cleared. - // Under the mutant (if (false) instead of if (db->size == 8)), - // db->Set<uint32_t>(0, value) is executed, leaving the upper 32 bits - // untouched. - auto rv64 = Rv64TestContext::Create("rv64_scalar_test"); - ASSERT_OK(rv64); + // Ensures WriteScalar clears upper 32 bits on 64-bit registers rather than + // leaving them untouched. + ASSERT_OK_AND_ASSIGN(auto rv64, Rv64TestContext::Create("rv64_scalar_test")); // Turn on MS in mstatus so instructions don't trap. - (*rv64)->SetMstatusMs(kMstatusStateInitial); + rv64->SetMstatusMs(kMstatusStateInitial); // Initialize x1 register with high bits set. - auto* reg1 = (*rv64)->state.GetRegister<RV64Register>("x1").first; + auto* reg1 = rv64->state.GetRegister<RV64Register>("x1").first; reg1->data_buffer()->Set<uint64_t>(0, 0x1234'5678'9ABC'DEF0ULL); // Pre-seed a recycled 8-byte DataBuffer with non-zero upper bits to // guarantee that WriteScalar writes the full 64 bits and does not leave // upper bits intact. - // Kills mutant: if (false) in WriteScalar. - auto* recycled_db = (*rv64)->state.db_factory()->Allocate<uint64_t>(1); + auto* recycled_db = rv64->state.db_factory()->Allocate<uint64_t>(1); recycled_db->Set<uint64_t>(0, 0xDEAD'BEEF'CAFE'BABEULL); recycled_db->DecRef(); - auto* inst = new Instruction(0x1000, &(*rv64)->state); + auto* inst = new Instruction(0x1000, &rv64->state); inst->set_size(4); - inst->AppendSource(new ImmediateOperand<uint32_t>(4)); // requested col = 4 + inst->AppendSource(new ImmediateOperand<uint32_t>(/*col=*/4)); + inst->AppendDestination(reg1->CreateDestinationOperand(0)); inst->set_semantic_function(&RiscVZvtMsetTn); @@ -1097,47 +3248,43 @@ } TEST_F(RiscVZvtInstructionsTest, SetMatrixStateDirtyRv64UpdatesMstatusMsAndSd) { - auto rv64 = Rv64TestContext::Create("rv64_matrix_dirty_test"); - ASSERT_OK(rv64); + ASSERT_OK_AND_ASSIGN(auto rv64, + Rv64TestContext::Create("rv64_matrix_dirty_test")); // Set MS = Initial (1) so instructions don't trap, and clear SD (bit 63). - (*rv64)->SetMstatusMs(kMstatusStateInitial); - (*rv64)->state.mstatus()->Set((*rv64)->state.mstatus()->GetUint64() & - ~kMstatusSdMaskRv64); + rv64->SetMstatusMs(kMstatusStateInitial); + rv64->state.mstatus()->Set(rv64->state.mstatus()->GetUint64() & + ~kMstatusSdMaskRv64); - EXPECT_EQ((*rv64)->GetMstatusMs(), kMstatusStateInitial); - EXPECT_EQ((*rv64)->GetMstatusSd(), kMstatusSdClean); + EXPECT_EQ(rv64->GetMstatusMs(), kMstatusStateInitial); + EXPECT_EQ(rv64->GetMstatusSd(), kMstatusSdClean); - auto* inst = new Instruction(0x1000, &(*rv64)->state); + auto* inst = new Instruction(0x1000, &rv64->state); inst->set_size(4); - inst->AppendSource(new ImmediateOperand<uint32_t>(0)); // tile 0 + inst->AppendSource(new ImmediateOperand<uint32_t>(/*tile=*/0)); + inst->set_semantic_function(&RiscVZvtVtZero); inst->Execute(nullptr); inst->DecRef(); // Must set MS to Dirty (3) and SD (bit 63 on RV64) to 1. - // Kills mutant: sd_bit = (state->xlen() != RiscVXlen::RV32) ? 31 : 63. - EXPECT_EQ((*rv64)->GetMstatusMs(), kMstatusStateDirty); - EXPECT_EQ((*rv64)->GetMstatusSd(), kMstatusSdSet); - uint64_t mstatus_val = (*rv64)->state.mstatus()->GetUint64(); + EXPECT_EQ(rv64->GetMstatusMs(), kMstatusStateDirty); + EXPECT_EQ(rv64->GetMstatusSd(), kMstatusSdSet); + uint64_t mstatus_val = rv64->state.mstatus()->GetUint64(); EXPECT_EQ((mstatus_val >> kMstatusSdShiftRv32) & 1ULL, kMstatusSdClean); } TEST_F(RiscVZvtInstructionsTest, DoubleToFloatRODInexactJamsLsb) { - RiscVFPState fp_state(state_->csr_set(), state_); - state_->set_rv_fp(&fp_state); - // 1.0f in IEEE 754 is 0x3f800000 (even mantissa, LSB is 0). // 1.0 + 1e-12 in double precision rounds towards zero to 1.0f. // Inexact check triggers, and bit 0 is jammed to 1, producing 0x3f800001. - // Kills mutant: f = absl::bit_cast<float>(f_bits); in DoubleToFloatROD. double inexact_d = 1.0 + 1e-12; - float res = DoubleToFloatROD(inexact_d, &fp_state); + float res = DoubleToFloatROD(inexact_d, fp_state_.get()); EXPECT_EQ(absl::bit_cast<uint32_t>(res), 0x3f800001U); // Exact representation: 1.0 is exact in float, so LSB is not jammed. - float exact_res = DoubleToFloatROD(1.0, &fp_state); + float exact_res = DoubleToFloatROD(1.0, fp_state_.get()); EXPECT_EQ(absl::bit_cast<uint32_t>(exact_res), 0x3f800000U); // Null fp_state falls back to standard static_cast. @@ -1164,7 +3311,6 @@ // mtwiden must be reset to 0. EXPECT_EQ(matrix_state_->mtwiden(), 0); // SetVectorStateDirty must be called: VS becomes Dirty (3) and SD becomes 1. - // Kills mutant: SetVectorStateDirty(matrix_state); in RiscVZvtMsetMtypei. EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); EXPECT_EQ(GetMstatusSd(/*is_rv64=*/false), kMstatusSdSet); // UpdateVectorMatrixGeometry must NOT be called: no exception, vill=0. @@ -1191,35 +3337,43 @@ // mtwiden must be reset to 0. EXPECT_EQ(matrix_state_->mtwiden(), 0); // SetVectorStateDirty must be called: VS becomes Dirty (3) and SD becomes 1. - // Kills mutant: SetVectorStateDirty(matrix_state); in RiscVZvtMsetMtype. EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); EXPECT_EQ(GetMstatusSd(/*is_rv64=*/false), kMstatusSdSet); - // UpdateVectorMatrixGeometry must NOT be called: no exception, vill=0. - // Kills mutant: Changing line 443 `if (matrix_state->mtwiden() == 0)` to - // `if (false)`. + // UpdateVectorMatrixGeometry must NOT be called when mtwiden is zero: + // no exception, vill=0. EXPECT_FALSE(state_->rv_vector()->vector_exception()); EXPECT_EQ(state_->rv_vector()->vtype() & kVillMask, 0U); EXPECT_EQ(state_->rv_vector()->selected_element_width(), 2); } TEST_F(RiscVZvtInstructionsTest, MsetTnTrapsWhenMatrixStateMissing) { - ExpectTrapWithoutMatrixState(&RiscVZvtMsetTn); + ASSERT_OK_AND_ASSIGN(uint64_t trap_code, + ExecuteWithoutMatrixStateExpectTrap(&RiscVZvtMsetTn)); + EXPECT_EQ(trap_code, *ExceptionCode::kIllegalInstruction); } TEST_F(RiscVZvtInstructionsTest, MsetTmTrapsWhenMatrixStateMissing) { - ExpectTrapWithoutMatrixState(&RiscVZvtMsetTm); + ASSERT_OK_AND_ASSIGN(uint64_t trap_code, + ExecuteWithoutMatrixStateExpectTrap(&RiscVZvtMsetTm)); + EXPECT_EQ(trap_code, *ExceptionCode::kIllegalInstruction); } TEST_F(RiscVZvtInstructionsTest, MsetTkTrapsWhenMatrixStateMissing) { - ExpectTrapWithoutMatrixState(&RiscVZvtMsetTk); + ASSERT_OK_AND_ASSIGN(uint64_t trap_code, + ExecuteWithoutMatrixStateExpectTrap(&RiscVZvtMsetTk)); + EXPECT_EQ(trap_code, *ExceptionCode::kIllegalInstruction); } TEST_F(RiscVZvtInstructionsTest, MsetMtypeTrapsWhenMatrixStateMissing) { - ExpectTrapWithoutMatrixState(&RiscVZvtMsetMtype); + ASSERT_OK_AND_ASSIGN(uint64_t trap_code, + ExecuteWithoutMatrixStateExpectTrap(&RiscVZvtMsetMtype)); + EXPECT_EQ(trap_code, *ExceptionCode::kIllegalInstruction); } TEST_F(RiscVZvtInstructionsTest, MsetMtypeiTrapsWhenMatrixStateMissing) { - ExpectTrapWithoutMatrixState(&RiscVZvtMsetMtypei); + ASSERT_OK_AND_ASSIGN(uint64_t trap_code, ExecuteWithoutMatrixStateExpectTrap( + &RiscVZvtMsetMtypei)); + EXPECT_EQ(trap_code, *ExceptionCode::kIllegalInstruction); } TEST_F(RiscVZvtInstructionsTest, MsetTnClampsToEffectiveTileEdgeForTew64) { @@ -1257,12 +3411,9 @@ // Populate asymmetric matrix data in tile 0: // element at (r, c) = (r << 4) | c. - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - ASSERT_OK(matrix_state_->SetElem<uint8_t>( - 0, r, c, 8, static_cast<uint8_t>((r << 4) | c))); - } - } + ASSERT_OK(FillTilePattern<uint8_t>( + /*tile=*/0, /*rows=*/4, /*cols=*/4, + [](int r, int c) { return static_cast<uint8_t>((r << 4) | c); })); // TSS for column 1 of tile 0: pattern = column, tile = 0, index = 1. SetRegisterValue("x1", EncodeTss(/*tile=*/0, kTssPatternCol, /*index=*/1)); @@ -1341,8 +3492,9 @@ // If mutated to if (false), StoreTileBits stores into row 1 instead. // Check that row 1 was not written: (1, 0) should remain 0. - ASSERT_OK_AND_ASSIGN(auto elem_1_0, - matrix_state_->GetElem<uint8_t>(0, 1, 0, 8)); + ASSERT_OK_AND_ASSIGN(auto elem_1_0, matrix_state_->GetElem<uint8_t>( + /*tile=*/0, /*row=*/1, /*col=*/0, + /*element_width_in_bits=*/8)); EXPECT_EQ(elem_1_0, 0x00); // MS must be dirty. EXPECT_EQ(GetMstatusMs(), kMstatusStateDirty); @@ -1363,15 +3515,14 @@ instruction_->set_semantic_function(&RiscVZvtMsetMtypei); instruction_->Execute(nullptr); - // Kills mutants at lines 185, 187, 188. EXPECT_TRUE(state_->rv_vector()->vector_exception()); EXPECT_EQ(state_->rv_vector()->vector_length(), 0); EXPECT_EQ(matrix_state_->mtype(), 0); } -TEST_F(RiscVZvtInstructionsTest, - MsetTmZeroResetsTileMAndSetsVsDirtyWhenMtwidenIsZero) { +TEST_F(RiscVZvtInstructionsTest, MsetTmTrapsWhenMtwidenIsZero) { SetRegisterValue("x1", 500); + SetRegisterValue("x2", 99); instruction_->AppendSource(CreateScalarSource("x1")); instruction_->AppendDestination(CreateScalarDest("x2")); instruction_->set_semantic_function(&RiscVZvtMsetTm); @@ -1381,22 +3532,22 @@ EncodeMtype(kMtwidenUnconfigured, /*tk=*/0, /*tm=*/24)); ASSERT_EQ(matrix_state_->tile_m(), 24); - // Clear VS in mstatus to Off (0) to verify line 484 sets it dirty. SetMstatusVs(kMstatusStateOff); ASSERT_EQ(GetMstatusVs(), kMstatusStateOff); + ScopedTrapCapture trap_capture(state_.get()); instruction_->Execute(nullptr); - // Kills mutant removing matrix_state->set_tile_m(0); - EXPECT_EQ(matrix_state_->tile_m(), 0); - EXPECT_EQ(GetRegisterValue("x2"), 0); - // Kills mutant removing SetVectorStateDirty(matrix_state); - EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); + EXPECT_EQ(matrix_state_->tile_m(), 24); + EXPECT_EQ(GetRegisterValue("x2"), 99); + EXPECT_EQ(GetMstatusVs(), kMstatusStateOff); } -TEST_F(RiscVZvtInstructionsTest, - MsetTkZeroResetsTileKAndSetsVsDirtyWhenMtwidenIsZero) { +TEST_F(RiscVZvtInstructionsTest, MsetTkTrapsWhenMtwidenIsZero) { SetRegisterValue("x1", 500); + SetRegisterValue("x2", 77); instruction_->AppendSource(CreateScalarSource("x1")); instruction_->AppendDestination(CreateScalarDest("x2")); instruction_->set_semantic_function(&RiscVZvtMsetTk); @@ -1406,23 +3557,22 @@ EncodeMtype(kMtwidenUnconfigured, /*tk=*/4, /*tm=*/0)); ASSERT_EQ(matrix_state_->tile_k(), 4); - // Clear VS in mstatus to Off (0) to verify line 515 sets it dirty. SetMstatusVs(kMstatusStateOff); ASSERT_EQ(GetMstatusVs(), kMstatusStateOff); + ScopedTrapCapture trap_capture(state_.get()); instruction_->Execute(nullptr); - // Kills mutant removing matrix_state->set_tile_k(0); - EXPECT_EQ(matrix_state_->tile_k(), 0); - EXPECT_EQ(GetRegisterValue("x2"), 0); - // Kills mutant removing SetVectorStateDirty(matrix_state); - EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); + EXPECT_EQ(matrix_state_->tile_k(), 4); + EXPECT_EQ(GetRegisterValue("x2"), 77); + EXPECT_EQ(GetMstatusVs(), kMstatusStateOff); } TEST_F(RiscVZvtInstructionsTest, VtmvVtRespectsVectorRegisterBoundary) { // Use a localized state with 8-byte vector registers (VLEN = 64 bits). // With SEW = 8 bits, elements_per_vector = 8 / 1 = 8. - // Under the mutant (elements_per_vector - 1), it becomes 7. FlatDemandMemory memory; RiscVState state("boundary_vt_test", RiscVXlen::RV32, &memory); RiscVVectorState vec_state(&state, 8); @@ -1443,9 +3593,12 @@ (static_cast<uint64_t>(kMstatusStateInitial) << kMstatusMsShift))); // Populate row 0 of tile 0 with 8 distinct bytes: 0x10 .. 0x17. + absl::Status init_status; for (int c = 0; c < 8; ++c) { - ASSERT_OK(matrix_state->SetElem<uint8_t>(0, 0, c, 8, 0x10 + c)); + init_status.Update(matrix_state->SetElem<uint8_t>( + /*tile=*/0, /*row=*/0, c, /*element_width_in_bits=*/8, 0x10 + c)); } + ASSERT_OK(init_status); auto* v2 = state.GetRegister<RVVectorRegister>("v2").first; auto* v3 = state.GetRegister<RVVectorRegister>("v3").first; @@ -1481,8 +3634,6 @@ TEST_F(RiscVZvtInstructionsTest, VtmvTvRespectsVectorRegisterBoundary) { // Use a localized state with 8-byte vector registers (VLEN = 64 bits). // With SEW = 8 bits, elements_per_vector = 8 / 1 = 8. - // Under mutant (- 1), elements_per_vector = 7. - // Under mutant (+ 1), elements_per_vector = 9. FlatDemandMemory memory; RiscVState state("boundary_test", RiscVXlen::RV32, &memory); RiscVVectorState vec_state(&state, 8); @@ -1527,15 +3678,1829 @@ // For elem = 7: // Clean code: reg = 7 / 8 = 0, e = 7 % 8 = 7 -> reads v4[7] = 0x77. // Mutated code (- 1): reg = 7 / 7 = 1, e = 7 % 7 = 0 -> reads v5[0] = 0x88. - ASSERT_OK_AND_ASSIGN(auto elem_7, matrix_state->GetElem<uint8_t>(0, 0, 7, 8)); + ASSERT_OK_AND_ASSIGN(auto elem_7, matrix_state->GetElem<uint8_t>( + /*tile=*/0, /*row=*/0, /*col=*/7, + /*element_width_in_bits=*/8)); EXPECT_EQ(elem_7, 0x77); // For elem = 9: // Clean code: reg = 9 / 8 = 1, e = 9 % 8 = 1 -> reads v5[1] = 0x99. // Mutated code (+ 1): reg = 9 / 9 = 1, e = 9 % 9 = 0 -> reads v5[0] = 0x88. - ASSERT_OK_AND_ASSIGN(auto elem_9, matrix_state->GetElem<uint8_t>(0, 0, 9, 8)); + ASSERT_OK_AND_ASSIGN(auto elem_9, matrix_state->GetElem<uint8_t>( + /*tile=*/0, /*row=*/0, /*col=*/9, + /*element_width_in_bits=*/8)); EXPECT_EQ(elem_9, 0x99); EXPECT_EQ(vec_state.vstart(), 0); } +TEST_F(RiscVZvtInstructionsTest, VtfmmTvvFp8E4M3Matmul) { + // Zvt spec v0.4: vtfmm.tvv OCP FP8 E4M3 x E4M3 -> FP32. + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/2, + /*tm=*/2); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{1.25f, -0.25f}, {0.0f, 10.0f}})); + + // Populate matrix A (FP8 E4M3, SEW=8 => KMAX=4, stride=2): + WriteVectorRegister<uint8_t>("v8", {0x40, 0x38}); // 2.0f, 1.0f + WriteVectorRegister<uint8_t>("v10", {0xB0, 0x48}); // -0.5f, 4.0f + + // Populate matrix B (FP8 E4M3): + WriteVectorRegister<uint8_t>("v16", {0x30, 0x44}); // 0.5f, 3.0f + WriteVectorRegister<uint8_t>("v18", {0x40, 0xB8}); // 2.0f, -1.0f + + ExecuteMatmul(&RiscVZvtVtfmm); + + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<float>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(1.25f, 6.25f, 8.5f, 9.0f)); + + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->ms(), + state_->v() ? kMstatusStateDirty : kMstatusStateInitial); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmTvvFp8E4M3x5M2Matmul) { + // Zvt spec v0.4: vtfmm.tvv OCP FP8 E4M3 x E5M2 -> FP32. + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/2, + /*tm=*/2, /*vstart=*/0, /*vta=*/false, /*vma=*/false, + /*altfmt=*/true); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{1.25f, -0.25f}, {0.0f, 10.0f}})); + + WriteVectorRegister<uint8_t>("v8", {0x40, 0x38}); // 2.0f, 1.0f (E4M3) + WriteVectorRegister<uint8_t>("v10", {0xB0, 0x48}); // -0.5f, 4.0f (E4M3) + WriteVectorRegister<uint8_t>("v16", {0x38, 0x42}); // 0.5f, 3.0f (E5M2) + WriteVectorRegister<uint8_t>("v18", {0x40, 0xBC}); // 2.0f, -1.0f (E5M2) + + ExecuteMatmul(&RiscVZvtVtfmm); + + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<float>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(1.25f, 6.25f, 8.5f, 9.0f)); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmAltTvvFp8E5M2x4M3Matmul) { + // Zvt spec v0.4: vtfmm.alt.tvv OCP FP8 E5M2 x E4M3 -> FP32. + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/2, + /*tm=*/2); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{1.25f, -0.25f}, {0.0f, 10.0f}})); + + WriteVectorRegister<uint8_t>("v8", {0x40, 0x3C}); // 2.0f, 1.0f (E5M2) + WriteVectorRegister<uint8_t>("v10", {0xB8, 0x44}); // -0.5f, 4.0f (E5M2) + WriteVectorRegister<uint8_t>("v16", {0x30, 0x44}); // 0.5f, 3.0f (E4M3) + WriteVectorRegister<uint8_t>("v18", {0x40, 0xB8}); // 2.0f, -1.0f (E4M3) + + ExecuteMatmul(&RiscVZvtVtfmmAlt); + + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<float>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(1.25f, 6.25f, 8.5f, 9.0f)); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmAltTvvFp8E5M2Matmul) { + // Zvt spec v0.4: vtfmm.alt.tvv OCP FP8 E5M2 x E5M2 -> FP32. + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/2, + /*tm=*/2, /*vstart=*/0, /*vta=*/false, /*vma=*/false, + /*altfmt=*/true); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{1.25f, -0.25f}, {0.0f, 10.0f}})); + + WriteVectorRegister<uint8_t>("v8", {0x40, 0x3C}); // 2.0f, 1.0f (E5M2) + WriteVectorRegister<uint8_t>("v10", {0xB8, 0x44}); // -0.5f, 4.0f (E5M2) + WriteVectorRegister<uint8_t>("v16", {0x38, 0x42}); // 0.5f, 3.0f (E5M2) + WriteVectorRegister<uint8_t>("v18", {0x40, 0xBC}); // 2.0f, -1.0f (E5M2) + + ExecuteMatmul(&RiscVZvtVtfmmAlt); + + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<float>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::ElementsAre(1.25f, 6.25f, 8.5f, 9.0f)); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmuSewTrap) { + // SEW != 8 is invalid for vtmmu. + ConfigureMatrixUnit(kMtwiden4, kVsew16, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteMatmul(&RiscVZvtVtmmu); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmsSewTrap) { + // SEW != 8 is invalid for vtmms. + ConfigureMatrixUnit(kMtwiden4, kVsew32, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteMatmul(&RiscVZvtVtmms); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmuTwidenTrap) { + // TWIDEN != 4 is invalid for vtmmu. + ConfigureMatrixUnit(kMtwiden2, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteMatmul(&RiscVZvtVtmmu); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmsTwidenTrap) { + // TWIDEN != 4 is invalid for vtmms. + ConfigureMatrixUnit(kMtwiden2, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteMatmul(&RiscVZvtVtmms); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmuUnconfiguredTrap) { + ConfigureMatrixUnit(kMtwidenUnconfigured, kVsew8, kVlmul1, /*vl=*/2, + /*tk=*/1, /*tm=*/2); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteMatmul(&RiscVZvtVtmmu); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmsUnconfiguredTrap) { + ConfigureMatrixUnit(kMtwidenUnconfigured, kVsew8, kVlmul1, /*vl=*/0); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteMatmul(&RiscVZvtVtmms); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmUnconfiguredTrap) { + ConfigureMatrixUnit(kMtwidenUnconfigured, kVsew8, kVlmul1, /*vl=*/0); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteMatmul(&RiscVZvtVtfmm); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmAltUnconfiguredTrap) { + ConfigureMatrixUnit(kMtwidenUnconfigured, kVsew8, kVlmul1, /*vl=*/0); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteMatmul(&RiscVZvtVtfmmAlt); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulFcsrFlagsException) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + state_->set_v(/*v=*/false); + vsstatus()->set_vs(kMstatusStateInitial); + + // Preserve bits: DZ, UF, NX. Set them to 1. + const uint32_t preset_fcsr = *FPExceptions::kDivByZero | + *FPExceptions::kUnderflow | + *FPExceptions::kInexact; + fp_state_->fcsr()->Write(preset_fcsr); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + WriteVectorRegister<uint32_t>( + "v8", + {absl::bit_cast<uint32_t>(std::numeric_limits<float>::infinity()), 0}); + WriteVectorRegister<uint32_t>("v16", {absl::bit_cast<uint32_t>(0.0f), 0}); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteMatmul(&RiscVZvtVtfmm); + EXPECT_FALSE(trap_capture.trap_taken()); + + uint32_t fcsr_after = fp_state_->fcsr()->AsUint32(); + EXPECT_NE(fcsr_after & *FPExceptions::kInvalidOp, 0U); + EXPECT_EQ(fcsr_after & preset_fcsr, preset_fcsr); + + EXPECT_EQ(state_->mstatus()->fs(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->fs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulFcsrFlagsOverflowException) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + state_->set_v(/*v=*/false); + vsstatus()->set_vs(kMstatusStateInitial); + + // Preset FCSR to 0 to verify isolation of NX/UF/DZ. + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + const uint32_t max_bits = + absl::bit_cast<uint32_t>(std::numeric_limits<float>::max()); + WriteVectorRegister<uint32_t>("v8", {max_bits, 0}); + WriteVectorRegister<uint32_t>("v16", {max_bits, 0}); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteMatmul(&RiscVZvtVtfmm); + EXPECT_FALSE(trap_capture.trap_taken()); + + uint32_t fcsr_after = fp_state_->fcsr()->AsUint32(); + EXPECT_NE(fcsr_after & *FPExceptions::kOverflow, 0U); + const uint32_t preserved_mask = *FPExceptions::kDivByZero | + *FPExceptions::kUnderflow | + *FPExceptions::kInexact; + EXPECT_EQ(fcsr_after & preserved_mask, 0U); + + EXPECT_EQ(state_->mstatus()->fs(), kMstatusStateDirty); + EXPECT_EQ(vsstatus()->fs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, VtleTailElementEvaluationPolicy) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/0, /*tm=*/0, + /*vstart=*/0, /*vta=*/true); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemory<uint8_t>(kBaseAddr, {0x11, 0x22}); + + constexpr uint32_t kTileId = 1; + constexpr uint32_t kRowIndex = 2; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/8, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + // ETE for eew=8 is 32; cols 0..1 are loaded and tail 2..31 are filled with + // 0xFF when vta=1. + ASSERT_OK_AND_ASSIGN(auto row_vals, + GetTileRow<uint8_t>(kTileId, kRowIndex, /*count=*/32)); + std::vector<uint8_t> expected(32, 0xFF); + expected[0] = 0x11; + expected[1] = 0x22; + EXPECT_THAT(row_vals, testing::ElementsAreArray(expected)); +} + +TEST_F(RiscVZvtInstructionsTest, VtseTailElementEvaluationPolicy) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/0, /*tm=*/0, + /*vstart=*/0, /*vta=*/true); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemoryConstant<uint8_t>(kBaseAddr, /*count=*/32, 0x55); + + constexpr uint32_t kTileId = 1; + constexpr uint32_t kRowIndex = 2; + ASSERT_OK(SetTileRowPattern<uint8_t>(kTileId, kRowIndex, /*count=*/4, + [](int i) { return i + 1; })); + + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/8, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + // Only elements 0 and 1 are stored; elements 2..31 remain undisturbed (0x55) + // regardless of vta=1. + std::vector<uint8_t> expected(32, 0x55); + expected[0] = 1; + expected[1] = 2; + EXPECT_THAT(ReadMemory<uint8_t>(kBaseAddr, 32), + testing::ElementsAreArray(expected)); +} + +// --- Vtle TSS Exception Tests --- +TEST_F(RiscVZvtInstructionsTest, VtleTssPatternExceedsBoundsTrap) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/32, /*base_addr=*/0x1000, + EncodeTss(/*tile=*/1, kTssPatternInvalid, /*index=*/0)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtleTssRowIndexOverflowTrap) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/32, /*base_addr=*/0x1000, + EncodeTss(/*tile=*/1, kTssPatternRow, /*index=*/32)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtleTssColIndexOverflowTrap) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/32, /*base_addr=*/0x1000, + EncodeTss(/*tile=*/1, kTssPatternCol, /*index=*/32)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +// --- Vtse TSS Exception Tests --- +TEST_F(RiscVZvtInstructionsTest, VtseTssPatternExceedsBoundsTrap) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/32, /*base_addr=*/0x1000, + EncodeTss(/*tile=*/1, kTssPatternInvalid, /*index=*/0)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtseTssRowIndexOverflowTrap) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/32, /*base_addr=*/0x1000, + EncodeTss(/*tile=*/1, kTssPatternRow, /*index=*/32)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtseTssColIndexOverflowTrap) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/32, /*base_addr=*/0x1000, + EncodeTss(/*tile=*/1, kTssPatternCol, /*index=*/32)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, Vtle8AddressMisalignedExceptions) { + ConfigureMatrixUnit(kMtwiden1, kVsew64, kVlmul2, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + constexpr uint64_t kUnalignedBase = 0x2000 + 1; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/8, kUnalignedBase, + EncodeTss(/*tile=*/1, kTssPatternRow, /*index=*/0)); + + EXPECT_FALSE(trap_capture.trap_taken()); +} + +TEST_F(RiscVZvtInstructionsTest, Vtle16AddressMisalignedExceptions) { + ConfigureMatrixUnit(kMtwiden1, kVsew64, kVlmul2, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + constexpr uint64_t kUnalignedBase = 0x2000 + 1; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/16, kUnalignedBase, + EncodeTss(/*tile=*/1, kTssPatternRow, /*index=*/0)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kLoadAddressMisaligned); +} + +TEST_F(RiscVZvtInstructionsTest, Vtle32AddressMisalignedExceptions) { + ConfigureMatrixUnit(kMtwiden1, kVsew64, kVlmul2, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + constexpr uint64_t kUnalignedBase = 0x2000 + 1; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/32, kUnalignedBase, + EncodeTss(/*tile=*/1, kTssPatternRow, /*index=*/0)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kLoadAddressMisaligned); +} + +TEST_F(RiscVZvtInstructionsTest, Vtle64AddressMisalignedExceptions) { + ConfigureMatrixUnit(kMtwiden1, kVsew64, kVlmul2, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + constexpr uint64_t kUnalignedBase = 0x2000 + 1; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/64, kUnalignedBase, + EncodeTss(/*tile=*/1, kTssPatternRow, /*index=*/0)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kLoadAddressMisaligned); +} + +TEST_F(RiscVZvtInstructionsTest, Vtse8AddressMisalignedExceptions) { + ConfigureMatrixUnit(kMtwiden1, kVsew64, kVlmul2, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + constexpr uint64_t kUnalignedBase = 0x2000 + 1; + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/8, kUnalignedBase, + EncodeTss(/*tile=*/1, kTssPatternRow, /*index=*/0)); + + EXPECT_FALSE(trap_capture.trap_taken()); +} + +TEST_F(RiscVZvtInstructionsTest, Vtse16AddressMisalignedExceptions) { + ConfigureMatrixUnit(kMtwiden1, kVsew64, kVlmul2, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + constexpr uint64_t kUnalignedBase = 0x2000 + 1; + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/16, kUnalignedBase, + EncodeTss(/*tile=*/1, kTssPatternRow, /*index=*/0)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kStoreAddressMisaligned); +} + +TEST_F(RiscVZvtInstructionsTest, Vtse32AddressMisalignedExceptions) { + ConfigureMatrixUnit(kMtwiden1, kVsew64, kVlmul2, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + constexpr uint64_t kUnalignedBase = 0x2000 + 1; + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/32, kUnalignedBase, + EncodeTss(/*tile=*/1, kTssPatternRow, /*index=*/0)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kStoreAddressMisaligned); +} + +TEST_F(RiscVZvtInstructionsTest, Vtse64AddressMisalignedExceptions) { + ConfigureMatrixUnit(kMtwiden1, kVsew64, kVlmul2, /*vl=*/4); + ScopedTrapCapture trap_capture(state_.get()); + + constexpr uint64_t kUnalignedBase = 0x2000 + 1; + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/64, kUnalignedBase, + EncodeTss(/*tile=*/1, kTssPatternRow, /*index=*/0)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kStoreAddressMisaligned); +} + +TEST_F(RiscVZvtInstructionsTest, VtseVstartLowerBoundLimitation) { + ConfigureMatrixUnit(kMtwiden1, kVsew16, kVlmul2, /*vl=*/4, /*tk=*/0, /*tm=*/0, + /*vstart=*/2); + + constexpr uint64_t kBaseAddr = 0x2000; + // Pre-fill memory to verify elements < vstart are unchanged. + WriteMemoryConstant<uint16_t>(kBaseAddr, /*count=*/4, 0xBBBB); + + constexpr uint32_t kTileId = 0; + constexpr uint32_t kRowIndex = 2; + ASSERT_OK(SetTileRowPattern<uint16_t>( + kTileId, kRowIndex, /*count=*/4, + [](int i) { return static_cast<uint16_t>(0xAA00 + i); })); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/16, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + EXPECT_FALSE(trap_capture.trap_taken()); + + EXPECT_THAT(ReadMemory<uint16_t>(kBaseAddr, 4), + testing::ElementsAre(0xBBBB, 0xBBBB, 0xAA02, 0xAA03)); + EXPECT_EQ(vector_state_->vstart(), 0); +} + +TEST_F(RiscVZvtInstructionsTest, VtleAscendingElementOrderTraversalLimitation) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4); + + constexpr uint64_t kBaseAddr = 0x2000; + WriteMemory<uint8_t>(kBaseAddr, {0xAA, 0xBB, 0xCC, 0xDD}); + + constexpr uint32_t kTileId = 1; + constexpr uint32_t kRowIndex = 2; + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/8, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + ASSERT_OK_AND_ASSIGN(auto row_vals, + GetTileRow<uint8_t>(kTileId, kRowIndex, /*count=*/4)); + EXPECT_THAT(row_vals, testing::ElementsAre(0xAA, 0xBB, 0xCC, 0xDD)); +} + +TEST_F(RiscVZvtInstructionsTest, VtseAscendingElementOrderTraversalLimitation) { + ConfigureMatrixUnit(kMtwiden1, kVsew8, kVlmul1, /*vl=*/4); + + constexpr uint32_t kTileId = 1; + constexpr uint32_t kRowIndex = 2; + ASSERT_OK(SetTileRow<uint8_t>(kTileId, kRowIndex, {0x11, 0x22, 0x33, 0x44})); + + constexpr uint64_t kBaseAddr = 0x2000; + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/8, kBaseAddr, + EncodeTss(kTileId, kTssPatternRow, kRowIndex)); + + EXPECT_THAT(ReadMemory<uint8_t>(kBaseAddr, 4), + testing::ElementsAre(0x11, 0x22, 0x33, 0x44)); +} + +TEST_F(RiscVZvtInstructionsTest, DoubleToFloatRODPrecision) { + // Normal value + EXPECT_EQ(DoubleToFloatROD(1.0, fp_state_.get()), 1.0f); + + // Tie breaking for ROD (Round to Odd). E.g. Exact halfway between two floats. + // We can just test generic correctness for Inf and NaN for now. + EXPECT_TRUE(std::isinf(DoubleToFloatROD( + std::numeric_limits<double>::infinity(), fp_state_.get()))); + EXPECT_TRUE(std::isnan(DoubleToFloatROD( + std::numeric_limits<double>::quiet_NaN(), fp_state_.get()))); + EXPECT_EQ(DoubleToFloatROD(0.0, fp_state_.get()), 0.0f); + EXPECT_EQ(DoubleToFloatROD(-0.0, fp_state_.get()), -0.0f); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulFcsrNxExceptionInvarianceTrace) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + WriteVectorRegister<uint32_t>("v8", + {absl::bit_cast<uint32_t>(1.0000001f), 0}); + WriteVectorRegister<uint32_t>("v16", + {absl::bit_cast<uint32_t>(1.0000001f), 0}); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteMatmul(&RiscVZvtVtfmm); + EXPECT_FALSE(trap_capture.trap_taken()); + + ASSERT_OK_AND_ASSIGN(uint32_t res_val, + GetTileElem<uint32_t>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_NE(res_val, 0U); + EXPECT_EQ(fp_state_->fcsr()->AsUint32() & *FPExceptions::kInexact, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulFcsrNxExceptionInvarianceTraceFp8) { + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + WriteVectorRegister<uint8_t>("v8", {0x40, 0}); + WriteVectorRegister<uint8_t>("v16", {0x40, 0}); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteMatmul(&RiscVZvtVtfmm); + EXPECT_FALSE(trap_capture.trap_taken()); + + ASSERT_OK_AND_ASSIGN(uint32_t res_val, + GetTileElem<uint32_t>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_NE(res_val, 0U); + EXPECT_EQ(fp_state_->fcsr()->AsUint32() & *FPExceptions::kInexact, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulFcsrNxExceptionInvarianceTraceFp16) { + ConfigureMatrixUnit(kMtwiden2, kVsew16, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + WriteVectorRegister<uint16_t>("v8", {0x3C00, 0}); + WriteVectorRegister<uint16_t>("v16", {0x3C00, 0}); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteMatmul(&RiscVZvtVtfmm); + EXPECT_FALSE(trap_capture.trap_taken()); + + ASSERT_OK_AND_ASSIGN(uint32_t res_val, + GetTileElem<uint32_t>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_NE(res_val, 0U); + EXPECT_EQ(fp_state_->fcsr()->AsUint32() & *FPExceptions::kInexact, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulFcsrNxExceptionInvarianceTraceBf16) { + ConfigureMatrixUnit(kMtwiden2, kVsew16, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2, /*vstart=*/0, /*vta=*/false, /*vma=*/false, + /*altfmt=*/true); + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + WriteVectorRegister<uint16_t>("v8", {0x3C00, 0}); + WriteVectorRegister<uint16_t>("v16", {0x3C00, 0}); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteMatmul(&RiscVZvtVtfmmAlt); + EXPECT_FALSE(trap_capture.trap_taken()); + + ASSERT_OK_AND_ASSIGN(uint32_t res_val, + GetTileElem<uint32_t>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_NE(res_val, 0U); + EXPECT_EQ(fp_state_->fcsr()->AsUint32() & *FPExceptions::kInexact, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulFcsrUfExceptionInvarianceTrace) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + WriteVectorRegister<uint32_t>( + "v8", {absl::bit_cast<uint32_t>(std::numeric_limits<float>::min()), 0}); + WriteVectorRegister<uint32_t>("v16", {absl::bit_cast<uint32_t>(0.5f), 0}); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteMatmul(&RiscVZvtVtfmm); + EXPECT_FALSE(trap_capture.trap_taken()); + + ASSERT_OK_AND_ASSIGN(uint32_t res_val, + GetTileElem<uint32_t>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_NE(res_val, 0U); + EXPECT_EQ(fp_state_->fcsr()->AsUint32() & *FPExceptions::kUnderflow, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulFcsrUfExceptionInvarianceTraceFp8) { + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + WriteVectorRegister<uint8_t>("v8", {0x40, 0}); + WriteVectorRegister<uint8_t>("v16", {0x40, 0}); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteMatmul(&RiscVZvtVtfmm); + EXPECT_FALSE(trap_capture.trap_taken()); + + ASSERT_OK_AND_ASSIGN(uint32_t res_val, + GetTileElem<uint32_t>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_NE(res_val, 0U); + EXPECT_EQ(fp_state_->fcsr()->AsUint32() & *FPExceptions::kUnderflow, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulFcsrUfExceptionInvarianceTraceFp16) { + ConfigureMatrixUnit(kMtwiden2, kVsew16, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + WriteVectorRegister<uint16_t>("v8", {0x3C00, 0}); + WriteVectorRegister<uint16_t>("v16", {0x3C00, 0}); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteMatmul(&RiscVZvtVtfmm); + EXPECT_FALSE(trap_capture.trap_taken()); + + ASSERT_OK_AND_ASSIGN(uint32_t res_val, + GetTileElem<uint32_t>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_NE(res_val, 0U); + EXPECT_EQ(fp_state_->fcsr()->AsUint32() & *FPExceptions::kUnderflow, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulFcsrUfExceptionInvarianceTraceBf16) { + ConfigureMatrixUnit(kMtwiden2, kVsew16, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2, /*vstart=*/0, /*vta=*/false, /*vma=*/false, + /*altfmt=*/true); + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + WriteVectorRegister<uint16_t>("v8", {0x3C00, 0}); + WriteVectorRegister<uint16_t>("v16", {0x3C00, 0}); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteMatmul(&RiscVZvtVtfmmAlt); + EXPECT_FALSE(trap_capture.trap_taken()); + + ASSERT_OK_AND_ASSIGN(uint32_t res_val, + GetTileElem<uint32_t>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_NE(res_val, 0U); + EXPECT_EQ(fp_state_->fcsr()->AsUint32() & *FPExceptions::kUnderflow, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulFcsrDzExceptionInvarianceTrace) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + WriteVectorRegister<uint32_t>("v8", {absl::bit_cast<uint32_t>(1.0f), 0}); + WriteVectorRegister<uint32_t>("v16", {absl::bit_cast<uint32_t>(1.0f), 0}); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteMatmul(&RiscVZvtVtfmm); + EXPECT_FALSE(trap_capture.trap_taken()); + + ASSERT_OK_AND_ASSIGN(uint32_t res_val, + GetTileElem<uint32_t>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_NE(res_val, 0U); + EXPECT_EQ(fp_state_->fcsr()->AsUint32() & *FPExceptions::kDivByZero, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulFcsrDzExceptionInvarianceTraceFp8) { + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + WriteVectorRegister<uint8_t>("v8", {0x40, 0}); + WriteVectorRegister<uint8_t>("v16", {0x40, 0}); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteMatmul(&RiscVZvtVtfmm); + EXPECT_FALSE(trap_capture.trap_taken()); + + ASSERT_OK_AND_ASSIGN(uint32_t res_val, + GetTileElem<uint32_t>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_NE(res_val, 0U); + EXPECT_EQ(fp_state_->fcsr()->AsUint32() & *FPExceptions::kDivByZero, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulFcsrDzExceptionInvarianceTraceFp16) { + ConfigureMatrixUnit(kMtwiden2, kVsew16, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2); + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + WriteVectorRegister<uint16_t>("v8", {0x3C00, 0}); + WriteVectorRegister<uint16_t>("v16", {0x3C00, 0}); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteMatmul(&RiscVZvtVtfmm); + EXPECT_FALSE(trap_capture.trap_taken()); + + ASSERT_OK_AND_ASSIGN(uint32_t res_val, + GetTileElem<uint32_t>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_NE(res_val, 0U); + EXPECT_EQ(fp_state_->fcsr()->AsUint32() & *FPExceptions::kDivByZero, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulFcsrDzExceptionInvarianceTraceBf16) { + ConfigureMatrixUnit(kMtwiden2, kVsew16, kVlmul1, /*vl=*/2, /*tk=*/1, + /*tm=*/2, /*vstart=*/0, /*vta=*/false, /*vma=*/false, + /*altfmt=*/true); + fp_state_->fcsr()->Write(0U); + + ASSERT_OK(SetTileMatrix<float>(/*tile=*/0, {{0.0f}})); + WriteVectorRegister<uint16_t>("v8", {0x3C00, 0}); + WriteVectorRegister<uint16_t>("v16", {0x3C00, 0}); + + ScopedTrapCapture trap_capture(state_.get()); + ExecuteMatmul(&RiscVZvtVtfmmAlt); + EXPECT_FALSE(trap_capture.trap_taken()); + + ASSERT_OK_AND_ASSIGN(uint32_t res_val, + GetTileElem<uint32_t>(/*tile=*/0, /*row=*/0, /*col=*/0)); + EXPECT_NE(res_val, 0U); + EXPECT_EQ(fp_state_->fcsr()->AsUint32() & *FPExceptions::kDivByZero, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmDynamicDispatchFp8E4M3) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + vsstatus()->set_ms(kMstatusStateInitial); + + matrix_state_->set_mtype(EncodeMtype(kMtwiden4)); + matrix_state_->set_tile_m(2); + matrix_state_->set_tile_k(2); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1, /*vta=*/false, + /*vma=*/false, + /*altfmt=*/false)); + + std::vector<RegisterBase*> reg_vec; + for (int i = 0; i < 8; i++) { + reg_vec.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 8 + i)).first); + } + for (int i = 0; i < 8; ++i) { + auto dest = reg_vec[i]->data_buffer()->Get<uint32_t>(); + for (size_t j = 0; j < dest.size(); ++j) { + dest[j] = 0x40404040; + } + } + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/0)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + // Should not crash, basically testing it reaches the proper matmul function + ScopedTrapCapture trap_capture(state_.get()); + instruction_->set_semantic_function(&RiscVZvtVtfmm); + instruction_->Execute(nullptr); + EXPECT_FALSE(trap_capture.trap_taken()); + + // Assert output is physically calculated and present + ASSERT_OK_AND_ASSIGN(uint32_t res_val, matrix_state_->GetElem<uint32_t>( + /*tile=*/0, /*row=*/0, /*col=*/0, + /*element_width_in_bits=*/32)); + EXPECT_NE(res_val, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmDynamicDispatchFp8E4M3xE5M2) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + matrix_state_->set_mtype(EncodeMtype(kMtwiden4)); + matrix_state_->set_tile_m(2); + matrix_state_->set_tile_k(1); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1, + /*vta=*/false, /*vma=*/false, + /*altfmt=*/true)); + + std::vector<RegisterBase*> reg_vec; + for (int i = 0; i < 8; i++) { + reg_vec.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 8 + i)).first); + } + for (int i = 0; i < 8; ++i) { + auto dest = reg_vec[i]->data_buffer()->Get<uint32_t>(); + for (size_t j = 0; j < dest.size(); ++j) { + dest[j] = 0x40404040; + } + } + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/0)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + ScopedTrapCapture trap_capture(state_.get()); + instruction_->set_semantic_function(&RiscVZvtVtfmm); + instruction_->Execute(nullptr); + EXPECT_FALSE(trap_capture.trap_taken()); + + // Assert output is physically calculated and present + ASSERT_OK_AND_ASSIGN(uint32_t res_val, matrix_state_->GetElem<uint32_t>( + /*tile=*/0, /*row=*/0, /*col=*/0, + /*element_width_in_bits=*/32)); + EXPECT_NE(res_val, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmDynamicDispatchFp16) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + matrix_state_->set_mtype(EncodeMtype(kMtwiden2)); + matrix_state_->set_tile_m(2); + matrix_state_->set_tile_k(1); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew16, kVlmul1)); + + std::vector<RegisterBase*> reg_vec; + for (int i = 0; i < 8; i++) { + reg_vec.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 8 + i)).first); + } + for (int i = 0; i < 8; ++i) { + auto dest = reg_vec[i]->data_buffer()->Get<uint32_t>(); + for (size_t j = 0; j < dest.size(); ++j) { + dest[j] = 0x40404040; + } + } + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/0)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + ScopedTrapCapture trap_capture(state_.get()); + instruction_->set_semantic_function(&RiscVZvtVtfmm); + instruction_->Execute(nullptr); + EXPECT_FALSE(trap_capture.trap_taken()); + + // Assert output is physically calculated and present + ASSERT_OK_AND_ASSIGN(uint32_t res_val, matrix_state_->GetElem<uint32_t>( + /*tile=*/0, /*row=*/0, /*col=*/0, + /*element_width_in_bits=*/32)); + EXPECT_NE(res_val, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmDynamicDispatchFp32) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + matrix_state_->set_tile_m(2); + matrix_state_->set_tile_k(1); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew32, kVlmul1)); + + std::vector<RegisterBase*> reg_vec; + for (int i = 0; i < 8; i++) { + reg_vec.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 8 + i)).first); + } + for (int i = 0; i < 8; ++i) { + auto dest = reg_vec[i]->data_buffer()->Get<uint32_t>(); + for (size_t j = 0; j < dest.size(); ++j) { + dest[j] = 0x40404040; + } + } + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/0)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + ScopedTrapCapture trap_capture(state_.get()); + instruction_->set_semantic_function(&RiscVZvtVtfmm); + instruction_->Execute(nullptr); + EXPECT_FALSE(trap_capture.trap_taken()); + + // Assert output is physically calculated and present + ASSERT_OK_AND_ASSIGN(uint32_t res_val, matrix_state_->GetElem<uint32_t>( + /*tile=*/0, /*row=*/0, /*col=*/0, + /*element_width_in_bits=*/32)); + EXPECT_NE(res_val, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmDynamicDispatchFp64) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + matrix_state_->set_tile_m(2); + matrix_state_->set_tile_k(1); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew64, kVlmul1)); + + std::vector<RegisterBase*> reg_vec; + for (int i = 0; i < 8; i++) { + reg_vec.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 8 + i)).first); + } + for (int i = 0; i < 8; ++i) { + auto dest = reg_vec[i]->data_buffer()->Get<uint32_t>(); + for (size_t j = 0; j < dest.size(); ++j) { + dest[j] = 0x40404040; + } + } + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/0)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + ScopedTrapCapture trap_capture(state_.get()); + instruction_->set_semantic_function(&RiscVZvtVtfmm); + instruction_->Execute(nullptr); + EXPECT_FALSE(trap_capture.trap_taken()); + + // Assert output is physically calculated and present + ASSERT_OK_AND_ASSIGN(uint64_t res_val, matrix_state_->GetElem<uint64_t>( + /*tile=*/0, /*row=*/0, /*col=*/0, + /*element_width_in_bits=*/64)); + EXPECT_NE(res_val, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmAltDynamicDispatchFp8E5M2xE4M3) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + matrix_state_->set_mtype(EncodeMtype(kMtwiden4)); + matrix_state_->set_tile_m(2); + matrix_state_->set_tile_k(1); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + + std::vector<RegisterBase*> reg_vec; + for (int i = 0; i < 8; i++) { + reg_vec.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 8 + i)).first); + } + for (int i = 0; i < 8; ++i) { + auto dest = reg_vec[i]->data_buffer()->Get<uint32_t>(); + for (size_t j = 0; j < dest.size(); ++j) { + dest[j] = 0x40404040; + } + } + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/0)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + ScopedTrapCapture trap_capture(state_.get()); + instruction_->set_semantic_function(&RiscVZvtVtfmmAlt); + instruction_->Execute(nullptr); + EXPECT_FALSE(trap_capture.trap_taken()); + + // Assert output is physically calculated and present + ASSERT_OK_AND_ASSIGN(uint32_t res_val, matrix_state_->GetElem<uint32_t>( + /*tile=*/0, /*row=*/0, /*col=*/0, + /*element_width_in_bits=*/32)); + EXPECT_NE(res_val, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmAltDynamicDispatchFp8E5M2) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + matrix_state_->set_mtype(EncodeMtype(kMtwiden4)); + matrix_state_->set_tile_m(2); + matrix_state_->set_tile_k(1); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1, + /*vta=*/false, /*vma=*/false, + /*altfmt=*/true)); + + std::vector<RegisterBase*> reg_vec; + for (int i = 0; i < 8; i++) { + reg_vec.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 8 + i)).first); + } + for (int i = 0; i < 8; ++i) { + auto dest = reg_vec[i]->data_buffer()->Get<uint32_t>(); + for (size_t j = 0; j < dest.size(); ++j) { + dest[j] = 0x40404040; + } + } + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/0)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + ScopedTrapCapture trap_capture(state_.get()); + instruction_->set_semantic_function(&RiscVZvtVtfmmAlt); + instruction_->Execute(nullptr); + EXPECT_FALSE(trap_capture.trap_taken()); + + // Assert output is physically calculated and present + ASSERT_OK_AND_ASSIGN(uint32_t res_val, matrix_state_->GetElem<uint32_t>( + /*tile=*/0, /*row=*/0, /*col=*/0, + /*element_width_in_bits=*/32)); + EXPECT_NE(res_val, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmAltDynamicDispatchBf16) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + matrix_state_->set_mtype(EncodeMtype(kMtwiden2)); + matrix_state_->set_tile_m(2); + matrix_state_->set_tile_k(1); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew16, kVlmul1, + /*vta=*/false, /*vma=*/false, + /*altfmt=*/true)); + + std::vector<RegisterBase*> reg_vec; + for (int i = 0; i < 8; i++) { + reg_vec.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 8 + i)).first); + } + for (int i = 0; i < 8; ++i) { + auto dest = reg_vec[i]->data_buffer()->Get<uint32_t>(); + for (size_t j = 0; j < dest.size(); ++j) { + dest[j] = 0x40404040; + } + } + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/0)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + ScopedTrapCapture trap_capture(state_.get()); + instruction_->set_semantic_function(&RiscVZvtVtfmmAlt); + instruction_->Execute(nullptr); + EXPECT_FALSE(trap_capture.trap_taken()); + + // Assert output is physically calculated and present + ASSERT_OK_AND_ASSIGN(uint32_t res_val, matrix_state_->GetElem<uint32_t>( + /*tile=*/0, /*row=*/0, /*col=*/0, + /*element_width_in_bits=*/32)); + EXPECT_NE(res_val, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmTrapUnsupportedSewTwidenAltfmt) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + // Test SEW=16 altfmt=1 for vtfmm.tvv which is unsupported + matrix_state_->set_mtype(EncodeMtype(kMtwiden2)); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew16, kVlmul1, /*vta=*/false, + /*vma=*/false, /*altfmt=*/true)); + + ScopedTrapCapture trap_capture(state_.get()); + + std::vector<RegisterBase*> reg_vec; + for (int i = 0; i < 8; i++) { + reg_vec.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 8 + i)).first); + } + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/0)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + instruction_->set_semantic_function(&RiscVZvtVtfmm); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmAltTrapUnsupportedSewTwidenAltfmt) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + // Test SEW=32 for vtfmm.alt.tvv which is unsupported + matrix_state_->set_mtype(EncodeMtype(kMtwiden2)); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew32, kVlmul1)); + + ScopedTrapCapture trap_capture(state_.get()); + + std::vector<RegisterBase*> reg_vec; + for (int i = 0; i < 8; i++) { + reg_vec.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 8 + i)).first); + } + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource( + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec), "v8")); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/0)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + instruction_->set_semantic_function(&RiscVZvtVtfmmAlt); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, MsetmtypeiConfiguresAltfmtBit) { + // mtwiden (zimm10) = 1, vsew = 2, altfmt = 1 + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(/*mtwiden=*/kMtwiden1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vsew=*/kVsew16)); + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(/*altfmt=*/kAltfmtAlternate)); + + instruction_->set_semantic_function(&RiscVZvtMsetMtypei); + instruction_->Execute(nullptr); + + // vsew=2 (1<<4), altfmt=1 (1<<8) => 0x110 + EXPECT_EQ(GetVtypeAltfmt(vector_state_.get()), 1); +} + +TEST_F(RiscVZvtInstructionsTest, VectorConfigInvalidationZerosAltfmt) { + // First set altfmt=1 + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1, + /*vta=*/false, /*vma=*/false, + /*altfmt=*/true)); + EXPECT_EQ(GetVtypeAltfmt(vector_state_.get()), 1); + + // Now set vill (invalid) by setting MSB + vector_state_->SetVectorType(kVillMask); + EXPECT_EQ(GetVtypeAltfmt(vector_state_.get()), 0); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulVmaqaExecutionLoops) { + // Zvt spec v0.4: vtmmu.tvv (altfmt=0) uint8 x uint8 -> int32. + // Use tile_k = 4 to exercise multiple k-accumulation iterations. + ConfigureMatrixUnit(kMtwiden4, kVsew8, kVlmul1, /*vl=*/2, /*tk=*/4, + /*tm=*/2); + + ASSERT_OK(SetTileMatrix<int32_t>(/*tile=*/0, {{10, 10}, {10, 10}})); + + // KMAX(8) = 4, kStride = 8 / 4 = 2. + for (int i = 0; i < 8; ++i) { + FillVectorRegister<uint8_t>(absl::StrCat("v", 8 + i), 2); + FillVectorRegister<uint8_t>(absl::StrCat("v", 16 + i), 3); + } + + ExecuteMatmul(&RiscVZvtVtmmu); + + // acc = 10 + (4 * (2 * 3)) = 34 + ASSERT_OK_AND_ASSIGN( + auto result, GetTileRegion<int32_t>(/*tile=*/0, /*rows=*/2, /*cols=*/2)); + EXPECT_THAT(result, testing::Each(34)); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulLmulCapacityAlignmentTrap) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + vsstatus()->set_ms(kMstatusStateInitial); + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->set_vector_length(4); + vector_state_->SetVectorType(EncodeVtype(kVsew64, kVlmul4)); + + ScopedTrapCapture trap_capture(state_.get()); + + std::vector<RegisterBase*> reg_vec_a; + for (int i = 0; i < 8; i++) { + reg_vec_a.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 1 + i)).first); + } + // reg_a = 1, lmul = 4. reg_a % lmul = 1 != 0 + auto* src_op_a = new RV32VectorSourceOperand(absl::MakeSpan(reg_vec_a), "v1"); + instruction_->AppendSource(src_op_a); + + std::vector<RegisterBase*> reg_vec_b; + for (int i = 0; i < 8; i++) { + reg_vec_b.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 8 + i)).first); + } + auto* src_op_b = new RV32VectorSourceOperand(absl::MakeSpan(reg_vec_b), "v8"); + instruction_->AppendSource(src_op_b); + + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/0)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + instruction_->set_semantic_function(&RiscVZvtVtfmm); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, MatmulExecutionStrideTrap) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + vsstatus()->set_ms(kMstatusStateInitial); + matrix_state_->set_mtype(EncodeMtype(kMtwiden2)); + vector_state_->set_vector_length(4); + vector_state_->SetVectorType(EncodeVtype(kVsew16, kVlmul1)); + + ScopedTrapCapture trap_capture(state_.get()); + + std::vector<RegisterBase*> reg_vec_a; + for (int i = 0; i < 8; i++) { + reg_vec_a.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 5 + i)).first); + } + // SEW=16 -> stride = 4. reg_a = 5. reg_a % 8 = 5 >= 4 + auto* src_op_a = new RV32VectorSourceOperand(absl::MakeSpan(reg_vec_a), "v5"); + instruction_->AppendSource(src_op_a); + + std::vector<RegisterBase*> reg_vec_b; + for (int i = 0; i < 8; i++) { + reg_vec_b.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 8 + i)).first); + } + auto* src_op_b = new RV32VectorSourceOperand(absl::MakeSpan(reg_vec_b), "v8"); + instruction_->AppendSource(src_op_b); + + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/0)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/5)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + instruction_->set_semantic_function(&RiscVZvtVtfmm); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, Fp8E4m3ToF32NaNPermutation) { + // E4M3 NaN is when exp = 1111 and mantissa != 0 + // 0x7F = 0 1111 111 + float res = ConvertFp8E4m3ToSingle(Fp8E4m3{0x7F}); + EXPECT_TRUE(std::isnan(res)); +} + +TEST_F(RiscVZvtInstructionsTest, Fp8E5m2ToF32NaNPermutation) { + // E5M2 NaN is when exp = 11111 and mantissa != 0 + // 0x7F = 0 11111 11 + float res = ConvertFp8E5m2ToSingle(Fp8E5m2{0x7F}); + EXPECT_TRUE(std::isnan(res)); +} + +TEST_F(RiscVZvtInstructionsTest, Bf16ToF32NaNPermutation) { + // Bf16 NaN is when exp = 11111111 and mantissa != 0 + // 0x7FC0 + float res = ConvertBf16ToSingle(Bfloat16{0x7FC0}); + EXPECT_TRUE(std::isnan(res)); +} + +TEST_F(RiscVZvtInstructionsTest, Fp8E4m3ToF32SubnormalPermutation) { + // E4M3 subnormal is when exp = 0 and mantissa != 0 + // 0x01 = 0 0000 001 + float res = ConvertFp8E4m3ToSingle(Fp8E4m3{0x01}); + EXPECT_TRUE(std::fpclassify(res) == FP_NORMAL); +} + +TEST_F(RiscVZvtInstructionsTest, Fp8E5m2ToF32SubnormalPermutation) { + // E5M2 subnormal is when exp = 0 and mantissa != 0 + // 0x01 = 0 00000 01 + float res = ConvertFp8E5m2ToSingle(Fp8E5m2{0x01}); + EXPECT_TRUE(std::fpclassify(res) == FP_NORMAL); +} + +TEST_F(RiscVZvtInstructionsTest, Bf16ToF32SubnormalPermutation) { + // Bf16 subnormal is when exp = 0 and mantissa != 0 + // 0x0001 + float res = ConvertBf16ToSingle(Bfloat16{0x0001}); + EXPECT_TRUE(std::fpclassify(res) == FP_SUBNORMAL); +} + +TEST_F(RiscVZvtInstructionsTest, VtleMisalignedTrapCalculatedAddress) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/0, /*tm=*/0, + /*vstart=*/2); + + constexpr uint64_t kBaseAddr = 0x2001; // misaligned! + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/32, kBaseAddr, + EncodeTss(/*tile=*/1, kTssPatternRow, /*index=*/2)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kLoadAddressMisaligned); + EXPECT_EQ(trap_capture.trap_value(), 0x2001 + 2 * 4); +} + +TEST_F(RiscVZvtInstructionsTest, VtseMisalignedTrapCalculatedAddress) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/0, /*tm=*/0, + /*vstart=*/2); + + constexpr uint64_t kBaseAddr = 0x2001; // misaligned! + ScopedTrapCapture trap_capture(state_.get()); + + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/32, kBaseAddr, + EncodeTss(/*tile=*/1, kTssPatternRow, /*index=*/2)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kStoreAddressMisaligned); + EXPECT_EQ(trap_capture.trap_value(), 0x2001 + 2 * 4); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmUnmappedTopologyTrapsIllegalInstruction) { + // mtwiden = 2 + matrix_state_->set_mtype(EncodeMtype(kMtwiden2)); + vector_state_->SetVectorType(EncodeVtype(kVsew16, kVlmul1, + /*vta=*/false, /*vma=*/false, + /*altfmt=*/true)); + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->Submit(); + + ScopedTrapCapture trap_capture(state_.get()); + + AppendMatmulSources(/*reg_a=*/8, /*reg_b=*/16, /*dest_tile=*/0); + instruction_->set_semantic_function(&RiscVZvtVtfmm); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, + VtfmmAltUnmappedTopologyTrapsIllegalInstruction) { + // SEW=8 TWIDEN=2 is unmapped for vtfmm.alt.tvv (which requires TWIDEN=4 for + // SEW=8) + matrix_state_->set_mtype(EncodeMtype(kMtwiden2)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->Submit(); + + ScopedTrapCapture trap_capture(state_.get()); + + AppendMatmulSources(/*reg_a=*/8, /*reg_b=*/16, /*dest_tile=*/0); + instruction_->set_semantic_function(&RiscVZvtVtfmmAlt); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmSew32IntermediateRoundingTdd) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_fs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + matrix_state_->set_tile_m(2); + matrix_state_->set_tile_k(1); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew32, kVlmul1)); + + // A = 1 + 2^-12, B = 1 + 2^-12. Product = 1 + 2^-11 + 2^-24. + // TEW=32 rounding should truncate the 2^-24 before accumulation. + + std::vector<RegisterBase*> reg_vec_a; + for (int i = 0; i < 8; i++) { + reg_vec_a.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 8 + i)).first); + } + auto* src_op_a = new RV32VectorSourceOperand(absl::MakeSpan(reg_vec_a), "v8"); + instruction_->AppendSource(src_op_a); + + std::vector<RegisterBase*> reg_vec_b; + for (int i = 0; i < 8; i++) { + reg_vec_b.push_back( + state_->GetRegister<RVVectorRegister>(absl::StrCat("v", 16 + i)).first); + } + auto* src_op_b = + new RV32VectorSourceOperand(absl::MakeSpan(reg_vec_b), "v16"); + instruction_->AppendSource(src_op_b); + + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/0)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/16)); + + instruction_->set_semantic_function(&RiscVZvtVtfmm); + instruction_->Execute(nullptr); +} + +TEST_F(RiscVZvtInstructionsTest, VtDiscardDowngradesToInitialState) { + state_->mstatus()->set_ms(kMstatusStateDirty); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + vector_state_->SetVectorType(EncodeVtype(kVsew32, kVlmul1)); + + instruction_->set_semantic_function(&RiscVZvtVtDiscard); + instruction_->Execute(nullptr); + + EXPECT_EQ(state_->mstatus()->ms(), kMstatusStateInitial); + EXPECT_EQ(state_->mstatus()->vs(), + kMstatusStateDirty); // Clearing vstart dirties VS. +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmDirtiesMstatusFsOnMatmul) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->set_fs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + matrix_state_->set_tile_m(2); + matrix_state_->set_tile_k(1); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew32, kVlmul1)); + + AppendMatmulSources(/*reg_a=*/8, /*reg_b=*/16, /*dest_tile=*/0); + + instruction_->set_semantic_function(&RiscVZvtVtfmm); + instruction_->Execute(nullptr); + + EXPECT_EQ(state_->mstatus()->fs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, VtzeroTrapReservedTile) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->Submit(); + + // Configure TEW=32 (SEW=8, TWIDEN=4 -> mtwiden=2) + matrix_state_->set_mtype(EncodeMtype(kMtwiden2)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + + // For TEW=32, valid canonical tiles are multiples of 4 (0, 4, 8, 12). + // Pass tile=1 (reserved / non-canonical) to trigger illegal instruction trap. + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/1)); + + ScopedTrapCapture trap_capture(state_.get()); + + instruction_->set_semantic_function(&RiscVZvtVtZero); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtleReservedTssTrapOverMisalignedTrap) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/0, /*tm=*/0, + /*vstart=*/2); + + ScopedTrapCapture trap_capture(state_.get()); + constexpr uint64_t kBaseAddr = 0x2001; // Misaligned address. + + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/32, kBaseAddr, + EncodeTss(/*tile=*/1, kTssPatternInvalid, /*index=*/2)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); + EXPECT_EQ(trap_capture.trap_value(), 0); +} + +TEST_F(RiscVZvtInstructionsTest, VtseReservedTssTrapOverMisalignedTrap) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/0, /*tm=*/0, + /*vstart=*/2); + + ScopedTrapCapture trap_capture(state_.get()); + constexpr uint64_t kBaseAddr = 0x2001; // Misaligned address. + + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/32, kBaseAddr, + EncodeTss(/*tile=*/1, kTssPatternInvalid, /*index=*/2)); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); + EXPECT_EQ(trap_capture.trap_value(), 0); +} + +TEST_F(RiscVZvtInstructionsTest, VtleVstartGreaterOrEqualCountSkipLimit) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/0, /*tm=*/0, + /*vstart=*/200); + + ScopedTrapCapture trap_capture(state_.get()); + constexpr uint64_t kBaseAddr = 0x2001; // Misaligned address. + + ExecuteTileMemoryOp(&RiscVZvtVtle, /*eew=*/32, kBaseAddr, + EncodeTss(/*tile=*/0, kTssPatternRow, /*index=*/2)); + + EXPECT_FALSE(trap_capture.trap_taken()); + EXPECT_EQ(vector_state_->vstart(), 0); + EXPECT_EQ(state_->mstatus()->vs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, VtseVstartGreaterOrEqualCountSkipLimit) { + ConfigureMatrixUnit(kMtwiden1, kVsew32, kVlmul1, /*vl=*/4, /*tk=*/0, /*tm=*/0, + /*vstart=*/200); + + ScopedTrapCapture trap_capture(state_.get()); + constexpr uint64_t kBaseAddr = 0x2001; // Misaligned address. + + ExecuteTileMemoryOp(&RiscVZvtVtse, /*eew=*/32, kBaseAddr, + EncodeTss(/*tile=*/0, kTssPatternRow, /*index=*/2)); + + EXPECT_FALSE(trap_capture.trap_taken()); + EXPECT_EQ(vector_state_->vstart(), 0); + EXPECT_EQ(state_->mstatus()->vs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmTrapWhenMtwidenNotZeroAndUnaligned) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->set_fs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + // mtwiden = 2 -> TWIDEN = 2, tew = 32, align = 4 + matrix_state_->set_mtype(EncodeMtype(kMtwiden2)); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew16, kVlmul1)); + + ScopedTrapCapture trap_capture(state_.get()); + + AppendVectorGroupSource(/*base_reg=*/8); + AppendVectorGroupSource(/*base_reg=*/8); + // Unaligned tile_d. + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + instruction_->set_semantic_function(&RiscVZvtVtfmm); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmAltTrapWhenMtwidenNotZeroAndUnaligned) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->set_fs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + matrix_state_->set_mtype(EncodeMtype(kMtwiden2)); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew16, kVlmul1, /*vta=*/false, + /*vma=*/false, /*altfmt=*/true)); + + ScopedTrapCapture trap_capture(state_.get()); + + AppendVectorGroupSource(/*base_reg=*/8); + AppendVectorGroupSource(/*base_reg=*/8); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + instruction_->set_semantic_function(&RiscVZvtVtfmmAlt); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmuTrapWhenMtwidenNotZeroAndUnaligned) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + // mtwiden = 3 -> TWIDEN = 4, tew = 32, align = 4 + matrix_state_->set_mtype(EncodeMtype(kMtwiden4)); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + + ScopedTrapCapture trap_capture(state_.get()); + + AppendVectorGroupSource(/*base_reg=*/8); + AppendVectorGroupSource(/*base_reg=*/8); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + instruction_->set_semantic_function(&RiscVZvtVtmmu); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmsTrapWhenMtwidenNotZeroAndUnaligned) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + matrix_state_->set_mtype(EncodeMtype(kMtwiden4)); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + + ScopedTrapCapture trap_capture(state_.get()); + + AppendVectorGroupSource(/*base_reg=*/8); + AppendVectorGroupSource(/*base_reg=*/8); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + instruction_->set_semantic_function(&RiscVZvtVtmms); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmuUnmappedTopologyTrapsIllegalInstruction) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden2)); + vector_state_->SetVectorType(EncodeVtype(kVsew16, kVlmul1)); + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->Submit(); + + ScopedTrapCapture trap_capture(state_.get()); + + AppendVectorGroupSource(/*base_reg=*/8); + AppendVectorGroupSource(/*base_reg=*/8); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + instruction_->set_semantic_function(&RiscVZvtVtmmu); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmsUnmappedTopologyTrapsIllegalInstruction) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden2)); + vector_state_->SetVectorType(EncodeVtype(kVsew16, kVlmul1)); + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->Submit(); + + ScopedTrapCapture trap_capture(state_.get()); + + AppendVectorGroupSource(/*base_reg=*/8); + AppendVectorGroupSource(/*base_reg=*/8); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*tile_d=*/1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs1=*/8)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(/*vs2=*/8)); + + instruction_->set_semantic_function(&RiscVZvtVtmms); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmuMappedTopologyComputesCorrectly) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden4)); + matrix_state_->set_tile_m(1); + matrix_state_->set_tile_k(2); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + ASSERT_OK(matrix_state_->SetElem<int32_t>( + /*tile=*/0, /*row=*/0, /*col=*/0, /*element_width_in_bits=*/32, + /*value=*/0)); + + ScopedTrapCapture trap_capture(state_.get()); + + auto* reg_v8 = state_->GetRegister<RVVectorRegister>("v8").first; + auto span_v8 = reg_v8->data_buffer()->Get<uint8_t>(); + span_v8[0] = 2; + span_v8[1] = 3; + + auto* reg_v16 = state_->GetRegister<RVVectorRegister>("v16").first; + auto span_v16 = reg_v16->data_buffer()->Get<uint8_t>(); + span_v16[0] = 4; + span_v16[1] = 5; + + AppendMatmulSources(/*reg_a=*/8, /*reg_b=*/16, /*dest_tile=*/0); + + instruction_->set_semantic_function(&RiscVZvtVtmmu); + instruction_->Execute(nullptr); + + EXPECT_FALSE(trap_capture.trap_taken()); + ASSERT_OK_AND_ASSIGN(auto elem, matrix_state_->GetElem<int32_t>( + /*tile=*/0, /*row=*/0, /*col=*/0, + /*element_width_in_bits=*/32)); + EXPECT_EQ(elem, 8); +} + +TEST_F(RiscVZvtInstructionsTest, VtmmsMappedTopologyComputesCorrectly) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden4)); + matrix_state_->set_tile_m(1); + matrix_state_->set_tile_k(2); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->Submit(); + + ASSERT_OK(matrix_state_->SetElem<int32_t>( + /*tile=*/0, /*row=*/0, /*col=*/0, /*element_width_in_bits=*/32, + /*value=*/0)); + + ScopedTrapCapture trap_capture(state_.get()); + + auto* reg_v8 = state_->GetRegister<RVVectorRegister>("v8").first; + auto span_v8 = reg_v8->data_buffer()->Get<int8_t>(); + span_v8[0] = -2; + span_v8[1] = 3; + + auto* reg_v16 = state_->GetRegister<RVVectorRegister>("v16").first; + auto span_v16 = reg_v16->data_buffer()->Get<int8_t>(); + span_v16[0] = 4; + span_v16[1] = -5; + + AppendMatmulSources(/*reg_a=*/8, /*reg_b=*/16, /*dest_tile=*/0); + + instruction_->set_semantic_function(&RiscVZvtVtmms); + instruction_->Execute(nullptr); + + EXPECT_FALSE(trap_capture.trap_taken()); + ASSERT_OK_AND_ASSIGN(auto elem, matrix_state_->GetElem<int32_t>( + /*tile=*/0, /*row=*/0, /*col=*/0, + /*element_width_in_bits=*/32)); + EXPECT_EQ(elem, -8); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmTrapWhenFpStateOff) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->set_fs(kMstatusStateOff); // FS Off -> must trap! + state_->mstatus()->Submit(); + + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + matrix_state_->set_tile_m(2); + matrix_state_->set_tile_k(1); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew32, kVlmul1)); + + ScopedTrapCapture trap_capture(state_.get()); + + AppendMatmulSources(/*reg_a=*/8, /*reg_b=*/16, /*dest_tile=*/0); + + instruction_->set_semantic_function(&RiscVZvtVtfmm); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + +TEST_F(RiscVZvtInstructionsTest, VtfmmAltTrapWhenFpStateOff) { + state_->mstatus()->set_ms(kMstatusStateInitial); + state_->mstatus()->set_vs(kMstatusStateInitial); + state_->mstatus()->set_fs(kMstatusStateOff); // FS Off -> must trap! + state_->mstatus()->Submit(); + + matrix_state_->set_mtype(EncodeMtype(kMtwiden4)); + matrix_state_->set_tile_m(2); + matrix_state_->set_tile_k(1); + vector_state_->set_vector_length(2); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + + ScopedTrapCapture trap_capture(state_.get()); + + AppendMatmulSources(/*reg_a=*/8, /*reg_b=*/16, /*dest_tile=*/0); + + instruction_->set_semantic_function(&RiscVZvtVtfmmAlt); + instruction_->Execute(nullptr); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), *ExceptionCode::kIllegalInstruction); +} + } // namespace