Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ LLVM class functionality

Tags:

c++

class

llvm

I'm playing around with LLVM, but now I got stuck at generating code for classes.

How would one create class functionality using LLVM?

  • Are class operators handled just like functions?
  • How is automated allocation handled, (like C++)?
  • How to support interfaces like Java does, through virtual inheritence like C++?
like image 401
Tim Avatar asked Jan 13 '13 20:01

Tim


1 Answers

Long Version

General class behavior

A straightforward approach is to create structs, then model methods as regular functions that receive a pointer to a struct representing the containing class - in essence, a this pointer - as the first parameter. Allocation could be modeled by allocating the struct and then calling a special initializing function - the constructor, really - on the allocated data.

Inheritance could be done by building a struct which contains a special "parent" field (or fields, for multiple inheritance), that has a type identical to the type of the struct for the base class.

Polymorphism

Read about virtual tables; I think they're the best starting point. You could find that the compiler basically:

  1. Creates a static table in memory, mapping from a function "name" to its implementation,
  2. Adds a pointer to the class struct that points to such a table,
  3. Whenever a virtual method is called, compiles it into an indirect call which dereferences the address from the appropriate virtual table entry.

Short Version

Write some code which uses classes in C++, then compile it to LLVM IR with Clang and look at the generated code.

like image 82
Oak Avatar answered Oct 17 '22 23:10

Oak