Skip to content

Cpp 10 build exercises

Mugundan edited this page Nov 27, 2026 · 1 revision

Building, Debugging and Exercises

Relevant source files

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

This page shows how to compile your own small programs against an LLVM build, how to debug the usual crashes, a set of exercises that follow the wiki, and a glossary.

Purpose and Scope

This page covers compiling against LLVM headers and libraries, the build settings that matter (assertions, exceptions, RTTI), debugging tools, coding style, exercises with hints, and a glossary. Writing a full pass is in the LLVM IR wiki.

Compiling Against LLVM

flowchart LR
    S["your.cpp"] --> C["compiler<br/>+ -I llvm/include<br/>+ -I build/include (generated config)"]
    C --> O["your.obj"]
    O --> L["linker<br/>+ LLVMSupport.lib (+ LLVMCore.lib for IR)<br/>+ system libraries"]
    L --> E["your.exe"]
Loading

Every // example: program in this wiki was built on Windows with exactly this command, from a Visual Studio x64 developer prompt (vcvars64.bat):

cl /nologo /std:c++17 /O2 /MD /EHs-c- /D_HAS_EXCEPTIONS=0 ^
   /I C:\source\llvm-project\llvm\include /I C:\source\llvm-project\build\include ^
   example.cpp ^
   /link /LIBPATH:C:\source\llvm-project\build\Release\lib ^
   LLVMSupport.lib LLVMDemangle.lib ntdll.lib ws2_32.lib psapi.lib shell32.lib ole32.lib uuid.lib advapi32.lib
Part Why
/std:c++17 LLVM's language level at this commit
two /I paths Source headers, plus generated headers such as llvm/Config/llvm-config.h in the build directory
/MD Must match the runtime library LLVM was built with
/EHs-c- /D_HAS_EXCEPTIONS=0 LLVM is built without exceptions; match it
LLVMSupport.lib raw_ostream, Error, StringRef helpers, and more

On Linux or macOS the easiest route is llvm-config:

clang++ example.cpp $(llvm-config --cxxflags --ldflags --libs support core) -o example

For anything bigger, use CMake with find_package(LLVM REQUIRED CONFIG), as on the LLVM IR: Writing a Pass page.

Sources: LLVM: Getting Started

Build Settings That Change Behaviour

CMake option Effect for you
-DLLVM_ENABLE_ASSERTIONS=ON assert, cast<> checks and dump() work; strongly recommended while learning
-DCMAKE_BUILD_TYPE=Debug Debug info, no optimisation; large and slow but debuggable
RelWithDebInfo Optimised with debug info: a good everyday choice
LLVM_ENABLE_RTTI (default OFF) Your code must be built without RTTI too, or link errors about typeinfo appear

The local build used for this wiki is a Release build, so its cast<> assertions are compiled out.

Debugging Common Crashes

flowchart TD
    C["Crash or wrong output"] --> A{"Assertion message?"}
    A -->|"yes"| R["Read it: it names the broken rule<br/>(e.g. 'cast<Ty>() argument of incompatible type')"]
    A -->|"no"| D["Run in a debugger; get a backtrace"]
    D --> U{"Use-after-free / garbage values?"}
    U -->|"yes"| S["Build with AddressSanitizer;<br/>check erase-while-iterating and dangling StringRef/ArrayRef"]
    U -->|"no"| V["Print state: errs() << *I, F.dump();<br/>run 'opt -passes=verify'"]
Loading
Tool Catches
Debugger (Visual Studio, gdb, lldb) Where it crashed, values of variables
AddressSanitizer (-fsanitize=address, MSVC /fsanitize=address) Use-after-free, out-of-bounds, dangling pointers
UndefinedBehaviorSanitizer (-fsanitize=undefined) Signed overflow, bad shifts, misaligned access
opt -passes='my-pass,verify' IR your pass broke
LLVM_DEBUG(dbgs() << ...) with -debug-only=my-pass Tracing your pass

Style Reviewers Expect

From the LLVM Coding Standards:

Rule Example
Variables and types CamelCase, starting upper case BasicBlock *EntryBB;
Functions start lower case getOperand(), eraseFromParent()
Early returns instead of deep nesting if (!F.hasBody()) return false;
No using namespace in headers
Format with clang-format git clang-format before sending a patch
Comments are full sentences

Modern C++ Features You Will Also See

Feature One-line meaning
constexpr Computed at compile time (cppreference)
std::optional<T> A value or nothing
Structured bindings auto [A, B] = Pair; Unpack a pair or struct (used on LLVM Data Structures)
std::string_view The standard equivalent of StringRef (cppreference)
[[nodiscard]] Warn if a return value is ignored; LLVM puts it on Error, Expected, isa, cast
enum class Scoped, strongly typed enum

Exercises

  1. Pointers (Basics). Write swapInts(int &A, int &B) and swapPtrs(int *A, int *B). Why must the pointer version check for null?
  2. RAII (Classes). Write a Timer class that prints how long its scope took when destroyed. Return early from a function using it and check the message still prints.
  3. Virtual (Classes). Remove virtual from ~Pass() in the virtual example. Why is deleting through Pass * now wrong?
  4. Move (Ownership). Add a std::vector<std::unique_ptr<Node>> to a class and try to copy the class. Read the error, then fix it by moving instead.
  5. Templates (Templates). Write template <typename T> T sumAll(ArrayRef<T>) and call it with int and double.
  6. SmallVector (ADT). Make SmallVector<int, 2>, push 3 elements, and print capacity() after each push. Then change N to 8. (The adt example showed capacity 4 before growing.)
  7. StringRef lifetime (ADT). Write a function that returns a StringRef to a local std::string, build it with AddressSanitizer, and watch it report the bug.
  8. DenseMap (ADT). Count word frequencies in a sentence. Then check membership with M["x"] and show it changed M.size().
  9. LLVM RTTI (Casting). Add a Triangle to the casting example. Then add an abstract Polygon between Shape and Square/Triangle and give it a range-based classof.
  10. Error (Errors). Write Expected<std::pair<int,int>> parseRange(StringRef S) for "3-7", rejecting bad input and lo > hi.
  11. Ranges (Ranges). Remove all negative numbers from a SmallVector two ways: with erase_if, and with a manual loop that is correct about invalidation.
  12. Read real code. Open llvm/lib/Transforms/Scalar/DCE.cpp and find each of: a SmallSetVector, an isa/dyn_cast, a worklist loop, and PreservedAnalyses. Then move on to LLVM IR: Writing a Pass.

Glossary

Term Meaning Page
ArrayRef<T> Non-owning view of a contiguous array ADT
assert Check a condition in builds with assertions on Errors
auto Let the compiler deduce a variable's type Ranges
cast<T> Convert, asserting the type is right Casting
classof Static function that makes isa work for a class Casting
const Cannot be modified through this name Basics
CRTP A base class template parameterised by its derived class Templates
DenseMap LLVM's fast open-addressing hash map ADT
Destructor Runs automatically when an object is destroyed Classes
dyn_cast<T> Convert, or null if the type is wrong Casting
Error / Expected<T> LLVM's checked error values Errors
function_ref Non-owning reference to something callable Templates
isa<T> Test the dynamic type Casting
Iterator invalidation An iterator becoming unusable after the container changes Ranges
Lambda An inline, unnamed function object Templates
lvalue / rvalue Has a name and persists / a temporary that can be moved from Ownership
make_early_inc_range Iterate while allowing erasure of the current element Ranges
Move semantics Transferring resources instead of copying Ownership
ODR One definition rule Basics
override Mark a function as overriding a virtual base function Classes
RAII Resources released by destructors automatically Classes
Reference An alias that must always refer to an object Basics
raw_ostream LLVM's output stream: outs(), errs(), dbgs() Errors
RTTI Run-time type information; turned off in LLVM Casting
SmallVector<T, N> Vector with N elements of inline storage ADT
StringRef Non-owning view of characters ADT
Template Code parameterised by types or values Templates
Twine Lazy string concatenation for parameters ADT
UB Undefined behaviour Basics
unique_ptr Single-owner smart pointer Ownership
virtual / vtable Run-time dispatch / table of function pointers Classes

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