How to know if a value type includes heap allocations and ref counting

This is encoded in the reflection metadata that is consumed by the reflection library. You can look at a binary, and starting from the mangled name of a type, compute its layout, which recursively breaks down into POD or reference counted values.

Another approach is to hook into the front end to get this information from IRGen. Here is some code I added a few years ago (edit: it was 6 years ago :scream:) to dump the size and alignment of a given list of types in YAML format: swift/lib/IRGen/TypeLayoutDumper.cpp at main · swiftlang/swift · GitHub. This can be expanded upon to get more information out of the TypeInfo object.

The difference in the two approaches is that the front end won’t see inside a resilient type’s layout, because you’re seeing the compile-time view of the world. The reflection library on the other hand always computes the exact runtime layout, using full knowledge of the reflection metadata in all libraries.

For generic types, this depends on the instantiation though, so it’s more difficult to boil down the “cost” of passing the abstract type, without knowing the generic arguments. However, you can similarly determine if the size of the generic type depends on the size of the arguments or not, which also changes the runtime costs involved.

2 Likes