Skip to content

Cpp 06 adt

Mugundan edited this page Nov 27, 2026 · 1 revision

LLVM Data Structures (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.

Purpose and Scope

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.

The Five Everyday Types

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

SmallVector

flowchart LR
    subgraph Small["SmallVector&lt;int, 4&gt; 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
Loading

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

ArrayRef and StringRef: Views

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)"]
Loading

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

DenseMap

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

Twine

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

Choosing a Container

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&lt;T, N&gt;"]
    L1 -->|"no, just read"| AR["ArrayRef&lt;T&gt;"]
    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)"]
Loading

Key Points

  • SmallVector avoids heap allocation for short lists; take SmallVectorImpl<T> & in APIs.
  • ArrayRef, StringRef and Twine are non-owning views: pass them, don't store them past their data's life.
  • DenseMap is the default map; M[K] inserts, so use find/count to look.

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