Pure dynamic casts?

Jeremie Pelletier jeremiep at gmail.com
Mon Sep 21 17:30:00 PDT 2009


bearophile wrote:
> I don't know much about this topic, but this post is mostly in question form.
> 
> Are dynamic casts pure? I have compiled the following small program with LDC:
> 
> 
> version (Tango)
>     import tango.stdc.stdio: printf;
> else version (D1)
>     import std.c.stdio: printf;
> else
>     import core.stdc.stdio: printf;
> 
> class A { int a; }
> 
> void main() {
>     Object o = new A();
>     A a = cast(A)o;
>     a.a = 10;
>     printf("%d %d\n", a.a, cast(A)o);
> }
> 
> 
> LDC based on DMD v1.045 and llvm 2.6 (Thu Sep 10 23:50:27 2009)
> ldc -O5 -release -inline -output-s dyncast_test.d
> 
> The asm it produces shows two calls to _d_dynamic_cast:
> 
> [snip]
> 
> If the dynamic cast are pure the compiler can call it only once here (LLVM already has two functions attributes for pure functions).
> 
> (Related: can the code that performs the dynamic casts be in some situations inlined by LDC?)
> 
> Bye,
> bearophile

One cast for the assignment to a and one cast for the call to printf.

I would say the casts are pure to a certain level, they don't always 
return the same value to the same input because they return references. 
They do however perform the exact same code path for the same inputs. So 
it should be possible to inline them.

Take a look at the _d_dynamic_cast implementation of my runtime:

Object _d_dynamic_cast(in Object p, in ClassInfo ci) {
	uint offset = void;
	return p && _d_isbaseof2(p.classinfo, ci, offset) ?
		cast(Object)(*cast(void**)&p + offset) : null;
}

You can clearly see all there is to a dynamic cast is simply adjusting 
the pointer to the object's virtual table. So a compiler knowing the 
source and destination offset of the vtable can easily inline the code 
for such a cast.

An interface dynamic cast is similar but the interface reference has to 
be converted into an object reference first and then passed to 
_d_dynamic cast.

Maybe you could open a ticket in bugzilla about this?

Jeremie



More information about the Digitalmars-d mailing list