Repository navigation
Cpp 06 adt
Relevant source files
The following files were used as context for generating this wiki page:
LLVM's llvm/ADT/ directory ("abstract data types") holds containers tuned for compilers: lots of small collections, lots of string lookups, and no time to waste on heap allocation. You will use five of them every day.
This page covers SmallVector, ArrayRef, StringRef, DenseMap and Twine, when to use each, and their lifetime traps. Iterating over them is on Iterators and Ranges.
| Type | Owns data? | Think of it as | Use for |
|---|---|---|---|
SmallVector<T, N> |
Yes |
std::vector with room for N elements inside the object |
Local lists that are usually short |
ArrayRef<T> |
No | (pointer, length) view of any array | Read-only array parameters |
StringRef |
No | (pointer, length) view of characters | String parameters and names |
DenseMap<K, V> |
Yes | Fast hash map | Pointer- or integer-keyed maps |
Twine |
No | A lazy "string to be built" | Building messages and names as arguments |
// example: adt
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
int sum(ArrayRef<int> A) { int S = 0; for (int X : A) S += X; return S; }
void report(const Twine &Msg) { outs() << Msg.str() << "\n"; }
int main() {
SmallVector<int, 4> V = {1, 2, 3, 4};
outs() << "capacity " << V.capacity() << "\n";
V.push_back(5); // 5th element: moves to the heap
outs() << "size " << V.size() << ", grew to heap\n";
int Arr[] = {10, 20};
outs() << "sum " << sum(V) << " " << sum(Arr) << " " << sum({7, 8}) << "\n";
StringRef S = "llvm.memcpy.p0";
auto [Head, Rest] = S.split('.');
outs() << Head << " | " << Rest << " | " << S.size() << " | " << S.drop_front(5) << "\n";
DenseMap<StringRef, unsigned> Counts;
for (StringRef Op : {"add", "load", "add", "store", "add"})
++Counts[Op];
outs() << "add " << Counts["add"] << ", lookup mul found " << Counts.count("mul") << "\n";
report("pass " + Twine(3) + " of " + Twine(7));
}capacity 4
size 5, grew to heap
sum 15 30 15
llvm | memcpy.p0 | 14 | memcpy.p0
add 3, lookup mul found 0
pass 3 of 7
flowchart LR
subgraph Small["SmallVector<int, 4> with 3 elements"]
H1["begin, size, capacity"] --> I1["inline storage: 1 2 3 _"]
end
subgraph Big["after growing past 4"]
H2["begin, size, capacity"] --> HP["heap buffer: 1 2 3 4 5 ..."]
end
The first N elements live inside the object, usually on the stack. Only when it grows past N does it allocate. Pick N so the common case fits (LLVM code often writes SmallVector<Value *, 8>, or leaves N out to let LLVM choose). In function parameters write SmallVectorImpl<T> &, see Templates and Lambdas.
Sources: llvm/include/llvm/ADT/SmallVector.h:592, llvm/include/llvm/ADT/SmallVector.h:1249
Both are just a pointer and a length. Copying them is free, which is why they are passed by value. One ArrayRef<int> parameter accepts a SmallVector, a std::vector, a C array or {7, 8}.
flowchart LR
SR["StringRef<br/>Data ptr | Length = 6"] --> BUF["...'m' 'e' 'm' 'c' 'p' 'y'... (owned by someone else)"]
StringRef methods you will use: starts_with, ends_with, split, drop_front, substr, trim, getAsInteger, str() (copy to std::string), ==.
The lifetime trap. A view must not outlive the data it points to:
// illustrative: BUG
StringRef getName() {
std::string S = "temp";
return S; // StringRef to S, but S is destroyed here: dangling
}Store a std::string (or SmallString) when you need to keep text; use StringRef to look at it.
Sources: llvm/include/llvm/ADT/StringRef.h:56-69, llvm/include/llvm/ADT/ArrayRef.h:40
A hash map stored in one flat array (open addressing), which makes it much faster and more cache-friendly than std::map or std::unordered_map for small keys such as pointers.
| Do | Don't |
|---|---|
Key by Value *, BasicBlock *, integers, StringRef
|
Key by large objects |
Use count(K) or find(K) to test membership |
Use M[K] just to look: it inserts a default value |
| Re-find after inserting | Keep pointers/iterators across insertions: they may move |
Related: DenseSet, SmallPtrSet (small set of pointers), StringMap (owns its string keys), MapVector (insertion order).
Sources: llvm/include/llvm/ADT/DenseMap.h:831
A Twine is a tree of pieces to concatenate, built on the stack and only turned into a string when someone needs it. Functions that take names (setName, createStringError, IRBuilder::CreateAdd(..., "sum")) take const Twine &, so callers can write "x." + Twine(I) without building a temporary string.
Rule: only use Twine as a const Twine & parameter; never store one in a variable, because its pieces are temporaries.
Sources: llvm/include/llvm/ADT/Twine.h:82
flowchart TD
Q["What do you need?"] --> L["A list"]
Q --> M["A map / set"]
Q --> S["Text"]
L --> L1{"Own it?"}
L1 -->|"yes"| SV["SmallVector<T, N>"]
L1 -->|"no, just read"| AR["ArrayRef<T>"]
M --> M1{"Key type"}
M1 -->|"pointer / int"| DM["DenseMap / DenseSet / SmallPtrSet"]
M1 -->|"string, owned"| SM["StringMap"]
S --> S1{"Own it?"}
S1 -->|"yes"| ST["std::string / SmallString"]
S1 -->|"no, parameter"| SR2["StringRef (or const Twine & to build)"]
-
SmallVectoravoids heap allocation for short lists; takeSmallVectorImpl<T> &in APIs. -
ArrayRef,StringRefandTwineare non-owning views: pass them, don't store them past their data's life. -
DenseMapis the default map;M[K]inserts, so usefind/countto look.
- 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