[SPIR-V] Rebuild pointer constant arms of an aggregate PHI or select #236370
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-backend-spir-v
Author: Gonsolo (gonsolo)
<details>
<summary>Changes</summary>
A composite constant arm of an aggregate PHI or select gets its type from deduceNestedTypeHelper. Once the inttoptr constants in it have a deduced pointee type, which constant expressions carry across functions, that is a distinct struct with typed pointer members, i.e. a different SPIR-V type than the select and its other arms: selectSelect asserts. The test needs a second function that uses one of the constants first.
Every arm of a PHI or select has the result's type, so its constant arms now get that type.
Testing: the new test fails without the change; llvm/test/CodeGen/SPIRV passes (1375 tests) and the output passes spirv-val. Found while compiling Mojo GPU kernels (a path tracer, 117 modules) for an Intel Arc B580: with this and two related SPIR-V fixes, every module compiles to valid SPIR-V without frontend workarounds.
This change was prepared with AI assistance (Claude Code); I have reviewed it and will answer for it in review.
🤖 Generated with Claude Code
https://claude.ai/code/session_01LqBCeZyWd3hVdxTTAumnrq
---
Full diff: https://github.com/llvm/llvm-project/pull/236370.diff
2 Files Affected:
````````````diff --git a/llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp b/llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp
index 9b45b9ebc32cf..6f430314fc532 100644
--- a/llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp
+++ b/llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp
@@ -3899,6 +3899,13 @@ bool SPIRVEmitIntrinsicsImpl::runOnFunction(Function &Func) {
continue;
// Give multi-register arms a value-id first, before the result is mutated.
insertCompositeAggregateArms(&I, B);
+ // Every arm has the result's type. A constant arm's deduced type can be a
+ // distinct struct with typed pointer members (pointee types deduced in
+ // another function), which would no longer match.
+ for (Value *Op : I.operands())
+ if (auto *OpI = dyn_cast<Instruction>(Op))
+ if (auto It = AggrConstTypes.find(OpI); It != AggrConstTypes.end())
+ It->second = I.getType();
AggrConstTypes[&I] = I.getType();
I.mutateType(I32Ty);
}
diff --git a/llvm/test/CodeGen/SPIRV/instructions/select-constant-arm-deduced-pointee.ll b/llvm/test/CodeGen/SPIRV/instructions/select-constant-arm-deduced-pointee.ll
new file mode 100644
index 0000000000000..e589fabd88e4b
--- /dev/null
+++ b/llvm/test/CodeGen/SPIRV/instructions/select-constant-arm-deduced-pointee.ll
@@ -0,0 +1,25 @@
+; Every arm of an aggregate select has the select's type. A constant arm's
+; deduced type became a distinct struct with typed pointer members once the
+; inttoptr constants it holds had a pointee type deduced (here in @a, since
+; constant expressions are shared between functions), which no longer matched
+; the select and its zeroinitializer arm.
+
+; RUN: llc -O0 -mtriple=spirv64-unknown-unknown %s -o - | FileCheck %s
+; RUN: %if spirv-tools %{ llc -O0 -mtriple=spirv64-unknown-unknown %s -o - -filetype=obj | spirv-val %}
+
+; CHECK: %[[#Ptr:]] = OpTypePointer Generic
+; CHECK: %[[#Q:]] = OpTypeStruct %[[#Ptr]] %[[#Ptr]]
+; CHECK-NOT: OpTypeStruct %[[#Ptr]] %[[#Ptr]]
+; CHECK: OpSelect %[[#Q]] %[[#]] %[[#]] %[[#]]
+
+%P = type { ptr addrspace(4), i32 }
+%Q = type { ptr addrspace(4), ptr addrspace(4) }
+
+define %P @a() {
+ ret %P { ptr addrspace(4) inttoptr (i64 4 to ptr addrspace(4)), i32 0 }
+}
+
+define %Q @b(i1 %c) {
+ %s = select i1 %c, %Q zeroinitializer, %Q { ptr addrspace(4) inttoptr (i64 8 to ptr addrspace(4)), ptr addrspace(4) inttoptr (i64 4 to ptr addrspace(4)) }
+ ret %Q %s
+}
</details>
The override is only correct when the deduced pointee happens to be i8, which is what the test in the PR exercises. With a typed member the deduced struct really differs and forcing the select's type without casting the members produces invalid SPIR-V instead of the current assert
You're right, thanks. Forcing the type only covered an i8 pointee: with an i32 pointee deduced for the same constant in another function it still asserts. I've replaced the override with rebuilding such a constant arm as an insertvalue chain, so the member casts from #227599 apply. The test now covers both pointees and a PHI arm; it fails without the change, check-llvm-codegen-spirv passes and spirv-val accepts the output.
Session: https://claude.ai/code/session_0141xq22BhyCNa4pRpmwvhAc
I feel like this routine could be broken for a case with a switch, whose two cases lead into the same block. Could you add a test for this?
You're right, a switch with two cases into the same block got two different insertvalue chains for one predecessor, which the verifier rejects. Fixed in ec6d19eada by building one chain per incoming block, with a switch test.
Thanks, this also fixes a case Julia's GPU back-ends can hit. Julia's bits-union return values produce this pattern (phi { ptr, i8 } [ { ptr getelementptr (i8, ptr @box, i64 8), i8 -124 }, ... ] from a @noinline function returning a Union). On main that becomes an OpPhi spirv-val rejects. With this PR it validates, and our test suite still passes.
Nested aggregates still assert though, since only top-level members are checked:
@g = addrspace(1) global i32 0
%Q = type { ptr addrspace(1), i32 }
%R = type { %Q, i32 }
define %R @nested(i1 %c) {
%s = select i1 %c, %R zeroinitializer, %R { %Q { ptr addrspace(1) @g, i32 1 }, i32 2 }
ret %R %s
}
Rebuilding nested ConstantAggregate members recursively, each as its own chain, probably fixes that.
I don't think this even needs a second function: any pointer member with a known pointee is enough, e.g. select i1 %c, %Q zeroinitializer, %Q { ptr addrspace(1) @g, i32 1 } asserts on its own. For a PHI there's no assert, just an OpPhi that spirv-val rejects.
Thanks for testing it with Julia! Nested aggregates are handled in 5e6f553d9f: a nested struct or array member with pointers is rebuilt as its own insertvalue chain, with your reproducer as a test (select and PHI). And 91857e6d59 simplifies the test as you suggested: one global with a known pointee instead of the extra functions.
hasPointerMember() misses pointers nested inside ConstantVector. I believe that handling could be added here as well
Could we rebuild only when the deduced spirv type actually differs from the result type? Otherwise we're spamming too much with insertvalue instruments
Done in a5e35f8c1bd9. An arm is now rebuilt only when deduceNestedTypeHelper gives it a different type than its LLVM type, which happens when a pointer member has a known pointee. preprocessCompositeConstants uses the same helper to type the constant. Nested members are rebuilt only under the same condition, and an arm with only null pointers is kept as it is (new CHECK-NOT case in select-constant-arm-deduced-pointee.ll).
Right, a <2 x ptr addrspace(1)> member hit the same selectSelect assert. hasPointerMember is gone (see the other thread), and 34401a29edce rebuilds a vector member as an insertelement chain. That needed 55b64abc20f1 first: unlike insertvalue, insertelement did not cast an inserted pointer to the element type, so a plain insertelement of @g into a <2 x ptr addrspace(1)> already failed spirv-val. Tests: select-constant-arm-pointer-vector.ll and insertelement-typed-pointer.ll, both pass spirv-val.
This excludes vectors, so a vector-of-pointers select hits the same selectSelect assert you're fixing for other types. The PHI version below is currently stopped earlier at legalizer, but with #241166 it produces an invalid OpPhi instead. Reproducible with:
@g = addrspace(1) global i32 0
define <2 x ptr addrspace(1)> @s(i1 %c) {
%s = select i1 %c, <2 x ptr addrspace(1)> zeroinitializer, <2 x ptr addrspace(1)> <ptr addrspace(1) @g, ptr addrspace(1) @g>
ret <2 x ptr addrspace(1)> %s
}
define <2 x ptr addrspace(1)> @p(i1 %c) {
entry:
br i1 %c, label %then, label %join
then:
br label %join
join:
%p = phi <2 x ptr addrspace(1)> [ zeroinitializer, %entry ], [ <ptr addrspace(1) @g, ptr addrspace(1) @g>, %then ]
ret <2 x ptr addrspace(1)> %p
}
I tried with the code below instead (and with #241166), and the reproducer above passes and all the LIT tests too. Note the reproducer above needs --spirv-ext=+SPV_INTEL_masked_gather_scatter.
if (!isAggregateValueIdInstr(I) &&
!(isa<PHINode, SelectInst>(I) && I.getType()->isVectorTy()))
continue;
Did I not see this before in other PRs you authored? I think #236369 has it too, or very similar. Could be factored out to a helper?
// Rebuild C as an insertvalue (insertelement for a vector) chain before InsertPt.
// Members with deduced pointee get their own chain.
Isn't this always nullptr? Couldn't find an input that shows otherwise. As a result, the conditional below is always taking i8 branch. Is that intended?
I think the name is misleading, it doesn't really reflect what it does. What about deducedTypeDiffers?
deduceNestedTypeHelper only checks operand 0 for arrays and vectors. Something like [null, @g] is missed.
; A constant select/PHI arm holding @g (i32 pointee) is rebuilt with
; OpCompositeInsert in the result type. A PHI arm is built once in its incoming
; block, even for duplicate switch edges; a null-only arm stays a constant.
We like to read what the test expects.
; A pointer in a nested struct of a constant arm: inner and outer structs are
; rebuilt with OpCompositeInsert in the result's types.
; A pointer in a vector member of a constant arm is bitcast to the vector's
; element type; the vector and struct are rebuilt with OpCompositeInsert.
; @g (i32 pointee) inserted into a pointer vector is bitcast to
; the vector's element type (pointer to i8).
Thank you for the patch. It fixes the select/PHI cases shown in the tests you added. However, I think this is not directly addressing the root-cause, which IMO is in preprocessCompositeConstants. It gives every constant aggregate its deduced type no matter what the user is: https://github.com/llvm/llvm-project/blob/5ed1f2f3b3633b8a18377fdba569b5d8814786b9/llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp#L1900
This PR addresses when the user is Select/PHI/freeze, but the mismatch happens also when the constant is returned, passed to a call, or inserted into another aggregate. For example, these are all invalid even with this PR:
@g = addrspace(1) global i32 0
%Q = type { ptr addrspace(1), i32 }
%R = type { %Q, i32 }
declare void @use(%Q)
define %Q @ret() {
ret %Q { ptr addrspace(1) @g, i32 1 }
}
define void @call() {
call void @use(%Q { ptr addrspace(1) @g, i32 1 })
ret void
}
define %R @ins(i32 %x) {
%r = insertvalue %R poison, %Q { ptr addrspace(1) @g, i32 1 }, 0
%r2 = insertvalue %R %r, i32 %x, 1
ret %R %r2
}
Would it make sense to decide this in
preprocessCompositeConstants instead? When it lowers a constant aggregate operand of I to spv_const_composite, it knows both the user and the deduced type, so if I isn't an intrinsic and the deduced type differs from the LLVM type, it could build the insertvalue chain there. As a quick check, I added ReturnInst, InsertValueInst and non-intrinsic CallInst to the filter in insertPointerConstantArms and all three cases became valid.Would it make sense to decide this in preprocessCompositeConstants instead?Yes, that's the better place, thanks. preprocessCompositeConstants now rebuilds such a constant as an insertvalue (insertelement for a vector) chain for every user except intrinsics and extractvalue. extractvalue reads the deduced type, and composite-ptr-member-bitcast.ll relies on that. insertPointerConstantArms is gone. Nested members need no recursion: the chain's insertvalues go back on the worklist, so a nested member with a known pointee gets its own chain. Your ret/call/insertvalue examples are in the new constant-deduced-pointee-users.ll and pass spirv-val.
This excludes vectors, so a vector-of-pointers select hits the same selectSelect assertThe same change covers it, and the vector select is in the new test. With #241166 applied, your PHI reproducer passes spirv-val as well.
Did I not see this before in other PRs you authored? […] Could be factored out to a helper?
The map is gone. A PHI's chain now goes into the entry block like its other constants, and replaceUsesOfWith gives duplicate switch edges the same value.
Isn't this always nullptr?
Yes. A vector's elements are untyped pointers, so it was always i8; it now casts to i8 directly.
I think the name is misleading, it doesn't really reflect what it does.
The function is gone; the check is inline now (DeducedTy != AggrConst->getType()).
deduceNestedTypeHelperonly checks operand 0 for arrays and vectors. Something like[null, @g]is missed.
Fixed: it now deduces from every element. select-constant-arm-array-null-first.ll tests [null, @g]. It's a separate file because a null pointer is uniqued per module, so an earlier function in a shared file could already have given it a pointee.
I applied the test comment suggestions, with the PHI sentence changed to say the arm is now built in the entry block.
I noticed in the existing composite-ptr-member-bitcast.ll test (its CHECK lines don't pin this, so we should probably update it) that ret_nested_aggr now returns a 4-instruction OpCompositeInsert chain instead of the OpConstantComposite it had before, although none of its members has a known pointee. If I read it right, ptr null is uniqued, so once an earlier function uses it (ret_aggr here, or even just ret ptr null) it carries a deduced element type, and every later aggregate constant holding ptr null takes this path. Two identical functions returning { ptr null, i8 1 } get a constant for the first and a chain for the second. The output is still valid, but should a null member count as a known pointee here?
Thanks for addressing this. Can we have a test for this? I didn't see any. Maybe a <null, @g> variant of @select in select-constant-arm-pointer-vector.ll?
// Users other than an intrinsic or extractvalue expect the LLVM type.
// Rebuild the constant as an insert chain, which casts each member
// to it.
// Lower a constant aggregate member to null in the target address space
// if it's `addrspacecast(null)`, and nested `undef/poison` because they're
// missed in `preprocessUndefsAndPoisons()`.
; A constant holding @g (i32 pointee) is rebuilt with OpCompositeInsert in its
; LLVM type for any user other than an intrinsic or extractvalue.
If I read it right,ptr nullis uniqued, so once an earlier function uses it (ret_aggrhere, or even justret ptr null) it carries a deduced element type, and every later aggregate constant holdingptr nulltakes this path. [...] should a null member count as a known pointee here?
You read it right, and no, it shouldn't. deduceNestedTypeHelper now skips a ConstantPointerNull member (88cafcded700), so ret_nested_aggr is an OpConstantComposite again regardless of what used the null before. I pinned that in composite-ptr-member-bitcast.ll; the check fails without the fix. While there, the struct, array and vector branches share one lambda for the member deduction.
Can we have a test for this? I didn't see any. Maybe a<null, @g>variant of@selectinselect-constant-arm-pointer-vector.ll?
Added @select_null_first there (696daa0483c2): with the null first and nulls no longer contributing a pointee, only @g gives the element type, so it checks the deduction looks past element 0. The array case is in select-constant-arm-array-null-first.ll.
> // Users other than an intrinsic or extractvalue expect the LLVM type. > // Rebuild the constant as an insert chain, which casts each member > // to it. >
Done.
> // Lower a constant aggregate member to null in the target address space > // if it's `addrspacecast(null)`, and nested `undef/poison` because they're > // missed in `preprocessUndefsAndPoisons()`. >
Done.
> ; A constant holding @g (i32 pointee) is rebuilt with OpCompositeInsert in its > ; LLVM type for any user other than an intrinsic or extractvalue. >
Done.
Approved these changes.
Approved these changes.
Thanks for the reviews! I don't have commit access; could one of you merge this?
maarquitos14
gonsolo
A constant arm's pointer members carry the pointee types deduced for them anywhere in the module (constant expressions are shared between functions), so the constant can be a different SPIR-V type than the PHI or select and its other arms:
selectSelectasserts. Rebuild such an arm withinsertvalue, which casts each member to the result's member type.Assisted-by: Claude Opus 5.5