A small independent technical notebook

The Compiler Workshop

Compilers · C and C++ · LLVM · Build Systems · Low-Level Notes

[ WORKSHOP NOTICE ]   Notes, diagrams and practical references for people who like to know what happens between source code and machine code.

Welcome to the workshop

A compiler is more than a program that turns one language into another. It is a chain of analysers, transformations and code generators that turns a programmer's intent into instructions a machine can execute.

This page collects notes about that chain: how source text becomes tokens, how tokens become syntax trees, how types and names are checked, how intermediate representations are optimized, and how object files are finally linked into an executable.

THE CENTRAL QUESTION

What exactly happens after pressing Build — and where can a build fail?

THE PRACTICAL ANGLE

Understand compiler output, inspect binaries, track dependencies and make builds reproducible.

Start with the pipeline below, then follow the individual stages.

01. The compiler pipeline

A traditional ahead-of-time compiler can be understood as a sequence of stages. Real toolchains may combine stages, repeat analyses or use several intermediate representations.

StageInputTypical resultPurpose
PreprocessingSource + directivesExpanded sourceIncludes headers and handles macros and conditional compilation.
LexingCharacter streamToken streamGroups characters into identifiers, keywords, literals and operators.
ParsingTokensSyntax treeChecks grammatical structure and builds a representation of the program.
Semantic analysisSyntax treeAnnotated treeResolves names, scopes, types, overloads and language constraints.
IR generationAnnotated treeIntermediate representationConverts language constructs into a form suitable for analysis and transformation.
OptimizationIROptimized IRApplies transformations while preserving observable program behavior.
Code generationTarget-oriented IRAssembly / object codeSelects instructions, registers and calling-convention details.
LinkingObject files + librariesExecutable / libraryResolves symbols and combines compiled pieces into a program image.

A simplified view

source.cpp
    |
    v
preprocessor
    |
    v
lexer ---> tokens
    |
    v
parser ---> syntax tree
    |
    v
semantic analysis
    |
    v
intermediate representation (IR)
    |
    v
optimization passes
    |
    v
instruction selection / register allocation
    |
    v
assembly ---> object file
                    |
                    v
                 linker
                    |
                    v
               executable

This is a conceptual model, not a promise that every compiler uses precisely these separate programs or this exact order.

02. The front end: understanding source code

Lexical analysis

The lexer reads a stream of characters and groups them into tokens. The text count = total + 1; can be represented as an identifier, assignment operator, identifier, plus operator, integer literal and semicolon.

IDENTIFIER("count")
ASSIGN("=")
IDENTIFIER("total")
PLUS("+")
INTEGER_LITERAL("1")
SEMICOLON(";")

Lexers commonly track source locations so later diagnostics can point to a file, line and column. A useful diagnostic says what was found and where.

Parsing and syntax trees

The parser checks whether the token sequence follows the grammar of the language. A syntax tree records the structure of expressions and statements rather than merely preserving the original characters.

       (+)
      /   \
  total    1

assignment: count = (total + 1)

Common parsing approaches include recursive descent, Pratt parsing, LR parsing and parser generators. The appropriate choice depends on the grammar, error-recovery needs and implementation goals.

Semantic analysis and type checking

A syntactically valid program can still be meaningless. Semantic analysis checks that names exist, types are compatible, functions are called correctly and language-specific rules are respected.

EXAMPLE

int result = "hello"; may be tokenized and parsed successfully, but a statically typed language can reject it during semantic analysis because the initializer is not compatible with the declared type.

Symbol tables and scopes

A symbol table records information about declarations: names, types, storage, visibility and other attributes. Nested scopes require a way to find the nearest visible declaration while preserving shadowed declarations in outer scopes.

03. Intermediate representation

An intermediate representation (IR) gives a compiler a structured language for analysis and transformation. It separates many source-language details from target-machine details.

LLVM IR is one well-known example. It has a textual form useful for inspection, as well as bitcode used by LLVM tools.

; A tiny illustrative LLVM IR function

define i32 @add_one(i32 %value) {
entry:
  %result = add i32 %value, 1
  ret i32 %result
}

Why use an IR?

  • Optimization passes can operate on a common representation.
  • Several source languages can target the same compiler infrastructure.
  • One front end can support several machine targets through different back ends.
  • Developers can inspect transformations without reading machine code first.

IR design is a set of trade-offs. A representation convenient for high-level language analysis may differ from one designed for low-level instruction selection.

04. Optimization notes

Compiler optimizations transform a program while preserving the language's required observable behavior. The permitted transformations depend on language rules, target and compilation options.

Common transformations

  • Constant folding
  • Dead-code elimination
  • Common subexpression elimination
  • Loop-invariant code motion
  • Inlining
  • Strength reduction

Questions to ask

  • Is the result observable?
  • Are aliasing rules understood?
  • Can overflow or undefined behavior matter?
  • Does code size increase?
  • Is the target CPU relevant?
  • Can the optimization be measured?
MEASURE, DON'T GUESS

Optimization flags do not guarantee that every program becomes faster. Use representative workloads, repeatable measurements and profiling before drawing conclusions.

05. The back end: from IR to instructions

The back end maps compiler operations to a target architecture. It must account for the instruction set, registers, calling convention, stack layout, data alignment and object-file format.

Instruction selection

The compiler chooses machine instructions that implement the operations represented in its IR. Different instruction sequences may compute the same result but vary in latency, throughput, code size and register pressure.

Register allocation

Programs can have more live values than the target has available registers. Register allocation decides which values stay in registers and which must be spilled to memory. Algorithms include graph-coloring approaches and linear-scan allocation.

Object files and symbols

An object file usually contains machine-code sections, data, symbol information and relocation entries. It is not necessarily a complete executable: references may still need to be resolved by a linker.

06. C and C++ field notes

Compilation is not linking

A C++ translation unit is compiled independently. The resulting object file can contain references to functions and objects defined elsewhere. The linker later resolves those references using other object files and libraries.

# Compile only
c++ -std=c++20 -O2 -Wall -Wextra -c main.cpp -o main.o

# Link an executable
c++ main.o math.o -o workshop-demo

Headers and translation units

Headers provide declarations and other text included by source files. In traditional compilation models, included headers are processed as part of each translation unit. This is one reason unnecessary header dependencies can increase build times.

Templates

C++ templates are instantiated based on use and the definitions available to the compiler. Template-heavy code can increase compile time and make diagnostics more complex. Explicit instantiation and careful interface design can help in selected cases.

ABI and binary compatibility

An application binary interface describes low-level conventions such as symbol naming, calling conventions, object layout and exception handling. Source compatibility does not automatically imply ABI compatibility between separately built binaries.

Useful inspection commands

# Show compiler version
clang++ --version
g++ --version

# Inspect symbols in an object file
nm -C main.o

# Inspect ELF headers and sections
readelf -h -S main.o

# Disassemble machine code
objdump -d -C main.o

07. Toolchain and build systems

GCC and Clang

GCC and Clang are widely used compiler families. Clang is built on LLVM infrastructure; GCC has its own compiler infrastructure and back ends. Both support C and C++ on many platforms, but their diagnostics, options, extensions and implementation details are not identical.

GCC TOOLCHAIN

Compiler drivers, language front ends, optimization passes, target back ends and supporting tools such as the GNU assembler and linker.

LLVM TOOLCHAIN

Clang, LLVM IR, optimization and code-generation libraries, plus tools such as llvm-ar, llvm-nm and lld.

CMake and Ninja

CMake describes how a project is configured and how build-system files are generated. Ninja is a build executor designed to run the generated build graph efficiently. They have different responsibilities: CMake generates; Ninja executes.

cmake -S . -B build -G Ninja \
  -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_CXX_STANDARD=20

cmake --build build --parallel

ctest --test-dir build --output-on-failure

Reproducible builds

A reliable build should make its important inputs explicit: compiler version, target, build options, dependency versions and generated files. Lockfiles, pinned toolchains and clean build directories help reduce accidental variation.

Dependency management

Package managers can make native dependencies easier to describe and reproduce. They do not remove the need to understand ABI compatibility, compiler settings, static versus shared libraries, or transitive dependencies.

08. Debugging a difficult build

When a build fails, begin with the first meaningful error rather than the final summary. Build logs often contain follow-on failures caused by one earlier problem.

  1. Record the exact compiler, linker and build-system versions.
  2. Preserve the full command line from the failing build step.
  3. Find the first error in the log and inspect the surrounding output.
  4. Check include paths, library paths, definitions and language-standard flags.
  5. Verify that dependencies were built for the same architecture and compatible ABI.
  6. Reproduce the failure in a clean build directory.

Useful diagnostics

  • -v — ask compiler drivers to print more detail about invoked tools.
  • -### — inspect commands a Clang driver would run without executing them.
  • -ftime-trace — generate a time trace with supported Clang versions.
  • --verbose — request more detail from many build tools.
  • ninja -t commands — inspect commands recorded in a Ninja build.
GOOD BUG REPORTS INCLUDE

A minimal reproducer, exact versions, target platform, complete failing command and the first relevant diagnostic. “It does not compile” is rarely enough information.

09. Reading room — official references

These links lead to primary project documentation and language references. They are useful starting points when a command-line option or implementation detail needs verification.


Suggested study order

  1. Learn the compilation and linking model of C and C++.
  2. Read about lexing, parsing, symbol tables and type checking.
  3. Inspect LLVM IR and follow a small function through optimization.
  4. Build a small project with CMake and Ninja.
  5. Inspect object files, symbols, relocations and disassembly.
  6. Compare GCC and Clang using the same small test program.

10. Testing, static analysis and quality gates

A successful compiler exit code proves that a translation unit was accepted and an output was produced. It does not prove that the program is correct, secure, portable or fast. A healthy native-development workflow combines several independent checks.

Unit and integration tests

Unit tests exercise small pieces of behavior. Integration tests verify the boundaries between modules, libraries, processes and external services. Keep tests deterministic and make their dependencies explicit.

Static analysis

Static analyzers inspect code without executing the complete application. They can identify suspicious control flow, lifetime errors, unsafe API use, null dereferences and other patterns that deserve review.

Useful compiler diagnostics

# GCC / Clang warnings for a C++ project
-Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion

# Clang static analyzer
scan-build cmake --build build

# Run registered CTest tests
ctest --test-dir build --output-on-failure

Sanitizers during development

AddressSanitizer helps detect many out-of-bounds accesses and use-after-free errors. UndefinedBehaviorSanitizer checks selected forms of undefined behavior. ThreadSanitizer can find data races in supported environments. These tools add runtime overhead and are usually enabled in dedicated test builds rather than production binaries.

QUALITY GATE

Build with warnings, run tests, inspect sanitizer output, and keep a reproducible record of toolchain versions. A green build is one signal, not a substitute for review.

11. Cross-compilation and target platforms

Cross-compilation means building a program on one machine for a different target platform. The build host runs the compiler; the target system runs the resulting binary. The distinction matters for architecture, operating-system interfaces, libraries and ABI assumptions.

Host, target and toolchain

A cross toolchain usually includes a compiler that emits target instructions, a target-aware assembler and linker, and a sysroot containing the target headers and libraries. CMake toolchain files record those choices so that configuration does not silently use host dependencies.

# Example shape of a CMake toolchain file
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR aarch64)
set(CMAKE_C_COMPILER aarch64-linux-gnu-gcc)
set(CMAKE_CXX_COMPILER aarch64-linux-gnu-g++)
set(CMAKE_SYSROOT /opt/sysroots/aarch64)

Common sources of failure

  • Host headers or libraries leak into a target build.
  • The target sysroot is incomplete or from an incompatible release.
  • Binary dependencies use a different architecture or ABI.
  • Generated code is executed on the build host even though it was compiled for the target.
  • Endianness, alignment or feature assumptions differ between systems.

When a target build fails, inspect the compiler triple, sysroot, linker search paths and the architecture of every linked object. A successful link is still not proof that the binary behaves correctly on the target device.

12. Performance engineering and profiling

Compiler optimization is only one part of performance engineering. The application's algorithms, memory access patterns, concurrency model, I/O and deployment environment often matter more than an individual compiler flag.

Start with a baseline

Choose representative input data, define the measurement you care about, and record a baseline before changing the implementation. For throughput-sensitive work, measure completed operations per second. For interactive work, examine latency distributions rather than only averages.

Inspect before tuning

  • Use a sampling profiler to find where CPU time is spent.
  • Use hardware counters to investigate cache misses, branch behavior and instruction throughput.
  • Inspect generated assembly when a source-level explanation is not enough.
  • Measure release builds with the same compiler options used in deployment.
  • Repeat runs and report variation instead of selecting the best result.
LATENCY

Look at median and tail percentiles, queueing, allocation and synchronization costs.

THROUGHPUT

Look at batching, data locality, parallel work, contention and memory bandwidth.

Optimization decisions should be tied to evidence. If a change makes a benchmark faster but makes the application less reliable or harder to maintain, the trade-off must be explicit.

13. Safer native-code practices

Native applications interact directly with memory, operating-system interfaces and external libraries. Good security practices start with clear ownership and input boundaries, then continue through build configuration and release management.

Review the boundaries

  • Validate lengths and ranges before copying or indexing data.
  • Prefer interfaces with explicit buffer sizes and ownership rules.
  • Make resource lifetime clear; use RAII in C++ where practical.
  • Avoid undefined behavior and treat compiler warnings as useful evidence.
  • Keep third-party dependencies updated and inventory what is linked into releases.

Hardened release builds

Compiler and linker hardening flags vary by compiler, operating system and deployment target. Verify support before enabling them globally. Stack protection, position-independent executables, relocation read-only sections and control-flow protections can add defense in depth, but they do not repair unsafe program logic.

Security checks should be part of the normal build and review process, not a last-minute release checkbox.

Workshop index card

Subject: compiler construction and native software

Languages: C, C++, intermediate representations

Platforms: Linux and common native toolchains

Approach: inspect, measure, reproduce

Format: static notes and reference material

Dependencies: none — this page is self-contained

This is an independent technical notebook. Project names and trademarks belong to their respective owners.