www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Can the D compiler detect final and optimize?

reply IGotD- <nise nise.com> writes:
A little bit related to that some want class methods to be final 
by default just like in C++. If I'm not mistaken one benefit of 
final as default is that the compiler will insert hard coded 
branches to the method as well as the possibility to do inlining. 
Are my assumptions correct?

Instead of having final as default, can't the compiler itself 
infer when a class is implicitly final and do the optimizations 
itself? Benefits would be that a programmer has the possibility 
to extend about all classes (in C++ would only be possible if 
class author makes all methods virtual). The final keyword would 
just mean that a class method is not allowed to be overridden.

Is this possible at all?
Mar 13
next sibling parent reply rikki cattermole <rikki cattermole.co.nz> writes:
Why would this be needed?

With ldc -O3 the test function can be completely erased:

import std;
void main()
{
     Foo foo = new Foo;
     foo.x = 7;
     test(foo);
}

void test(Foo foo) {
     writeln(foo.get);
}

class Foo {
     int x;

     int get() { return x; }
}
Mar 13
parent IGotD- <nise nise.com> writes:
On Friday, 13 March 2020 at 15:15:50 UTC, rikki cattermole wrote:
 Why would this be needed?

 With ldc -O3 the test function can be completely erased:

 import std;
 void main()
 {
     Foo foo = new Foo;
     foo.x = 7;
     test(foo);
 }

 void test(Foo foo) {
     writeln(foo.get);
 }

 class Foo {
     int x;

     int get() { return x; }
 }
The D programming language by Andrei Alexandrescu. Chapter 6.6. "So final non-override methods are never subjected to indrect calls; instead they enjoy the same calling convention, low overhead and inlining opportunities as regular functions" I think I saw a difference between DMD and LDC previously where LDC actually could in some cases infer that the method is final. If the compiler can infer that a method is final (officially by language standard), then what would the argument for final as default be?
Mar 13
prev sibling parent Dennis <dkorpel gmail.com> writes:
On Friday, 13 March 2020 at 15:08:34 UTC, IGotD- wrote:
 Instead of having final as default, can't the compiler itself 
 infer when a class is implicitly final and do the optimizations 
 itself?
The problem is that only at runtime are all the derived classes known, and by then the code is already compiled. I think the Java Virtual Machine can automatically elide virtual calls by virtue of being a JIT, but for D this would mean either telling the compiler 'assume all derived classes are present in the source files provided here' or doing fancy link-time optimization.
Mar 13