Example code

class A {
public:
    virtual void foo() {printf("A");}
};
class B : public A {
public:
    virtual void foo() {printf("B");}
};
int main() {
    A *o1 = new B();
    o1->foo();
}

LLVM bc

We can generate example.bc by clang -O0 -emit-llvm example.cpp -c -o example.bc

The class hierarchy info is revealed in the example.bc as follows

%class.A = type { i32 (...)** }
%class.B = type { %class.A }
@_ZTV1A = linkonce_odr unnamed_addr constant { [3 x i8*] } { [3 x i8*] [i8* null, i8* bitcast ({ i8*, i8* }* @_ZTI1A to i8*), i8* bitcast (void (%class.A*)* @_ZN1A3fooEv to i8*)] }, align 8
@_ZTV1B = linkonce_odr unnamed_addr constant { [3 x i8*] } { [3 x i8*] [i8* null, i8* bitcast ({ i8*, i8*, i8* }* @_ZTI1B to i8*), i8* bitcast (void (%class.B*)* @_ZN1B3fooEv to i8*)] }, align 8

Dynamic Binding

class A {
public:
    virtual void vfunc1();
    virtual void vfunc2();
    void func1();
    void func2();
private:
    int m_data1, m_data2;
};

class B : public A {
public:
    virtual void vfunc1();
    void func1();
private:
    int m_data3;
};

class C: public B {
public:
    virtual void vfunc2();
    void func2();
private:
    int m_data1, m_data4;
};

The object model is as follows.

Practice: CHA and RTA

Analyze the virtual call based on CHA(Class Hierarchy Analysis) and RTA(Rapid Type Analysis)