Repository navigation
Cpp 02 basics
Relevant source files
The following references were used as context for generating this wiki page:
- cppreference: References
- cppreference: Undefined behavior
- Wikipedia: One Definition Rule
- Book: Bjarne Stroustrup, A Tour of C++, chapters 1-3
This page covers the parts of C++ you meet on every line of LLVM code: values, pointers and references, const, headers and namespaces. If you already write C, most of it is familiar; the new parts are references and const-correctness, which LLVM uses everywhere.
This page covers variables and types, pointers, references, const, passing arguments, nullptr, headers and the one-definition rule, namespaces, and undefined behaviour. Classes are on Classes and RAII.
| Everyday | C++ |
|---|---|
| A house | An object in memory |
| The house's street address written on paper | A pointer (T *): can be changed, can be blank (nullptr) |
| A nickname for the house | A reference (T &): always refers to the same house, never blank |
| "Look but don't touch" sign | const |
// example: refs
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
void addOnePtr(int *P) { if (P) *P += 1; } // may be null: must check
void addOneRef(int &R) { R += 1; } // never null
int twice(const int &R) { return R * 2; } // read-only
int main() {
int X = 10;
int *P = &X; // P holds X's address
int &R = X; // R is another name for X
addOnePtr(P);
addOneRef(R);
outs() << "X = " << X << ", twice = " << twice(X) << "\n";
addOnePtr(nullptr); // safe: the function checks
outs() << "done\n";
}X = 12, twice = 24
done
flowchart LR
P["P (int *)<br/>holds address of X"] --> X["X = 12"]
R["R (int &)<br/>another name"] -.-> X
Pointer T *
|
Reference T &
|
|
|---|---|---|
| Can be null | Yes | No |
| Can be re-pointed | Yes | No |
| Access syntax |
*P, P->field
|
R, R.field
|
| LLVM convention | "May be null" or "optional" | "Always valid" |
LLVM convention: a function taking Function &F guarantees F exists; one taking Instruction *I might receive null (check the documentation). Most IR objects are passed around as pointers, e.g. Value *, BasicBlock *.
Sources: cppreference: References
| Declaration | Meaning |
|---|---|
const int X = 5; |
X cannot change |
const Value *V |
Can't modify the value V points to; V itself can be reassigned |
Value *const V |
V can't be reassigned; the pointee can change |
int size() const; (member function) |
The function does not modify the object |
LLVM is const-correct: F.getName() works on a const Function & because getName is a const member. Getting this wrong produces confusing errors like "cannot convert const Value * to Value *" — the fix is usually to use the const version of a type throughout, not to cast const away.
flowchart TD
Q["How should a function take T?"] --> S{"Small and cheap to copy?<br/>(int, pointer, StringRef, ArrayRef)"}
S -->|"yes"| V["By value: T"]
S -->|"no"| M{"Will the function modify it?"}
M -->|"yes"| R["By reference: T &"]
M -->|"no"| C["By const reference: const T &"]
M -->|"it takes ownership"| U["By value and move: std::unique_ptr<T>"]
C++ code is split into headers (.h, declarations) and source files (.cpp, definitions).
// illustrative: Counter.h
#ifndef MYPASS_COUNTER_H // include guard: header body seen once per .cpp
#define MYPASS_COUNTER_H
namespace mypass {
int countDown(int N); // declaration: "this exists somewhere"
}
#endif
// Counter.cpp
#include "Counter.h"
int mypass::countDown(int N) { return N > 0 ? N - 1 : 0; } // definitionflowchart LR
H["Counter.h<br/>declarations"] -->|"#include"| A["Counter.cpp"]
H -->|"#include"| B["Main.cpp"]
A -->|"compile"| AO["Counter.obj"]
B -->|"compile"| BO["Main.obj"]
AO --> L["linker"]
BO --> L
L --> EXE["program"]
The one-definition rule (ODR): a non-inline function or global variable must be defined exactly once in the whole program. Defining a normal function in a header that two .cpp files include gives "multiply defined symbol" link errors; mark it inline or move it to a .cpp.
LLVM's include order rule (from the Coding Standards): the file's own header first, then LLVM headers, then system headers.
Sources: Wikipedia: One Definition Rule
Everything in LLVM is in namespace llvm. In .cpp files LLVM code writes using namespace llvm;; in headers it never does, because that would leak into every includer. Helpers private to one .cpp go in an anonymous namespace, which gives them internal linkage:
// illustrative
namespace { // only visible in this .cpp file
struct MyHelperPass { /* ... */ };
} // end anonymous namespaceSome mistakes are not errors but undefined behaviour (UB): the program may do anything, including appear to work.
| Example | Why it is UB |
|---|---|
| Reading an uninitialised variable | No defined value |
| Dereferencing null or a dangling pointer | No object there |
| Out-of-bounds array access | Past the object |
| Signed integer overflow | The standard says so (LLVM's nsw flag exploits this, see LLVM IR: Arithmetic) |
Use the sanitizers described on Building, Debugging, Exercises to catch UB.
Sources: cppreference: Undefined behavior
-
int &R;without initialising is an error: references must bind at once. - Returning a reference or pointer to a local variable gives a dangling reference.
-
using namespacein a header. - Forgetting
conston member functions, so they can't be called on const objects.
- Pointers may be null and can be re-pointed; references are always-valid aliases.
- Be
const-correct; pass small things by value, big things byconst &. - Declarations in headers, definitions once in
.cpp(ODR); LLVM lives innamespace llvm.
- 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