Search code examples
c++vtableasm.js

asm.js - How should function pointers be implemented


Note: This question is purely about asm.js not about C++ nor any other programming language.

As the title already says:

How should a function pointer be implemented in a efficient way?

I couldn't find anything on the web, so I figured asking it here.

Edit: I would like to implement virtual functions in the compiler I'm working on.

In C++ I would do something like this to generate a vtable:

#include <iostream>

class Base {
  public:
    virtual void doSomething() = 0;
};

class Derived : public Base {
  public:
    void doSomething() {
        std::cout << "I'm doing something..." << std::endl;
    }
};

int main()
{
    Base* instance = new Derived();
    instance->doSomething();
    return 0;
}

To be more precise; how can I generate a vtable in asm.js without the need of plain JavaScript? In any case, I would like the "near native" capabilities of asm.js while using function pointers.

The solution may be suitable for computer generated code only.


Solution

  • Looking over how asm.js works, I believe your best bet would be to use the method the original CFront compiler used: compile the virtual methods down to functions that take a this pointer, and use thunks to correct the this pointer before passing it. I'll go through it step by step:

    No Inheritance

    Reduce methods to special functions:

    void ExampleObject::foo( void );
    

    would be transformed into

    void exampleobject_foo( ExampleObject* this );
    

    This works fine for non-inheritance based objects.

    Single Inheritance

    We can easily add support for arbitrary large amount of single inheritance through a simple trick: always store the object in memory base first:

    class A : public B
    

    would become, in memory:

    [[ B ] A ]
    

    Getting closer!

    Multiple Inheritance Now, multiple inheritance makes this much harder to work with

    class A : public B, public C
    

    It's impossible for both B and C to be at the start of A; they simply cannot co-exist. There are two choices:

    1. Store an explicit offset (known as delta) for each call to base.
    2. Do not allow calls through A to B or C

    The second choice is much preferable for a variety of reasons; if you are calling a base class member function, it's rare you would want to do it through a derived class. Instead, you could simply go C::conlyfunc, which could then do the adjustment to your pointer for you at no cost. Allowing A::conlyfunc removes important information that the compiler could have used, at very little benefit.

    The first choice is used in C++; all multiple inheritance objects call a thunk before each call to a base class, which adjusts the this pointer to point to the subobject inside it. In a simple example:

    class ExampleBaseClass
    {
        void foo( void );
    }
    
    class ExampleDerivedClass : public ExampleBaseClass, private IrrelevantBaseClass
    {
        void bar( void );
    }
    

    would then become

    void examplebaseclass_foo( ExampleBaseClass* this );
    void examplederivedclass_bar( ExampleDerivedClass* this);
    
    void examplederivedclass_thunk_foo( ExampleDerivedClass* this)
    {
        examplebaseclass_foo( this + delta );
    }
    

    This could be inlined in many situations, so it's not too big of overhead. However, if you could never refer to ExampleBaseClass::foo as ExampleDerivedClass::foo, these thunks wouldn't be needed, as the delta would be easily discernible from the call itself.

    Virtual functions

    Virtual functions adds a whole new layer of complexity. In the multiple inheritance example, the thunks had fixed addresses to call; we were just adjusting the this before passing it to an already known function. With virtual functions, the function we're calling is unknown; we could be overridden by a derived object we have no possibility of knowing about at compile time, due to it being in another translation unit or a library, etc.

    This means we need some form of dynamic dispatch for each object that has a virtually overridable function; many methods are possible, but C++ implementations tend to use a simple array of function pointers, or a vtable. To each object that has virtual functions, we add a point to an array as a hidden member, usually at the front:

    class A
    {
    hidden:
        void* vtable;
    public:
        virtual void foo( void );
    }
    

    We add thunk functions which redirect to the vtable

    void a_foo( A* this )
    {
        int vindex = 0;
        this->vtable[vindex](this);
    }
    

    The vtable is then populated with pointers to the functions we actually want to call:

    vtable[0] = &A::foo_default; // our baseclass implimentation of foo

    In a derived class, if we wish to override this virtual function, all we need to do is change the vtable in our own object, to point to the new function, and it will override in the base class as well:

    class B: public A
    {
        virtual void foo( void );
    }
    

    will then do this in the constructor:

    ((A*)this)->vtable[0] = &B::foo;
    

    Finally, we have support for all forms of inheritance! Almost.

    Virtual Inheritance There is one final caveat with this implementation: if you continue to allow Derived::foo to be used when what you really mean is Base::foo, you get the diamond problem:

    class A : public B, public C;
    class B : public D;
    class C : public D;
    
    A::DFunc(); // Which D?
    

    This problem can also occur when you use base classes as stateful classes, or when you put function that should be has-a rather than is-a; generally, it's a sign of a need for a restructure. But not always.

    In C++, this has a solution that is not very elegant, but works:

    class A : public B, public C;
    class B : virtual D;
    class C : virtual D;
    

    This requires those who implement such classes and hierarchies to think ahead and intentionally make their classes a little slower, to support a possible future usage. But it does solve the problem.

    How can we implement this solution?

    [ [ D ] [ B ] [ Dptr ] [ C ] [ Dptr ] A ]
    

    Rather than use the base class directly, as in normal inheritance, with virtual inheritance we push all usages of D through a pointer, adding an indirection, while stomping the multiple instantiations into a single one. Notice that both B and C have their own pointer, that both point to the same D; this is because B and C don't know if they are free floating copies or bound in derived objects. The same calls need to be used for both, or virtual functions won't work as expected.

    Summary

    1. Transform method calls into function calls with a special this parameter in base classes
    2. Structure objects in memory so single inheritance is no different from no inheritance
    3. Add thunks to adjust this pointers then call base classes for multiple inheritance
    4. Add vtables to classes with virtual methods, and make all calls to methods go through vtable to method (thunk -> vtable -> method)
    5. Deal with virtual inheritance through a pointer-to-baseobject rather than derive object calls

    All of this is straightforward in js.asm.