Repository navigation
Cpp 03 classes
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.
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.
| 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
|
// 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 &
|
// 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()
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
// 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"]
| 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
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
Sources: llvm/include/llvm/IR/Instructions.h:65
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
- Forgetting
virtualon 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
Derivedinto aBasevalue drops the derived part; use pointers or references.
- Constructors acquire, destructors release, automatically and in reverse order: that is RAII.
-
virtual+overridegive 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.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look