From: Tamas Demjen on
John N. wrote:

> If a virtual method is not referenced in the entire executable, then
> why is it required?

The compiler doesn't know if it's going to be called, therefore it has
no choice but to put it into the vtable. And once it's there, the
function must be linked.

Certain optimizations could only be done at link time. Traditionally
linkers weren't smart enough to make significant modifications to the
machine code, so link-time optimizations were ruled out.

In recent versions of Visual Studio whole program optimization is
actually available as an option:
http://msdn.microsoft.com/en-us/library/0zza0de8%28VS.80%29.aspx

This requires the compiler to produce an intermediate code, and the
linker is responsible for generating the final machine code, so it has a
chance to perform a bunch of optimizations that the compiler couldn't
see at the object file level. This way it can remove unused functions,
unused vtable entries, and decide to make virtual functions non-virtual
when possible (when they're not called via a base pointer, they don't
really need to be virtual).

Another example is Java, where every function is virtual by default. It
is the responsibility of the JIT compiler to figure out which functions
actually require dynamic dispatching. That decision is not part of the
intermediate byte-code. Virtual functions can even be inlined when the
type is known at JIT-time.

Tom
From: Tim Roberts on
"John N." <ortp21(a)gmail.com> wrote:
>
>On Feb 7, 1:08�pm, Tim Roberts <t...(a)probo.com> wrote:
>
>>There's no way to tell whether a particular virtual function
>> will ever be called without simulating the executing the code, and Turing
>> gets in the way of that.
>
>If a virtual method is not referenced in the entire executable, then
>why is it required?

Consider the assembler code for calling a non-virtual method:

mov ecx, [ObjectInstance]
call CMyClass::GetObjectData

There is an explicit reference to the method name. The linker sees that
reference, and knows that someone needs that function. A function that is
not called is never referenced, and can safely be removed;

Now consider calling a virtual method:

CMyClass_vtable:
dd CMyClass::QueryInterface
dd CMyClass::AddRef
dd CMyClass::Release
dd CMyClass::GetObjectData
....
mov ecx, [ObjectInstance]
mov eax, [ecx] ; Get address of vtable
call dword ptr [eax+12] ; call 4th entry

The call goes indirectly through the function pointers in the vtable. The
linker sees explicit references to ALL of the virtual function names.
There's no way for the linker to know that some of them are not actually
used in the code.
--
Tim Roberts, timr(a)probo.com
Providenza & Boekelheide, Inc.