No public description PiperOrigin-RevId: 1009112258 Change-Id: Ia8ef5890bef5e8d69d2c2bac06ff9c11950e0289
diff --git a/MODULE.bazel b/MODULE.bazel index d0e4c32..0f93867 100644 --- a/MODULE.bazel +++ b/MODULE.bazel
@@ -20,7 +20,7 @@ # Core Dependencies bazel_dep( name = "mpact-sim", - version = "1.0.2", + version = "1.0.3", ) bazel_dep( name = "abseil-cpp",
diff --git a/README.md b/README.md index ae27dcc..e5429d4 100644 --- a/README.md +++ b/README.md
@@ -21,10 +21,10 @@ MPACT-Sim utilizes the [Bazel](https://bazel.build/) build system. The easiest way to install bazel is to use [Bazelisk](https://github.com/bazelbuild/bazelisk), a wrapper for Bazel that -automates selecting and downloading the right version of bazel. Use `brew -install bazelisk` on macOS, `choco install bazelisk` on Windows, and on linux, -download the Bazelisk binary, add it to your `PATH`, then alias bazel to the -bazelisk binary. +automates selecting and downloading the right version of bazel. Use +`brew install bazelisk` on macOS, `choco install bazelisk` on Windows, and on +linux, download the Bazelisk binary, add it to your `PATH`, then alias bazel to +the bazelisk binary. ### Java @@ -38,8 +38,9 @@ `bazel build ...:all` from the top level directory. To run the tests, use the command `bazel test ...:all`. -For Apple computers with Arm64 M series chips, use `bazel build ---cpu=darwin_arm64 ...:all` and `bazel test --cpu=darwin_arm64 ...:all`. +For Apple computers with Arm64 M series chips, use +`bazel build --cpu=darwin_arm64 ...:all` and +`bazel test --cpu=darwin_arm64 ...:all`. The build targets `rv32g_sim` and `rv64g_sim` provide RiscV simulators for the 32 bit and 64 bit variants of RiscV scalar architectures respectively. Decoding
diff --git a/riscv/BUILD b/riscv/BUILD index aa9aee9..40598c6 100644 --- a/riscv/BUILD +++ b/riscv/BUILD
@@ -28,6 +28,7 @@ exports_files([ "riscv_zvt.isa", "riscv_zvt.bin_fmt", + "riscv_zvt_decoder.bin_fmt", "riscv_zicbom.isa", "riscv_zicbom.bin_fmt", "riscv_zicboz.isa", @@ -104,6 +105,7 @@ "@abseil-cpp//absl/functional:any_invocable", "@abseil-cpp//absl/log", "@abseil-cpp//absl/log:check", + "@abseil-cpp//absl/numeric:int128", "@abseil-cpp//absl/status", "@abseil-cpp//absl/status:statusor", "@abseil-cpp//absl/strings", @@ -1761,19 +1763,23 @@ cc_library( name = "riscv_zvt_instructions", srcs = ["riscv_zvt_instructions.cc"], - hdrs = ["riscv_zvt_instructions.h"], + hdrs = [ + "riscv_instruction_helpers.h", + "riscv_zvt_instructions.h", + ], copts = ["-O3"], deps = [ + ":riscv_fp_state", ":riscv_state", ":riscv_zvt_state", "@abseil-cpp//absl/base", "@abseil-cpp//absl/log", - "@abseil-cpp//absl/status", - "@abseil-cpp//absl/status:statusor", - "@abseil-cpp//absl/strings", + "@abseil-cpp//absl/log:absl_check", "@abseil-cpp//absl/types:span", + "@mpact-sim//mpact/sim/generic:arch_state", "@mpact-sim//mpact/sim/generic:core", "@mpact-sim//mpact/sim/generic:instruction", + "@mpact-sim//mpact/sim/generic:type_helpers", ], ) @@ -1792,3 +1798,33 @@ "@mpact-sim//mpact/sim/generic:type_helpers", ], ) + +mpact_isa_decoder( + name = "riscv_zvt_isa", + src = "riscv_zvt.isa", + includes = [], + isa_name = "RiscVZvt", + prefix = "riscv_zvt", + deps = [ + ":riscv_g", + ":riscv_zvt_instructions", + "@abseil-cpp//absl/functional:bind_front", + ], +) + +mpact_bin_fmt_decoder( + name = "riscv_zvt_bin_fmt", + src = "riscv_zvt_decoder.bin_fmt", + decoder_name = "RiscVZvt", + includes = [ + "riscv32g.bin_fmt", + "riscv_format16.bin_fmt", + "riscv_format32.bin_fmt", + "riscv_vector.bin_fmt", + "riscv_zvt.bin_fmt", + ], + prefix = "riscv_zvt", + deps = [ + ":riscv_zvt_isa", + ], +)
diff --git a/riscv/riscv32gzb_vec_encoding.cc b/riscv/riscv32gzb_vec_encoding.cc index 99b3b35..09d7c9e 100644 --- a/riscv/riscv32gzb_vec_encoding.cc +++ b/riscv/riscv32gzb_vec_encoding.cc
@@ -35,7 +35,7 @@ namespace mpact::sim::riscv::isa32gvzb { -using ::mpact::sim::generic::operator*; // NOLINT: clang-tidy false positive. +using ::mpact::sim::generic::operator*; // NOLINT(misc-unused-using-decls) RiscV32GZBVecEncoding::RiscV32GZBVecEncoding(RiscVState* state) : state_(state), @@ -79,6 +79,7 @@ source_op_getters_, this); AddRiscVVectorDestGetters<DestOpEnum, Extractors, RVVectorRegister>( dest_op_getters_, this); + // Verify that there are getters for each enum value. for (int i = *SourceOpEnum::kNone; i < *SourceOpEnum::kPastMaxValue; ++i) { if (source_op_getters_.find(i) == source_op_getters_.end()) {
diff --git a/riscv/riscv_format32.bin_fmt b/riscv/riscv_format32.bin_fmt index e3c38bb..a841d36 100644 --- a/riscv/riscv_format32.bin_fmt +++ b/riscv/riscv_format32.bin_fmt
@@ -258,3 +258,17 @@ // Named tile index (mt0..mt15): rd[11:8], i.e. mtd[4..1]. unsigned mtile[4] = mtd[4..1]; }; + +format MsetmtypeiFormat[32] : Inst32Format { + fields: + unsigned opc1[3]; + unsigned altfmt[1]; + unsigned opc2[3]; + unsigned vsew[2]; + unsigned opc3[3]; + unsigned opc4[3]; + unsigned mtwiden[2]; + unsigned func3[3]; + unsigned rd[5]; + unsigned opcode[7]; +};
diff --git a/riscv/riscv_instruction_helpers.h b/riscv/riscv_instruction_helpers.h index 1e8813d..1564eb9 100644 --- a/riscv/riscv_instruction_helpers.h +++ b/riscv/riscv_instruction_helpers.h
@@ -18,6 +18,7 @@ #include <cmath> #include <cstddef> #include <cstdint> +#include <cstring> #include <functional> #include <limits> #include <tuple> @@ -765,6 +766,24 @@ return sign ? 1 << 1 : 1 << 6; } +// Converts a double-precision floating-point value to single-precision float +// using Round to Odd (ROD) / jamming rounding mode. +// If 'fp_state' is null, falls back to standard static_cast conversion. +inline float DoubleToFloatROD(double d, RiscVFPState* fp_state) { + if (!fp_state) return static_cast<float>(d); + + ScopedFPRoundingMode scoped_rm(fp_state->host_fp_interface(), + FPRoundingMode::kRoundTowardsZero); + float f = static_cast<float>(d); + if (std::isfinite(d) && static_cast<double>(f) != d) { + uint32_t f_bits = 0; + std::memcpy(&f_bits, &f, sizeof(f)); + f_bits |= 1; + std::memcpy(&f, &f_bits, sizeof(f)); + } + return f; +} + } // namespace riscv } // namespace sim } // namespace mpact
diff --git a/riscv/riscv_zvt.bin_fmt b/riscv/riscv_zvt.bin_fmt index dde5ca3..5837da4 100644 --- a/riscv/riscv_zvt.bin_fmt +++ b/riscv/riscv_zvt.bin_fmt
@@ -15,14 +15,21 @@ // Matrix configuration instructions, encoded in the vector-configuration // (OP-V) major opcode like the vset* family (spec 15.1.1.4). They are // distinguished from vsetvl (func7 == 0b100'0000) by func7: -// msetmtype func7 == 0b100'0001 +// msetmtype func7 == 0b100'0010 // msettn/tm/tk func7 == 0b100'0010, selected by the low rs2 bits. instruction group RiscVZvtInst32[32] : Inst32Format { + msetmtype : VConfig : func7 == 0b100'0010, rd == 0b00000, func3 == 0b111, opcode == 0b101'0111; + msetmtypei : MsetmtypeiFormat : opc1 == 0b100, opc2 == 0b100, opc3 == 0b100, opc4 == 0b000, func3 == 0b111, rd == 0b00000, opcode == 0b101'0111; + msettn : VConfig : func7 == 0b100'0100, rs2 == 0b00000, func3 == 0b111, opcode == 0b101'0111; + msettm : VConfig : func7 == 0b100'0100, rs2 == 0b00001, func3 == 0b111, opcode == 0b101'0111; + msettk : VConfig : func7 == 0b100'0100, rs2 == 0b00010, func3 == 0b111, opcode == 0b101'0111; + + // Legacy Zvt v0.3 compatibility encodings for unmigrated leaf simulators (coralnpu_m4). msetmtype : VConfig : func7 == 0b100'0001, func3 == 0b111, opcode == 0b101'0111; - msettn : VConfig : func7 == 0b100'0010, rs2 == 0b00000, func3 == 0b111, opcode == 0b101'0111; - msettm : VConfig : func7 == 0b100'0010, rs2 == 0b00001, func3 == 0b111, opcode == 0b101'0111; - msettk : VConfig : func7 == 0b100'0010, rs2 == 0b00010, func3 == 0b111, opcode == 0b101'0111; + msettn : VConfig : func7 == 0b100'0010, rs2 == 0b00000, rd != 0, func3 == 0b111, opcode == 0b101'0111; + msettm : VConfig : func7 == 0b100'0010, rs2 == 0b00001, rd != 0, func3 == 0b111, opcode == 0b101'0111; + msettk : VConfig : func7 == 0b100'0010, rs2 == 0b00010, rd != 0, func3 == 0b111, opcode == 0b101'0111; // Tile manipulation (OP-V, func3 == 0b110). vtmv_v_t : VArith : func6 == 0b010'000, vs2 == 0b11111, func3 == 0b110, opcode == 0b101'0111;
diff --git a/riscv/riscv_zvt.isa b/riscv/riscv_zvt.isa index db77d9e..882d6f3 100644 --- a/riscv/riscv_zvt.isa +++ b/riscv/riscv_zvt.isa
@@ -12,16 +12,31 @@ // See the License for the specific language governing permissions and // limitations under the License. +isa RiscVZvt { + namespace mpact::sim::riscv::zvt; + slots { + riscv_zvt; + } +} + // Zvtbase matrix configuration instructions (spec 15.1.1.4). slot riscv_zvt { includes { + #include "absl/functional/bind_front.h" + #include "riscv/riscv_i_instructions.h" #include "riscv/riscv_zvt_instructions.h" } default size = 4; + default opcode = + disasm: "Illegal instruction at 0x%(@:08x)", + semfunc: "&::mpact::sim::riscv::RiscVIllegalInstruction"; opcodes { msetmtype{: rs1, rs2 : }, disasm: "msetmtype", "%rs1, %rs2", semfunc: "&::mpact::sim::riscv::RiscVZvtMsetMtype"; + msetmtypei{: mtwiden, vsew, altfmt : }, + disasm: "msetmtypei", "%mtwiden, %vsew, %altfmt", + semfunc: "&::mpact::sim::riscv::RiscVZvtMsetMtypei"; msettn{: rs1 : rd}, disasm: "msettn", "%rd, %rs1", semfunc: "&::mpact::sim::riscv::RiscVZvtMsetTn"; @@ -33,8 +48,8 @@ semfunc: "&::mpact::sim::riscv::RiscVZvtMsetTk"; // Tile manipulation. - vtzero{: mtd : }, - disasm: "vtzero", "%mtd", + vtzero{: mtile : }, + disasm: "vtzero", "%mtile", semfunc: "&::mpact::sim::riscv::RiscVZvtVtZero"; vtdiscard{: : }, disasm: "vtdiscard", @@ -73,17 +88,17 @@ semfunc: "absl::bind_front(&::mpact::sim::riscv::RiscVZvtVtse, 64)"; // Matrix multiply: C += A^T * B. - vtmms_tvv{: matA, matB, mtd : }, - disasm: "vtmms.tvv", "%mtd, %matA, %matB", - semfunc: "absl::bind_front(&::mpact::sim::riscv::RiscVZvtMatmul, ::mpact::sim::riscv::RiscVZvtMatmulKind::kInt8Signed)"; - vtmmu_tvv{: matA, matB, mtd : }, - disasm: "vtmmu.tvv", "%mtd, %matA, %matB", - semfunc: "absl::bind_front(&::mpact::sim::riscv::RiscVZvtMatmul, ::mpact::sim::riscv::RiscVZvtMatmulKind::kInt8Unsigned)"; - vtfmm_tvv{: matA, matB, mtd : fflags}, - disasm: "vtfmm.tvv", "%mtd, %matA, %matB", - semfunc: "absl::bind_front(&::mpact::sim::riscv::RiscVZvtMatmul, ::mpact::sim::riscv::RiscVZvtMatmulKind::kFp32)"; - vtfmm_alt_tvv{: matA, matB, mtd : fflags}, - disasm: "vtfmm.alt.tvv", "%mtd, %matA, %matB", - semfunc: "absl::bind_front(&::mpact::sim::riscv::RiscVZvtMatmul, ::mpact::sim::riscv::RiscVZvtMatmulKind::kBf16)"; + vtmms_tvv{: matA, matB, mtile, vs2_idx, vs1_idx : }, + disasm: "vtmms.tvv", "%mtile, %matA, %matB", + semfunc: "&::mpact::sim::riscv::RiscVZvtVtmms"; + vtmmu_tvv{: matA, matB, mtile, vs2_idx, vs1_idx : }, + disasm: "vtmmu.tvv", "%mtile, %matA, %matB", + semfunc: "&::mpact::sim::riscv::RiscVZvtVtmmu"; + vtfmm_tvv{: matA, matB, mtile, vs2_idx, vs1_idx : fflags}, + disasm: "vtfmm.tvv", "%mtile, %matA, %matB", + semfunc: "&::mpact::sim::riscv::RiscVZvtVtfmm"; + vtfmm_alt_tvv{: matA, matB, mtile, vs2_idx, vs1_idx : fflags}, + disasm: "vtfmm.alt.tvv", "%mtile, %matA, %matB", + semfunc: "&::mpact::sim::riscv::RiscVZvtVtfmmAlt"; } }
diff --git a/riscv/riscv_zvt_decoder.bin_fmt b/riscv/riscv_zvt_decoder.bin_fmt new file mode 100644 index 0000000..2ba09d4 --- /dev/null +++ b/riscv/riscv_zvt_decoder.bin_fmt
@@ -0,0 +1,28 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "riscv32g.bin_fmt" +#include "riscv_vector.bin_fmt" +#include "riscv_zvt.bin_fmt" + +decoder RiscVZvt { + namespace mpact::sim::riscv::zvt; + opcode_enum = "OpcodeEnum"; + includes { + #include "riscv/riscv_zvt_enums.h" + } + ZvtInst32 = { + RiscVZvtInst32, + }; +}
diff --git a/riscv/riscv_zvt_getters.h b/riscv/riscv_zvt_getters.h index cabe02b..b9f101b 100644 --- a/riscv/riscv_zvt_getters.h +++ b/riscv/riscv_zvt_getters.h
@@ -29,7 +29,6 @@ #include "mpact/sim/generic/immediate_operand.h" #include "mpact/sim/generic/operand_interface.h" #include "mpact/sim/generic/register.h" -#include "mpact/sim/generic/type_helpers.h" #include "riscv/riscv_encoding_common.h" #include "riscv/riscv_getter_helpers.h" #include "riscv/riscv_register.h" @@ -78,13 +77,14 @@ // eight-register group, per spec 15.1.1.3). inline constexpr int kRiscVZvtMatrixGroupRegs = 8; +// Registers operand getters for Zvt source operands into 'getter_map'. template <typename SourceOpEnum, typename Extractors> void AddRiscVZvtSourceGetters( ::mpact::sim::riscv::SourceOpGetterMap& getter_map, ::mpact::sim::riscv::RiscVEncodingCommon* common) { using ::mpact::sim::generic::ImmediateOperand; + using ::mpact::sim::generic::operator*; // NOLINT(misc-unused-using-decls) using ::mpact::sim::generic::SourceOperandInterface; - using ::mpact::sim::generic::operator*; // NOLINT using ::mpact::sim::riscv::Insert; using ::mpact::sim::riscv::RVVectorRegister; @@ -103,18 +103,48 @@ common->state(), num, kRiscVZvtMatrixGroupRegs); }); // Destination tile specifier (named tile index, 0..15) from the rd MSBs. - Insert(getter_map, *SourceOpEnum::kMtd, + Insert(getter_map, *SourceOpEnum::kMtile, [common]() -> SourceOperandInterface* { int tile = Extractors::VMatrix::ExtractMtile(common->inst_word()); return new ImmediateOperand<uint32_t>(tile); }); + // Register indices for matrix operands vs2 and vs1 extracted at decode time. + Insert(getter_map, *SourceOpEnum::kVs2Idx, + [common]() -> SourceOperandInterface* { + int num = Extractors::VMatrix::ExtractVs2(common->inst_word()); + return new ImmediateOperand<uint32_t>(num); + }); + Insert(getter_map, *SourceOpEnum::kVs1Idx, + [common]() -> SourceOperandInterface* { + int num = Extractors::VMatrix::ExtractVs1(common->inst_word()); + return new ImmediateOperand<uint32_t>(num); + }); + Insert(getter_map, *SourceOpEnum::kMtwiden, + [common]() -> SourceOperandInterface* { + int mtwiden = Extractors::MsetmtypeiFormat::ExtractMtwiden( + common->inst_word()); + return new ImmediateOperand<uint32_t>(mtwiden); + }); + Insert(getter_map, *SourceOpEnum::kVsew, + [common]() -> SourceOperandInterface* { + int vsew = + Extractors::MsetmtypeiFormat::ExtractVsew(common->inst_word()); + return new ImmediateOperand<uint32_t>(vsew); + }); + Insert(getter_map, *SourceOpEnum::kAltfmt, + [common]() -> SourceOperandInterface* { + int altfmt = + Extractors::MsetmtypeiFormat::ExtractAltfmt(common->inst_word()); + return new ImmediateOperand<uint32_t>(altfmt); + }); } +// Registers operand getters for Zvt destination operands into 'getter_map'. template <typename DestOpEnum, typename Extractors> void AddRiscVZvtDestGetters(::mpact::sim::riscv::DestOpGetterMap& getter_map, ::mpact::sim::riscv::RiscVEncodingCommon* common) { using ::mpact::sim::generic::DestinationOperandInterface; - using ::mpact::sim::generic::operator*; // NOLINT + using ::mpact::sim::generic::operator*; // NOLINT(misc-unused-using-decls) using ::mpact::sim::riscv::Insert; using ::mpact::sim::riscv::RVVectorRegister;
diff --git a/riscv/riscv_zvt_instructions.cc b/riscv/riscv_zvt_instructions.cc index 2975cba..8b62189 100644 --- a/riscv/riscv_zvt_instructions.cc +++ b/riscv/riscv_zvt_instructions.cc
@@ -17,15 +17,16 @@ #include <algorithm> #include <cstdint> #include <cstring> +#include <optional> -#include "absl/base/casts.h" #include "absl/log/log.h" -#include "absl/status/status.h" -#include "absl/status/statusor.h" -#include "absl/strings/str_cat.h" #include "absl/types/span.h" #include "mpact/sim/generic/data_buffer.h" #include "mpact/sim/generic/instruction.h" +#include "mpact/sim/generic/type_helpers.h" +#include "riscv/riscv_fp_host.h" +#include "riscv/riscv_fp_state.h" +#include "riscv/riscv_instruction_helpers.h" #include "riscv/riscv_register.h" #include "riscv/riscv_state.h" #include "riscv/riscv_vector_state.h" @@ -35,106 +36,216 @@ using ::mpact::sim::generic::DataBuffer; using ::mpact::sim::generic::GetInstructionSource; -using ::mpact::sim::generic::operator*; // NOLINT +using ::mpact::sim::generic::operator*; // NOLINT(misc-unused-using-decls) + using ::mpact::sim::riscv::RiscVVectorState; using ::mpact::sim::riscv::RV32VectorDestinationOperand; using ::mpact::sim::riscv::RV32VectorSourceOperand; namespace { -// ELEN for the Zve32{x,f} kBase. +// Returns whether the vill bit is set in vtype. +// TODO(b/575522744): Per RISC-V Vector Spec 1.0 (Section 3.1.2 & 3.4.4), vill +// 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; + 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) { + switch (vector_state->selected_element_width()) { + case 1: + return 8; + case 2: + return 16; + case 4: + return 32; + case 8: + return 64; + default: + return 0; + } +} + +// Calculates the tile element width (TEW) in bits from 'sew_bits' and 'twiden'. +inline int CalculateTew(int sew_bits, int twiden) { + switch (twiden) { + case 1: + return sew_bits; + case 2: + return sew_bits << 1; + case 4: + return sew_bits << 2; + default: + return 0; + } +} + +// ELEN for the Zve32{x,f} base. constexpr int kElen = 32; -// Decoded kTile subset specifier (TSS). Spec 15.1.1.5. +// Represents a decoded Tile Subset Specifier (TSS, per spec 15.1.1.5). struct Tss { - int kTile; // bits[30:27] + int tile; // bits[30:27] int pattern; // bits[26:24]: 0 = row, 1 = col. uint32_t index; // bits[23:0]. }; -Tss DecodeTss(uint32_t tss) { +// 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{ - .kTile = static_cast<int>((tss >> 27) & 0xF), + .tile = + matrix_state->MaskTssTile(static_cast<int>((tss >> 27) & 0xF), tew), .pattern = static_cast<int>((tss >> 24) & 0x7), .index = tss & 0xFFFFFF, }; } -constexpr int kTssPatternCol = 1; // pattern 0 = row (the default branch). +constexpr int kTssPatternCol = 1; -// Reinterprets the low 16 bits of a bf16 value as the high half of an fp32. -float Bf16ToF32(uint16_t bits) { - uint32_t u = static_cast<uint32_t>(bits) << 16; - return absl::bit_cast<float>(u); -} - -// Reads kTile element (row,col) of `kTile` at width `tile_element_width` as a -// generic 64-bit container, and the inverse. Used by the move/load/store paths -// which carry the element width dynamically. -uint64_t LoadTileBits(RiscVZvtMatrixState* matrix_state, int kTile, int row, - int col, int tile_element_width) { - const int kEffectiveTileEdge = tile_element_width < 64 - ? matrix_state->tile_elements() - : matrix_state->tile_elements() / 2; - if (row < 0 || row >= kEffectiveTileEdge || col < 0 || - col >= kEffectiveTileEdge) { - return 0; - } - auto load_elem = [](auto status_or_val) -> uint64_t { - if (!status_or_val.ok()) { - LOG(ERROR) << status_or_val.status(); - return 0; - } - return static_cast<uint64_t>(*status_or_val); - }; - switch (tile_element_width) { - case 8: - return load_elem(matrix_state->GetElem<uint8_t>(kTile, row, col, 8)); - case 16: - return load_elem(matrix_state->GetElem<uint16_t>(kTile, row, col, 16)); - case 32: - return load_elem(matrix_state->GetElem<uint32_t>(kTile, row, col, 32)); - case 64: - return load_elem(matrix_state->GetElem<uint64_t>(kTile, row, col, 64)); - default: - LOG(ERROR) << "Invalid tile element width: " << tile_element_width; - return 0; - } -} - -void StoreTileBits(RiscVZvtMatrixState* matrix_state, int kTile, int row, - int col, int tile_element_width, uint64_t value) { - const int kEffectiveTileEdge = tile_element_width < 64 - ? matrix_state->tile_elements() - : matrix_state->tile_elements() / 2; - if (row < 0 || row >= kEffectiveTileEdge || col < 0 || - col >= kEffectiveTileEdge) { +// 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; + const int sew_bits = GetSewBits(vector_state); + if ((vector_state->vtype() >> vill_shift) || sew_bits == 0) { + matrix_state->set_mtype(0); return; } - absl::Status status; - switch (tile_element_width) { + 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); + + int max_k_lmul_num = 8; + int max_k_lmul_den = max_k; + int ete_eve_lmul_num = effective_tile_elements; + int ete_eve_lmul_den = vector_state->vector_register_byte_length() / + vector_state->selected_element_width(); + int ceil_ete_eve = + (ete_eve_lmul_num + ete_eve_lmul_den - 1) / ete_eve_lmul_den; + + int vlmul_max_k = (8 * max_k_lmul_num) / max_k_lmul_den; + int vlmul_ete_eve = 8 * ceil_ete_eve; + + // Per Zvt v0.4 spec 15.1.1.4: target LMUL is min(LMUL_max_k, LMUL_twiden, + // LMUL_ete_eve). With kElen = 32, LMUL_twiden (64 / twiden) is mathematically + // >= LMUL_max_k (64 / max_k = 2 * SEW) for all non-vill configurations + // where SEW * twiden <= 32, making it strictly dominated by LMUL_max_k. + int target_vlmul_scaled = std::min(vlmul_max_k, vlmul_ete_eve); + if (target_vlmul_scaled < 1) target_vlmul_scaled = 1; + if (target_vlmul_scaled > 64) target_vlmul_scaled = 64; + + uint32_t vlmul_enc = 0; + switch (target_vlmul_scaled) { + case 1: + vlmul_enc = 5; + break; + case 2: + vlmul_enc = 6; + break; + case 4: + vlmul_enc = 7; + break; case 8: - status = matrix_state->SetElem<uint8_t>(kTile, row, col, 8, - static_cast<uint8_t>(value)); + vlmul_enc = 0; break; case 16: - status = matrix_state->SetElem<uint16_t>(kTile, row, col, 16, - static_cast<uint16_t>(value)); + vlmul_enc = 1; break; case 32: - status = matrix_state->SetElem<uint32_t>(kTile, row, col, 32, - static_cast<uint32_t>(value)); + vlmul_enc = 2; break; case 64: - status = matrix_state->SetElem<uint64_t>(kTile, row, col, 64, value); + vlmul_enc = 3; break; default: - status = absl::InvalidArgumentError( - absl::StrCat("Invalid tile element width: ", tile_element_width)); + vlmul_enc = 0; break; } - if (!status.ok()) { - LOG(ERROR) << status; + + uint32_t new_vtype = + (vector_state->vtype() & ~0x7u) | vlmul_enc | (1u << 6) | (1u << 7); + vector_state->SetVectorType(new_vtype); + const int lmul_elements = vector_state->max_vector_length(); + + const bool vill = tew > kElen; + if (vill) { + vector_state->set_vector_exception(); + vector_state->SetVectorType(1ull << vill_shift); + matrix_state->set_mtype(0); + return; + } + + matrix_state->set_tile_k(std::min(matrix_state->tile_k(), max_k)); + matrix_state->set_tile_m( + std::min(static_cast<int>(matrix_state->tile_m()), + std::min(lmul_elements, effective_tile_elements))); +} + +// Reads 'tew'-bit element bits from tile 'tile' at index [row, col]. +uint64_t LoadTileBits(RiscVZvtMatrixState* matrix_state, int tile, int row, + int col, int tew) { + const int effective_tile_edge = matrix_state->effective_tile_edge(tew); + if (row < 0 || row >= effective_tile_edge || col < 0 || + col >= effective_tile_edge) { + return 0; + } + switch (tew) { + case 8: + return matrix_state->GetElem<uint8_t>(tile, row, col, 8).value_or(0); + case 16: + return matrix_state->GetElem<uint16_t>(tile, row, col, 16).value_or(0); + case 32: + return matrix_state->GetElem<uint32_t>(tile, row, col, 32).value_or(0); + case 64: + return matrix_state->GetElem<uint64_t>(tile, row, col, 64).value_or(0); + default: + return 0; + } +} + +// Stores 'tew'-bit element bits into tile 'tile' at index [row, col]. +void StoreTileBits(RiscVZvtMatrixState* matrix_state, int tile, int row, + int col, int tew, uint64_t value) { + const int effective_tile_edge = matrix_state->effective_tile_edge(tew); + if (row < 0 || row >= effective_tile_edge || col < 0 || + col >= effective_tile_edge) { + return; + } + switch (tew) { + case 8: + matrix_state + ->SetElem<uint8_t>(tile, row, col, 8, static_cast<uint8_t>(value)) + .IgnoreError(); + break; + case 16: + matrix_state + ->SetElem<uint16_t>(tile, row, col, 16, static_cast<uint16_t>(value)) + .IgnoreError(); + break; + case 32: + matrix_state + ->SetElem<uint32_t>(tile, row, col, 32, static_cast<uint32_t>(value)) + .IgnoreError(); + break; + case 64: + matrix_state->SetElem<uint64_t>(tile, row, col, 64, value).IgnoreError(); + break; } } @@ -142,114 +253,287 @@ void WriteScalar(const Instruction* inst, int dest_index, uint32_t value) { auto* dest = inst->Destination(dest_index); DataBuffer* db = dest->AllocateDataBuffer(); - db->Set<uint32_t>(0, value); + if (db->size<uint8_t>() == 8) { + db->Set<uint64_t>(0, value); + } else { + db->Set<uint32_t>(0, value); + } db->Submit(); } +// Traps with an Illegal Instruction if mstatus.MS is off. +bool TrapIfMatrixStateOff(const RiscVZvtMatrixState* matrix_state, + const Instruction* inst) { + auto* state = matrix_state->riscv_state(); + + bool trap = false; + if ((state->mstatus()->GetUint32() & 0x60000000U) == 0) { + trap = true; + } + + if (trap) { + state->Trap( + /*is_interrupt=*/false, /*trap_value=*/0, + *::mpact::sim::riscv::ExceptionCode::kIllegalInstruction, + inst->address(), inst); + return true; + } + return false; +} + +// Traps with an Illegal Instruction if mstatus.FS is off. +bool TrapIfFpStateOff(const Instruction* inst) { + auto* state = static_cast<RiscVState*>(inst->state()); + + bool trap = false; + if (state->mstatus()->fs() == 0) { + trap = true; + } + + if (trap) { + state->Trap( + /*is_interrupt=*/false, /*trap_value=*/0, + *::mpact::sim::riscv::ExceptionCode::kIllegalInstruction, + inst->address(), inst); + return true; + } + return false; +} + +// Sets mstatus.MS to Initial (1). +void SetMatrixStateInitial(const RiscVZvtMatrixState* matrix_state) { + 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(); + uint64_t val = + (csr->GetUint64() & ~kMstatusMsMask) | + (static_cast<uint64_t>(kMstatusStateInitial) << kMstatusMsShift); + csr->Set(val); + } +} + +// Sets mstatus.MS to Dirty (3) and updates mstatus.SD accordingly. +void SetMatrixStateDirty(const RiscVZvtMatrixState* matrix_state) { + 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(); + uint64_t sd_mask = (state->xlen() == RiscVXlen::RV32) ? kMstatusSdMaskRv32 + : kMstatusSdMaskRv64; + uint64_t val = + csr->GetUint64() | + (static_cast<uint64_t>(kMstatusStateDirty) << kMstatusMsShift) | + sd_mask; + csr->Set(val); + } +} + +// Sets mstatus.VS to Dirty (3) and updates mstatus.SD accordingly. +void SetVectorStateDirty(const RiscVZvtMatrixState* matrix_state) { + 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(); + uint64_t sd_mask = (state->xlen() == RiscVXlen::RV32) ? kMstatusSdMaskRv32 + : kMstatusSdMaskRv64; + uint64_t val = + csr->GetUint64() | + (static_cast<uint64_t>(kMstatusStateDirty) << kMstatusVsShift) | + sd_mask; + csr->Set(val); + } +} + +// 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) { + matrix_state->riscv_state()->Trap( + /*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return true; + } + const uint32_t effective_tile_edge = + static_cast<uint32_t>(matrix_state->effective_tile_edge(tew)); + if (tss.index >= effective_tile_edge) { + matrix_state->riscv_state()->Trap( + /*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return true; + } + return false; +} + +// Returns the number of tile-subset elements processed: +// min(vl, EFFECTIVE_TILE_EDGE) for element width 'tew'. +int TileSubsetCount(RiscVZvtMatrixState* matrix_state, + RiscVVectorState* vector_state, int tew) { + const int effective_tile_edge = matrix_state->effective_tile_edge(tew); + return std::min(vector_state->vector_length(), effective_tile_edge); +} + } // namespace -void RiscVZvtMsetMtype(const Instruction* inst) { +void RiscVZvtMsetMtypei(const Instruction* inst) { auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } auto* matrix_state = *m_result; auto* vector_state = matrix_state->riscv_state()->rv_vector(); - const uint32_t kRs1 = GetInstructionSource<uint32_t>(inst, 0); // rs1 - const uint32_t kRs2 = GetInstructionSource<uint32_t>(inst, 1); // rs2 - // Spec 15.1.1.4: vl = 0; mtype = rs1; then vtype = rs2 as if by vsetvl. + matrix_state->riscv_state()->mstatus()->Submit(); + + const uint32_t mtwiden = GetInstructionSource<uint32_t>(inst, 0); + const uint32_t vsew = GetInstructionSource<uint32_t>(inst, 1); + const uint32_t altfmt = GetInstructionSource<uint32_t>(inst, 2) & 0x1; + vector_state->set_vector_length(0); - matrix_state->set_mtype(kRs1); - vector_state->SetVectorType(kRs2); + matrix_state->set_mtype(mtwiden << kMtypeMtwidenShift); + + // vtype fields: vsew at [5:3], altfmt at [8] + uint32_t vtype = (vsew << 3) | ((altfmt & 1) << 8); + + vector_state->SetVectorType(vtype); if (matrix_state->mtwiden() == 0) { matrix_state->set_mtype(0); + SetVectorStateDirty(matrix_state); return; } - const int kSewBits = vector_state->selected_element_width() * 8; - const int kTwiden = matrix_state->twiden(); - const int kTileElementWidth = kSewBits * kTwiden; - const int kEffectiveTileElements = kTileElementWidth < 64 - ? matrix_state->tile_elements() - : matrix_state->tile_elements() / 2; - const int kmax = RiscVZvtKmax(kSewBits); - const int kLmulElements = - vector_state->max_vector_length(); // LMUL * (VLEN/SEW). + UpdateVectorMatrixGeometry(vector_state, matrix_state); + SetVectorStateDirty(matrix_state); + SetMatrixStateDirty(matrix_state); +} - // If the matrix unit is configured, force vma/vta = 1. - // TODO: also derive vtype.vlmul per the spec's min() formula; deferred while - // the v0.3 encoding firms up. - vector_state->SetVectorType(vector_state->vtype() | (1u << 6) | (1u << 7)); +void RiscVZvtMsetMtype(const Instruction* inst) { + auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + auto* matrix_state = *m_result; + auto* vector_state = matrix_state->riscv_state()->rv_vector(); - // kVill if the resulting TILE_ELEMENT_WIDTH is unsupported for the kBase - // (SEW*TWIDEN > ELEN). - const bool kVill = kTileElementWidth > kElen; - if (kVill) { - vector_state->set_vector_exception(); + const uint32_t rs1 = GetInstructionSource<uint32_t>(inst, 0); // rs1 + const uint32_t rs2 = GetInstructionSource<uint32_t>(inst, 1); // rs2 + + // Spec 15.1.1.4: vl = 0; mtype = rs1; then vtype = rs2 as if by vsetvl. + vector_state->set_vector_length(0); + matrix_state->set_mtype(rs1); + vector_state->SetVectorType(rs2); + + if (matrix_state->mtwiden() == 0) { matrix_state->set_mtype(0); + SetVectorStateDirty(matrix_state); return; } - // kTileK = min(kTileK, KMAX); kTileM = min(kTileM, LMUL*EVE, - // EFFECTIVE_TILE_EDGE). - matrix_state->set_tile_k(std::min(matrix_state->tile_k(), kmax)); - matrix_state->set_tile_m(std::min( - {matrix_state->tile_m(), kLmulElements, kEffectiveTileElements})); + UpdateVectorMatrixGeometry(vector_state, matrix_state); + SetVectorStateDirty(matrix_state); + SetMatrixStateDirty(matrix_state); } void RiscVZvtMsetTn(const Instruction* inst) { auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } auto* matrix_state = *m_result; auto* vector_state = matrix_state->riscv_state()->rv_vector(); - const uint32_t kRs1 = GetInstructionSource<uint32_t>(inst, 0); - uint32_t kTileN; + const uint32_t rs1 = GetInstructionSource<uint32_t>(inst, 0); + + uint32_t tile_n; if (matrix_state->mtwiden() == 0) { // Degenerates to vsetvl using the current vtype: vl = min(rs1, VLMAX). - kTileN = std::min<uint32_t>(kRs1, vector_state->max_vector_length()); + tile_n = std::min<uint32_t>(rs1, vector_state->max_vector_length()); } else { - const int kBound = std::min(vector_state->max_vector_length(), - matrix_state->effective_tile_edge( - matrix_state->tile_element_width_bits())); - kTileN = std::min<uint32_t>(kRs1, kBound); + const int bound = std::min(vector_state->max_vector_length(), + matrix_state->effective_tile_edge()); + tile_n = std::min<uint32_t>(rs1, bound); } - vector_state->set_vector_length(kTileN); - WriteScalar(inst, 0, kTileN); + vector_state->set_vector_length(tile_n); + WriteScalar(inst, 0, tile_n); + SetVectorStateDirty(matrix_state); + SetMatrixStateDirty(matrix_state); } void RiscVZvtMsetTm(const Instruction* inst) { auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } auto* matrix_state = *m_result; auto* vector_state = matrix_state->riscv_state()->rv_vector(); - const uint32_t kRs1 = GetInstructionSource<uint32_t>(inst, 0); - uint32_t kTileM; + const uint32_t rs1 = GetInstructionSource<uint32_t>(inst, 0); + if (matrix_state->mtwiden() == 0) { - kTileM = 0; - } else { - const int kBound = std::min(vector_state->max_vector_length(), - matrix_state->effective_tile_edge( - matrix_state->tile_element_width_bits())); - kTileM = std::min<uint32_t>(kRs1, kBound); + matrix_state->set_tile_m(0); + WriteScalar(inst, 0, 0); + SetVectorStateDirty(matrix_state); + return; } - matrix_state->set_tile_m(kTileM); - WriteScalar(inst, 0, kTileM); + + const int bound = std::min(vector_state->max_vector_length(), + matrix_state->effective_tile_edge()); + uint32_t tile_m = std::min<uint32_t>(rs1, bound); + matrix_state->set_tile_m(tile_m); + WriteScalar(inst, 0, tile_m); + SetVectorStateDirty(matrix_state); + SetMatrixStateDirty(matrix_state); } void RiscVZvtMsetTk(const Instruction* inst) { auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } auto* matrix_state = *m_result; auto* vector_state = matrix_state->riscv_state()->rv_vector(); - const uint32_t kRs1 = GetInstructionSource<uint32_t>(inst, 0); - uint32_t kTileK; + const uint32_t rs1 = GetInstructionSource<uint32_t>(inst, 0); + if (matrix_state->mtwiden() == 0) { - kTileK = 0; - } else { - const int kSewBits = vector_state->selected_element_width() * 8; - kTileK = std::min<uint32_t>(kRs1, RiscVZvtKmax(kSewBits)); + matrix_state->set_tile_k(0); + WriteScalar(inst, 0, 0); + SetVectorStateDirty(matrix_state); + return; } - matrix_state->set_tile_k(kTileK); - WriteScalar(inst, 0, kTileK); + + const int sew_bits = GetSewBits(vector_state); + uint32_t tile_k = std::min<uint32_t>(rs1, RiscVZvtKmax(sew_bits)); + matrix_state->set_tile_k(tile_k); + WriteScalar(inst, 0, tile_k); + SetVectorStateDirty(matrix_state); + SetMatrixStateDirty(matrix_state); } // ---------------------------------------------------------------------------- @@ -258,146 +542,312 @@ void RiscVZvtVtZero(const Instruction* inst) { auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } auto* matrix_state = *m_result; + if (TrapIfMatrixStateOff(matrix_state, inst)) return; auto* vector_state = matrix_state->riscv_state()->rv_vector(); - const int kTile = GetInstructionSource<uint32_t>(inst, 0); // mtd - const int kTileElementWidth = matrix_state->tile_element_width_bits(); - const int kTileM = matrix_state->tile_m(); - const int kEffectiveTileEdge = kTileElementWidth < 64 - ? matrix_state->tile_elements() - : matrix_state->tile_elements() / 2; - const int kTileN = - std::min(vector_state->vector_length(), kEffectiveTileEdge); - for (int row = 0; row < kTileM; row++) { - for (int col = 0; col < kTileN; col++) { - StoreTileBits(matrix_state, kTile, row, col, kTileElementWidth, 0); + const int tile = GetInstructionSource<uint32_t>(inst, 0); // mtile + const int tew = matrix_state->sew_bits() * matrix_state->twiden(); + if (matrix_state->twiden() != 0) { + if (!matrix_state->IsValidTile(tile, tew)) { + matrix_state->riscv_state()->Trap( + /*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; } } + const int tile_m = matrix_state->tile_m(); + const int effective_tile_edge = matrix_state->effective_tile_edge(tew); + const int tile_n = + std::min(vector_state->vector_length(), effective_tile_edge); + for (int row = 0; row < tile_m; row++) { + for (int col = 0; col < tile_n; col++) { + StoreTileBits(matrix_state, tile, row, col, tew, 0); + } + } + SetMatrixStateDirty(matrix_state); + SetVectorStateDirty(matrix_state); } -void RiscVZvtVtDiscard(const Instruction* /*inst*/) { - // Architecturally hints the kTile state is dead. No-op in the ISS. -} +void RiscVZvtVtDiscard(const Instruction* inst) { + // Architecturally hints the tile state is dead. No-op in the ISS. + auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + auto* matrix_state = *m_result; + if (TrapIfMatrixStateOff(matrix_state, inst)) return; -// Number of kTile-subset elements processed: min(vl, EFFECTIVE_TILE_EDGE) for -// the given TILE_ELEMENT_WIDTH. -static int TileSubsetCount(RiscVZvtMatrixState* matrix_state, - RiscVVectorState* vector_state, - int tile_element_width) { - const int kEffectiveTileEdge = tile_element_width < 64 - ? matrix_state->tile_elements() - : matrix_state->tile_elements() / 2; - return std::min(vector_state->vector_length(), kEffectiveTileEdge); + auto* rv_vector = matrix_state->riscv_state()->rv_vector(); + if (GetVtypeVill(rv_vector)) { + matrix_state->riscv_state()->Trap( + /*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + + rv_vector->clear_vstart(); + SetMatrixStateInitial(matrix_state); + SetVectorStateDirty(matrix_state); } void RiscVZvtVtmvVt(const Instruction* inst) { - // Tile row/col subset -> vector register group. Move TILE_ELEMENT_WIDTH = - // SEW. + // Transfers a tile row or column subset to a vector register group + // (vtmv.v.t). auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } auto* matrix_state = *m_result; - auto* vector_state = matrix_state->riscv_state()->rv_vector(); - const Tss kTss = DecodeTss(GetInstructionSource<uint32_t>(inst, 0)); - const int kSewBytes = vector_state->selected_element_width(); - const int kTileElementWidth = kSewBytes * 8; - const int kCount = - TileSubsetCount(matrix_state, vector_state, kTileElementWidth); - const int kElementsPerVector = - vector_state->vector_register_byte_length() / kSewBytes; + if (TrapIfMatrixStateOff(matrix_state, inst)) return; + auto* state = matrix_state->riscv_state(); + if (!matrix_state->configured()) { + state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + auto* vector_state = state->rv_vector(); + const int sew_bytes = vector_state->selected_element_width(); + const int tew = sew_bytes * 8; + const Tss tss = + DecodeTss(matrix_state, GetInstructionSource<uint32_t>(inst, 0), tew); + if (TrapIfTssInvalid(matrix_state, tss, tew, inst)) return; + const int count = TileSubsetCount(matrix_state, vector_state, tew); + const int start_element = vector_state->vstart(); + if (start_element >= count) { + vector_state->clear_vstart(); + SetVectorStateDirty(matrix_state); + return; + } + const int elements_per_vector = + vector_state->vector_register_byte_length() / sew_bytes; auto* vd = static_cast<RV32VectorDestinationOperand*>(inst->Destination(0)); - const int kNumRegs = (kCount + kElementsPerVector - 1) / kElementsPerVector; - for (int r = 0; r < kNumRegs; r++) { - DataBuffer* db = vd->AllocateDataBuffer(r); + const int num_regs = (count + elements_per_vector - 1) / elements_per_vector; + const int start_reg = start_element / elements_per_vector; + for (int r = start_reg; r < num_regs; r++) { + // Copy the destination buffer to retain undisturbed elements. + DataBuffer* db = vd->CopyDataBuffer(r); absl::Span<uint8_t> bytes = db->Get<uint8_t>(); - std::memset(bytes.data(), 0, bytes.size()); // tail-agnostic fill. - for (int kE = 0; kE < kElementsPerVector; kE++) { - const int kElem = r * kElementsPerVector + kE; - if (kElem >= kCount) break; - const uint64_t kVal = - (kTss.pattern == kTssPatternCol) - ? LoadTileBits(matrix_state, kTss.kTile, kElem, kTss.index, - kTileElementWidth) - : LoadTileBits(matrix_state, kTss.kTile, kTss.index, kElem, - kTileElementWidth); - std::memcpy(&bytes[kE * kSewBytes], &kVal, kSewBytes); + // Overwrite target elements in the active range [start_element, count). + for (int e = 0; e < elements_per_vector; e++) { + const int elem = r * elements_per_vector + e; + if (elem < start_element) continue; + if (elem >= count) { + // Zero-fill tail elements past the active count. + std::memset(&bytes[e * sew_bytes], 0, sew_bytes); + continue; + } + const uint64_t val = + (tss.pattern == kTssPatternCol) + ? LoadTileBits(matrix_state, tss.tile, elem, tss.index, tew) + : LoadTileBits(matrix_state, tss.tile, tss.index, elem, tew); + std::memcpy(&bytes[e * sew_bytes], &val, sew_bytes); } db->Submit(); } + vector_state->clear_vstart(); + SetVectorStateDirty(matrix_state); } void RiscVZvtVtmvTv(const Instruction* inst) { - // Vector register group -> kTile row/col subset. Move TILE_ELEMENT_WIDTH = - // SEW. + // Transfers a vector register group to a tile row or column subset + // (vtmv.t.v). auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } auto* matrix_state = *m_result; - auto* vector_state = matrix_state->riscv_state()->rv_vector(); + if (TrapIfMatrixStateOff(matrix_state, inst)) return; + auto* state = matrix_state->riscv_state(); + if (!matrix_state->configured()) { + state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + auto* vector_state = state->rv_vector(); auto* vs = static_cast<RV32VectorSourceOperand*>(inst->Source(0)); - const Tss kTss = DecodeTss(GetInstructionSource<uint32_t>(inst, 1)); - const int kSewBytes = vector_state->selected_element_width(); - const int kTileElementWidth = kSewBytes * 8; - const int kCount = - TileSubsetCount(matrix_state, vector_state, kTileElementWidth); - const int kElementsPerVector = - vector_state->vector_register_byte_length() / kSewBytes; - for (int kElem = 0; kElem < kCount; kElem++) { - const int kReg = kElem / kElementsPerVector; - const int kE = kElem % kElementsPerVector; - auto bytes = vs->GetRegister(kReg)->data_buffer()->Get<uint8_t>(); - uint64_t kVal = 0; - std::memcpy(&kVal, &bytes[kE * kSewBytes], kSewBytes); - if (kTss.pattern == kTssPatternCol) { - StoreTileBits(matrix_state, kTss.kTile, kElem, kTss.index, - kTileElementWidth, kVal); + const int sew_bytes = vector_state->selected_element_width(); + const int tew = sew_bytes * 8; + const Tss tss = + DecodeTss(matrix_state, GetInstructionSource<uint32_t>(inst, 1), tew); + if (TrapIfTssInvalid(matrix_state, tss, tew, inst)) return; + const int count = TileSubsetCount(matrix_state, vector_state, tew); + const int start_element = vector_state->vstart(); + if (start_element >= count) { + vector_state->clear_vstart(); + SetVectorStateDirty(matrix_state); + return; + } + const int elements_per_vector = + vector_state->vector_register_byte_length() / sew_bytes; + for (int elem = start_element; elem < count; elem++) { + const int reg = elem / elements_per_vector; + const int e = elem % elements_per_vector; + auto bytes = vs->GetRegister(reg)->data_buffer()->Get<uint8_t>(); + uint64_t val = 0; + std::memcpy(&val, &bytes[e * sew_bytes], sew_bytes); + if (tss.pattern == kTssPatternCol) { + StoreTileBits(matrix_state, tss.tile, elem, tss.index, tew, val); } else { - StoreTileBits(matrix_state, kTss.kTile, kTss.index, kElem, - kTileElementWidth, kVal); + StoreTileBits(matrix_state, tss.tile, tss.index, elem, tew, val); } } + vector_state->clear_vstart(); + SetMatrixStateDirty(matrix_state); } void RiscVZvtVtle(int eew_bits, const Instruction* inst) { - // Memory -> kTile row/col subset. EEW is statically encoded. + // Loads a tile row or column subset from memory into a tile register (vtle*). auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } auto* matrix_state = *m_result; + if (TrapIfMatrixStateOff(matrix_state, inst)) return; + + if (!matrix_state->configured()) { + matrix_state->riscv_state()->Trap( + /*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + auto* state = matrix_state->riscv_state(); auto* vector_state = state->rv_vector(); - const uint64_t kBase = GetInstructionSource<uint64_t>(inst, 0); // rs1 - const Tss kTss = DecodeTss(GetInstructionSource<uint32_t>(inst, 1)); // rs2 - const int kElementSize = eew_bits / 8; - const int kCount = TileSubsetCount(matrix_state, vector_state, eew_bits); - DataBuffer* db = matrix_state->GetScratchDb(kCount * kElementSize); - state->memory()->Load(kBase, db, nullptr, nullptr); + const uint64_t base = GetInstructionSource<uint64_t>(inst, 0); // rs1 + const int element_size = eew_bits / 8; + const int tew = eew_bits; + const Tss tss = DecodeTss( + matrix_state, GetInstructionSource<uint32_t>(inst, 1), tew); // rs2 + if (TrapIfTssInvalid(matrix_state, tss, tew, inst)) return; + const int count = TileSubsetCount(matrix_state, vector_state, tew); + const int start_element = vector_state->vstart(); + if (start_element >= count) { + vector_state->clear_vstart(); + SetVectorStateDirty(matrix_state); + return; + } + if (element_size > 1 && + ((base + vector_state->vstart() * element_size) % element_size) != 0) { + state->Trap(/*is_interrupt=*/false, + /*trap_value=*/base + vector_state->vstart() * element_size, + *ExceptionCode::kLoadAddressMisaligned, inst->address(), inst); + return; + } + const int elements_to_load = count - start_element; + DataBuffer* db = matrix_state->GetScratchDb(elements_to_load * element_size); + state->memory()->Load(base + start_element * element_size, db, nullptr, + nullptr); + if (state->branch()) return; absl::Span<uint8_t> bytes = db->Get<uint8_t>(); - for (int kE = 0; kE < kCount; kE++) { - uint64_t kVal = 0; - std::memcpy(&kVal, &bytes[kE * kElementSize], kElementSize); - if (kTss.pattern == kTssPatternCol) { - StoreTileBits(matrix_state, kTss.kTile, kE, kTss.index, eew_bits, kVal); + for (int e = start_element; e < count; e++) { + uint64_t val = 0; + std::memcpy(&val, &bytes[(e - start_element) * element_size], element_size); + if (tss.pattern == kTssPatternCol) { + StoreTileBits(matrix_state, tss.tile, e, tss.index, eew_bits, val); } else { - StoreTileBits(matrix_state, kTss.kTile, kTss.index, kE, eew_bits, kVal); + StoreTileBits(matrix_state, tss.tile, tss.index, e, eew_bits, val); } } + if (vector_state->vector_tail_agnostic()) { + const int effective_tile_edge = matrix_state->effective_tile_edge(eew_bits); + for (int e = count; e < effective_tile_edge; e++) { + if (tss.pattern == kTssPatternCol) { + StoreTileBits(matrix_state, tss.tile, e, tss.index, eew_bits, ~0ULL); + } else { + StoreTileBits(matrix_state, tss.tile, tss.index, e, eew_bits, ~0ULL); + } + } + } + vector_state->clear_vstart(); + SetMatrixStateDirty(matrix_state); } void RiscVZvtVtse(int eew_bits, const Instruction* inst) { - // Tile row/col subset -> memory. EEW is statically encoded. + // Stores a tile row or column subset from a tile register into memory + // (vtse*). auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } auto* matrix_state = *m_result; + if (TrapIfMatrixStateOff(matrix_state, inst)) return; + + if (!matrix_state->configured()) { + matrix_state->riscv_state()->Trap( + /*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + auto* state = matrix_state->riscv_state(); auto* vector_state = state->rv_vector(); - const uint64_t kBase = GetInstructionSource<uint64_t>(inst, 0); // rs1 - const Tss kTss = DecodeTss(GetInstructionSource<uint32_t>(inst, 1)); // rs2 - const int kElementSize = eew_bits / 8; - const int kCount = TileSubsetCount(matrix_state, vector_state, eew_bits); - DataBuffer* db = matrix_state->GetScratchDb(kCount * kElementSize); - absl::Span<uint8_t> bytes = db->Get<uint8_t>(); - for (int kE = 0; kE < kCount; kE++) { - const uint64_t kVal = - (kTss.pattern == kTssPatternCol) - ? LoadTileBits(matrix_state, kTss.kTile, kE, kTss.index, eew_bits) - : LoadTileBits(matrix_state, kTss.kTile, kTss.index, kE, eew_bits); - std::memcpy(&bytes[kE * kElementSize], &kVal, kElementSize); + const uint64_t base = GetInstructionSource<uint64_t>(inst, 0); // rs1 + const int element_size = eew_bits / 8; + const int tew = eew_bits; + const Tss tss = DecodeTss( + matrix_state, GetInstructionSource<uint32_t>(inst, 1), tew); // rs2 + if (TrapIfTssInvalid(matrix_state, tss, tew, inst)) return; + const int count = TileSubsetCount(matrix_state, vector_state, tew); + const int start_element = vector_state->vstart(); + if (start_element >= count) { + vector_state->clear_vstart(); + SetVectorStateDirty(matrix_state); + return; } - state->memory()->Store(kBase, db); + if (element_size > 1 && + ((base + vector_state->vstart() * element_size) % element_size) != 0) { + state->Trap(/*is_interrupt=*/false, + /*trap_value=*/base + vector_state->vstart() * element_size, + *ExceptionCode::kStoreAddressMisaligned, inst->address(), inst); + return; + } + const int elements_to_store = count - start_element; + DataBuffer* db = matrix_state->GetScratchDb(elements_to_store * element_size); + absl::Span<uint8_t> bytes = db->Get<uint8_t>(); + for (int e = start_element; e < count; e++) { + const uint64_t val = + (tss.pattern == kTssPatternCol) + ? LoadTileBits(matrix_state, tss.tile, e, tss.index, eew_bits) + : LoadTileBits(matrix_state, tss.tile, tss.index, e, eew_bits); + std::memcpy(&bytes[(e - start_element) * element_size], &val, element_size); + } + state->memory()->Store(base + start_element * element_size, db); + if (state->branch()) return; + vector_state->clear_vstart(); + SetVectorStateDirty(matrix_state); } // ---------------------------------------------------------------------------- @@ -406,107 +856,424 @@ void RiscVZvtMatmul(RiscVZvtMatmulKind kind, const Instruction* inst) { auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } auto* matrix_state = *m_result; + if (TrapIfMatrixStateOff(matrix_state, inst)) return; auto* vector_state = matrix_state->riscv_state()->rv_vector(); - const int kSewBytes = vector_state->selected_element_width(); - const int kSewBits = kSewBytes * 8; - const int kElementsPerVector = - vector_state->vector_register_byte_length() / kSewBytes; // elems/kReg. - const int kStride = 8 / RiscVZvtKmax(kSewBits); // regs between rows. - const int kTileK = + if (vector_state->vstart() > 0) { + matrix_state->riscv_state()->Trap( + /*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + if (!matrix_state->configured()) { + matrix_state->riscv_state()->Trap( + /*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + const int sew_bytes = vector_state->selected_element_width(); + const int sew_bits = sew_bytes * 8; + + const int elements_per_vector = + vector_state->vector_register_byte_length() / sew_bytes; // elems/reg. + const int stride = 8 / RiscVZvtKmax(sew_bits); // regs between rows. + const int tile_k = matrix_state->tile_k(); // K: the inner dimension of the dot product. - const int kTileM = - matrix_state - ->tile_m(); // M: the number of rows of the accumulator kTile. - const int kDestTile = GetInstructionSource<uint32_t>(inst, 2); // mtd - const int kTileElementWidth = - matrix_state - ->tile_element_width_bits(); // == 32 for the supported datatypes. - const int kEffectiveTileEdge = kTileElementWidth < 64 - ? matrix_state->tile_elements() - : matrix_state->tile_elements() / 2; - // N: the number of columns of the accumulator kTile (derived from vector + const int tile_m = + matrix_state->tile_m(); // M: the number of rows of the accumulator tile. + const uint32_t raw_mtile = GetInstructionSource<uint32_t>(inst, 2); + const int dest_tile = raw_mtile; + const int tew = matrix_state->sew_bits() * matrix_state->twiden(); + const int effective_tile_edge = matrix_state->effective_tile_edge(tew); + // N: the number of columns of the accumulator tile (derived from vector // length). - const int kTileN = - std::min(vector_state->vector_length(), kEffectiveTileEdge); + const int tile_n = + std::min(vector_state->vector_length(), effective_tile_edge); auto* a = static_cast<RV32VectorSourceOperand*>(inst->Source(0)); auto* b = static_cast<RV32VectorSourceOperand*>(inst->Source(1)); + const uint32_t reg_a = GetInstructionSource<uint32_t>(inst, 3); + const uint32_t reg_b = GetInstructionSource<uint32_t>(inst, 4); + + int lmul = std::max(1, vector_state->vector_length_multiplier() / 8); + if (!matrix_state->IsValidTile(dest_tile, tew) || (reg_a % lmul != 0) || + (reg_b % lmul != 0) || (reg_a % 8 >= stride) || (reg_b % 8 >= stride)) { + matrix_state->riscv_state()->Trap( + /*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + + if (tile_m == 0 || tile_n == 0 || tile_k == 0) { + return; + } + absl::Span<uint8_t> a_spans[32] = {}; absl::Span<uint8_t> b_spans[32] = {}; - const bool kIsFp = - (kind == RiscVZvtMatmulKind::kFp32 || kind == RiscVZvtMatmulKind::kBf16); + const bool is_fp = + (kind == RiscVZvtMatmulKind::kFp32 || kind == RiscVZvtMatmulKind::kBf16 || + kind == RiscVZvtMatmulKind::kFp16 || + kind == RiscVZvtMatmulKind::kFp8E4M3 || + kind == RiscVZvtMatmulKind::kFp8E4M3E5M2 || + kind == RiscVZvtMatmulKind::kFp8E5M2E4M3 || + kind == RiscVZvtMatmulKind::kFp8E5M2 || + kind == RiscVZvtMatmulKind::kFp64); - // Reads element `col` of row `kk` from a vector-group operand. - auto read_fp = [&](RV32VectorSourceOperand* op, absl::Span<uint8_t>* spans, - int kk, int col) -> float { - const int kReg = kk * kStride + col / kElementsPerVector; - const int kE = col % kElementsPerVector; - if (spans[kReg].empty()) { - spans[kReg] = op->GetRegister(kReg)->data_buffer()->Get<uint8_t>(); + auto get_span = [](absl::Span<uint8_t>* spans, int reg, + RV32VectorSourceOperand* op) { + if (spans[reg].empty()) { + auto* reg_ptr = op->GetRegister(reg); + if (reg_ptr) { + spans[reg] = reg_ptr->data_buffer()->Get<uint8_t>(); + } } - absl::Span<uint8_t> span = spans[kReg]; + return spans[reg]; + }; + + // Reads element `col` of row `kk` from a vector-group operand for matrix A. + auto read_fp_a = [&get_span, kind, stride, elements_per_vector, sew_bytes]( + RV32VectorSourceOperand* op, absl::Span<uint8_t>* spans, + int kk, int col) -> float { + const int reg = kk * stride + col / elements_per_vector; + const int e = col % elements_per_vector; + absl::Span<uint8_t> span = get_span(spans, reg, op); if (kind == RiscVZvtMatmulKind::kBf16) { uint16_t u; - std::memcpy(&u, &span[kE * kSewBytes], sizeof(u)); - return Bf16ToF32(u); + std::memcpy(&u, &span[e * sew_bytes], sizeof(u)); + return ::mpact::sim::generic::ConvertBf16ToSingle( + ::mpact::sim::generic::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}); + } + 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}); + } + 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}); } float f; - std::memcpy(&f, &span[kE * kSewBytes], sizeof(f)); + std::memcpy(&f, &span[e * sew_bytes], sizeof(f)); return f; }; - auto read_int = [&](RV32VectorSourceOperand* op, absl::Span<uint8_t>* spans, - int kk, int col) -> int32_t { - const int kReg = kk * kStride + col / kElementsPerVector; - const int kE = col % kElementsPerVector; - if (spans[kReg].empty()) { - spans[kReg] = op->GetRegister(kReg)->data_buffer()->Get<uint8_t>(); + + // Reads element `col` of row `kk` from a vector-group operand for matrix B. + auto read_fp_b = [&get_span, kind, stride, elements_per_vector, sew_bytes]( + RV32VectorSourceOperand* op, absl::Span<uint8_t>* spans, + int kk, int col) -> float { + const int reg = kk * stride + col / elements_per_vector; + const int e = col % elements_per_vector; + absl::Span<uint8_t> span = get_span(spans, reg, op); + 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}); } - absl::Span<uint8_t> span = spans[kReg]; - if (kind == RiscVZvtMatmulKind::kInt8Signed) { - return static_cast<int8_t>(span[kE]); + 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 static_cast<uint8_t>(span[kE]); + 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}); + } + 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}); + } + float f; + std::memcpy(&f, &span[e * sew_bytes], sizeof(f)); + return f; + }; + auto read_fp64 = [&get_span, stride, elements_per_vector, sew_bytes]( + RV32VectorSourceOperand* op, absl::Span<uint8_t>* spans, + int kk, int col) -> double { + const int reg = kk * stride + col / elements_per_vector; + const int e = col % elements_per_vector; + absl::Span<uint8_t> span = get_span(spans, reg, op); + double d; + std::memcpy(&d, &span[e * sew_bytes], sizeof(d)); + return d; + }; + auto read_int_a = [&get_span, kind, stride, elements_per_vector]( + RV32VectorSourceOperand* op, absl::Span<uint8_t>* spans, + int kk, int col) -> int32_t { + const int reg = kk * stride + col / elements_per_vector; + const int e = col % elements_per_vector; + absl::Span<uint8_t> span = get_span(spans, reg, op); + if (kind == RiscVZvtMatmulKind::kInt8Signed || + kind == RiscVZvtMatmulKind::kInt8SignedUnsigned) { + return static_cast<int8_t>(span[e]); + } + return static_cast<uint8_t>(span[e]); + }; + auto read_int_b = [&get_span, kind, stride, elements_per_vector]( + RV32VectorSourceOperand* op, absl::Span<uint8_t>* spans, + int kk, int col) -> int32_t { + const int reg = kk * stride + col / elements_per_vector; + const int e = col % elements_per_vector; + absl::Span<uint8_t> span = get_span(spans, reg, op); + if (kind == RiscVZvtMatmulKind::kInt8Signed || + kind == RiscVZvtMatmulKind::kInt8UnsignedSigned) { + return static_cast<int8_t>(span[e]); + } + return static_cast<uint8_t>(span[e]); }; - for (int mm = 0; mm < kTileM; mm++) { - for (int nn = 0; nn < kTileN; nn++) { - if (kIsFp) { - absl::StatusOr<float> acc_res = - matrix_state->GetElem<float>(kDestTile, mm, nn, kTileElementWidth); - if (!acc_res.ok()) { - LOG(ERROR) << acc_res.status(); - return; + auto* fp_state = matrix_state->riscv_state()->rv_fp(); + uint32_t orig_fcsr = 0; + if (is_fp && fp_state) { + orig_fcsr = fp_state->fcsr()->AsUint32(); + } + + { + std::optional<ScopedFPStatus> fp_status; + if (is_fp && fp_state) { + fp_status.emplace(fp_state->host_fp_interface()); + } + + for (int mm = 0; mm < tile_m; mm++) { + for (int nn = 0; nn < tile_n; nn++) { + if (is_fp) { + if (kind == RiscVZvtMatmulKind::kFp64) { + double acc = matrix_state->GetElem<double>(dest_tile, mm, nn, tew) + .value_or(0.0); + for (int kk = 0; kk < tile_k; kk++) { + double product = + read_fp64(a, a_spans, kk, mm) * read_fp64(b, b_spans, kk, nn); + // For Fp64 (SEW=64, TWIDEN=1), TEW=64. The product is implicitly + // rounded to Fp64. + acc += product; + } + matrix_state->SetElem<double>(dest_tile, mm, nn, tew, acc) + .IgnoreError(); + } else { + double sum_products = 0.0; + for (int kk = 0; kk < tile_k; kk++) { + double product = + static_cast<double>(read_fp_a(a, a_spans, kk, mm)) * + static_cast<double>(read_fp_b(b, b_spans, kk, nn)); + + if (kind == RiscVZvtMatmulKind::kFp32) { + // For Fp32 (SEW=32, TWIDEN=1), TEW=32. Implement TEW-bit + // intermediate rounding. + product = static_cast<double>(static_cast<float>(product)); + } + sum_products += product; + } + + float sum_products_f; + if (kind != RiscVZvtMatmulKind::kFp32) { + sum_products_f = DoubleToFloatROD(sum_products, fp_state); + } else { + sum_products_f = static_cast<float>(sum_products); + } + + float initial_acc = + matrix_state->GetElem<float>(dest_tile, mm, nn, tew) + .value_or(0.0f); + double final_acc_d = static_cast<double>(initial_acc) + + static_cast<double>(sum_products_f); + + float final_acc; + if (kind != RiscVZvtMatmulKind::kFp32) { + final_acc = DoubleToFloatROD(final_acc_d, fp_state); + } else { + final_acc = static_cast<float>(final_acc_d); + } + + matrix_state->SetElem<float>(dest_tile, mm, nn, tew, final_acc) + .IgnoreError(); + } + } else { + int32_t acc = matrix_state->GetElem<int32_t>(dest_tile, mm, nn, tew) + .value_or(0); + for (int kk = 0; kk < tile_k; kk++) { + auto av = read_int_a(a, a_spans, kk, mm); + auto bv = read_int_b(b, b_spans, kk, nn); + acc += av * bv; + } + matrix_state->SetElem<int32_t>(dest_tile, mm, nn, tew, acc) + .IgnoreError(); } - float acc = *acc_res; - for (int kk = 0; kk < kTileK; kk++) { - acc += read_fp(a, a_spans, kk, mm) * read_fp(b, b_spans, kk, nn); - } - // SetElem cannot fail because GetElem with the same parameters - // succeeded above. - matrix_state->SetElem<float>(kDestTile, mm, nn, kTileElementWidth, acc) - .IgnoreError(); - } else { - absl::StatusOr<int32_t> acc_res = matrix_state->GetElem<int32_t>( - kDestTile, mm, nn, kTileElementWidth); - if (!acc_res.ok()) { - LOG(ERROR) << acc_res.status(); - return; - } - int32_t acc = *acc_res; - for (int kk = 0; kk < kTileK; kk++) { - acc += read_int(a, a_spans, kk, mm) * read_int(b, b_spans, kk, nn); - } - // SetElem cannot fail because GetElem with the same parameters - // succeeded above. - matrix_state - ->SetElem<int32_t>(kDestTile, mm, nn, kTileElementWidth, acc) - .IgnoreError(); } } } + + if (is_fp && fp_state) { + uint32_t current_fcsr = fp_state->fcsr()->AsUint32(); + constexpr uint32_t kFcsrDzBit = 1 << 3; + constexpr uint32_t kFcsrUfBit = 1 << 1; + constexpr uint32_t kFcsrNxBit = 1 << 0; + uint32_t preservation_mask = kFcsrDzBit | kFcsrUfBit | kFcsrNxBit; + uint32_t intended_fcsr = + (current_fcsr & ~preservation_mask) | (orig_fcsr & preservation_mask); + + if (intended_fcsr != current_fcsr) { + fp_state->fcsr()->Write(intended_fcsr); + } + + if (intended_fcsr != orig_fcsr || + (tile_m > 0 && tile_n > 0 && tile_k > 0)) { + auto* mstatus = matrix_state->riscv_state()->mstatus(); + if (mstatus != nullptr) { + mstatus->set_fs(3); + mstatus->Submit(); + } + } + } + + SetMatrixStateDirty(matrix_state); +} + +void RiscVZvtVtmms(const Instruction* inst) { + auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + auto* matrix_state = *m_result; + auto* vector_state = matrix_state->riscv_state()->rv_vector(); + const int sew_bits = GetSewBits(vector_state); + if (sew_bits != 8 || matrix_state->twiden() != 4) { + matrix_state->riscv_state()->Trap( + /*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + const uint32_t altfmt = (vector_state->vtype() >> 8) & 1; + RiscVZvtMatmul(altfmt ? RiscVZvtMatmulKind::kInt8Signed + : RiscVZvtMatmulKind::kInt8SignedUnsigned, + inst); +} + +void RiscVZvtVtmmu(const Instruction* inst) { + auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + auto* matrix_state = *m_result; + auto* vector_state = matrix_state->riscv_state()->rv_vector(); + const int sew_bits = GetSewBits(vector_state); + if (sew_bits != 8 || matrix_state->twiden() != 4) { + matrix_state->riscv_state()->Trap( + /*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + const uint32_t altfmt = (vector_state->vtype() >> 8) & 1; + RiscVZvtMatmul(altfmt ? RiscVZvtMatmulKind::kInt8UnsignedSigned + : RiscVZvtMatmulKind::kInt8Unsigned, + inst); +} + +void RiscVZvtVtfmm(const Instruction* inst) { + if (TrapIfFpStateOff(inst)) return; + + auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + auto* matrix_state = *m_result; + auto* vector_state = matrix_state->riscv_state()->rv_vector(); + const uint32_t altfmt = (vector_state->vtype() >> 8) & 1; + const int sew_bits = GetSewBits(vector_state); + const uint32_t twiden = matrix_state->twiden(); + + RiscVZvtMatmulKind kind = RiscVZvtMatmulKind::kFp32; + if (sew_bits == 8 && twiden == 4) { + kind = altfmt ? RiscVZvtMatmulKind::kFp8E4M3E5M2 + : RiscVZvtMatmulKind::kFp8E4M3; + } else if (sew_bits == 16 && twiden == 2 && altfmt == 0) { + kind = RiscVZvtMatmulKind::kFp16; + } else if (sew_bits == 32 && twiden == 1 && altfmt == 0) { + kind = RiscVZvtMatmulKind::kFp32; + } else if (sew_bits == 64 && twiden == 1 && altfmt == 0) { + kind = RiscVZvtMatmulKind::kFp64; + } else { + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + RiscVZvtMatmul(kind, inst); +} + +void RiscVZvtVtfmmAlt(const Instruction* inst) { + if (TrapIfFpStateOff(inst)) return; + + auto m_result = GetMatrixState(inst); + if (!m_result.ok()) { + LOG(ERROR) << "No matrix state found while executing Zvt instruction: " + << m_result.status().message(); + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + auto* matrix_state = *m_result; + auto* vector_state = matrix_state->riscv_state()->rv_vector(); + const uint32_t altfmt = (vector_state->vtype() >> 8) & 1; + const int sew_bits = GetSewBits(vector_state); + const uint32_t twiden = matrix_state->twiden(); + + RiscVZvtMatmulKind kind = RiscVZvtMatmulKind::kBf16; + if (sew_bits == 8 && twiden == 4) { + kind = altfmt ? RiscVZvtMatmulKind::kFp8E5M2 + : RiscVZvtMatmulKind::kFp8E5M2E4M3; + } else if (sew_bits == 16 && twiden == 2 && altfmt == 0) { + kind = RiscVZvtMatmulKind::kBf16; + } else { + auto* rv_state = static_cast<RiscVState*>(inst->state()); + rv_state->Trap(/*is_interrupt=*/false, /*trap_value=*/0, + *ExceptionCode::kIllegalInstruction, inst->address(), inst); + return; + } + RiscVZvtMatmul(kind, inst); } } // namespace mpact::sim::riscv
diff --git a/riscv/riscv_zvt_instructions.h b/riscv/riscv_zvt_instructions.h index 94779de..60bdd99 100644 --- a/riscv/riscv_zvt_instructions.h +++ b/riscv/riscv_zvt_instructions.h
@@ -13,20 +13,41 @@ // limitations under the License. // Semantic functions for the RISC-V Vector Matrix Extension (Zvt / "VME", -// spec v0.3). This header declares the matrix configuration instructions +// spec v0.4). This header declares the matrix configuration instructions // (Zvtbase, spec 15.1.1.4). Tile move/load/store and the matrix-multiply // instructions are added in their respective translation units. #ifndef THIRD_PARTY_MPACT_RISCV_RISCV_ZVT_INSTRUCTIONS_H_ #define THIRD_PARTY_MPACT_RISCV_RISCV_ZVT_INSTRUCTIONS_H_ +#include <cstdint> + #include "mpact/sim/generic/instruction.h" namespace mpact::sim::riscv { using ::mpact::sim::generic::Instruction; -// KMAX (max inner dot-product depth) as a function of SEW in bits. +// Architectural mstatus field shifts and bitmasks (RISC-V Privileged, +// Vector, and Matrix specs). +inline constexpr int kMstatusVsShift = 9; +inline constexpr uint64_t kMstatusVsMask = 0x3ULL << kMstatusVsShift; +inline constexpr int kMstatusFsShift = 13; +inline constexpr uint64_t kMstatusFsMask = 0x3ULL << kMstatusFsShift; +inline constexpr int kMstatusMsShift = 29; +inline constexpr uint64_t kMstatusMsMask = 0x3ULL << kMstatusMsShift; +inline constexpr int kMstatusSdShiftRv32 = 31; +inline constexpr uint64_t kMstatusSdMaskRv32 = 1ULL << kMstatusSdShiftRv32; +inline constexpr int kMstatusSdShiftRv64 = 63; +inline constexpr uint64_t kMstatusSdMaskRv64 = 1ULL << kMstatusSdShiftRv64; + +// mstatus field state values (Off = 0, Initial = 1, Clean = 2, Dirty = 3). +inline constexpr uint32_t kMstatusStateOff = 0; +inline constexpr uint32_t kMstatusStateInitial = 1; +inline constexpr uint32_t kMstatusStateClean = 2; +inline constexpr uint32_t kMstatusStateDirty = 3; + +// Returns KMAX (maximum inner dot-product depth) as a function of 'sew_bits'. // Per spec 15.1.1.4: KMAX = max(1, 32 / SEW). int8->4, bf16(16)->2, fp32->1. inline int RiscVZvtKmax(int sew_bits) { return sew_bits >= 32 ? 1 : (32 / sew_bits); @@ -38,43 +59,206 @@ // - M represents the number of rows of the accumulator tile. // - N represents the number of columns of the accumulator tile. // - K represents the inner dimension of the dot product. + +// Sets mtype (from rs1) and vtype (from rs2), and clears vl to 0. // -// msetmtype rs1, rs2 : sets mtype (rs1) and vtype (rs2), zeroes vl. +// Source operands: +// 0: rs1: Scalar register holding requested mtype configuration. +// 1: rs2: Scalar register holding requested vtype configuration. +// Destination operands: +// None. Directly updates matrix state, vector state, and CSRs. void RiscVZvtMsetMtype(const Instruction* inst); -// msettn rd, rs1 : sets tn (== vl), bounded by the matrix config. (N is -// num columns) + +// Configures mtwiden, vsew, and altfmt from immediate instruction fields, +// and clears vl to 0. +// +// Source operands: +// 0: mtwiden: Immediate operand containing the matrix widening mode. +// 1: vsew: Immediate operand containing selected element width encoding. +// 2: altfmt: Immediate operand selecting standard vs alternate datatypes. +// Destination operands: +// None. Directly updates matrix state, vector state, and CSRs. +void RiscVZvtMsetMtypei(const Instruction* inst); + +// Sets the matrix column dimension (TN) and vector length (vl) bounded by +// the current matrix configuration. +// +// Source operands: +// 0: rs1: Scalar register specifying requested column dimension. +// Destination operands: +// 0: rd: Scalar register returning actual granted column dimension / vl. void RiscVZvtMsetTn(const Instruction* inst); -// msettm rd, rs1 : sets mtype.tm. (M is num rows) + +// Sets the matrix row dimension (TM) bounded by the current matrix +// configuration. +// +// Source operands: +// 0: rs1: Scalar register specifying requested row dimension. +// Destination operands: +// 0: rd: Scalar register returning actual granted row dimension. void RiscVZvtMsetTm(const Instruction* inst); -// msettk rd, rs1 : sets mtype.tk. (K is inner dimension) + +// Sets the matrix dot-product depth (TK) bounded by KMAX. +// +// Source operands: +// 0: rs1: Scalar register specifying requested dot-product depth. +// Destination operands: +// 0: rd: Scalar register returning actual granted dot-product depth. void RiscVZvtMsetTk(const Instruction* inst); // Tile manipulation instructions (Zvtbase). -// vtzero mtd : zeroes the tm x tn submatrix of tile mtd. + +// Zeroes the active TM x TN submatrix of the specified destination tile. +// +// Source operands: +// 0: mtile: Immediate operand specifying destination tile index. +// Destination operands: +// None. Directly clears tile storage in matrix state. void RiscVZvtVtZero(const Instruction* inst); -// vtdiscard : hints the tile state is dead (no-op in the ISS). + +// Hints to the execution unit that active tile resources may be discarded. +// +// Source operands: +// None. +// Destination operands: +// None. void RiscVZvtVtDiscard(const Instruction* inst); -// vtmv.v.t vd, rs1 : moves a tile row/col subset (TSS in rs1) to vd. + +// Moves a row or column subset of a tile into a vector destination register +// group. +// +// Source operands: +// 0: rs1: Scalar register holding the Tile Subset Specifier (TSS). +// Destination operands: +// 0: matVd: Vector register group receiving the extracted tile slice. void RiscVZvtVtmvVt(const Instruction* inst); -// vtmv.t.v rs1, vs2 : moves vs2 to a tile row/col subset (TSS in rs1). + +// Moves data from a vector source register group into a row or column tile +// subset. +// +// Source operands: +// 0: matA: Vector register group holding the source data to write. +// 1: rs1: Scalar register holding the destination Tile Subset Specifier +// (TSS). +// Destination operands: +// None. Updates targeted tile elements in matrix state directly. void RiscVZvtVtmvTv(const Instruction* inst); -// vtle{8,16,32,64} rs2,(rs1) : loads a tile subset (TSS rs2) from memory. + +// Loads a tile row/column subset from memory with explicit element width. +// +// Bound arguments: +// eew_bits: Effective element width in bits (8, 16, 32, or 64). +// Source operands: +// 0: rs1: Scalar base address register. +// 1: rs2: Scalar register holding the Tile Subset Specifier (TSS). +// Destination operands: +// None. Updates targeted tile storage directly from memory. void RiscVZvtVtle(int eew_bits, const Instruction* inst); -// vtse{8,16,32,64} rs2,(rs1) : stores a tile subset (TSS rs2) to memory. + +// Stores a tile row/column subset to memory with explicit element width. +// +// Bound arguments: +// eew_bits: Effective element width in bits (8, 16, 32, or 64). +// Source operands: +// 0: rs1: Scalar base address register. +// 1: rs2: Scalar register holding the Tile Subset Specifier (TSS). +// Destination operands: +// None. Reads tile elements and writes directly to memory. void RiscVZvtVtse(int eew_bits, const Instruction* inst); -// Matrix-multiply instructions: C[m,n] += sum_k A[k,m] * B[k,n], with C in a -// tile and A/B sourced from vector register groups (spec 15.1.1.8). +// Specifies the element data types and accumulation mode for +// matrix-multiplication operations (spec 15.1.1.8): +// C[m,n] += sum_k A[k,m] * B[k,n], +// with C in a tile and A/B sourced from vector register groups. // M is the number of rows of C, N is the number of columns of C, and // K is the inner dimension of the dot product. enum class RiscVZvtMatmulKind { - kInt8Signed, // vtmms.tvv: int8 x int8 -> int32. - kInt8Unsigned, // vtmmu.tvv: uint8 x uint8 -> int32. - kFp32, // vtfmm.tvv: fp32 x fp32 -> fp32. - kBf16, // vtfmm.alt.tvv: bf16 x bf16 -> fp32. + kInt8Signed, // vtmms.tvv (altfmt=1): int8 x int8 -> int32. + kInt8Unsigned, // vtmmu.tvv (altfmt=0): uint8 x uint8 -> int32. + kInt8UnsignedSigned, // vtmmu.tvv (altfmt=1): uint8 x int8 -> int32. + kInt8SignedUnsigned, // vtmms.tvv (altfmt=0): int8 x uint8 -> int32. + kFp8E4M3, // vtfmm.tvv (altfmt=0): E4M3 x E4M3 + kFp8E4M3E5M2, // vtfmm.tvv (altfmt=1): E4M3 x E5M2 + kFp8E5M2E4M3, // vtfmm.alt.tvv (altfmt=0): E5M2 x E4M3 + kFp8E5M2, // vtfmm.alt.tvv (altfmt=1): E5M2 x E5M2 + kFp16, // vtfmm.tvv: fp16 x fp16 -> fp32 + kBf16, // vtfmm.alt.tvv: bf16 x bf16 -> fp32. + kFp32, // vtfmm.tvv: fp32 x fp32 -> fp32. + kFp64, // vtfmm.tvv: fp64 x fp64 -> fp64. }; + +// Dispatches matrix multiplication according to kind: C += A^T * B. +// +// Source operands: +// 0: matA: Vector register group holding matrix A (vs2). +// 1: matB: Vector register group holding matrix B (vs1). +// 2: mtile: Immediate operand specifying destination accumulator tile C. +// 3: vs2_idx: Immediate operand specifying the base register number of matrix +// A. +// 4: vs1_idx: Immediate operand specifying the base register number of matrix +// B. +// Destination operands: +// 0: fflags: Accrued floating-point exception flags (for floating-point +// variants). void RiscVZvtMatmul(RiscVZvtMatmulKind kind, const Instruction* inst); +// Performs signed integer matrix multiply-accumulate: C += A^T * B. +// +// Source operands: +// 0: matA: Vector register group holding matrix A (vs2). +// 1: matB: Vector register group holding matrix B (vs1). +// 2: mtile: Immediate operand specifying destination accumulator tile C. +// 3: vs2_idx: Immediate operand specifying the base register number of matrix +// A. +// 4: vs1_idx: Immediate operand specifying the base register number of matrix +// B. +// Destination operands: +// None. Accumulates result directly into accumulator tile C. +void RiscVZvtVtmms(const Instruction* inst); + +// Performs unsigned integer matrix multiply-accumulate: C += A^T * B. +// +// Source operands: +// 0: matA: Vector register group holding matrix A (vs2). +// 1: matB: Vector register group holding matrix B (vs1). +// 2: mtile: Immediate operand specifying destination accumulator tile C. +// 3: vs2_idx: Immediate operand specifying the base register number of matrix +// A. +// 4: vs1_idx: Immediate operand specifying the base register number of matrix +// B. +// Destination operands: +// None. Accumulates result directly into accumulator tile C. +void RiscVZvtVtmmu(const Instruction* inst); + +// Performs floating-point matrix multiply-accumulate: C += A^T * B. +// +// Source operands: +// 0: matA: Vector register group holding matrix A (vs2). +// 1: matB: Vector register group holding matrix B (vs1). +// 2: mtile: Immediate operand specifying destination accumulator tile C. +// 3: vs2_idx: Immediate operand specifying the base register number of matrix +// A. +// 4: vs1_idx: Immediate operand specifying the base register number of matrix +// B. +// Destination operands: +// 0: fflags: Accrued floating-point exception flags. +void RiscVZvtVtfmm(const Instruction* inst); + +// Performs alternate floating-point (e.g. BF16 / FP8) matrix +// multiply-accumulate: C += A^T * B. +// +// Source operands: +// 0: matA: Vector register group holding matrix A (vs2). +// 1: matB: Vector register group holding matrix B (vs1). +// 2: mtile: Immediate operand specifying destination accumulator tile C. +// 3: vs2_idx: Immediate operand specifying the base register number of matrix +// A. +// 4: vs1_idx: Immediate operand specifying the base register number of matrix +// B. +// Destination operands: +// 0: fflags: Accrued floating-point exception flags. +void RiscVZvtVtfmmAlt(const Instruction* inst); + } // namespace mpact::sim::riscv #endif // THIRD_PARTY_MPACT_RISCV_RISCV_ZVT_INSTRUCTIONS_H_
diff --git a/riscv/riscv_zvt_state.h b/riscv/riscv_zvt_state.h index 1e63c8f..af76568 100644 --- a/riscv/riscv_zvt_state.h +++ b/riscv/riscv_zvt_state.h
@@ -189,18 +189,23 @@ // size. ::mpact::sim::generic::DataBuffer* GetScratchDb(int size); - // SEW (bytes/bits) from the current vector configuration. + // Returns the vector selected element width (SEW) in bytes. [[nodiscard]] int sew_bytes() const; + // Returns the vector selected element width (SEW) in bits. [[nodiscard]] int sew_bits() const { return sew_bytes() * 8; } - // TILE_ELEMENT_WIDTH (tile element width) in bits = SEW * TWIDEN. + // Returns the tile element width (TEW) in bits (SEW * TWIDEN). [[nodiscard]] int tile_element_width_bits() const { return sew_bits() * twiden(); } - // EFFECTIVE_TILE_EDGE: effective tile edge for a given TILE_ELEMENT_WIDTH - // (tew_bits). = TE for tew_bits < 64, TE/2 else. + // Returns the effective tile edge for a given tile element width (tew_bits): + // equals TE for tew_bits < 64, and TE/2 otherwise. [[nodiscard]] int effective_tile_edge(int tew_bits) const { return tew_bits < 64 ? tile_elements_ : tile_elements_ / 2; } + // Returns the effective tile edge for the current matrix configuration. + [[nodiscard]] int effective_tile_edge() const { + return effective_tile_edge(tile_element_width_bits()); + } private: explicit RiscVZvtMatrixState(
diff --git a/riscv/test/BUILD b/riscv/test/BUILD index 26d2f68..7c61ae6 100644 --- a/riscv/test/BUILD +++ b/riscv/test/BUILD
@@ -29,6 +29,7 @@ "@abseil-cpp//absl/functional:bind_front", "@abseil-cpp//absl/random", "@abseil-cpp//absl/strings", + "@abseil-cpp//absl/time", "@abseil-cpp//absl/types:span", "@mpact-sim//mpact/sim/generic:arch_state", "@mpact-sim//mpact/sim/generic:core", @@ -109,6 +110,7 @@ "@abseil-cpp//absl/log:check", "@abseil-cpp//absl/strings", "@com_google_googletest//:gtest_main", + "@mpact-sim//mpact/sim/generic:type_helpers", "@mpact-sim//mpact/sim/util/memory", ], ) @@ -352,6 +354,19 @@ ) cc_test( + name = "riscv_zvt_encoding_test", + size = "small", + srcs = [ + "riscv_zvt_encoding_test.cc", + ], + deps = [ + "//riscv:riscv_zvt_bin_fmt", + "//riscv:riscv_zvt_isa", + "@com_google_googletest//:gtest_main", + ], +) + +cc_test( name = "riscv64gzb_encoding_test", size = "small", srcs = [ @@ -541,6 +556,7 @@ deps = [ "//riscv:riscv32gv_bin_fmt", "//riscv:riscv32gv_isa", + "@abseil-cpp//absl/functional:function_ref", "@com_google_googletest//:gtest_main", ], ) @@ -1056,6 +1072,28 @@ ) cc_test( + name = "riscv_zvt_instructions_test", + size = "small", + srcs = ["riscv_zvt_instructions_test.cc"], + deps = [ + "//riscv:riscv_fp_state", + "//riscv:riscv_state", + "//riscv:riscv_v", + "//riscv:riscv_zvt_instructions", + "//riscv:riscv_zvt_state", + "@abseil-cpp//absl/base", + "@abseil-cpp//absl/log:check", + "@abseil-cpp//absl/status:statusor", + "@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 = [
diff --git a/riscv/test/riscv32gv_bin_decoder_test.cc b/riscv/test/riscv32gv_bin_decoder_test.cc index f4af564..6970365 100644 --- a/riscv/test/riscv32gv_bin_decoder_test.cc +++ b/riscv/test/riscv32gv_bin_decoder_test.cc
@@ -526,15 +526,15 @@ // instead of deleting them and then having to put them back later as more // encodings are added. TEST(RiscV32GVBinDecoderTest, None) { - (void)kRdValue; - (void)kSuccValue; - (void)kPredValue; - (void)SetRd(0, 0); - (void)SetRs1(0, 0); - (void)SetPred(0, 0); - (void)SetSucc(0, 0); - (void)Set16Rd(0, 0); - (void)Set16Rs2(0, 0); + EXPECT_NE(kRdValue, 0); + EXPECT_NE(kSuccValue, 0); + EXPECT_NE(kPredValue, 0); + EXPECT_NE(SetRd(0, 0), -1); + EXPECT_NE(SetRs1(0, 0), -1); + EXPECT_NE(SetPred(0, 0), -1); + EXPECT_NE(SetSucc(0, 0), -1); + EXPECT_NE(Set16Rd(0, 0), -1); + EXPECT_NE(Set16Rs2(0, 0), -1); } TEST(RiscV32GVBinDecoderTest, VectorConfig) {
diff --git a/riscv/test/riscv64g_vec_encoding_test.cc b/riscv/test/riscv64g_vec_encoding_test.cc index 98a1700..cd3c7cd 100644 --- a/riscv/test/riscv64g_vec_encoding_test.cc +++ b/riscv/test/riscv64g_vec_encoding_test.cc
@@ -14,6 +14,8 @@ #include "riscv/riscv64g_vec_encoding.h" +#include <cstdint> + #include "googlemock/include/gmock/gmock.h" // IWYU pragma: keep #include "googletest/include/gtest/gtest.h" #include "mpact/sim/generic/type_helpers.h" @@ -26,7 +28,7 @@ namespace { -using ::mpact::sim::generic::operator*; // NOLINT: clang-tidy false positive. +using ::mpact::sim::generic::operator*; // NOLINT(misc-unused-using-decls) using mpact::sim::riscv::RiscVState; using mpact::sim::riscv::RiscVXlen; @@ -93,4 +95,23 @@ } } +TEST_F(RiscV64GVecEncodingTest, Decode32BitBaseAndVector) { + // RV64G instruction: add x1, x2, x3 + constexpr uint32_t kAdd = 0b0000000'00011'00010'000'00001'0110011; + enc_->ParseInstruction(kAdd); + EXPECT_EQ(enc_->GetOpcode(SlotEnum::kRiscv64gv, 0), OpcodeEnum::kAdd); + + // RV64V instruction: vadd.vv v1, v2, v3 + constexpr uint32_t kVaddVv = 0b000000'0'00011'00010'000'00001'1010111; + enc_->ParseInstruction(kVaddVv); + EXPECT_EQ(enc_->GetOpcode(SlotEnum::kRiscv64gv, 0), OpcodeEnum::kVaddVv); +} + +TEST_F(RiscV64GVecEncodingTest, Decode16BitCompressed) { + // 16-bit compressed instruction: c.nop (0x0001) + constexpr uint16_t kCnop = 0x0001; + enc_->ParseInstruction(kCnop); + EXPECT_EQ(enc_->GetOpcode(SlotEnum::kRiscv64gv, 0), OpcodeEnum::kCnop); +} + } // namespace
diff --git a/riscv/test/riscv_zvt_encoding_test.cc b/riscv/test/riscv_zvt_encoding_test.cc new file mode 100644 index 0000000..b1464ee --- /dev/null +++ b/riscv/test/riscv_zvt_encoding_test.cc
@@ -0,0 +1,107 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Functional encoding and binary decoding tests for the RISC-V Vector Matrix +// Extension (Zvt v0.4 and legacy v0.3 compatibility instructions). + +#include <cstdint> + +#include "googletest/include/gtest/gtest.h" +#include "riscv/riscv_zvt_bin_decoder.h" +#include "riscv/riscv_zvt_enums.h" + +namespace { + +using ::mpact::sim::riscv::zvt::DecodeZvtInst32; +using ::mpact::sim::riscv::zvt::OpcodeEnum; + +// Base RV32G instruction. +constexpr uint32_t kAdd = 0b0000000'00011'00010'000'00001'0110011; + +// Zvt v0.4 instructions. +constexpr uint32_t kMsetmtype = 0b1000010'00000'00000'111'00000'1010111; +constexpr uint32_t kMsetmtypei = 0b1000100'00100'00000'111'00000'1010111; +constexpr uint32_t kMsettn = 0b1000100'00000'00000'111'00000'1010111; +constexpr uint32_t kMsettm = 0b1000100'00001'00000'111'00000'1010111; +constexpr uint32_t kMsettk = 0b1000100'00010'00000'111'00000'1010111; +constexpr uint32_t kVtzero = 0b010000'1'11110'00000'110'00000'1010111; +constexpr uint32_t kVtdiscard = 0b010000'1'11100'00000'110'00000'1010111; +constexpr uint32_t kVtmvVt = 0b010000'1'11111'00000'110'00000'1010111; +constexpr uint32_t kVtmvTv = 0b010111'1'00000'00000'110'00000'1010111; +constexpr uint32_t kVtle8 = 0b0001001'00000'00000'111'00000'0000111; +constexpr uint32_t kVtle16 = 0b0011001'00000'00000'111'00000'0000111; +constexpr uint32_t kVtle32 = 0b0101001'00000'00000'111'00000'0000111; +constexpr uint32_t kVtle64 = 0b0111001'00000'00000'111'00000'0000111; +constexpr uint32_t kVtse8 = 0b0001001'00000'00000'111'00000'0100111; +constexpr uint32_t kVtse16 = 0b0011001'00000'00000'111'00000'0100111; +constexpr uint32_t kVtse32 = 0b0101001'00000'00000'111'00000'0100111; +constexpr uint32_t kVtse64 = 0b0111001'00000'00000'111'00000'0100111; +constexpr uint32_t kVtmmuTvv = 0b1111000'00000'00000'000'00000'1110111; +constexpr uint32_t kVtmmsTvv = 0b1111000'00000'00000'000'00001'1110111; +constexpr uint32_t kVtfmmTvv = 0b1111000'00000'00000'001'00000'1110111; +constexpr uint32_t kVtfmmAltTvv = 0b1111000'00000'00000'001'00001'1110111; + +// Legacy Zvt v0.3 instructions. +constexpr uint32_t kV0_3_Msetmtype = 0b1000001'00010'00001'111'00011'1010111; +constexpr uint32_t kV0_3_Msettn = 0b1000010'00000'00001'111'00011'1010111; +constexpr uint32_t kV0_3_Msettm = 0b1000010'00001'00001'111'00011'1010111; +constexpr uint32_t kV0_3_Msettk = 0b1000010'00010'00001'111'00011'1010111; + +TEST(RiscVZvtEncodingTest, DecodeZvtV0_4ConfigurationInstructions) { + EXPECT_EQ(DecodeZvtInst32(kMsetmtype), OpcodeEnum::kMsetmtype); + EXPECT_EQ(DecodeZvtInst32(kMsetmtypei), OpcodeEnum::kMsetmtypei); + EXPECT_EQ(DecodeZvtInst32(kMsettn), OpcodeEnum::kMsettn); + EXPECT_EQ(DecodeZvtInst32(kMsettm), OpcodeEnum::kMsettm); + EXPECT_EQ(DecodeZvtInst32(kMsettk), OpcodeEnum::kMsettk); +} + +TEST(RiscVZvtEncodingTest, DecodeZvtV0_4TileManipulationInstructions) { + EXPECT_EQ(DecodeZvtInst32(kVtzero), OpcodeEnum::kVtzero); + EXPECT_EQ(DecodeZvtInst32(kVtdiscard), OpcodeEnum::kVtdiscard); + EXPECT_EQ(DecodeZvtInst32(kVtmvVt), OpcodeEnum::kVtmvVT); + EXPECT_EQ(DecodeZvtInst32(kVtmvTv), OpcodeEnum::kVtmvTV); +} + +TEST(RiscVZvtEncodingTest, DecodeZvtV0_4TileLoadStoreInstructions) { + EXPECT_EQ(DecodeZvtInst32(kVtle8), OpcodeEnum::kVtle8); + EXPECT_EQ(DecodeZvtInst32(kVtle16), OpcodeEnum::kVtle16); + EXPECT_EQ(DecodeZvtInst32(kVtle32), OpcodeEnum::kVtle32); + EXPECT_EQ(DecodeZvtInst32(kVtle64), OpcodeEnum::kVtle64); + + EXPECT_EQ(DecodeZvtInst32(kVtse8), OpcodeEnum::kVtse8); + EXPECT_EQ(DecodeZvtInst32(kVtse16), OpcodeEnum::kVtse16); + EXPECT_EQ(DecodeZvtInst32(kVtse32), OpcodeEnum::kVtse32); + EXPECT_EQ(DecodeZvtInst32(kVtse64), OpcodeEnum::kVtse64); +} + +TEST(RiscVZvtEncodingTest, DecodeZvtV0_4MatrixMultiplyInstructions) { + EXPECT_EQ(DecodeZvtInst32(kVtmmuTvv), OpcodeEnum::kVtmmuTvv); + EXPECT_EQ(DecodeZvtInst32(kVtmmsTvv), OpcodeEnum::kVtmmsTvv); + EXPECT_EQ(DecodeZvtInst32(kVtfmmTvv), OpcodeEnum::kVtfmmTvv); + EXPECT_EQ(DecodeZvtInst32(kVtfmmAltTvv), OpcodeEnum::kVtfmmAltTvv); +} + +TEST(RiscVZvtEncodingTest, RejectNonZvtInstructions) { + EXPECT_EQ(DecodeZvtInst32(kAdd), OpcodeEnum::kNone); + EXPECT_EQ(DecodeZvtInst32(0x00000000), OpcodeEnum::kNone); +} + +TEST(RiscVZvtEncodingTest, DecodeLegacyZvtV0_3CompatibilityInstructions) { + EXPECT_EQ(DecodeZvtInst32(kV0_3_Msetmtype), OpcodeEnum::kMsetmtype); + EXPECT_EQ(DecodeZvtInst32(kV0_3_Msettn), OpcodeEnum::kMsettn); + EXPECT_EQ(DecodeZvtInst32(kV0_3_Msettm), OpcodeEnum::kMsettm); + EXPECT_EQ(DecodeZvtInst32(kV0_3_Msettk), OpcodeEnum::kMsettk); +} + +} // namespace
diff --git a/riscv/test/riscv_zvt_instructions_test.cc b/riscv/test/riscv_zvt_instructions_test.cc new file mode 100644 index 0000000..eda9d5a --- /dev/null +++ b/riscv/test/riscv_zvt_instructions_test.cc
@@ -0,0 +1,1541 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// 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. + +#include "riscv/riscv_zvt_instructions.h" + +#include <algorithm> +#include <cstdint> +#include <memory> +#include <string> +#include <utility> +#include <vector> + +#include "absl/base/casts.h" +#include "absl/status/statusor.h" +#include "absl/types/span.h" +#include "googlemock/include/gmock/gmock.h" +#include "googletest/include/gtest/gtest.h" +#include "mpact/sim/generic/immediate_operand.h" +#include "mpact/sim/generic/instruction.h" +#include "mpact/sim/generic/operand_interface.h" +#include "mpact/sim/generic/register.h" +#include "mpact/sim/util/memory/flat_demand_memory.h" +#include "riscv/riscv_fp_state.h" +#include "riscv/riscv_instruction_helpers.h" +#include "riscv/riscv_register.h" +#include "riscv/riscv_state.h" +#include "riscv/riscv_vector_state.h" +#include "riscv/riscv_zvt_state.h" + +/* start - helper test macro */ +#define CONCAT_INNER(a, b) a##b +#define CONCAT(a, b) CONCAT_INNER(a, b) +#define ASSERT_OK(expression) ASSERT_TRUE((expression).ok()) +#define ASSERT_OK_AND_ASSIGN(lhs, rexpr) \ + auto CONCAT(status_or_line_, __LINE__) = (rexpr); \ + ASSERT_OK(CONCAT(status_or_line_, __LINE__)); \ + lhs = std::move(CONCAT(status_or_line_, __LINE__)).value(); +/* end - helper test macro */ + +namespace { + +using ::mpact::sim::generic::DestinationOperandInterface; +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::kMstatusMsMask; +using ::mpact::sim::riscv::kMstatusMsShift; +using ::mpact::sim::riscv::kMstatusSdMaskRv32; +using ::mpact::sim::riscv::kMstatusSdMaskRv64; +using ::mpact::sim::riscv::kMstatusSdShiftRv32; +using ::mpact::sim::riscv::kMstatusSdShiftRv64; +using ::mpact::sim::riscv::kMstatusStateDirty; +using ::mpact::sim::riscv::kMstatusStateInitial; +using ::mpact::sim::riscv::kMstatusStateOff; +using ::mpact::sim::riscv::kMstatusVsMask; +using ::mpact::sim::riscv::kMstatusVsShift; +using ::mpact::sim::riscv::kMtypeMtwidenShift; +using ::mpact::sim::riscv::kMtypeTkMask; +using ::mpact::sim::riscv::kMtypeTkShift; +using ::mpact::sim::riscv::kMtypeTmMask; +using ::mpact::sim::riscv::kMtypeTmShift; +using ::mpact::sim::riscv::RiscVFPState; +using ::mpact::sim::riscv::RiscVState; +using ::mpact::sim::riscv::RiscVVectorState; +using ::mpact::sim::riscv::RiscVXlen; +using ::mpact::sim::riscv::RiscVZvtMatrixState; +using ::mpact::sim::riscv::RiscVZvtMsetMtype; +using ::mpact::sim::riscv::RiscVZvtMsetMtypei; +using ::mpact::sim::riscv::RiscVZvtMsetTk; +using ::mpact::sim::riscv::RiscVZvtMsetTm; +using ::mpact::sim::riscv::RiscVZvtMsetTn; +using ::mpact::sim::riscv::RiscVZvtVtDiscard; +using ::mpact::sim::riscv::RiscVZvtVtmvTv; +using ::mpact::sim::riscv::RiscVZvtVtmvVt; +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::util::FlatDemandMemory; + +// Architectural mstatus SD bit states. +inline constexpr uint64_t kMstatusSdSet = 1ULL; +inline constexpr uint64_t kMstatusSdClean = 0ULL; + +// RVV vtype bitfield encodings. +inline constexpr uint32_t kVsew8 = 0; // 8-bit SEW (1 byte) +inline constexpr uint32_t kVsew16 = 1; // 16-bit SEW (2 bytes) +inline constexpr uint32_t kVsew32 = 2; // 32-bit SEW (4 bytes) +inline constexpr uint32_t kVsew64 = 3; // 64-bit SEW (8 bytes) +inline constexpr uint32_t kVsewShift = 3; + +inline constexpr uint32_t kVlmul1 = 0; // LMUL = 1 +inline constexpr uint32_t kVlmul2 = 1; // LMUL = 2 +inline constexpr uint32_t kVlmul4 = 2; // LMUL = 4 +inline constexpr uint32_t kVlmul8 = 3; // LMUL = 8 +inline constexpr uint32_t kVlmulF8 = 5; // LMUL = 1/8 +inline constexpr uint32_t kVlmulF4 = 6; // LMUL = 1/4 +inline constexpr uint32_t kVlmulF2 = 7; // LMUL = 1/2 +inline constexpr uint32_t kVlmulMask = 0x7; + +inline constexpr uint32_t kVtaShift = 6; +inline constexpr uint32_t kVmaShift = 7; +inline constexpr uint32_t kVtypeAltfmtShift = 8; +inline constexpr uint32_t kVillMask = 1U << 31; + +// 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) { + return (vsew << kVsewShift) | (vlmul & kVlmulMask) | + (static_cast<uint32_t>(vta) << kVtaShift) | + (static_cast<uint32_t>(vma) << kVmaShift) | + (static_cast<uint32_t>(altfmt) << kVtypeAltfmtShift); +} + +// Zvt mtype mtwiden encodings. +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) + +// Zvt msetmtypei altfmt encodings. +inline constexpr uint32_t kAltfmtStandard = 0; +inline constexpr uint32_t kAltfmtAlternate = 1; + +// Assembles a Zvt mtype configuration value from mtwiden, tk, and tm fields. +constexpr uint32_t EncodeMtype(uint32_t mtwiden, uint32_t tk = 0, + uint32_t tm = 0) { + return (mtwiden << kMtypeMtwidenShift) | + ((tk & kMtypeTkMask) << kMtypeTkShift) | + ((tm & kMtypeTmMask) << kMtypeTmShift); +} + +// 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 kTssPatternShift = 24; +inline constexpr uint32_t kTssTileShift = 27; + +// 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) | + ((pattern & 0x7) << kTssPatternShift) | (index & 0xFFFFFF); +} + +// Holds expected vector geometry scaling results. +struct ExpectedVectorGeometry { + uint32_t vlmul = 0; + uint32_t max_vector_length = 0; +}; + +// Calculates the expected architectural LMUL and VLMAX resulting from +// Zvt vector-matrix geometry scaling (Zvt v0.4 spec 15.1.1.4). +ExpectedVectorGeometry CalculateExpectedVectorGeometry(int vlen_bytes, + int tile_elements, + int sew_bits, + int twiden) { + const int sew_bytes = sew_bits / 8; + const int tew = sew_bits * twiden; + // Effective tile elements scale inversely with element width above 32 bits. + const int effective_tile_elements = + (tew > 32) ? (tile_elements / (tew / 32)) : tile_elements; + const int max_k = std::max(1, 32 / sew_bits); + + const int eve = vlen_bytes / sew_bytes; + const int ceil_ete_eve = (effective_tile_elements + eve - 1) / eve; + + const int vlmul_max_k = 64 / max_k; + const int vlmul_twiden = 64 / twiden; + const int vlmul_ete_eve = 8 * ceil_ete_eve; + + int target_vlmul_scaled = + std::min({vlmul_max_k, vlmul_twiden, vlmul_ete_eve}); + target_vlmul_scaled = std::clamp(target_vlmul_scaled, 1, 64); + + uint32_t vlmul_enc = kVlmul1; + int lmul_num = 1; + int lmul_den = 1; + switch (target_vlmul_scaled) { + case 1: + vlmul_enc = kVlmulF8; + lmul_den = 8; + break; + case 2: + vlmul_enc = kVlmulF4; + lmul_den = 4; + break; + case 4: + vlmul_enc = kVlmulF2; + lmul_den = 2; + break; + case 8: + vlmul_enc = kVlmul1; + lmul_num = 1; + break; + case 16: + vlmul_enc = kVlmul2; + lmul_num = 2; + break; + case 32: + vlmul_enc = kVlmul4; + lmul_num = 4; + break; + case 64: + vlmul_enc = kVlmul8; + lmul_num = 8; + break; + default: + vlmul_enc = kVlmul1; + lmul_num = 1; + break; + } + const uint32_t max_vl = (eve * lmul_num) / lmul_den; + return {.vlmul = vlmul_enc, .max_vector_length = max_vl}; +} + +// RAII test helper that intercepts trap callbacks on a RiscVState instance +// and records whether a trap was taken along with its exception code. +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; + }); + } + + bool trap_taken() const { return trap_taken_; } + uint64_t trap_code() const { return trap_code_; } + + private: + RiscVState* state_; + bool trap_taken_ = false; + uint64_t trap_code_ = 0; +}; + +// Encapsulates a localized 64-bit RISC-V state, vector state, and matrix +// state along with mstatus status accessors for RV64-specific instruction +// tests. +struct Rv64TestContext { + FlatDemandMemory memory; + RiscVState state; + RiscVVectorState vector_state; + std::unique_ptr<RiscVZvtMatrixState> matrix_state; + + explicit Rv64TestContext(const std::string& 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) { + 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()); + return ctx; + } + + void SetMstatusVs(uint32_t state_val) { + uint64_t val = state.mstatus()->GetUint64() & ~kMstatusVsMask; + val |= (static_cast<uint64_t>(state_val & 3U) << kMstatusVsShift); + state.mstatus()->Set(val); + } + + void SetMstatusMs(uint32_t state_val) { + uint64_t val = state.mstatus()->GetUint64() & ~kMstatusMsMask; + val |= (static_cast<uint64_t>(state_val & 3U) << kMstatusMsShift); + state.mstatus()->Set(val); + } + + uint32_t GetMstatusVs() const { + return (state.mstatus()->GetUint32() >> kMstatusVsShift) & + kMstatusStateDirty; + } + + uint32_t GetMstatusMs() const { + return (state.mstatus()->GetUint32() >> kMstatusMsShift) & + kMstatusStateDirty; + } + + uint64_t GetMstatusSd() const { + return (state.mstatus()->GetUint64() >> kMstatusSdShiftRv64) & 1ULL; + } +}; + +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_); + + instruction_ = new Instruction(0x1000, state_); + 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_; + } + + void ResetInstruction() { + if (instruction_ != nullptr) { + instruction_->DecRef(); + } + instruction_ = new Instruction(0x1000, state_); + instruction_->set_size(4); + } + + // Sets the value of scalar register 'name' to 'value'. + void SetRegisterValue(const std::string& 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 { + return state_->GetRegister<RV32Register>(name) + .first->data_buffer() + ->Get<uint32_t>(0); + } + + // Sets the mstatus.MS (matrix state) field to 'state_val'. + void SetMstatusMs(uint32_t state_val) { + uint64_t val = state_->mstatus()->GetUint64() & ~kMstatusMsMask; + val |= (static_cast<uint64_t>(state_val & 3U) << kMstatusMsShift); + state_->mstatus()->Set(val); + } + + // Sets the mstatus.VS (vector state) field to 'state_val'. + void SetMstatusVs(uint32_t state_val) { + uint64_t val = state_->mstatus()->GetUint64() & ~kMstatusVsMask; + val |= (static_cast<uint64_t>(state_val & 3U) << kMstatusVsShift); + state_->mstatus()->Set(val); + } + + // Returns the mstatus.VS (vector state) field value. + uint32_t GetMstatusVs() const { + return (state_->mstatus()->GetUint32() >> kMstatusVsShift) & + kMstatusStateDirty; + } + + // Returns the mstatus.MS (matrix state) field value. + uint32_t GetMstatusMs() const { + return (state_->mstatus()->GetUint32() >> kMstatusMsShift) & + kMstatusStateDirty; + } + + // Returns the mstatus.SD (state dirty) bit value. + uint64_t GetMstatusSd(bool is_rv64 = false) const { + int shift = is_rv64 ? kMstatusSdShiftRv64 : kMstatusSdShiftRv32; + return (state_->mstatus()->GetUint64() >> shift) & 1ULL; + } + + // Creates a scalar source operand for register 'name'. + SourceOperandInterface* CreateScalarSource(const std::string& name) { + return state_->GetRegister<RV32Register>(name).first->CreateSourceOperand(); + } + + // Creates a scalar destination operand for register 'name'. + DestinationOperandInterface* CreateScalarDest(const std::string& 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) { + auto* reg = state_->GetRegister<RVVectorRegister>(reg_name).first; + std::vector<RegisterBase*> group = {reg}; + return new RV32VectorDestinationOperand(absl::Span<RegisterBase*>(group), 0, + reg_name); + } + + // Creates a vector source operand for vector register group 'reg_name'. + RV32VectorSourceOperand* CreateVectorSourceOperand( + const std::string& reg_name) { + auto* reg = state_->GetRegister<RVVectorRegister>(reg_name).first; + std::vector<RegisterBase*> group = {reg}; + return new RV32VectorSourceOperand(absl::Span<RegisterBase*>(group), + reg_name); + } + + // Verifies that 'semantic_function' triggers an IllegalInstruction trap + // when called on a state lacking matrix extension support. + void ExpectTrapWithoutMatrixState( + void (*semantic_function)(const Instruction*)) { + FlatDemandMemory memory; + RiscVState rv_state("test_no_matrix", RiscVXlen::RV32, &memory); + ScopedTrapCapture trap_capture(&rv_state); + + auto* inst = new Instruction(0x1000, &rv_state); + inst->set_size(4); + inst->set_semantic_function(semantic_function); + inst->Execute(nullptr); + inst->DecRef(); + + EXPECT_TRUE(trap_capture.trap_taken()); + EXPECT_EQ(trap_capture.trap_code(), + static_cast<uint64_t>(ExceptionCode::kIllegalInstruction)); + } + + // Reads 'count' elements from row 'row' of tile 'tile' into a vector. + template <typename T> + absl::StatusOr<std::vector<T>> GetTileRow(uint32_t tile, uint32_t row, + int count, + int elem_bits = sizeof(T) * 8) { + std::vector<T> elements; + elements.reserve(count); + for (int c = 0; c < count; ++c) { + auto elem_or = matrix_state_->GetElem<T>(tile, row, c, elem_bits); + if (!elem_or.ok()) return elem_or.status(); + elements.push_back(*elem_or); + } + return elements; + } + + // Reads 'count' elements from column 'col' of tile 'tile' into a vector. + template <typename T> + absl::StatusOr<std::vector<T>> GetTileColumn(uint32_t tile, uint32_t col, + int count, + int elem_bits = sizeof(T) * 8) { + std::vector<T> elements; + elements.reserve(count); + for (int r = 0; r < count; ++r) { + auto elem_or = matrix_state_->GetElem<T>(tile, r, col, elem_bits); + if (!elem_or.ok()) return elem_or.status(); + elements.push_back(*elem_or); + } + return elements; + } + + FlatDemandMemory memory_; + RiscVState* state_; + RiscVVectorState* vector_state_; + RiscVZvtMatrixState* matrix_state_; + Instruction* instruction_; +}; + +TEST_F(RiscVZvtInstructionsTest, MsetmtypeFunctionalDecoding) { + // Configure matrix state mtype with TWIDEN = 1 (no widening, mtwiden = 1) + // and vector state vtype with SEW = 32 bits, LMUL = 1/8. + const uint32_t mtype_val = EncodeMtype(kMtwiden1); + const uint32_t vtype_val = EncodeVtype(kVsew32, kVlmulF8); + SetRegisterValue("x1", mtype_val); + SetRegisterValue("x2", vtype_val); + + instruction_->AppendSource(CreateScalarSource("x1")); + instruction_->AppendSource(CreateScalarSource("x2")); + + instruction_->set_semantic_function(&RiscVZvtMsetMtype); + instruction_->Execute(nullptr); + + // Semantics state vl = 0; mtype = rs1; vtype = rs2 (as if by vsetvl) + EXPECT_EQ(matrix_state_->mtype(), mtype_val); + EXPECT_EQ(state_->rv_vector()->vector_length(), 0); + EXPECT_EQ(state_->rv_vector()->selected_element_width(), 4); +} + +TEST_F(RiscVZvtInstructionsTest, MsetmtypeDestinationZeroRegister) { + // Verifies that msetmtype does not write to any destination register, + // matching the architectural requirement that rd = 0b00000 (x0) and acts + // only as a structural encoding constraint, not a true destination operand. + const uint32_t mtype_val = EncodeMtype(kMtwiden1); + const uint32_t vtype_val = EncodeVtype(kVsew32, kVlmulF8); + SetRegisterValue("x1", mtype_val); + SetRegisterValue("x2", vtype_val); + + instruction_->AppendSource(CreateScalarSource("x1")); + instruction_->AppendSource(CreateScalarSource("x2")); + + instruction_->set_semantic_function(&RiscVZvtMsetMtype); + instruction_->Execute(nullptr); + + // Assert no destination operands are appended or written by the semantic + // function + EXPECT_EQ(instruction_->DestinationsSize(), 0); +} + +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_->set_semantic_function(&RiscVZvtMsetMtypei); + instruction_->Execute(nullptr); + + // Semantics state vl = 0; mtype.mtwiden = 1 + EXPECT_EQ(matrix_state_->mtwiden(), kMtwiden1); + EXPECT_EQ(state_->rv_vector()->vector_length(), 0); + EXPECT_EQ(state_->rv_vector()->selected_element_width(), 1); +} + +TEST_F(RiscVZvtInstructionsTest, MsetmtypeiImmediateDecoding) { + // mtwiden = 1 (TWIDEN = 1), vsew = 2 (SEW = 32 bits), altfmt = 1 (alternate). + instruction_->AppendSource(new ImmediateOperand<uint32_t>(kMtwiden1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(kVsew32)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(kAltfmtAlternate)); + + instruction_->set_semantic_function(&RiscVZvtMsetMtypei); + instruction_->Execute(nullptr); + + 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()->max_vector_length(), 32); +} + +TEST_F(RiscVZvtInstructionsTest, MsettnFunctionalDecoding) { + // Case 1: mtwiden != 0, rs1 > bounds -> clamps to min(VLMAX, + // effective_tile_edge) + SetRegisterValue("x1", 500); // Exceeds bounds + instruction_->AppendSource(CreateScalarSource("x1")); + instruction_->AppendDestination(CreateScalarDest("x2")); + + instruction_->set_semantic_function(&RiscVZvtMsetTn); + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType( + EncodeVtype(kVsew8, kVlmul1)); // SEW = 8 bits, kmax = 4, VLMAX = 128. + + instruction_->Execute(nullptr); + // effective_tile_edge for 8-bit is 32. min(128, 32) = 32. + EXPECT_EQ(state_->rv_vector()->vector_length(), 32); + EXPECT_EQ(GetRegisterValue("x2"), 32); + EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); + EXPECT_EQ(GetMstatusMs(), kMstatusStateDirty); + EXPECT_EQ(GetMstatusSd(), kMstatusSdSet); + + // Case 2: mtwiden == 0, rs1 > bounds -> clamps to VLMAX + SetMstatusVs(kMstatusStateInitial); + EXPECT_EQ(GetMstatusVs(), kMstatusStateInitial); + + matrix_state_->set_mtype(EncodeMtype(kMtwidenUnconfigured)); + instruction_->Execute(nullptr); + EXPECT_EQ(state_->rv_vector()->vector_length(), 128); + EXPECT_EQ(GetRegisterValue("x2"), 128); + EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, MsettmFunctionalDecoding) { + SetRegisterValue("x1", 500); + instruction_->AppendSource(CreateScalarSource("x1")); + instruction_->AppendDestination(CreateScalarDest("x2")); + + instruction_->set_semantic_function(&RiscVZvtMsetTm); + + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType( + EncodeVtype(kVsew8, kVlmul1)); // SEW = 8 bits, VLMAX = 128, bound = 32. + + instruction_->Execute(nullptr); + EXPECT_EQ(matrix_state_->tile_m(), 32); + EXPECT_EQ(GetRegisterValue("x2"), 32); + EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); + EXPECT_EQ(GetMstatusMs(), kMstatusStateDirty); + EXPECT_EQ(GetMstatusSd(), kMstatusSdSet); + + SetMstatusVs(kMstatusStateInitial); + EXPECT_EQ(GetMstatusVs(), kMstatusStateInitial); + + // mtwiden = 0, but retain active TM in mtype to ensure msettm resets it. + matrix_state_->set_mtype( + EncodeMtype(kMtwidenUnconfigured, /*tk=*/0, /*tm=*/32)); + ASSERT_EQ(matrix_state_->tile_m(), 32); + instruction_->Execute(nullptr); + EXPECT_EQ(matrix_state_->tile_m(), 0); + EXPECT_EQ(GetRegisterValue("x2"), 0); + EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, MsettkFunctionalDecoding) { + SetRegisterValue("x1", 500); // Exceeds Kmax + instruction_->AppendSource(CreateScalarSource("x1")); + instruction_->AppendDestination(CreateScalarDest("x2")); + + instruction_->set_semantic_function(&RiscVZvtMsetTk); + + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType( + EncodeVtype(kVsew8, kVlmul1)); // SEW = 8 bits, Kmax = 32 / 8 = 4. + + instruction_->Execute(nullptr); + EXPECT_EQ(matrix_state_->tile_k(), 4); + EXPECT_EQ(GetRegisterValue("x2"), 4); + EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); + EXPECT_EQ(GetMstatusMs(), kMstatusStateDirty); + EXPECT_EQ(GetMstatusSd(), kMstatusSdSet); + + SetMstatusVs(kMstatusStateInitial); + EXPECT_EQ(GetMstatusVs(), kMstatusStateInitial); + + // mtwiden = 0, but retain active TK in mtype to ensure msettk resets it. + matrix_state_->set_mtype( + EncodeMtype(kMtwidenUnconfigured, /*tk=*/4, /*tm=*/0)); + ASSERT_EQ(matrix_state_->tile_k(), 4); + instruction_->Execute(nullptr); + EXPECT_EQ(matrix_state_->tile_k(), 0); + EXPECT_EQ(GetRegisterValue("x2"), 0); + EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, CeilEteEveScalesVlmulCorrectly) { + // Use a configuration where vector register byte length is 16 (128 bits) + // and tile_elements is 32, so that effective_tile_elements / ete_eve_lmul_den + // > 1. + FlatDemandMemory memory; + RiscVState rv_state("rv32_16B", RiscVXlen::RV32, &memory); + RiscVVectorState vec_state(&rv_state, /*vector_register_byte_length=*/16); + rv_state.set_rv_vector(&vec_state); + + ASSERT_OK_AND_ASSIGN(auto matrix_state, RiscVZvtMatrixState::Create( + &rv_state, /*tile_elements=*/32)); + + auto* inst = new Instruction(0x1000, &rv_state); + inst->set_size(4); + inst->AppendSource(new ImmediateOperand<uint32_t>(kMtwiden1)); + inst->AppendSource(new ImmediateOperand<uint32_t>(kVsew8)); + inst->AppendSource(new ImmediateOperand<uint32_t>(kAltfmtStandard)); + inst->set_semantic_function(&RiscVZvtMsetMtypei); + + inst->Execute(nullptr); + inst->DecRef(); + + const auto expected = CalculateExpectedVectorGeometry( + /*vlen_bytes=*/16, /*tile_elements=*/32, /*sew_bits=*/8, /*twiden=*/1); + EXPECT_EQ(vec_state.vtype() & kVlmulMask, expected.vlmul); + EXPECT_EQ(vec_state.max_vector_length(), expected.max_vector_length); +} + +TEST_F(RiscVZvtInstructionsTest, UpdateVectorMatrixGeometryEteEveDenScaling) { + // Configuration: vector register length = 32 bytes (256 bits), + // tile_elements = 32, sew = 16 bits (2 bytes), twiden = 1. + FlatDemandMemory memory; + RiscVState rv_state("rv32_32B", RiscVXlen::RV32, &memory); + RiscVVectorState vec_state(&rv_state, /*vector_register_byte_length=*/32); + rv_state.set_rv_vector(&vec_state); + + ASSERT_OK_AND_ASSIGN(auto matrix_state, RiscVZvtMatrixState::Create( + &rv_state, /*tile_elements=*/32)); + + auto* inst = new Instruction(0x1000, &rv_state); + inst->set_size(4); + inst->AppendSource(new ImmediateOperand<uint32_t>(kMtwiden1)); + inst->AppendSource(new ImmediateOperand<uint32_t>(kVsew16)); + inst->AppendSource(new ImmediateOperand<uint32_t>(kAltfmtStandard)); + inst->set_semantic_function(&RiscVZvtMsetMtypei); + + inst->Execute(nullptr); + inst->DecRef(); + + const auto expected = CalculateExpectedVectorGeometry( + /*vlen_bytes=*/32, /*tile_elements=*/32, /*sew_bits=*/16, /*twiden=*/1); + EXPECT_EQ(vec_state.vtype() & kVlmulMask, expected.vlmul); + EXPECT_EQ(vec_state.max_vector_length(), expected.max_vector_length); +} + +TEST_F(RiscVZvtInstructionsTest, + UpdateVectorMatrixGeometryEteEveDenScalingPlusOne) { + // Configuration: VLEN = 16 bytes (128 bits), TE = 32, SEW = 32 bits (4B). + // twiden = 1 -> tew = 32 bits. + FlatDemandMemory memory; + RiscVState rv_state("rv32_16B_sew32", RiscVXlen::RV32, &memory); + RiscVVectorState vec_state(&rv_state, /*vector_register_byte_length=*/16); + rv_state.set_rv_vector(&vec_state); + + ASSERT_OK_AND_ASSIGN(auto matrix_state, RiscVZvtMatrixState::Create( + &rv_state, /*tile_elements=*/32)); + + auto* inst = new Instruction(0x1000, &rv_state); + inst->set_size(4); + inst->AppendSource(new ImmediateOperand<uint32_t>(kMtwiden1)); + inst->AppendSource(new ImmediateOperand<uint32_t>(kVsew32)); + inst->AppendSource(new ImmediateOperand<uint32_t>(kAltfmtStandard)); + inst->set_semantic_function(&RiscVZvtMsetMtypei); + + inst->Execute(nullptr); + inst->DecRef(); + + const auto expected = CalculateExpectedVectorGeometry( + /*vlen_bytes=*/16, /*tile_elements=*/32, /*sew_bits=*/32, /*twiden=*/1); + EXPECT_EQ(vec_state.vtype() & kVlmulMask, expected.vlmul); + EXPECT_EQ(vec_state.max_vector_length(), expected.max_vector_length); +} + +TEST_F(RiscVZvtInstructionsTest, UpdateVectorMatrixGeometryMaxKScaling) { + // Configuration: VLEN = 8 bytes (64 bits), TE = 32, SEW = 8 bits (1B). + // twiden = 1 -> tew = 8 bits. + FlatDemandMemory memory; + RiscVState rv_state("rv32_8B_sew8", RiscVXlen::RV32, &memory); + RiscVVectorState vec_state(&rv_state, /*vector_register_byte_length=*/8); + rv_state.set_rv_vector(&vec_state); + + ASSERT_OK_AND_ASSIGN(auto matrix_state, RiscVZvtMatrixState::Create( + &rv_state, /*tile_elements=*/32)); + + auto* inst = new Instruction(0x1000, &rv_state); + inst->set_size(4); + inst->AppendSource(new ImmediateOperand<uint32_t>(kMtwiden1)); + inst->AppendSource(new ImmediateOperand<uint32_t>(kVsew8)); + inst->AppendSource(new ImmediateOperand<uint32_t>(kAltfmtStandard)); + inst->set_semantic_function(&RiscVZvtMsetMtypei); + + inst->Execute(nullptr); + inst->DecRef(); + + const auto expected = CalculateExpectedVectorGeometry( + /*vlen_bytes=*/8, /*tile_elements=*/32, /*sew_bits=*/8, /*twiden=*/1); + EXPECT_EQ(vec_state.vtype() & kVlmulMask, expected.vlmul); + EXPECT_EQ(vec_state.max_vector_length(), expected.max_vector_length); +} + +TEST_F(RiscVZvtInstructionsTest, UpdateVectorMatrixGeometryTwidenScaling) { + // Configuration: VLEN = 16 bytes (128 bits), TE = 32, SEW = 16 bits (2B). + // mtwiden = 2 (twiden = 2) -> tew = 32 bits (<= 32, no vill). + FlatDemandMemory memory; + RiscVState rv_state("rv32_16B_sew16_twiden2", RiscVXlen::RV32, &memory); + RiscVVectorState vec_state(&rv_state, /*vector_register_byte_length=*/16); + rv_state.set_rv_vector(&vec_state); + + ASSERT_OK_AND_ASSIGN(auto matrix_state, RiscVZvtMatrixState::Create( + &rv_state, /*tile_elements=*/32)); + + auto* inst = new Instruction(0x1000, &rv_state); + inst->set_size(4); + inst->AppendSource(new ImmediateOperand<uint32_t>(kMtwiden2)); + inst->AppendSource(new ImmediateOperand<uint32_t>(kVsew16)); + inst->AppendSource(new ImmediateOperand<uint32_t>(kAltfmtStandard)); + inst->set_semantic_function(&RiscVZvtMsetMtypei); + + inst->Execute(nullptr); + inst->DecRef(); + + const auto expected = CalculateExpectedVectorGeometry( + /*vlen_bytes=*/16, /*tile_elements=*/32, /*sew_bits=*/16, /*twiden=*/2); + EXPECT_EQ(vec_state.vtype() & kVlmulMask, expected.vlmul); + EXPECT_EQ(vec_state.max_vector_length(), expected.max_vector_length); +} + +TEST_F(RiscVZvtInstructionsTest, SetVectorStateDirtyRv32UpdatesMstatusVsAndSd) { + // Clear mstatus.VS to Initial (1) and clear SD. + SetMstatusVs(kMstatusStateInitial); + state_->mstatus()->Set(state_->mstatus()->GetUint64() & ~kMstatusSdMaskRv32); + + EXPECT_EQ(GetMstatusVs(), kMstatusStateInitial); + EXPECT_EQ(GetMstatusSd(/*is_rv64=*/false), kMstatusSdClean); + + // 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_->set_semantic_function(&RiscVZvtMsetMtypei); + + instruction_->Execute(nullptr); + + // Must set VS to Dirty (3) and SD (bit 31 on RV32) to 1. + // If state != nullptr return; was mutated, neither bit is set. + // If sd_bit was mutated to 63 on RV32, bit 31 is not set. + EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); + EXPECT_EQ(GetMstatusSd(/*is_rv64=*/false), kMstatusSdSet); + EXPECT_EQ(GetMstatusSd(/*is_rv64=*/true), kMstatusSdClean); +} + +TEST_F(RiscVZvtInstructionsTest, SetVectorStateDirtyRv64UpdatesMstatusVsAndSd) { + auto rv64 = Rv64TestContext::Create("rv64_test"); + ASSERT_OK(rv64); + + // Clear VS and SD (bit 63 on RV64). + (*rv64)->SetMstatusVs(kMstatusStateInitial); + (*rv64)->state.mstatus()->Set((*rv64)->state.mstatus()->GetUint64() & + ~kMstatusSdMaskRv64); + + EXPECT_EQ((*rv64)->GetMstatusVs(), kMstatusStateInitial); + EXPECT_EQ((*rv64)->GetMstatusSd(), kMstatusSdClean); + + 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)); + inst->AppendSource(new ImmediateOperand<uint32_t>(kAltfmtStandard)); + inst->set_semantic_function(&RiscVZvtMsetMtypei); + + inst->Execute(nullptr); + inst->DecRef(); + + // 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); +} + +TEST_F(RiscVZvtInstructionsTest, MsetmtypeInvalidSewSetsVill) { + ResetInstruction(); + // SEW = 64 bits (kVsew64 > kElen of 32 bits for Zve32x base). + instruction_->AppendSource(new ImmediateOperand<uint32_t>(kMtwiden1)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(kVsew64)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(kAltfmtStandard)); + instruction_->set_semantic_function(&RiscVZvtMsetMtypei); + + instruction_->Execute(nullptr); + + // Per spec, when tew > kElen, vill is set and vl is set to 0. + EXPECT_NE(vector_state_->vtype() & kVillMask, 0U); + EXPECT_EQ(vector_state_->vector_length(), 0); +} + +TEST_F(RiscVZvtInstructionsTest, + VtZeroClearsActiveTileElementsAndDirtiesState) { + // Configure matrix state: TM = 4, TN (vl) = 4, TEW = 8. + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + matrix_state_->set_tile_m(4); + 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); + } + } + + // Clear mstatus MS and VS. + SetMstatusMs(kMstatusStateInitial); + SetMstatusVs(kMstatusStateInitial); + + ResetInstruction(); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(0)); // 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))); + } + + // MS and VS must both be Dirty. + EXPECT_EQ(GetMstatusMs(), kMstatusStateDirty); + EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, VtDiscardHintsTileDeadAndDirtiesVectorState) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + vector_state_->set_vstart(2); + + // Set VS = initial (1) and MS = dirty (3). + SetMstatusVs(kMstatusStateInitial); + SetMstatusMs(kMstatusStateDirty); + state_->mstatus()->Set(state_->mstatus()->GetUint64() | kMstatusSdMaskRv32); + + ResetInstruction(); + instruction_->set_semantic_function(&RiscVZvtVtDiscard); + instruction_->Execute(nullptr); + + // vstart is cleared, matrix state reset to initial (1), vector state dirtied + // (3). If SetMatrixStateInitial's csr->Set(val) was removed, MS remains dirty + // (3). + EXPECT_EQ(vector_state_->vstart(), 0); + EXPECT_EQ(GetMstatusMs(), kMstatusStateInitial); + EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); + EXPECT_EQ(GetMstatusSd(/*is_rv64=*/false), kMstatusSdSet); +} + +TEST_F(RiscVZvtInstructionsTest, VtDiscardTrapsWhenVtypeVill) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(kVillMask); + + // Turn on MS and VS in mstatus so trap is specifically due to vill. + SetMstatusVs(kMstatusStateInitial); + SetMstatusMs(kMstatusStateInitial); + + ScopedTrapCapture trap_capture(state_); + + 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)); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvVtTransfersTileSliceToVectorRegister) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + matrix_state_->set_tile_m(4); + vector_state_->set_vector_length(4); + + // Ensure MS is on (initial). + 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))); + } + + // TSS for row 1 of tile 0: pattern = row, tile = 0, index = 1. + SetRegisterValue("x1", EncodeTss(/*tile=*/0, kTssPatternRow, /*index=*/1)); + + ResetInstruction(); + instruction_->AppendSource(CreateScalarSource("x1")); + instruction_->AppendDestination(CreateVectorDestOperand("v2")); + instruction_->set_semantic_function(&RiscVZvtVtmvVt); + + instruction_->Execute(nullptr); + + // Vector register v2 must receive the row data. + auto* v2 = state_->GetRegister<RVVectorRegister>("v2").first; + auto span = v2->data_buffer()->Get<uint8_t>(); + EXPECT_THAT(span.subspan(0, 4), testing::ElementsAre(0x10, 0x11, 0x12, 0x13)); + // VS must be dirty. + EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvTvTransfersVectorRegisterToTileSlice) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + matrix_state_->set_tile_m(4); + vector_state_->set_vector_length(4); + + // Ensure MS is on (initial). + SetMstatusMs(kMstatusStateInitial); + + // Set up source vector register v4 with 4 bytes: 0x51, 0x52, 0x53, 0x54. + auto* v4 = state_->GetRegister<RVVectorRegister>("v4").first; + auto* db = v4->data_buffer(); + auto span = db->Get<uint8_t>(); + span[0] = 0x51; + span[1] = 0x52; + span[2] = 0x53; + span[3] = 0x54; + + // TSS for row 2 of tile 0: pattern = row, tile = 0, index = 2. + SetRegisterValue("x1", EncodeTss(/*tile=*/0, kTssPatternRow, /*index=*/2)); + + ResetInstruction(); + instruction_->AppendSource(CreateVectorSourceOperand("v4")); + instruction_->AppendSource(CreateScalarSource("x1")); + instruction_->set_semantic_function(&RiscVZvtVtmvTv); + + instruction_->Execute(nullptr); + + // Check tile elements at (0, 2, c). + ASSERT_OK_AND_ASSIGN(auto row_elements, + GetTileRow<uint8_t>(/*tile=*/0, /*row=*/2, /*count=*/4)); + EXPECT_THAT(row_elements, testing::ElementsAre(0x51, 0x52, 0x53, 0x54)); + // MS must be dirty. + EXPECT_EQ(GetMstatusMs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvVtResetsVstartToZero) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + matrix_state_->set_tile_m(4); + vector_state_->set_vector_length(4); + vector_state_->set_vstart(1); + + // Ensure MS is on (initial). + 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))); + } + + // TSS for row 1 of tile 0: pattern = row, tile = 0, index = 1. + SetRegisterValue("x1", EncodeTss(/*tile=*/0, kTssPatternRow, /*index=*/1)); + auto* v2 = state_->GetRegister<RVVectorRegister>("v2").first; + // Initialize v2 elements: element 0 will be undisturbed since vstart = 1. + v2->data_buffer()->Get<uint8_t>()[0] = 0xAA; + + ResetInstruction(); + instruction_->AppendSource(CreateScalarSource("x1")); + instruction_->AppendDestination(CreateVectorDestOperand("v2")); + instruction_->set_semantic_function(&RiscVZvtVtmvVt); + + instruction_->Execute(nullptr); + + auto span = v2->data_buffer()->Get<uint8_t>(); + EXPECT_THAT(span.subspan(0, 2), testing::ElementsAre(0xAA, 0x11)); + EXPECT_EQ(vector_state_->vstart(), 0); +} + +TEST_F(RiscVZvtInstructionsTest, VtmvTvResetsVstartToZero) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + matrix_state_->set_tile_m(4); + vector_state_->set_vector_length(4); + vector_state_->set_vstart(1); + + // Ensure MS is on (initial). + SetMstatusMs(kMstatusStateInitial); + + auto* v4 = state_->GetRegister<RVVectorRegister>("v4").first; + auto* db = v4->data_buffer(); + auto span = db->Get<uint8_t>(); + span[0] = 0x51; + span[1] = 0x52; + span[2] = 0x53; + 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)); + + // TSS for row 2 of tile 0: pattern = row, tile = 0, index = 2. + SetRegisterValue("x1", EncodeTss(/*tile=*/0, kTssPatternRow, /*index=*/2)); + + ResetInstruction(); + instruction_->AppendSource(CreateVectorSourceOperand("v4")); + instruction_->AppendSource(CreateScalarSource("x1")); + instruction_->set_semantic_function(&RiscVZvtVtmvTv); + + instruction_->Execute(nullptr); + + ASSERT_OK_AND_ASSIGN(auto row_elements, + GetTileRow<uint8_t>(/*tile=*/0, /*row=*/2, /*count=*/2)); + EXPECT_THAT(row_elements, testing::ElementsAre(0xEE, 0x52)); + EXPECT_EQ(vector_state_->vstart(), 0); +} + +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); + + // Turn on MS in mstatus so instructions don't trap. + (*rv64)->SetMstatusMs(kMstatusStateInitial); + + // Initialize x1 register with high bits set. + 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); + recycled_db->Set<uint64_t>(0, 0xDEAD'BEEF'CAFE'BABEULL); + recycled_db->DecRef(); + + auto* inst = new Instruction(0x1000, &(*rv64)->state); + inst->set_size(4); + inst->AppendSource(new ImmediateOperand<uint32_t>(4)); // requested col = 4 + inst->AppendDestination(reg1->CreateDestinationOperand(0)); + inst->set_semantic_function(&RiscVZvtMsetTn); + + inst->Execute(nullptr); + inst->DecRef(); + + // Entire 64 bits must be written (upper 32 bits zeroed). + EXPECT_EQ(reg1->data_buffer()->Get<uint64_t>(0), 4ULL); + EXPECT_EQ(reg1->data_buffer()->Get<uint64_t>(0) >> 32, 0ULL); +} + +TEST_F(RiscVZvtInstructionsTest, SetMatrixStateDirtyRv64UpdatesMstatusMsAndSd) { + auto rv64 = Rv64TestContext::Create("rv64_matrix_dirty_test"); + ASSERT_OK(rv64); + + // 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); + + EXPECT_EQ((*rv64)->GetMstatusMs(), kMstatusStateInitial); + EXPECT_EQ((*rv64)->GetMstatusSd(), kMstatusSdClean); + + auto* inst = new Instruction(0x1000, &(*rv64)->state); + inst->set_size(4); + inst->AppendSource(new ImmediateOperand<uint32_t>(0)); // 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((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); + 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); + EXPECT_EQ(absl::bit_cast<uint32_t>(exact_res), 0x3f800000U); + + // Null fp_state falls back to standard static_cast. + float null_res = DoubleToFloatROD(inexact_d, nullptr); + EXPECT_EQ(null_res, static_cast<float>(inexact_d)); +} + +TEST_F(RiscVZvtInstructionsTest, + MsetmtypeiZeroMtwidenResetsMtypeAndDirtiesVectorState) { + // Set VS = Initial (1) and clear SD. + SetMstatusVs(kMstatusStateInitial); + state_->mstatus()->Set(state_->mstatus()->GetUint64() & ~kMstatusSdMaskRv32); + + ResetInstruction(); + // mtwiden = 0 (unconfigured), vsew = 16 bits, altfmt = 0 (standard). + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(kMtwidenUnconfigured)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(kVsew16)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(kAltfmtStandard)); + instruction_->set_semantic_function(&RiscVZvtMsetMtypei); + + instruction_->Execute(nullptr); + + // 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. + EXPECT_FALSE(state_->rv_vector()->vector_exception()); + EXPECT_EQ(state_->rv_vector()->vtype() & kVillMask, 0U); +} + +TEST_F(RiscVZvtInstructionsTest, + MsetmtypeZeroMtwidenResetsMtypeAndDirtiesVectorState) { + // Set VS = Initial (1) and clear SD. + SetMstatusVs(kMstatusStateInitial); + state_->mstatus()->Set(state_->mstatus()->GetUint64() & ~kMstatusSdMaskRv32); + + ResetInstruction(); + // rs1: mtwiden = 0 (unconfigured), rs2: vsew = 16 bits, vill = 0. + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(EncodeMtype(kMtwidenUnconfigured))); + instruction_->AppendSource( + new ImmediateOperand<uint32_t>(EncodeVtype(kVsew16, kVlmul1))); + instruction_->set_semantic_function(&RiscVZvtMsetMtype); + + instruction_->Execute(nullptr); + + // 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)`. + 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); +} + +TEST_F(RiscVZvtInstructionsTest, MsetTmTrapsWhenMatrixStateMissing) { + ExpectTrapWithoutMatrixState(&RiscVZvtMsetTm); +} + +TEST_F(RiscVZvtInstructionsTest, MsetTkTrapsWhenMatrixStateMissing) { + ExpectTrapWithoutMatrixState(&RiscVZvtMsetTk); +} + +TEST_F(RiscVZvtInstructionsTest, MsetMtypeTrapsWhenMatrixStateMissing) { + ExpectTrapWithoutMatrixState(&RiscVZvtMsetMtype); +} + +TEST_F(RiscVZvtInstructionsTest, MsetMtypeiTrapsWhenMatrixStateMissing) { + ExpectTrapWithoutMatrixState(&RiscVZvtMsetMtypei); +} + +TEST_F(RiscVZvtInstructionsTest, MsetTnClampsToEffectiveTileEdgeForTew64) { + // Configure matrix_state with SEW = 32 and twiden = 2 (tew = 64). + // ETE for tew = 64 is tile_elements_ / 2 = 32 / 2 = 16. + // If mutated to (sew_bits * twiden) - 1 = 63, ETE becomes 32. + matrix_state_->set_mtype(EncodeMtype(kMtwiden2)); + // SEW = 32 bits, LMUL = 1 -> max_vl = 32. + vector_state_->SetVectorType(EncodeVtype(kVsew32, kVlmul1)); + ASSERT_EQ(vector_state_->max_vector_length(), 32); + + SetRegisterValue("x1", 32); + + ResetInstruction(); + instruction_->AppendSource(CreateScalarSource("x1")); + instruction_->AppendDestination(CreateScalarDest("x1")); + instruction_->set_semantic_function(&RiscVZvtMsetTn); + + instruction_->Execute(nullptr); + + // Must clamp to effective_tile_edge(64) = 16. + EXPECT_EQ(GetRegisterValue("x1"), 16U); + EXPECT_EQ(vector_state_->vector_length(), 16U); +} + +TEST_F(RiscVZvtInstructionsTest, + VtmvVtTransfersColumnTileSliceToVectorRegister) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + matrix_state_->set_tile_m(4); + vector_state_->set_vector_length(4); + + // Ensure MS is on (initial). + SetMstatusMs(kMstatusStateInitial); + + // 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))); + } + } + + // TSS for column 1 of tile 0: pattern = column, tile = 0, index = 1. + SetRegisterValue("x1", EncodeTss(/*tile=*/0, kTssPatternCol, /*index=*/1)); + + ResetInstruction(); + instruction_->AppendSource(CreateScalarSource("x1")); + instruction_->AppendDestination(CreateVectorDestOperand("v2")); + instruction_->set_semantic_function(&RiscVZvtVtmvVt); + + instruction_->Execute(nullptr); + + // Vector register v2 must receive column 1 elements: + // row 0: 0x01, row 1: 0x11, row 2: 0x21, row 3: 0x31. + // If mutated to (false), row 1 is loaded instead: 0x10, 0x11, 0x12, 0x13. + auto* v2 = state_->GetRegister<RVVectorRegister>("v2").first; + auto span = v2->data_buffer()->Get<uint8_t>(); + EXPECT_THAT(span.subspan(0, 4), testing::ElementsAre(0x01, 0x11, 0x21, 0x31)); + EXPECT_EQ(GetMstatusVs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, MsetTmClampsToEffectiveTileEdgeForTew64) { + // Configure matrix_state with SEW = 32 and twiden = 2 (tew = 64). + // ETE for tew = 64 is tile_elements_ / 2 = 32 / 2 = 16. + // If mutated to (sew_bits * twiden) - 1 = 63, ETE becomes 32. + matrix_state_->set_mtype(EncodeMtype(kMtwiden2)); + // SEW = 32 bits, LMUL = 1 -> max_vl = 32. + vector_state_->SetVectorType(EncodeVtype(kVsew32, kVlmul1)); + ASSERT_EQ(vector_state_->max_vector_length(), 32); + + SetRegisterValue("x1", 32); + + ResetInstruction(); + instruction_->AppendSource(CreateScalarSource("x1")); + instruction_->AppendDestination(CreateScalarDest("x1")); + instruction_->set_semantic_function(&RiscVZvtMsetTm); + + instruction_->Execute(nullptr); + + // Must clamp to effective_tile_edge(64) = 16. + EXPECT_EQ(GetRegisterValue("x1"), 16U); + EXPECT_EQ(matrix_state_->tile_m(), 16U); +} + +TEST_F(RiscVZvtInstructionsTest, + VtmvTvTransfersVectorRegisterToColumnTileSlice) { + matrix_state_->set_mtype(EncodeMtype(kMtwiden1)); + vector_state_->SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + matrix_state_->set_tile_m(4); + vector_state_->set_vector_length(4); + + // Ensure MS is on (initial). + SetMstatusMs(kMstatusStateInitial); + + // Set up source vector register v4 with 4 bytes: 0xA1, 0xB2, 0xC3, 0xD4. + auto* v4 = state_->GetRegister<RVVectorRegister>("v4").first; + auto span = v4->data_buffer()->Get<uint8_t>(); + span[0] = 0xA1; + span[1] = 0xB2; + span[2] = 0xC3; + span[3] = 0xD4; + + // TSS for column 1 of tile 0: pattern = column, tile = 0, index = 1. + ResetInstruction(); + instruction_->AppendSource(CreateVectorSourceOperand("v4")); + instruction_->AppendSource(new ImmediateOperand<uint32_t>( + EncodeTss(/*tile=*/0, kTssPatternCol, /*index=*/1))); + instruction_->set_semantic_function(&RiscVZvtVtmvTv); + + instruction_->Execute(nullptr); + + // Column 1 must receive the elements: (r, 1) for r = 0..3. + ASSERT_OK_AND_ASSIGN( + auto col_elements, + GetTileColumn<uint8_t>(/*tile=*/0, /*col=*/1, /*count=*/4)); + EXPECT_THAT(col_elements, testing::ElementsAre(0xA1, 0xB2, 0xC3, 0xD4)); + + // 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)); + EXPECT_EQ(elem_1_0, 0x00); + // MS must be dirty. + EXPECT_EQ(GetMstatusMs(), kMstatusStateDirty); +} + +TEST_F(RiscVZvtInstructionsTest, + MsetmtypeSetsVectorExceptionWhenTewExceedsElen) { + // SEW = 32 (kVsew32), twiden = 2 (kMtwiden2) -> tew = 64 > kElen (32). + // vill triggers: sets vector exception, vill in vtype, vl = 0, mtype = 0. + // Set vl and mtype non-zero to verify set_vector_length(0) and set_mtype(0). + state_->rv_vector()->set_vector_length(16); + matrix_state_->set_mtype(123); + + instruction_->AppendSource(new ImmediateOperand<uint32_t>(kMtwiden2)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(kVsew32)); + instruction_->AppendSource(new ImmediateOperand<uint32_t>(kAltfmtStandard)); + + 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) { + SetRegisterValue("x1", 500); + instruction_->AppendSource(CreateScalarSource("x1")); + instruction_->AppendDestination(CreateScalarDest("x2")); + instruction_->set_semantic_function(&RiscVZvtMsetTm); + + // mtwiden = 0 with TM = 24 in mtype. + matrix_state_->set_mtype( + 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); + + 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); +} + +TEST_F(RiscVZvtInstructionsTest, + MsetTkZeroResetsTileKAndSetsVsDirtyWhenMtwidenIsZero) { + SetRegisterValue("x1", 500); + instruction_->AppendSource(CreateScalarSource("x1")); + instruction_->AppendDestination(CreateScalarDest("x2")); + instruction_->set_semantic_function(&RiscVZvtMsetTk); + + // mtwiden = 0 with TK = 4 in mtype. + matrix_state_->set_mtype( + 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); + + 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); +} + +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); + state.set_rv_vector(&vec_state); + vec_state.SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + vec_state.set_vector_length(8); + vec_state.set_vstart(2); + + ASSERT_OK_AND_ASSIGN(auto matrix_state, + RiscVZvtMatrixState::Create(&state, 16)); + matrix_state->set_mtype(EncodeMtype(kMtwiden1)); + matrix_state->set_tile_m(8); + + // Turn on MS in mstatus so instructions don't trap. + ASSERT_OK_AND_ASSIGN(auto* mstatus_csr, state.csr_set()->GetCsr("mstatus")); + mstatus_csr->Set(static_cast<uint64_t>( + mstatus_csr->GetUint64() | + (static_cast<uint64_t>(kMstatusStateInitial) << kMstatusMsShift))); + + // Populate row 0 of tile 0 with 8 distinct bytes: 0x10 .. 0x17. + for (int c = 0; c < 8; ++c) { + ASSERT_OK(matrix_state->SetElem<uint8_t>(0, 0, c, 8, 0x10 + c)); + } + + auto* v2 = state.GetRegister<RVVectorRegister>("v2").first; + auto* v3 = state.GetRegister<RVVectorRegister>("v3").first; + v2->data_buffer()->Get<uint8_t>()[7] = 0xAA; + v3->data_buffer()->Get<uint8_t>()[0] = 0xBB; + + std::vector<RegisterBase*> vd_group = {v2, v3}; + auto* vd = new RV32VectorDestinationOperand( + absl::Span<RegisterBase*>(vd_group), 0, "v2"); + + auto* inst = new Instruction(0x1000, &state); + inst->set_size(4); + // TSS: row 0 of tile 0 -> pattern = row, tile = 0, index = 0. + inst->AppendSource(new ImmediateOperand<uint32_t>( + EncodeTss(/*tile=*/0, kTssPatternRow, /*index=*/0))); + inst->AppendDestination(vd); + inst->set_semantic_function(&RiscVZvtVtmvVt); + + inst->Execute(nullptr); + inst->DecRef(); + + // Clean code: elements_per_vector = 8, num_regs = 1. + // Writes row 0 elements [0..7] into v2[0..7]. v2[7] becomes 0x17. + // v3 is untouched and retains 0xBB. + // Mutated code (elements_per_vector = 7): + // num_regs = 2. r = 0 writes elements 0..6 (v2[7] untouched = 0xAA). + // r = 1 writes element 7 into v3[0] (v3[0] becomes 0x17). + EXPECT_EQ(v2->data_buffer()->Get<uint8_t>()[7], 0x17); + EXPECT_EQ(v3->data_buffer()->Get<uint8_t>()[0], 0xBB); + EXPECT_EQ(vec_state.vstart(), 0); +} + +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); + state.set_rv_vector(&vec_state); + vec_state.SetVectorType(EncodeVtype(kVsew8, kVlmul1)); + vec_state.set_vector_length(10); + vec_state.set_vstart(2); + + ASSERT_OK_AND_ASSIGN(auto matrix_state, + RiscVZvtMatrixState::Create(&state, 16)); + matrix_state->set_mtype(EncodeMtype(kMtwiden1)); + matrix_state->set_tile_m(10); + + // Turn on MS in mstatus so instructions don't trap. + ASSERT_OK_AND_ASSIGN(auto* mstatus_csr, state.csr_set()->GetCsr("mstatus")); + mstatus_csr->Set(static_cast<uint64_t>( + mstatus_csr->GetUint64() | + (static_cast<uint64_t>(kMstatusStateInitial) << kMstatusMsShift))); + + auto* v4 = state.GetRegister<RVVectorRegister>("v4").first; + auto* v5 = state.GetRegister<RVVectorRegister>("v5").first; + // Initialize v4[7] with 0x77, v5[0] with 0x88, and v5[1] with 0x99. + v4->data_buffer()->Get<uint8_t>()[7] = 0x77; + v5->data_buffer()->Get<uint8_t>()[0] = 0x88; + v5->data_buffer()->Get<uint8_t>()[1] = 0x99; + + std::vector<RegisterBase*> vs_group = {v4, v5}; + auto* vs = + new RV32VectorSourceOperand(absl::Span<RegisterBase*>(vs_group), "v4"); + + auto* inst = new Instruction(0x1000, &state); + inst->set_size(4); + inst->AppendSource(vs); + // TSS: row 0 of tile 0 -> pattern = row, tile = 0, index = 0. + inst->AppendSource(new ImmediateOperand<uint32_t>( + EncodeTss(/*tile=*/0, kTssPatternRow, /*index=*/0))); + inst->set_semantic_function(&RiscVZvtVtmvTv); + + inst->Execute(nullptr); + inst->DecRef(); + + // 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)); + 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)); + EXPECT_EQ(elem_9, 0x99); + EXPECT_EQ(vec_state.vstart(), 0); +} + +} // namespace