Skip to content

ILGPU V2.0: Named Errors for Recursive Types + Nested Closures in Debug Builds - #1701

Open
m4rs-mt wants to merge 3 commits into
cpu_entry_point_indexfrom
recursive_type_errors
Open

m4rs-mt wants to merge 3 commits into
cpu_entry_point_indexfrom
recursive_type_errors

Conversation

@m4rs-mt

@m4rs-mt m4rs-mt commented Oct 31, 2026

Copy link
Copy Markdown
Owner

Builds on #1700. Types that refer to themselves through a class, such as a class holding a
reference to its own class or a structure holding a class that holds the structure again, are rejected with a compile
error naming the field path through which they refer to themselves. Before, they overflowed the compiler's stack and
took the process down. Generic types whose fields create ever larger instantiations of their own definition, such as
Node<T> holding Node<Node<T>>[], are rejected the same way, while deeply nested but finite instantiations, such as
the nested tuples of long C# tuples, keep compiling. A structure holding an array of itself, which #1688 already
rejects, now reports the same field-path message. Structures holding pointers to themselves keep compiling as #1688
made them. Separately, lambdas capturing locals of two nested scopes compile in Debug builds.

struct StructNode { public int Value; public ClassLink Link; }
sealed class ClassLink { public StructNode Node; }
struct Node<T> { public T Value; public Node<Node<T>>[] Children; }

var link = new StructNode { Value = index };  // error ILGPU1200: ... refers to itself through 'StructNode.Link.Node'
var node = new Node<int> { Value = index };   // error ILGPU1200: ... ever larger instantiations of 'Node<T>'

int offset = index * 10;
if (index >= 0)
{
    int bias = 3;
    Func<int, int> f = x => x + offset + bias;  // compiles and runs in Debug builds
    data[index] = f(index);
}

A note on authorship

This PR was done with AI-assistant pair programming (Claude via Claude Code). Every commit carries a
Co-Authored-By: Claude trailer.

What's in this PR

1. Fields of class types occupy one field (Src/ILGPUC/IR/TypeInformationManager.cs, Src/ILGPUC/IR/ModuleValues/Construction/ModuleBuilder.cs)

  • A value of a class type is a pointer in the IR and occupies a single field. The type information of a class counted
    all fields of the class as its flattened fields. A field holding a class reference was therefore accessed with a
    field span as wide as the class, and the fields of structures and classes behind such a field got shifted indices.
  • Debug builds of a lambda capturing locals of two nested scopes hit this. The C# compiler stores the locals in two
    closure classes, and the inner one refers to the outer one through a field. Storing that field sliced beyond the end
    of the inner closure class and failed with "Slice span out of range" on all backends.
  • The layout of a class itself is still described by its fields. The structure builder of a class layout takes the
    number of fields of the class as its capacity instead of its flattened field count.

2. Type information no longer recurses into referenced types (Src/ILGPUC/IR/TypeInformationManager.cs)

  • The type information of a structure eagerly resolved the element types of its arrays and views and the types of its
    class fields. Only arrays of and pointers to the structure being resolved were guarded, so a type referring to itself
    through a class or a view recursed until the stack overflowed. The existing guard against recursive classes in
    CreateClassStructureType never fired, because the type information overflowed before the class was reached again.
  • Pointers, arrays, views and enums now occupy a single field without resolving their element types, and fields of
    reference types count as single fields without resolving their types. The set of types in progress in the type
    information is no longer needed and is removed.
  • The IsBlittable and IsValidKernelParameter flags are removed. Nothing read them, and they could not be computed
    without resolving these types.

3. Recursive types are rejected (Src/ILGPUC/IR/ModuleValues/Construction/ModuleBuilder.cs, Src/ILGPU/Resources/ErrorMessages.resx)

  • Creating the IR type of a structure or a class registers it as in progress, together with the field being created.
    Reaching it again through its own fields raises an unsupported-construct error (ILGPU1200) at the kernel code that
    uses the type. The message names the field path, with auto-properties under their property names:

    Recursive type 'StructNode' is not supported in GPU kernels: it refers to itself through 'StructNode.Link.Node'.

  • This replaces the separate check for arrays of structures in progress, whose message named the reflection name of
    the array type. A structure holding an array of itself now reports its field path, such as 'ArrayNode.Children'.
    Pointers to a structure in progress stay opaque pointers, as ILGPU V2.0: Pointer Constructs in Kernels #1688 introduced.

  • Instantiating a generic type definition with an expanding cycle (ECMA-335 II.9.2) is rejected before its fields are
    created. In such a definition, a type parameter flows through the type arguments of its field types back into itself,
    nested in another type argument at least once, as in Node<T> holding Node<Node<T>>[] or Node<Box<T>>[], or
    through another type, as in MutualNode<T> holding MutualLink<T[]>. It never reaches the same instantiation twice
    but would create new ones without end. The result is cached per definition:

    Recursive type 'Node' is not supported in GPU kernels: it contains ever larger instantiations of 'Node'.

  • Finite types are not affected. Instantiations nested in their own type arguments, such as a wrapper nested 40 levels
    deep or the ValueTuple chains of long tuples, still compile. A type parameter passed only to other definitions, as
    in a field of type Box<Box<T>>, does not expand. A type holding an array of its own instantiation, such as
    GenericTree<T> with a GenericTree<T>[] field, is reported through its field path.

  • Type names use the C# spelling of the other frontend diagnostics (TypeDisplay.Format), such as Node<int>. The
    resource NotSupportedRecursiveReferenceType is renamed to NotSupportedRecursiveType, since it now covers
    structures, too, and NotSupportedExpandingGenericType is added.

4. Tests (Src/ILGPUC.Tests/)

  • RecursiveTypeTests (new, NonKernelTests/):
    • RecursiveStructure_ReferencesOccupySingleFields: the type information of self-referencing structures (through an
      array, a pointer, a class, and generic and expanding definitions) has two fields at offsets 0 and 1.
    • NestedInstantiations_AreCreated creates Wrapper<T> nested 1, 20 and 40 levels deep and ValueTuple chains of
      the same depths. NestedTypeArgument_IsCreated creates a structure with a Box<Box<T>> field.
      DeeplyNestedLocal_Compiles compiles a kernel with a local nested 20 levels deep, and PointerView_Compiles a
      kernel taking a view of a structure that points to itself.
    • Eight kernels are rejected with ILGPU1200, the exact message and the line of the kernel that uses the type:
      • StaticTree (a static field of a structure holding an array of itself);
      • CapturedClass (a lambda capturing a self-referencing class) and LocalStructClass (structure → class →
        structure, 'StructNode.Link.Node');
      • LocalGenericTree (field path), LocalGeneric, LocalExpanding, LocalGrowing and LocalMutual (expanding
        definitions).
  • SelfReferentialPointerTests.SelfReferentialArray_ReportsUnsupportedConstruct expects the field-path message.
  • KernelDiagnosticTests.RecursiveLocalType_FailsBuild: a structure holding a class that holds the structure fails an
    ilgpuc build with ILGPU1200 at the line of the local.
  • CompilerInternalsTests.TypeInfo_ClassField_OccupiesSingleField: a class, a class with a class field and a structure
    with a class field have one, one and two flattened fields, with unshifted offsets.
  • LambdaExecutionTests.NestedScopeCapture_ProducesCorrectOutput (TestPrograms/Lambda/NestedScopeCapture.cs) runs a
    lambda capturing locals of two nested scopes, with Release and Debug programs, on every backend with a device.
    LambdaKernels.NestedScopeCaptureKernel is used for source generation on every backend.

Depends on

#1700 (based on its head; the base is retargeted once it merges).

Testing

Suite This PR
Full test suite, Apple Silicon (CPU, Metal; CUDA, ROCm and OpenCL compile-only) 11524 passed, 1715 skipped, 0 failed
Release build with TreatWarningsAsErrors 0 errors
Every commit of the PR build (3/3, 0 warnings)

CUDA, ROCm and OpenCL were compiled with nvcc, hipcc and ocloc but not run on a device.

🤖 Generated with Claude Code

m4rs-mt and others added 3 commits September 5, 2026 01:11
…ld referring to another closure class, as in the debug closures of nested scopes, no longer spans the fields of that class and fails to compile.

Values of class types are pointers in the IR and occupy a single field, but
the type information of a class counted all fields of the class as its
flattened fields. A field holding a class reference was thus accessed with a
field span as wide as the class, and the fields of structures and classes
behind such a field were assigned shifted indices. Debug builds of lambdas
capturing locals of two nested scopes hit this: the inner closure class
refers to the outer one through a field, and storing that field sliced
beyond the end of the inner closure class ("Slice span out of range") on all
backends.

The layout of a class itself is still described by its fields. The
structure builder of a class layout now uses the number of fields of the
class as its capacity hint instead of its flattened field count.

Co-Authored-By: Claude <noreply@anthropic.com>
…h a compile error naming the field path instead of a stack overflow.

The type information of a structure resolved the type information of the
element types of its arrays and views and of all its fields of class types
eagerly. Only arrays of and pointers to the structure being resolved were
guarded, so a type referring to itself through a class or a view, such as a
structure holding a class that holds the structure again, recursed until the
stack overflowed and took the host process down. The guard against recursive
classes in CreateClassStructureType never fired: the type information it
asked for overflowed the stack before the class was reached again. Element
types and class field types are no longer resolved by the type information,
which only needs to count them as single fields, and its set of types in
progress is gone. This removes the IsBlittable and IsValidKernelParameter
flags, which nothing read and which could not be computed without resolving
these types.

Creating the IR type of a structure or class now registers it as being
created. Reaching it again through its own fields rejects it, and the
message names the field path, such as 'StructNode.Link.Node'. This
replaces the separate check for arrays of structures being created and its
message with the reflection name of the array type: a tree node holding an
array of child nodes now reports 'TreeNode.Children', too. Pointers to
structures being created stay opaque pointers, as before.

The error is reported as an unsupported construct (ILGPU1200) at the
kernel code using the type, with the C# type names of the other frontend
diagnostics, such as 'GenericTree<int>'. The resource
NotSupportedRecursiveReferenceType is renamed to NotSupportedRecursiveType,
as it covers structures, too.

Co-Authored-By: Claude <noreply@anthropic.com>
…Node<T> holding Node<Node<T>>[], with a compile error naming the definition instead of a stack overflow.

A generic type definition whose type parameter flows through the type
arguments of its field types back into itself, nested in another type
argument at least once, has an expanding cycle (ECMA-335 II.9.2), as in
Node<T> holding Node<Node<T>>[] or Node<Box<T>>[]: it never reaches the
same instantiation twice, so the check for types being created never
fires, but it would create new ones without end. Creating the IR type of
an instantiation of such a definition now rejects it, and the message
names the definition, such as 'Node<T>'. Instantiations nested in their
own type arguments, such as deeply nested wrappers or the ValueTuple`8
chains of long tuples, stay finite and are not mistaken for recursive
types, however deeply they are nested. A type parameter passed only to
other definitions, as in a field of type Box<Box<T>>, does not expand, and
a type holding an array of its own instantiation, as in GenericTree<T>
with a GenericTree<T>[] field, is still reported through its field path
rather than as an expanding definition.

The error is reported as an unsupported construct (ILGPU1200) at the
kernel code using the type, with the new resource
NotSupportedExpandingGenericType.

Co-Authored-By: Claude <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant