vulkan: under toggle, disguise matrix multiply operands - Add dawn::native::vulkan::PhysicalDevice::IsMesa - Also add a method to check whether a Mesa driver version is strictly older than a given version number. - Add toggle vulkan_disguise_transpose_matrix_multiply defaulted to true for Mesa drivers before 27.0 - When active, turns on a Tint IR transform in the SPIR-V backend that rewrites the first matrix operand to a matrix multiply when either matrix is non-square. When both operands are square, then they also have the same size, and the bug does not occur. - Add end2end ShaderMatrixLoweringTest verifying the result of a matrix multiply with transposed arguments. Fixed: 591811902 Change-Id: Icafe086a5856ad124d73578552f442b96a6a6964 Reviewed-on: https://dawn-review.googlesource.com/c/dawn/+/367196 Commit-Queue: James Price <jrprice@google.com> Reviewed-by: Steven Perron <stevenperron@google.com> Reviewed-by: James Price <jrprice@google.com>
diff --git a/src/dawn/native/Toggles.cpp b/src/dawn/native/Toggles.cpp index 7cd350a..8e51e5d 100644 --- a/src/dawn/native/Toggles.cpp +++ b/src/dawn/native/Toggles.cpp
@@ -975,6 +975,11 @@ "Allows the GL backend to defer GL commands until Queue::Submit is called. This includes " "backend resource creations which will also be deferred.", "https://crbug.com/dawn/451928481", ToggleStage::Device}}, + {Toggle::VulkanDisguiseTransposeMatrixMultiply, + {"vulkan_disguise_transpose_matrix_multiply", + "Disguise matrix multiplications with a transposed matrix operand to work around a " + "shader compiler bug in Mesa Vulkan drivers.", + "https://crbug.com/591811902", ToggleStage::Device}}, {Toggle::DisableTransientAttachment, {"disable_transient_attachment", "Disable TextureUsage TransientAttachment usage.", "https://crbug.com/dawn/462620664", ToggleStage::Device}},
diff --git a/src/dawn/native/Toggles.h b/src/dawn/native/Toggles.h index d7f7e21..440a71b 100644 --- a/src/dawn/native/Toggles.h +++ b/src/dawn/native/Toggles.h
@@ -233,6 +233,7 @@ IgnoreImportedAHardwareBufferVulkanImageSize, GLAllowContextOnMultiThreads, GLDefer, + VulkanDisguiseTransposeMatrixMultiply, DisableTransientAttachment, AutoMapBackendBuffer, PolyfillBoolVecDynamicLoad,
diff --git a/src/dawn/native/vulkan/PhysicalDeviceVk.cpp b/src/dawn/native/vulkan/PhysicalDeviceVk.cpp index 66ca04f..bf8a2cc 100644 --- a/src/dawn/native/vulkan/PhysicalDeviceVk.cpp +++ b/src/dawn/native/vulkan/PhysicalDeviceVk.cpp
@@ -62,7 +62,18 @@ namespace { -gpu_info::DriverVersion DecodeVulkanDriverVersion(uint32_t vendorID, uint32_t versionRaw) { +gpu_info::DriverVersion DecodeVulkanDriverVersion(const VulkanDeviceInfo& deviceInfo) { + const uint32_t vendorID = deviceInfo.properties.vendorID; + const uint32_t versionRaw = deviceInfo.properties.driverVersion; + + // Check Mesa first. It can cover many GPUs including the exceptional + // cases below. + if (deviceInfo.IsMesaDriver()) { + return {static_cast<uint16_t>(versionRaw >> 22), + static_cast<uint16_t>((versionRaw >> 12) & 0x3FF), + static_cast<uint16_t>(versionRaw & 0xFFF)}; + } + gpu_info::DriverVersion driverVersion; switch (vendorID) { case gpu_info::kVendorID_Nvidia: @@ -183,14 +194,13 @@ MaybeError PhysicalDevice::InitializeImpl() { DAWN_TRY_ASSIGN(mDeviceInfo, GatherDeviceInfo(*this)); - mDriverVersion = DecodeVulkanDriverVersion(mDeviceInfo.properties.vendorID, - mDeviceInfo.properties.driverVersion); + mDriverVersion = DecodeVulkanDriverVersion(mDeviceInfo); const std::string driverVersionStr = mDriverVersion.ToString(); // Disable Vulkan adapter on Windows Intel driver < 30.0.101.2111 due to flaky // issues. const gpu_info::IntelWindowsDriverVersion kDriverVersion({30, 0, 101, 2111}); - if (IsWindows() && gpu_info::IsIntel(mDeviceInfo.properties.vendorID) && + if (IsWindows() && !IsMesaDriver() && gpu_info::IsIntel(mDeviceInfo.properties.vendorID) && gpu_info::IntelWindowsDriverVersion(mDriverVersion) < kDriverVersion) { return DAWN_UNRECOVERABLE_ERROR( "Disable Intel Vulkan adapter on Windows driver version %s. See " @@ -1552,6 +1562,12 @@ } else { deviceToggles->Default(Toggle::VulkanUseRasterizationOrderAttachmentAccess, true); } + + // Work around a Mesa SPIR-V to NIR bug where it incorrectly lowers some + // matrix multiply operations. TODO(crbug.com/591905810) + if (IsMesaDriver() && GetDriverVersion() < gpu_info::DriverVersion({27, 0, 0})) { + deviceToggles->Default(Toggle::VulkanDisguiseTransposeMatrixMultiply, true); + } } ResultOrError<Ref<DeviceBase>> PhysicalDevice::CreateDeviceImpl( @@ -1675,6 +1691,10 @@ return gpu_info::IsNvidia(GetVendorId()); } +bool PhysicalDevice::IsMesaDriver() const { + return mDeviceInfo.IsMesaDriver(); +} + bool PhysicalDevice::IsIntelMesa() const { if (mDeviceInfo.HasExt(DeviceExt::DriverProperties)) { return mDeviceInfo.driverProperties.driverID == VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA_KHR;
diff --git a/src/dawn/native/vulkan/PhysicalDeviceVk.h b/src/dawn/native/vulkan/PhysicalDeviceVk.h index 368faf0..2c5c325 100644 --- a/src/dawn/native/vulkan/PhysicalDeviceVk.h +++ b/src/dawn/native/vulkan/PhysicalDeviceVk.h
@@ -77,6 +77,7 @@ bool IsNvidia() const; // Check using VkDriverId, which is available in Vk 1.2 or an extension. + bool IsMesaDriver() const; bool IsIntelMesa() const; bool IsAmdMesa() const;
diff --git a/src/dawn/native/vulkan/ShaderModuleVk.cpp b/src/dawn/native/vulkan/ShaderModuleVk.cpp index caab8db..5018898 100644 --- a/src/dawn/native/vulkan/ShaderModuleVk.cpp +++ b/src/dawn/native/vulkan/ShaderModuleVk.cpp
@@ -379,6 +379,8 @@ req.tintOptions.workarounds.polyfill_nested_aggregate_construct = GetDevice()->IsToggleEnabled(Toggle::VulkanPolyfillNestedAggregateConstruct); req.tintOptions.workarounds.polyfill_pow = GetDevice()->IsToggleEnabled(Toggle::PolyfillPow); + req.tintOptions.workarounds.disguise_transpose_matrix_multiply = + GetDevice()->IsToggleEnabled(Toggle::VulkanDisguiseTransposeMatrixMultiply); req.tintOptions.workarounds.pass_matrix_by_pointer = GetDevice()->IsToggleEnabled(Toggle::VulkanPassMatrixByPointer);
diff --git a/src/dawn/native/vulkan/VulkanInfo.cpp b/src/dawn/native/vulkan/VulkanInfo.cpp index 5d224783..def0654 100644 --- a/src/dawn/native/vulkan/VulkanInfo.cpp +++ b/src/dawn/native/vulkan/VulkanInfo.cpp
@@ -29,9 +29,11 @@ #include <cstring> #include <string> +#include <tuple> #include <utility> #include "absl/container/flat_hash_map.h" +#include "src/dawn/common/GPUInfo.h" #include "src/dawn/native/vulkan/BackendVk.h" #include "src/dawn/native/vulkan/PhysicalDeviceVk.h" #include "src/dawn/native/vulkan/UtilsVulkan.h" @@ -78,6 +80,59 @@ return extensions[ext]; } +bool VulkanDeviceInfo::IsMesaDriver() const { + if (HasExt(DeviceExt::DriverProperties)) { + switch (driverProperties.driverID) { + case VK_DRIVER_ID_MESA_RADV: + case VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA: + case VK_DRIVER_ID_MESA_LLVMPIPE: + case VK_DRIVER_ID_MESA_TURNIP: + case VK_DRIVER_ID_MESA_V3DV: + case VK_DRIVER_ID_MESA_PANVK: + case VK_DRIVER_ID_MESA_VENUS: + case VK_DRIVER_ID_MESA_DOZEN: + case VK_DRIVER_ID_MESA_NVK: + case VK_DRIVER_ID_IMAGINATION_OPEN_SOURCE_MESA: + case VK_DRIVER_ID_MESA_HONEYKRISP: + case VK_DRIVER_ID_MESA_KOSMICKRISP: + case VK_DRIVER_ID_MESA_GFXSTREAM: + return true; + + // Exhaustively cover all other driver IDs. + // This may need to be updated when vulkan/vulkan_core.h + // is updated. + // MAX_ENUM is not a driver, but must be covered. + case VK_DRIVER_ID_MAX_ENUM: + case VK_DRIVER_ID_AMD_PROPRIETARY: + case VK_DRIVER_ID_AMD_OPEN_SOURCE: + case VK_DRIVER_ID_NVIDIA_PROPRIETARY: + case VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS: + case VK_DRIVER_ID_IMAGINATION_PROPRIETARY: + case VK_DRIVER_ID_QUALCOMM_PROPRIETARY: + case VK_DRIVER_ID_ARM_PROPRIETARY: + case VK_DRIVER_ID_GOOGLE_SWIFTSHADER: + case VK_DRIVER_ID_GGP_PROPRIETARY: + case VK_DRIVER_ID_BROADCOM_PROPRIETARY: + case VK_DRIVER_ID_MOLTENVK: + case VK_DRIVER_ID_COREAVI_PROPRIETARY: + case VK_DRIVER_ID_JUICE_PROPRIETARY: + case VK_DRIVER_ID_VERISILICON_PROPRIETARY: + case VK_DRIVER_ID_SAMSUNG_PROPRIETARY: + case VK_DRIVER_ID_VULKAN_SC_EMULATION_ON_VULKAN: + case VK_DRIVER_ID_APE_SOFT: + case VK_DRIVER_ID_RESERVED_31: + case VK_DRIVER_ID_APEX: + case VK_DRIVER_ID_NIKKI: + case VK_DRIVER_ID_MOMOTEN: + case VK_DRIVER_ID_AURORA_BOREALIS: + return false; + } + } + // gpu_info::IsMesa returns true for Mesa software + // implementation, i.e. lavapipe. + return gpu_info::IsMesa(properties.vendorID); +} + ResultOrError<VulkanGlobalInfo> GatherGlobalInfo(const VulkanFunctions& vkFunctions) { VulkanGlobalInfo info = {}; // Gather info on available API version
diff --git a/src/dawn/native/vulkan/VulkanInfo.h b/src/dawn/native/vulkan/VulkanInfo.h index 252b0e5..5a4c228 100644 --- a/src/dawn/native/vulkan/VulkanInfo.h +++ b/src/dawn/native/vulkan/VulkanInfo.h
@@ -28,6 +28,7 @@ #ifndef SRC_DAWN_NATIVE_VULKAN_VULKANINFO_H_ #define SRC_DAWN_NATIVE_VULKAN_VULKANINFO_H_ +#include <cstdint> #include <vector> #include "src/dawn/common/ityp_array.h" @@ -119,6 +120,10 @@ std::vector<VkLayerProperties> layers; // TODO(cwallez@chromium.org): layer instance extensions + + // Checks using VkDriverId (or Mesa's software vendor ID when driver properties are + // unavailable) whether this device uses a Mesa driver. + bool IsMesaDriver() const; }; struct VulkanSurfaceInfo {
diff --git a/src/dawn/tests/BUILD.gn b/src/dawn/tests/BUILD.gn index e90525c..e35d664 100644 --- a/src/dawn/tests/BUILD.gn +++ b/src/dawn/tests/BUILD.gn
@@ -459,6 +459,7 @@ sources += [ "unittests/validation/YCbCrValidationTests.cpp", "unittests/vulkan/MemoryTypeSelectorTests.cpp", + "unittests/vulkan/VulkanInfoTests.cpp", ] if (is_chromeos || is_linux) { @@ -714,6 +715,7 @@ "end2end/ShaderBuiltinPartialConstArgsErrorTests.cpp", "end2end/ShaderF16Tests.cpp", "end2end/ShaderIOPolyfillTests.cpp", + "end2end/ShaderMatrixLowering.cpp", "end2end/ShaderModuleCachingTests.cpp", "end2end/ShaderPoisonTests.cpp", "end2end/ShaderPrintTests.cpp",
diff --git a/src/dawn/tests/CMakeLists.txt b/src/dawn/tests/CMakeLists.txt index de35e26..3701015 100644 --- a/src/dawn/tests/CMakeLists.txt +++ b/src/dawn/tests/CMakeLists.txt
@@ -194,6 +194,7 @@ "end2end/ShaderBuiltinPartialConstArgsErrorTests.cpp" "end2end/ShaderF16Tests.cpp" "end2end/ShaderIOPolyfillTests.cpp" + "end2end/ShaderMatrixLowering.cpp" "end2end/ShaderModuleCachingTests.cpp" "end2end/ShaderPoisonTests.cpp" "end2end/ShaderPrintTests.cpp" @@ -759,6 +760,7 @@ list(APPEND unittest_sources "unittests/validation/YCbCrValidationTests.cpp" "unittests/vulkan/MemoryTypeSelectorTests.cpp" + "unittests/vulkan/VulkanInfoTests.cpp" ) list(APPEND unittest_conditional_private_depends Vulkan::Headers)
diff --git a/src/dawn/tests/end2end/ShaderMatrixLowering.cpp b/src/dawn/tests/end2end/ShaderMatrixLowering.cpp new file mode 100644 index 0000000..5c6044a --- /dev/null +++ b/src/dawn/tests/end2end/ShaderMatrixLowering.cpp
@@ -0,0 +1,138 @@ +// Copyright 2026 The Dawn & Tint Authors +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include <array> + +#include "src/dawn/tests/DawnTest.h" +#include "src/dawn/utils/WGPUHelpers.h" + +namespace dawn { +namespace { + +class ShaderMatrixLoweringTest : public DawnTest {}; + +// Verifies matrix multiplication of two transposed matrices, including non-square operands +// (crbug.com/591811902). +TEST_P(ShaderMatrixLoweringTest, TransposeTimesTranspose) { + const char* shader = R"( +/* A = (1 4) B = (10 30) + (2 5) (20 40) + (3 6) + + Transpose(B) = (10 20) Transpose(A) = (1 2 3) + (30 40) (4 5 6) + + Transpose(B)*Transpose(A) = ( 10*1+20*4 10*2+20*5 10*3+20*6 ) + ( 30*1+40*4 30*2+40*5 30*3+40*6 ) +*/ + +@group(0) @binding(0) var<storage> A: mat2x3f; +@group(0) @binding(1) var<storage> B: mat2x2f; +@group(0) @binding(2) var<storage, read_write> Result: mat3x2f; + +@compute @workgroup_size(1) +fn main() { + Result = transpose(B) * transpose(A); +} +)"; + + wgpu::ShaderModule csModule = utils::CreateShaderModule(device, shader); + + wgpu::ComputePipelineDescriptor pipelineDesc = {}; + pipelineDesc.compute.module = csModule; + pipelineDesc.compute.entryPoint = "main"; + wgpu::ComputePipeline pipeline = device.CreateComputePipeline(&pipelineDesc); + + // A = (1 4) + // (2 5) + // (3 6) + // mat2x3f is stored in column-major order with 16-byte (4-float) column stride. + const std::array<float, 8> kMatrixA = { + 1.0f, 2.0f, 3.0f, 0.0f, // column 0 (+ padding) + 4.0f, 5.0f, 6.0f, 0.0f, // column 1 (+ padding) + }; + wgpu::Buffer bufferA = utils::CreateBufferFromData(device, kMatrixA.data(), sizeof(kMatrixA), + wgpu::BufferUsage::Storage); + + // B = (10 30) + // (20 40) + // mat2x2f is stored in column-major order with 8-byte (2-float) column stride. + const std::array<float, 4> kMatrixB = { + 10.0f, + 20.0f, // column 0 + 30.0f, + 40.0f, // column 1 + }; + wgpu::Buffer bufferB = utils::CreateBufferFromData(device, kMatrixB.data(), sizeof(kMatrixB), + wgpu::BufferUsage::Storage); + + const std::array<float, 6> kZeroResult = {}; + wgpu::Buffer bufferResult = + utils::CreateBufferFromData(device, kZeroResult.data(), sizeof(kZeroResult), + wgpu::BufferUsage::Storage | wgpu::BufferUsage::CopySrc); + + wgpu::BindGroup bindGroup = utils::MakeBindGroup( + device, pipeline.GetBindGroupLayout(0), {{0, bufferA}, {1, bufferB}, {2, bufferResult}}); + + wgpu::CommandEncoder encoder = device.CreateCommandEncoder(); + wgpu::ComputePassEncoder pass = encoder.BeginComputePass(); + pass.SetPipeline(pipeline); + pass.SetBindGroup(0, bindGroup); + pass.DispatchWorkgroups(1); + pass.End(); + wgpu::CommandBuffer commands = encoder.Finish(); + queue.Submit(1, &commands); + + // Result is mat3x2f (3 columns of vec2f, 8-byte column stride): + // Transpose(B)*Transpose(A) = ( 10*1+20*4 10*2+20*5 10*3+20*6 ) + // ( 30*1+40*4 30*2+40*5 30*3+40*6 ) + const std::array<float, 6> kExpected = { + // Column 0: (10*1+20*4, 30*1+40*4) = (90, 190) + 10.0f * 1.0f + 20.0f * 4.0f, + 30.0f * 1.0f + 40.0f * 4.0f, + // Column 1: (10*2+20*5, 30*2+40*5) = (120, 260) + 10.0f * 2.0f + 20.0f * 5.0f, + 30.0f * 2.0f + 40.0f * 5.0f, + // Column 2: (10*3+20*6, 30*3+40*6) = (150, 330) + 10.0f * 3.0f + 20.0f * 6.0f, + 30.0f * 3.0f + 40.0f * 6.0f, + }; + EXPECT_BUFFER_FLOAT_RANGE_EQ(kExpected.data(), bufferResult, 0, kExpected.size()); +} + +DAWN_INSTANTIATE_TEST(ShaderMatrixLoweringTest, + D3D11Backend(), + D3D12Backend(), + MetalBackend(), + OpenGLBackend(), + OpenGLESBackend(), + VulkanBackend(), + VulkanBackend({"vulkan_disguise_transpose_matrix_multiply"}), + WebGPUBackend()); + +} // anonymous namespace +} // namespace dawn
diff --git a/src/dawn/tests/unittests/vulkan/VulkanInfoTests.cpp b/src/dawn/tests/unittests/vulkan/VulkanInfoTests.cpp new file mode 100644 index 0000000..8b7d8fe --- /dev/null +++ b/src/dawn/tests/unittests/vulkan/VulkanInfoTests.cpp
@@ -0,0 +1,96 @@ +// Copyright 2026 The Dawn & Tint Authors +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include "gtest/gtest.h" +#include "src/dawn/common/GPUInfo.h" +#include "src/dawn/native/vulkan/VulkanInfo.h" + +namespace dawn::native::vulkan { +namespace { + +VulkanDeviceInfo MakeDeviceInfoWithDriverId(VkDriverId driverId, + uint32_t vendorId = gpu_info::kVendorID_Intel, + uint32_t driverVersion = 0) { + VulkanDeviceInfo info = {}; + info.extensions.set(DeviceExt::DriverProperties, true); + info.driverProperties.driverID = driverId; + info.properties.vendorID = vendorId; + info.properties.driverVersion = driverVersion; + return info; +} + +TEST(VulkanInfoTests, IsMesaForMesaDriverIds) { + const VkDriverId kMesaDriverIds[] = { + VK_DRIVER_ID_MESA_RADV, VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA, + VK_DRIVER_ID_MESA_LLVMPIPE, VK_DRIVER_ID_MESA_TURNIP, + VK_DRIVER_ID_MESA_V3DV, VK_DRIVER_ID_MESA_PANVK, + VK_DRIVER_ID_MESA_VENUS, VK_DRIVER_ID_MESA_DOZEN, + VK_DRIVER_ID_MESA_NVK, VK_DRIVER_ID_IMAGINATION_OPEN_SOURCE_MESA, + VK_DRIVER_ID_MESA_HONEYKRISP, VK_DRIVER_ID_MESA_KOSMICKRISP, + VK_DRIVER_ID_MESA_GFXSTREAM, + }; + + for (VkDriverId id : kMesaDriverIds) { + VulkanDeviceInfo info = MakeDeviceInfoWithDriverId(id); + EXPECT_TRUE(info.IsMesaDriver()) << "driverID=" << static_cast<int>(id); + } +} + +TEST(VulkanInfoTests, IsMesaFalseForNonMesaDriverIds) { + const VkDriverId kNonMesaDriverIds[] = { + static_cast<VkDriverId>(0), + VK_DRIVER_ID_AMD_PROPRIETARY, + VK_DRIVER_ID_AMD_OPEN_SOURCE, + VK_DRIVER_ID_NVIDIA_PROPRIETARY, + VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS, + VK_DRIVER_ID_IMAGINATION_PROPRIETARY, + VK_DRIVER_ID_QUALCOMM_PROPRIETARY, + VK_DRIVER_ID_ARM_PROPRIETARY, + VK_DRIVER_ID_GOOGLE_SWIFTSHADER, + VK_DRIVER_ID_MOLTENVK, + VK_DRIVER_ID_SAMSUNG_PROPRIETARY, + }; + + for (VkDriverId id : kNonMesaDriverIds) { + VulkanDeviceInfo info = MakeDeviceInfoWithDriverId(id); + EXPECT_FALSE(info.IsMesaDriver()) << "driverID=" << static_cast<int>(id); + } +} + +TEST(VulkanInfoTests, IsMesaWithoutDriverPropertiesExtension) { + VulkanDeviceInfo intelWithoutExt = {}; + intelWithoutExt.properties.vendorID = gpu_info::kVendorID_Intel; + intelWithoutExt.driverProperties.driverID = VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA; + EXPECT_FALSE(intelWithoutExt.IsMesaDriver()); + + VulkanDeviceInfo mesaSoftwareWithoutExt = {}; + mesaSoftwareWithoutExt.properties.vendorID = gpu_info::kVendorID_Mesa; + EXPECT_TRUE(mesaSoftwareWithoutExt.IsMesaDriver()); +} + +} // anonymous namespace +} // namespace dawn::native::vulkan
diff --git a/src/tint/cmd/tint/main.cc b/src/tint/cmd/tint/main.cc index a938534..0d01008 100644 --- a/src/tint/cmd/tint/main.cc +++ b/src/tint/cmd/tint/main.cc
@@ -176,6 +176,7 @@ bool use_float_controls_32bit = false; bool use_float_controls_16bit = false; bool polyfill_nested_aggregate_construct = false; + bool disguise_transpose_matrix_multiply = false; tint::spirv::writer::SpvVersion spirv_version = tint::spirv::writer::SpvVersion::kSpv13; std::unordered_set<tint::BindingPoint> ycbcr_bindings; @@ -535,6 +536,13 @@ TINT_DEFER(opts->polyfill_nested_aggregate_construct = *polyfill_nested_aggregate_construct.value); + auto& disguise_transpose_matrix_multiply = options.Add<BoolOption>( + "disguise-transpose-matrix-multiply", + "Disguise non-square matrix multiplications with a transposed matrix operand (SPIR-V only)", + Default{false}); + TINT_DEFER(opts->disguise_transpose_matrix_multiply = + *disguise_transpose_matrix_multiply.value); + tint::Vector<EnumName<tint::spirv::writer::SpvVersion>, 2> version_enum_names{ EnumName(tint::spirv::writer::SpvVersion::kSpv13, "1.3"), EnumName(tint::spirv::writer::SpvVersion::kSpv14, "1.4"), @@ -1164,6 +1172,8 @@ gen_options.workarounds.polyfill_nested_aggregate_construct = options.polyfill_nested_aggregate_construct; gen_options.workarounds.polyfill_pow = options.polyfill_pow; + gen_options.workarounds.disguise_transpose_matrix_multiply = + options.disguise_transpose_matrix_multiply; auto entry_point = inspector.GetEntryPoint(options.ep_name);
diff --git a/src/tint/lang/spirv/writer/binary_test.cc b/src/tint/lang/spirv/writer/binary_test.cc index 30489c7..eeee781 100644 --- a/src/tint/lang/spirv/writer/binary_test.cc +++ b/src/tint/lang/spirv/writer/binary_test.cc
@@ -306,6 +306,95 @@ EXPECT_INST("%result = OpMatrixTimesMatrix %mat3v3float %mat1 %mat2"); } +TEST_F(SpirvWriterTest, Binary_MatrixTimesMatrix_DisguiseTransposeMatrixMultiply_SquareUnchanged) { + auto* mat1 = b.FunctionParam("mat1", ty.mat3x3<f32>()); + auto* mat2 = b.FunctionParam("mat2", ty.mat3x3<f32>()); + auto* func = b.Function("foo", ty.void_()); + func->SetParams({mat1, mat2}); + b.Append(func->Block(), [&] { + auto* result = b.Multiply(mat1, mat2); + b.Return(func); + mod.SetName(result, "result"); + }); + + auto* eb = b.ComputeFunction("main"); + b.Append(eb->Block(), [&] { + b.Call(func, b.Zero(ty.mat3x3<f32>()), b.Zero(ty.mat3x3<f32>())); + b.Return(eb); + }); + + Options options; + options.workarounds.disguise_transpose_matrix_multiply = true; + auto result = Generate(options); + ASSERT_EQ(result, Success) << result.Failure() << output_; + EXPECT_INST("%result = OpMatrixTimesMatrix %mat3v3float %mat1 %mat2"); +} + +TEST_F(SpirvWriterTest, Binary_MatrixTimesMatrix_DisguiseTransposeMatrixMultiply_F32) { + auto* mat1 = b.FunctionParam("mat1", ty.mat4x3<f32>()); + auto* mat2 = b.FunctionParam("mat2", ty.mat3x4<f32>()); + auto* func = b.Function("foo", ty.void_()); + func->SetParams({mat1, mat2}); + b.Append(func->Block(), [&] { + auto* result = b.Multiply(mat1, mat2); + b.Return(func); + mod.SetName(result, "result"); + }); + + auto* eb = b.ComputeFunction("main"); + b.Append(eb->Block(), [&] { + b.Call(func, b.Zero(ty.mat4x3<f32>()), b.Zero(ty.mat3x4<f32>())); + b.Return(eb); + }); + + Options options; + options.workarounds.disguise_transpose_matrix_multiply = true; + auto result = Generate(options); + ASSERT_EQ(result, Success) << result.Failure() << output_; + EXPECT_INST(R"( + %12 = OpCompositeExtract %v3float %mat1 0 + %13 = OpCompositeExtract %v3float %mat1 1 + %14 = OpCompositeExtract %v3float %mat1 2 + %15 = OpCompositeExtract %v3float %mat1 3 + %16 = OpCompositeConstruct %mat4v3float %12 %13 %14 %15 + %result = OpMatrixTimesMatrix %mat3v3float %16 %mat2 +)"); +} + +TEST_F(SpirvWriterTest, Binary_TransposeMatrixTimesMatrix_DisguiseTransposeMatrixMultiply_F16) { + auto* mat1 = b.FunctionParam("mat1", ty.mat3x4<f16>()); + auto* mat2 = b.FunctionParam("mat2", ty.mat3x4<f16>()); + auto* func = b.Function("foo", ty.void_()); + func->SetParams({mat1, mat2}); + b.Append(func->Block(), [&] { + auto* transposed = b.Call(ty.mat4x3<f16>(), core::BuiltinFn::kTranspose, mat1); + mod.SetName(transposed, "transposed"); + auto* result = b.Multiply(transposed, mat2); + mod.SetName(result, "result"); + b.Return(func); + }); + + auto* eb = b.ComputeFunction("main"); + b.Append(eb->Block(), [&] { + b.Call(func, b.Zero(ty.mat3x4<f16>()), b.Zero(ty.mat3x4<f16>())); + b.Return(eb); + }); + + Options options; + options.workarounds.disguise_transpose_matrix_multiply = true; + auto result = Generate(options); + ASSERT_EQ(result, Success) << result.Failure() << output_; + EXPECT_INST(R"( + %transposed = OpTranspose %mat4v3half %mat1 + %13 = OpCompositeExtract %v3half %transposed 0 + %14 = OpCompositeExtract %v3half %transposed 1 + %15 = OpCompositeExtract %v3half %transposed 2 + %16 = OpCompositeExtract %v3half %transposed 3 + %17 = OpCompositeConstruct %mat4v3half %13 %14 %15 %16 + %result = OpMatrixTimesMatrix %mat3v3half %17 %mat2 +)"); +} + using Comparison = SpirvWriterTestWithParam<BinaryTestCase>; TEST_P(Comparison, Scalar) { auto params = GetParam();
diff --git a/src/tint/lang/spirv/writer/common/options.h b/src/tint/lang/spirv/writer/common/options.h index 1a0cabf..9e4733e 100644 --- a/src/tint/lang/spirv/writer/common/options.h +++ b/src/tint/lang/spirv/writer/common/options.h
@@ -183,6 +183,10 @@ /// Works around a shader compiler bug in Imagination/PowerVR drivers. bool fork_explicit_layout_matrix_structs = false; + /// Set to `true` to disguise matrix multiplications with a transposed matrix operand. + /// Works around a shader compiler bug in Mesa Vulkan drivers. + bool disguise_transpose_matrix_multiply = false; + TINT_REFLECT(Workarounds, polyfill_case_switch, scalarize_max_min_clamp, @@ -208,7 +212,8 @@ polyfill_nested_aggregate_construct, polyfill_pow, fork_explicit_layout_matrix_structs, - guard_control_flow_conditions); + guard_control_flow_conditions, + disguise_transpose_matrix_multiply); }; /// Any options which are controlled by the presence/absence of a vulkan extension.
diff --git a/src/tint/lang/spirv/writer/raise/BUILD.bazel b/src/tint/lang/spirv/writer/raise/BUILD.bazel index 1377f0c..05631ca 100644 --- a/src/tint/lang/spirv/writer/raise/BUILD.bazel +++ b/src/tint/lang/spirv/writer/raise/BUILD.bazel
@@ -45,6 +45,7 @@ srcs = [ "builtin_polyfill.cc", "case_switch_to_if_else.cc", + "disguise_transpose_matrix_multiply.cc", "expand_implicit_splats.cc", "fork_explicit_layout_types.cc", "guard_control_flow_conditions.cc", @@ -64,6 +65,7 @@ hdrs = [ "builtin_polyfill.h", "case_switch_to_if_else.h", + "disguise_transpose_matrix_multiply.h", "expand_implicit_splats.h", "fork_explicit_layout_types.h", "guard_control_flow_conditions.h", @@ -117,6 +119,7 @@ srcs = [ "builtin_polyfill_test.cc", "case_switch_to_if_else_test.cc", + "disguise_transpose_matrix_multiply_test.cc", "expand_implicit_splats_test.cc", "fork_explicit_layout_types_test.cc", "guard_control_flow_conditions_test.cc",
diff --git a/src/tint/lang/spirv/writer/raise/BUILD.cmake b/src/tint/lang/spirv/writer/raise/BUILD.cmake index 97dc4b1..8939323 100644 --- a/src/tint/lang/spirv/writer/raise/BUILD.cmake +++ b/src/tint/lang/spirv/writer/raise/BUILD.cmake
@@ -45,6 +45,8 @@ lang/spirv/writer/raise/builtin_polyfill.h lang/spirv/writer/raise/case_switch_to_if_else.cc lang/spirv/writer/raise/case_switch_to_if_else.h + lang/spirv/writer/raise/disguise_transpose_matrix_multiply.cc + lang/spirv/writer/raise/disguise_transpose_matrix_multiply.h lang/spirv/writer/raise/expand_implicit_splats.cc lang/spirv/writer/raise/expand_implicit_splats.h lang/spirv/writer/raise/fork_explicit_layout_types.cc @@ -119,6 +121,7 @@ tint_add_target(tint_lang_spirv_writer_raise_test test lang/spirv/writer/raise/builtin_polyfill_test.cc lang/spirv/writer/raise/case_switch_to_if_else_test.cc + lang/spirv/writer/raise/disguise_transpose_matrix_multiply_test.cc lang/spirv/writer/raise/expand_implicit_splats_test.cc lang/spirv/writer/raise/fork_explicit_layout_types_test.cc lang/spirv/writer/raise/guard_control_flow_conditions_test.cc
diff --git a/src/tint/lang/spirv/writer/raise/BUILD.gn b/src/tint/lang/spirv/writer/raise/BUILD.gn index 18b5e52..bbaf980 100644 --- a/src/tint/lang/spirv/writer/raise/BUILD.gn +++ b/src/tint/lang/spirv/writer/raise/BUILD.gn
@@ -49,6 +49,8 @@ "builtin_polyfill.h", "case_switch_to_if_else.cc", "case_switch_to_if_else.h", + "disguise_transpose_matrix_multiply.cc", + "disguise_transpose_matrix_multiply.h", "expand_implicit_splats.cc", "expand_implicit_splats.h", "fork_explicit_layout_types.cc", @@ -116,6 +118,7 @@ sources = [ "builtin_polyfill_test.cc", "case_switch_to_if_else_test.cc", + "disguise_transpose_matrix_multiply_test.cc", "expand_implicit_splats_test.cc", "fork_explicit_layout_types_test.cc", "guard_control_flow_conditions_test.cc",
diff --git a/src/tint/lang/spirv/writer/raise/disguise_transpose_matrix_multiply.cc b/src/tint/lang/spirv/writer/raise/disguise_transpose_matrix_multiply.cc new file mode 100644 index 0000000..1711f71 --- /dev/null +++ b/src/tint/lang/spirv/writer/raise/disguise_transpose_matrix_multiply.cc
@@ -0,0 +1,113 @@ +// Copyright 2026 The Dawn & Tint Authors +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include "src/tint/lang/spirv/writer/raise/disguise_transpose_matrix_multiply.h" + +#include <utility> + +#include "src/tint/lang/core/fluent_types.h" +#include "src/tint/lang/core/ir/builder.h" +#include "src/tint/lang/core/ir/core_binary.h" +#include "src/tint/lang/core/ir/module.h" +#include "src/tint/lang/core/ir/validator/validate.h" +#include "src/tint/lang/core/type/matrix.h" +#include "src/tint/utils/containers/vector.h" + +using namespace tint::core::fluent_types; // NOLINT + +namespace tint::spirv::writer::raise { + +namespace { + +/// PIMPL state for the transform. +struct State { + /// The IR module. + core::ir::Module& ir; + + /// The IR builder. + core::ir::Builder b{ir}; + + /// Process the module. + void Process() { + Vector<core::ir::CoreBinary*, 8> worklist; + for (auto* inst : ir.Instructions()) { + auto* binary_op = inst->As<core::ir::CoreBinary>(); + if (binary_op && ShouldRewrite(binary_op)) { + worklist.Push(binary_op); + } + } + + for (auto* binary_op : worklist) { + Rewrite(binary_op); + } + } + + /// @returns true if @p binary_op is a matrix-by-matrix multiply where at least one matrix + /// operand is non-square. + bool ShouldRewrite(core::ir::CoreBinary* binary_op) { + if (binary_op->Op() != core::BinaryOp::kMultiply) { + return false; + } + + auto* lhs_mat = binary_op->LHS()->Type()->As<core::type::Matrix>(); + auto* rhs_mat = binary_op->RHS()->Type()->As<core::type::Matrix>(); + if (!lhs_mat || !rhs_mat) { + return false; + } + + const bool lhs_is_square = lhs_mat->Columns() == lhs_mat->Rows(); + const bool rhs_is_square = rhs_mat->Columns() == rhs_mat->Rows(); + return !lhs_is_square || !rhs_is_square; + } + + /// Reconstructs the first matrix operand of @p binary_op from its column vectors. + void Rewrite(core::ir::CoreBinary* binary_op) { + auto* lhs = binary_op->LHS(); + auto* lhs_mat = lhs->Type()->As<core::type::Matrix>(); + + b.InsertBefore(binary_op, [&] { + Vector<core::ir::Value*, 4> cols; + for (uint32_t col = 0; col < lhs_mat->Columns(); col++) { + cols.Push(b.Access(lhs_mat->ColumnType(), lhs, u32(col))); + } + auto* reconstructed = b.Construct(lhs_mat, std::move(cols)); + binary_op->SetOperand(core::ir::Binary::kLhsOperandOffset, reconstructed); + }); + } +}; + +} // namespace + +Result<SuccessType> DisguiseTransposeMatrixMultiply(core::ir::Module& ir) { + AssertValid(ir, "before spirv.DisguiseTransposeMatrixMultiply"); + + State{ir}.Process(); + + return Success; +} + +} // namespace tint::spirv::writer::raise
diff --git a/src/tint/lang/spirv/writer/raise/disguise_transpose_matrix_multiply.h b/src/tint/lang/spirv/writer/raise/disguise_transpose_matrix_multiply.h new file mode 100644 index 0000000..10bfdd5 --- /dev/null +++ b/src/tint/lang/spirv/writer/raise/disguise_transpose_matrix_multiply.h
@@ -0,0 +1,50 @@ +// Copyright 2026 The Dawn & Tint Authors +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef SRC_TINT_LANG_SPIRV_WRITER_RAISE_DISGUISE_TRANSPOSE_MATRIX_MULTIPLY_H_ +#define SRC_TINT_LANG_SPIRV_WRITER_RAISE_DISGUISE_TRANSPOSE_MATRIX_MULTIPLY_H_ + +#include "src/tint/utils/result.h" + +// Forward declarations. +namespace tint::core::ir { +class Module; +} + +namespace tint::spirv::writer::raise { + +/// DisguiseTransposeMatrixMultiply reconstructs the first matrix operand of a matrix-by-matrix +/// multiplication from its column vectors whenever at least one of the matrix operands is +/// non-square. This defeats a buggy optimization in Mesa's SPIR-V to NIR lowering when multiplying +/// transposed matrices involving non-square dimensions. +/// @param ir the module to transform +/// @returns success or failure +Result<SuccessType> DisguiseTransposeMatrixMultiply(core::ir::Module& ir); + +} // namespace tint::spirv::writer::raise + +#endif // SRC_TINT_LANG_SPIRV_WRITER_RAISE_DISGUISE_TRANSPOSE_MATRIX_MULTIPLY_H_
diff --git a/src/tint/lang/spirv/writer/raise/disguise_transpose_matrix_multiply_test.cc b/src/tint/lang/spirv/writer/raise/disguise_transpose_matrix_multiply_test.cc new file mode 100644 index 0000000..7fb019d --- /dev/null +++ b/src/tint/lang/spirv/writer/raise/disguise_transpose_matrix_multiply_test.cc
@@ -0,0 +1,274 @@ +// Copyright 2026 The Dawn & Tint Authors +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include "src/tint/lang/spirv/writer/raise/disguise_transpose_matrix_multiply.h" + +#include "src/tint/lang/core/ir/transform/helper_test.h" +#include "src/tint/lang/core/type/matrix.h" + +namespace tint::spirv::writer::raise { +namespace { + +using namespace tint::core::fluent_types; // NOLINT +using namespace tint::core::number_suffixes; // NOLINT + +class SpirvWriter_DisguiseTransposeMatrixMultiplyTest : public core::ir::transform::TransformTest { + protected: + void SetUp() override { mod.properties.Add(core::ir::Property::kAllow16BitFloats); } +}; + +TEST_F(SpirvWriter_DisguiseTransposeMatrixMultiplyTest, NoModify_SquareTimesSquare) { + auto* lhs = b.FunctionParam("lhs", ty.mat3x3<f32>()); + auto* rhs = b.FunctionParam("rhs", ty.mat3x3<f32>()); + auto* func = b.Function("foo", ty.mat3x3<f32>()); + func->SetParams({lhs, rhs}); + + b.Append(func->Block(), [&] { + auto* result = b.Multiply(lhs, rhs); + b.Return(func, result); + }); + + auto* expect = R"( +%foo = func(%lhs:mat3x3<f32>, %rhs:mat3x3<f32>):mat3x3<f32> { + $B1: { + %4:mat3x3<f32> = mul %lhs, %rhs + ret %4 + } +} +)"; + + Run(DisguiseTransposeMatrixMultiply); + + EXPECT_EQ(expect, str()); +} + +TEST_F(SpirvWriter_DisguiseTransposeMatrixMultiplyTest, NoModify_MatrixTimesVector) { + auto* lhs = b.FunctionParam("lhs", ty.mat4x3<f32>()); + auto* rhs = b.FunctionParam("rhs", ty.vec4<f32>()); + auto* func = b.Function("foo", ty.vec3<f32>()); + func->SetParams({lhs, rhs}); + + b.Append(func->Block(), [&] { + auto* result = b.Multiply(lhs, rhs); + b.Return(func, result); + }); + + auto* expect = R"( +%foo = func(%lhs:mat4x3<f32>, %rhs:vec4<f32>):vec3<f32> { + $B1: { + %4:vec3<f32> = mul %lhs, %rhs + ret %4 + } +} +)"; + + Run(DisguiseTransposeMatrixMultiply); + + EXPECT_EQ(expect, str()); +} + +TEST_F(SpirvWriter_DisguiseTransposeMatrixMultiplyTest, NoModify_VectorTimesMatrix) { + auto* lhs = b.FunctionParam("lhs", ty.vec3<f32>()); + auto* rhs = b.FunctionParam("rhs", ty.mat4x3<f32>()); + auto* func = b.Function("foo", ty.vec4<f32>()); + func->SetParams({lhs, rhs}); + + b.Append(func->Block(), [&] { + auto* result = b.Multiply(lhs, rhs); + b.Return(func, result); + }); + + auto* expect = R"( +%foo = func(%lhs:vec3<f32>, %rhs:mat4x3<f32>):vec4<f32> { + $B1: { + %4:vec4<f32> = mul %lhs, %rhs + ret %4 + } +} +)"; + + Run(DisguiseTransposeMatrixMultiply); + + EXPECT_EQ(expect, str()); +} + +TEST_F(SpirvWriter_DisguiseTransposeMatrixMultiplyTest, NoModify_MatrixAddNonSquare) { + auto* lhs = b.FunctionParam("lhs", ty.mat2x3<f32>()); + auto* rhs = b.FunctionParam("rhs", ty.mat2x3<f32>()); + auto* func = b.Function("foo", ty.mat2x3<f32>()); + func->SetParams({lhs, rhs}); + + b.Append(func->Block(), [&] { + auto* result = b.Add(lhs, rhs); + b.Return(func, result); + }); + + auto* expect = R"( +%foo = func(%lhs:mat2x3<f32>, %rhs:mat2x3<f32>):mat2x3<f32> { + $B1: { + %4:mat2x3<f32> = add %lhs, %rhs + ret %4 + } +} +)"; + + Run(DisguiseTransposeMatrixMultiply); + + EXPECT_EQ(expect, str()); +} + +TEST_F(SpirvWriter_DisguiseTransposeMatrixMultiplyTest, LhsSquare_RhsNonSquare) { + auto* lhs = b.FunctionParam("lhs", ty.mat2x2<f32>()); + auto* rhs = b.FunctionParam("rhs", ty.mat3x2<f32>()); + auto* func = b.Function("foo", ty.mat3x2<f32>()); + func->SetParams({lhs, rhs}); + + b.Append(func->Block(), [&] { + auto* result = b.Multiply(lhs, rhs); + b.Return(func, result); + }); + + auto* src = R"( +%foo = func(%lhs:mat2x2<f32>, %rhs:mat3x2<f32>):mat3x2<f32> { + $B1: { + %4:mat3x2<f32> = mul %lhs, %rhs + ret %4 + } +} +)"; + EXPECT_EQ(src, str()); + + auto* expect = R"( +%foo = func(%lhs:mat2x2<f32>, %rhs:mat3x2<f32>):mat3x2<f32> { + $B1: { + %4:vec2<f32> = access %lhs, 0u + %5:vec2<f32> = access %lhs, 1u + %6:mat2x2<f32> = construct %4, %5 + %7:mat3x2<f32> = mul %6, %rhs + ret %7 + } +} +)"; + + Run(DisguiseTransposeMatrixMultiply); + + EXPECT_EQ(expect, str()); +} + +TEST_F(SpirvWriter_DisguiseTransposeMatrixMultiplyTest, LhsNonSquare_RhsSquare) { + auto* lhs = b.FunctionParam("lhs", ty.mat3x2<f32>()); + auto* rhs = b.FunctionParam("rhs", ty.mat3x3<f32>()); + auto* func = b.Function("foo", ty.mat3x2<f32>()); + func->SetParams({lhs, rhs}); + + b.Append(func->Block(), [&] { + auto* result = b.Multiply(lhs, rhs); + b.Return(func, result); + }); + + auto* expect = R"( +%foo = func(%lhs:mat3x2<f32>, %rhs:mat3x3<f32>):mat3x2<f32> { + $B1: { + %4:vec2<f32> = access %lhs, 0u + %5:vec2<f32> = access %lhs, 1u + %6:vec2<f32> = access %lhs, 2u + %7:mat3x2<f32> = construct %4, %5, %6 + %8:mat3x2<f32> = mul %7, %rhs + ret %8 + } +} +)"; + + Run(DisguiseTransposeMatrixMultiply); + + EXPECT_EQ(expect, str()); +} + +TEST_F(SpirvWriter_DisguiseTransposeMatrixMultiplyTest, BothNonSquare_F16) { + auto* lhs = b.FunctionParam("lhs", ty.mat4x3<f16>()); + auto* rhs = b.FunctionParam("rhs", ty.mat3x4<f16>()); + auto* func = b.Function("foo", ty.mat3x3<f16>()); + func->SetParams({lhs, rhs}); + + b.Append(func->Block(), [&] { + auto* result = b.Multiply(lhs, rhs); + b.Return(func, result); + }); + + auto* expect = R"( +%foo = func(%lhs:mat4x3<f16>, %rhs:mat3x4<f16>):mat3x3<f16> { + $B1: { + %4:vec3<f16> = access %lhs, 0u + %5:vec3<f16> = access %lhs, 1u + %6:vec3<f16> = access %lhs, 2u + %7:vec3<f16> = access %lhs, 3u + %8:mat4x3<f16> = construct %4, %5, %6, %7 + %9:mat3x3<f16> = mul %8, %rhs + ret %9 + } +} +)"; + + Run(DisguiseTransposeMatrixMultiply); + + EXPECT_EQ(expect, str()); +} + +TEST_F(SpirvWriter_DisguiseTransposeMatrixMultiplyTest, TransposeOperands) { + auto* a = b.FunctionParam("a", ty.mat2x3<f32>()); + auto* b_mat = b.FunctionParam("b_mat", ty.mat2x2<f32>()); + auto* func = b.Function("foo", ty.mat3x2<f32>()); + func->SetParams({a, b_mat}); + + b.Append(func->Block(), [&] { + auto* tb = b.Call(ty.mat2x2<f32>(), core::BuiltinFn::kTranspose, b_mat); + auto* ta = b.Call(ty.mat3x2<f32>(), core::BuiltinFn::kTranspose, a); + auto* result = b.Multiply(tb, ta); + b.Return(func, result); + }); + + auto* expect = R"( +%foo = func(%a:mat2x3<f32>, %b_mat:mat2x2<f32>):mat3x2<f32> { + $B1: { + %4:mat2x2<f32> = transpose %b_mat + %5:mat3x2<f32> = transpose %a + %6:vec2<f32> = access %4, 0u + %7:vec2<f32> = access %4, 1u + %8:mat2x2<f32> = construct %6, %7 + %9:mat3x2<f32> = mul %8, %5 + ret %9 + } +} +)"; + + Run(DisguiseTransposeMatrixMultiply); + + EXPECT_EQ(expect, str()); +} + +} // namespace +} // namespace tint::spirv::writer::raise
diff --git a/src/tint/lang/spirv/writer/raise/raise.cc b/src/tint/lang/spirv/writer/raise/raise.cc index 5257dfe..4a8d82a 100644 --- a/src/tint/lang/spirv/writer/raise/raise.cc +++ b/src/tint/lang/spirv/writer/raise/raise.cc
@@ -58,6 +58,7 @@ #include "src/tint/lang/spirv/writer/common/option_helpers.h" #include "src/tint/lang/spirv/writer/raise/builtin_polyfill.h" #include "src/tint/lang/spirv/writer/raise/case_switch_to_if_else.h" +#include "src/tint/lang/spirv/writer/raise/disguise_transpose_matrix_multiply.h" #include "src/tint/lang/spirv/writer/raise/expand_implicit_splats.h" #include "src/tint/lang/spirv/writer/raise/fork_explicit_layout_types.h" #include "src/tint/lang/spirv/writer/raise/guard_control_flow_conditions.h" @@ -281,6 +282,10 @@ TINT_CHECK_RESULT(raise::UnaryPolyfill(module, unary_polyfill_cfg)); + if (options.workarounds.disguise_transpose_matrix_multiply) { + TINT_CHECK_RESULT(raise::DisguiseTransposeMatrixMultiply(module)); + } + // kAllowAnyInputAttachmentIndexType required after ExpandImplicitSplats TINT_CHECK_RESULT(raise::HandleMatrixArithmetic(module)); TINT_CHECK_RESULT(raise::MergeReturn(module));
diff --git a/src/tint/lang/spirv/writer/writer_fuzz.cc b/src/tint/lang/spirv/writer/writer_fuzz.cc index 614dfca..661c334 100644 --- a/src/tint/lang/spirv/writer/writer_fuzz.cc +++ b/src/tint/lang/spirv/writer/writer_fuzz.cc
@@ -102,6 +102,7 @@ bool polyfill_pow; bool fork_explicit_layout_matrix_structs; bool guard_control_flow_conditions; + bool disguise_transpose_matrix_multiply; /// Reflect the fields of this class so that it can be used by tint::ForeachField() TINT_REFLECT(FuzzedOptions, @@ -149,7 +150,8 @@ polyfill_nested_aggregate_construct, polyfill_pow, fork_explicit_layout_matrix_structs, - guard_control_flow_conditions); + guard_control_flow_conditions, + disguise_transpose_matrix_multiply); TINT_REFLECT_HASH_CODE(FuzzedOptions); }; @@ -436,6 +438,8 @@ fuzzed_options.fork_explicit_layout_matrix_structs; options.workarounds.guard_control_flow_conditions = fuzzed_options.guard_control_flow_conditions; + options.workarounds.disguise_transpose_matrix_multiply = + fuzzed_options.disguise_transpose_matrix_multiply; options.multisampled_framebuffer_fetch = fuzzed_options.multisampled_framebuffer_fetch; // Find the next available immediate offset for the non-constant zero value if needed.