From e3afef145e67e74e054407606320be0e42a6aa63 Mon Sep 17 00:00:00 2001 From: Gangzheng Tong Date: Fri, 11 Jul 2025 13:16:10 -0700 Subject: Fix metal segfault by check vectorValue before accessing (#7688) * Check vectorValue before accessing * Fix metal segfault by using IRElementExtract for general vector handling Address review comments by replacing IRMakeVector-specific code with IRElementExtract to handle any vector instruction type (IRIntCast, etc). This makes the code more robust and fixes cases where float2(1,2) creates IRIntCast instead of IRMakeVector. Co-authored-by: Yong He * Fix sign comparison warning in metal legalize Cast originalElementCount->getValue() to UInt to avoid comparison between signed and unsigned integers. Co-authored-by: Yong He --------- Co-authored-by: Yong He Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Yong He --- source/slang/slang-ir-metal-legalize.cpp | 14 +++++++++++--- tests/metal/texture-store-vector.slang | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 tests/metal/texture-store-vector.slang diff --git a/source/slang/slang-ir-metal-legalize.cpp b/source/slang/slang-ir-metal-legalize.cpp index 589413cbf..116feeab4 100644 --- a/source/slang/slang-ir-metal-legalize.cpp +++ b/source/slang/slang-ir-metal-legalize.cpp @@ -32,10 +32,18 @@ void legalizeImageStoreValue(IRBuilder& builder, IRImageStore* imageStore) } } elementType = valueVectorType->getElementType(); - auto vectorValue = as(originalValue); - for (UInt i = 0; i < vectorValue->getOperandCount(); i++) + + // Extract components using IRElementExtract to handle any vector instruction type + if (auto originalElementCount = as(valueVectorType->getElementCount())) { - components.add(vectorValue->getOperand(i)); + for (UInt i = 0; i < (UInt)originalElementCount->getValue(); i++) + { + auto elementExtract = builder.emitElementExtract( + elementType, + originalValue, + builder.getIntValue(builder.getIntType(), i)); + components.add(elementExtract); + } } } else diff --git a/tests/metal/texture-store-vector.slang b/tests/metal/texture-store-vector.slang new file mode 100644 index 000000000..0f63b7ce3 --- /dev/null +++ b/tests/metal/texture-store-vector.slang @@ -0,0 +1,16 @@ +//TEST:SIMPLE(filecheck=CHECK): -target metal + +// Test that we can compile texture store operations with 2-component vectors +// without segfaulting. This reproduces the issue where legalizeImageStoreValue +// would crash when trying to expand a float2 to float4 for Metal texture writes. + +RWTexture2D output; + +[shader("compute")] +[numthreads(32, 32, 1)] +void computeMain(uint3 dispatchThreadID : SV_DispatchThreadID) +{ + // This should expand float2(1,2) to float4(1,2,0,0) + // CHECK: {{.*}}float4(1.0, 2.0, + output.Store(dispatchThreadID.xy, float2(1, 2)); +} \ No newline at end of file -- cgit v1.2.3