Skip to content

Cpp 03 classes

Mugundan edited this page Nov 27, 2026 · 1 revision

Classes and RAII

Relevant source files

The following files were used as context for generating this wiki page:

A class bundles data with the functions that work on it. LLVM's IR is a big class hierarchy (Value → User → Instruction → AllocaInst, ...), and almost every helper in LLVM relies on RAII: an object's destructor automatically cleans up when it goes out of scope. This page explains both.

Purpose and Scope

This page covers classes and structs, constructors and destructors, member initialiser lists, access control, inheritance, virtual functions and the vtable, RAII, and the rule of zero/three/five. Ownership with unique_ptr is on Ownership and Move.

The Hotel Key Card Analogy

Hotel RAII
Checking in gives you a key card The constructor acquires a resource
Checking out returns it automatically, whatever happened during the stay The destructor releases it when the object goes out of scope
You can't forget to return it No leaks, even on early return

A Class

// example: classes
#include "llvm/Support/raw_ostream.h"
using namespace llvm;

class Counter {
public:
  explicit Counter(int Start) : Value(Start) {}   // member initialiser list
  void increment() { ++Value; }
  int get() const { return Value; }               // const: doesn't modify
private:
  int Value;                                      // hidden from outside
};

int main() {
  Counter C(5);
  C.increment();
  C.increment();
  outs() << "count = " << C.get() << "\n";
}
count = 7
Piece Meaning
public: / private: Who may use the members; struct defaults to public, class to private
Constructor Counter(int) Runs when an object is created
: Value(Start) Initialiser list: initialises members before the body runs (prefer it to assignment in the body)
explicit Forbids silent conversion Counter C = 5;
const after get() Callable on const Counter &

Constructors and Destructors: RAII

// example: raii
#include "llvm/Support/raw_ostream.h"
using namespace llvm;

struct Scope {
  const char *Name;
  explicit Scope(const char *N) : Name(N) { outs() << "enter " << Name << "\n"; }
  ~Scope() { outs() << "leave " << Name << "\n"; }   // destructor
};

int work(bool EarlyExit) {
  Scope S("work");
  if (EarlyExit)
    return 1;          // destructor still runs
  Scope Inner("inner");
  return 2;            // destroyed in reverse order: inner, then work
}

int main() {
  work(true);
  work(false);
}
enter work
leave work
enter work
enter inner
leave inner
leave work
sequenceDiagram
    participant F as work(false)
    F->>F: construct S("work")
    F->>F: construct Inner("inner")
    F->>F: return 2
    F->>F: ~Inner() (last created, first destroyed)
    F->>F: ~S()
Loading

RAII is how C++ manages every resource: memory (std::unique_ptr), files, locks (std::lock_guard). In LLVM, IRBuilder insertion points, timers, and LLVMContext all use it. LLVM is compiled without exceptions, but RAII still matters for early returns.

Sources: cppreference: RAII

Inheritance and Virtual Functions

// example: virtual
#include "llvm/Support/raw_ostream.h"
#include <memory>
using namespace llvm;

struct Pass {
  virtual ~Pass() = default;              // virtual destructor in any base class
  virtual const char *name() const = 0;   // pure virtual: must override
  virtual void run() { outs() << name() << ": default run\n"; }
};

struct DCE : Pass {
  const char *name() const override { return "dce"; }
  void run() override { outs() << "dce: removing dead code\n"; }
};

struct Verify : Pass {
  const char *name() const override { return "verify"; }   // uses default run()
};

int main() {
  std::unique_ptr<Pass> Passes[] = {std::make_unique<DCE>(), std::make_unique<Verify>()};
  for (auto &P : Passes)
    P->run();     // calls the right version through the vtable
}
dce: removing dead code
verify: default run
flowchart LR
    P["Pass object<br/>(hidden vtable pointer)"] --> VT["DCE vtable"]
    VT --> R["run → DCE::run"]
    VT --> N["name → DCE::name"]
    VT --> D["~ → DCE::~DCE"]
Loading
Keyword Meaning
virtual Call is resolved at run time from the object's real type
= 0 Pure virtual; the class is abstract
override Compiler checks this really overrides a base function; always write it
final Cannot be overridden further
virtual ~Base() Needed so delete through a base pointer runs the derived destructor

Each class with virtual functions has a vtable (table of function pointers); each object holds a hidden pointer to it. A virtual call costs one indirect call.

LLVM note: the IR hierarchy (Value, Instruction, ...) deliberately does not use virtual functions for most operations, to save memory and time. Instead each object stores a kind number and uses LLVM-Style RTTI. Virtual functions appear in other places, e.g. TargetLowering, raw_ostream and legacy passes.

Sources: cppreference: virtual function specifier, Wikipedia: Virtual method table

A Real Hierarchy

AllocaInst derives from UnaryInstruction, which derives from Instruction:

class AllocaInst : public UnaryInstruction {
classDiagram
    Value <|-- User
    User <|-- Instruction
    Instruction <|-- UnaryInstruction
    UnaryInstruction <|-- AllocaInst
    UnaryInstruction <|-- LoadInst
    Instruction <|-- StoreInst
Loading

Sources: llvm/include/llvm/IR/Instructions.h:65

The Rule of Zero, Three and Five

A class that manages a resource directly may need five special members: destructor, copy constructor, copy assignment, move constructor, move assignment.

Rule Advice
Zero Prefer members that manage themselves (std::unique_ptr, SmallVector, std::string); then write none of the five
Three / Five If you write one of them, think about all of them
= delete Forbid copying when it makes no sense: LLVM IR objects such as Instruction cannot be copied
// illustrative
struct NoCopy {
  NoCopy() = default;
  NoCopy(const NoCopy &) = delete;            // no copies
  NoCopy &operator=(const NoCopy &) = delete;
};

Sources: cppreference: The rule of three/five/zero

Common Traps

  • Forgetting virtual on a base destructor.
  • Forgetting override, so a typo silently creates a new function instead of overriding.
  • Calling a virtual function from a constructor: it calls the base version.
  • Slicing: copying a Derived into a Base value drops the derived part; use pointers or references.

Key Points

  • Constructors acquire, destructors release, automatically and in reverse order: that is RAII.
  • virtual + override give run-time dispatch through a vtable; base classes need virtual destructors.
  • LLVM IR classes avoid virtual functions and copying; they use kind numbers and isa/cast.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally