Dynamic casts are pure. They don't use global state, and have the same output 
for the same reference as input. Interestingly, dynamic cast results are 
independent of intervening mutable calls... So there's even greater opportunity 
for optimization.

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:
> 
> _Dmain:
>     pushl   %esi
>     subl    $16, %esp
>     movl    $_D5cast51A7__ClassZ, (%esp)
>     call    _d_allocclass
>     movl    %eax, %esi
>     movl    $_D5cast51A6__vtblZ, (%esi)
>     movl    $0, 4(%esi)
>     movl    $0, 8(%esi)
>     movl    %esi, (%esp)
>     movl    $_D5cast51A7__ClassZ, 4(%esp)
>     call    _d_dynamic_cast
>     movl    $10, 8(%eax)
>     movl    %esi, (%esp)
>     movl    $_D5cast51A7__ClassZ, 4(%esp)
>     call    _d_dynamic_cast
>     movl    %eax, 8(%esp)
>     movl    $10, 4(%esp)
>     movl    $.str1, (%esp)
>     call    printf
>     xorl    %eax, %eax
>     addl    $16, %esp
>     popl    %esi
>     ret $8
> 
> 
> 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

Reply via email to