Skip to content

Instantly share code, notes, and snippets.

@paniq
Last active June 27, 2024 07:58
Show Gist options
  • Save paniq/738eaa6ca7071247f6eef212f39617f3 to your computer and use it in GitHub Desktop.
Save paniq/738eaa6ca7071247f6eef212f39617f3 to your computer and use it in GitHub Desktop.
Sum Type Tags

Encoding polymorphic values (sum types) in the heap can be trivially done by a type code/index (or simply tag) in the value's header.

For large per-tag pools of monotypal objects, the pool range itself can serve as identifying the type. A pointer into the pool can be checked against all known pool extents to extract the tag. Unfortunately this makes memory relocation difficult, and prohibits the use of multiple pools for the same tag.

A better approach when the heap supports baseable pointers (such as arcmem), is to store the tag of a pool at its beginning; a pointer into the pool can then be based to the pool header, amortizing the cost of a type tag.

All three mentioned approaches suffer from the issue however that casts are expensive as we need to copy values just to change their type, even though the actual attributes of the value did not change.

For the case where the number of types for a sum type S is smaller than the alignment of S, which is invariant, the type index (or tag) can instead be stored in the unused least significant bits of pointers to S. Recovering the original pointer is then as simple as masking out the tag.

On the x64 platform, this allows us to tag pointers to heap allocations with up to 16 separate tags.

Doubling the alignment also doubles the available number of tags.

For specialized heaps (like arcmem) where the alignment of a value is guaranteed to be equal or larger than the value's size, even though a sum type pointer's offset within the structure does not relate to the structure itself, the pointer still satisfies memory range checks and does not interfere with memory object tracing.

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