Pregunta

Xamarin is a system that compiles .NET code fully ahead-of-time (AOT) for platforms which disallow data execution and so can't have a JIT. This question is not about Xamarin, but is about an assertion that its documentation makes. It states here:

Generic virtual methods support is limited, it's not possible to determine statically what method will be called in all circumstances so the compiler might leave out a few of them.

I could be mistaken but they seem to be implying a broad statement about what is possible here through static analysis, not just what they've chosen to implement in their own software.

As Hans Passant aptly pointed out, the example they give doesn't actually demonstrate the problem they're referring to, so I've excluded it.

So, aside from these definitely intractable special cases:

  • Reflection;

  • dynamically generated code (illegal in this scenario anyway);

  • pathological circular references in type arguments involving value types; and

  • foreign assemblies;

what would make an AOT compiler unable to handle the virtual generic method case?

¿Fue útil?

Solución

That example is just borken and doesn't demonstrate the problem at all. Implicit in virtual methods is that the compiler cannot reliable determine from which call sites the method might be called. Which is an issue for a generic method since the compiler must create multiple versions of it.

One version is needed to handle any reference type, specifically covered by the remark "It's generally safe to use a generic virtual method with reference types, like Object or String, given the compiler always compile a version that can handle then". Or in other words, it probably just blindly generates that one.

The troublemakers are the versions where T is a value type. One distinct concrete method must be compiled for each distinct value type. Since the compiler can't guess at the call site, it also can't see which value types it must create a method for. Blindly generating them is not feasible due to struct types and methods with multiple type parameters.

Otros consejos

I fundamentally agree with your analysis.

Xamarin and similar tools could go about this in reverse order, so to speak, by including every conceivable combination of instance type and virtual method signature and then go on to remove only the ones that are provably not needed.

They probably tried that, though, and found that the resulting code does tend to become quite large/slow for complex object hierarchies.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top