A compiler translates a program from one representation to another while aiming to preserve its programming language semantics. Its input might be source code or an intermediate representation; its output might be another programming language, bytecode, an intermediate representation, or machine code. Producing machine code is therefore one possible destination, rather than the definition of compilation. For example, the LLVM 20.1.0 tutorial translates an abstract syntax tree into an intermediate representation before introducing execution.[ref]
Compilation can use an abstract syntax tree for checking and transformations such as constant folding before producing machine code. These are useful possibilities, not a compulsory sequence of separate stages for every compiler. The central distinction is between translating a program and executing its operations: a compiler can translate
x*(2+3)-4 without knowing the input value of x, whereas an interpreter needs that value to produce this program expression's result.Different representations expose different questions. Source code preserves what a programmer wrote; an abstract syntax tree exposes grouping; a type system checks permitted combinations; a stack machine makes operand movement explicit. Retaining abstract syntax tree source locations across compilation helps an error message identify the original construct even after constant folding has changed its shape. A malformed
x*(2+)-4 is a programming language syntax error; an unavailable x in the valid example is instead a missing input. Locating the failing rule is more helpful than treating both as an unexplained execution failure.A basic block is a sequence of operations with one entry at its beginning and no internal control transfer to another block. In LLVM's intermediate representation, it ends in a terminator that determines the next control transfer, such as a branch or return. Phi nodes at the beginning account for values arriving from different predecessors.[ref]
LLVM Language Reference Manual. Functions, basic-block structure; Terminator Instructions
For example,
a=x+1; b=2*a; branch next can form one basic block. A conditional branch after the first assignment would end that block and create successors. Grouping operations this way exposes paths through a control-flow graph while letting a compiler reason locally about an uninterrupted sequence. A basic block can execute repeatedly when it lies inside a loop; it is a static program region, not one execution event.A control-flow graph is a directed graph whose vertices represent program regions, commonly basic blocks, and whose edges represent possible immediate control transfers. It describes which execution paths the representation permits, rather than which path one particular run takes. Compiler optimization and data-flow analysis use this structure.
For
if c then x=1 else x=2; return x, use an entry vertex with edges to separate true and false basic blocks, each leading to one join basic block. The graph has a diamond shape. The join needs the incoming value selected by the executed path; static single-assignment form represents that choice using a phi node. LLVM's tutorial constructs precisely this branch-and-join structure.[ref]Kaleidoscope: Extending the Language: Control Flow in the LLVM documentation. §5.2.4, LLVM IR for If/Then/Else and control-flow graph
Loops add backward edges, so a control-flow graph need not be acyclic.A compiler back end translates an intermediate representation into operations suitable for a target machine. Typical tasks include instruction selection, register allocation, instruction scheduling and emission of assembly or object code. It uses facts about the target's instructions, registers, calling conventions and data layout.[ref]
For example, a load from
base + 4*i might use one indexed-addressing instruction when the target supports that addressing mode, or require separate address arithmetic otherwise. If more values are live than registers are available, Register allocation may spill some values to memory. Those choices change performance while having to preserve the source program's specified observable behavior. A target-independent intermediate form is therefore useful, but does not erase target-specific constraints.Register allocation maps temporary values or virtual registers in a compiler's representation to a limited supply of physical processor registers. A value's live range covers where it may still be needed. Overlapping live ranges constrain which values can share a processor register; register spilling moves some storage into computer memory when necessary.[ref]
The LLVM Target-Independent Code Generator. Live Intervals and Register Allocation
For example, in
a=x+y; b=a*z, the processor register holding a can hold b after a's final use, if the target operation permits. If both values are needed later, overwriting a would lose required information. An interference graph represents simultaneous storage requirements, connecting register allocation to graph coloring. Real targets add constraints from register classes, reserved registers, calling conventions and particular machine instructions; minimizing the number of names alone does not solve the whole problem.Register spilling is a compiler technique that keeps some values in computer memory when they cannot all remain in the available processor registers. Generated stores preserve a value before its register is reused; later loads recover it when needed. This is part of register allocation, whose choices affect the number of memory accesses.[ref]
The LLVM Target-Independent Code Generator. Register Allocation: mapping virtual to physical registers and spilling
For example, suppose three independently computed values must survive to later instructions, but only two suitable processor registers are available. The allocator may store one value in a stack slot, use its register for another value, and reload it before its next use. The best choice depends on live ranges, use frequency and instruction constraints; recomputing a cheap value can sometimes avoid the store.
A live range is the portion of a program during which a computed value must remain available for a possible future use. It connects a definition with uses reached before that value is replaced. The concept concerns a particular value's lifetime, which need not occupy the whole textual scope of its source program variable.[ref]
The LLVM Target-Independent Code Generator. Live Intervals and Live Variable Analysis
In
a = read(); b = a + 1; return b;, the value assigned to a must survive until the addition reads it. After that read it can be discarded, while b must survive until the return. Register allocation can reuse storage for values whose live ranges do not overlap. Branches and loops can make a live range span several regions of a control-flow graph, rather than one uninterrupted interval of source lines.A compiler front end reads a source language and checks or translates its meaning into a representation used by later compilation stages. lexical analysis groups characters into tokens; parsing builds structured syntax; name resolution and type checking establish which declarations and operations the program denotes. These responsibilities need not be implemented as completely separate passes.
For example,
x + 2 * y must be grouped as x + (2 * y) under the usual precedence rules. The parser establishes that grouping, while semantic analysis determines whether x and y exist and support the requested operations. An abstract syntax tree can retain source locations for precise diagnostics. The LLVM Kaleidoscope tutorial shows this transition from parsed syntax to LLVM intermediate code.[ref] The front end's language-facing checks complement the machine-facing decisions of a compiler back end.Compiler optimization transforms a program representation to improve a chosen resource objective while preserving the behavior required by its programming language semantics. Objectives include execution time, code size and memory traffic. A transformation need not find a globally best program, and improving one objective can worsen another.
For example, constant folding replaces
2+3 by 5, while common subexpression elimination may compute a repeated expression once. Reusing a load across a store is valid only if the store cannot change the loaded location; alias analysis helps establish that condition. Similarly, replacing floating-point (a+b)+c by a+(b+c) can change rounding, so an optimizer needs an applicable permission or proof. Data-flow analysis supplies facts used by transformations, and undefined behavior affects which executions the language requires an implementation to preserve.Data-flow analysis propagates facts about values or variable uses through a control-flow graph. Each program operation transforms incoming facts, and a join combines information from possible predecessor paths. A compiler can use the result to justify compiler optimization or issue warnings. Clang's introduction develops this method using sets of possible values and iteration to a fixed point.[ref]
For example, live-variable analysis asks which current values might be read later before being overwritten. For a basic block , with uses before any local definition in and definitions in , the backward equations areA use requires the incoming value; an intervening definition removes that requirement. Iterating from empty sets terminates for a finite graph and finite variable set because these equations only add facts. The result guides register allocation.
Live-variable analysis computes which program variables may be read in the future before their current values are overwritten. It is a backward data-flow analysis: future uses make information flow toward earlier instructions. For a basic block , let contain values read before being defined in that block and let contain its definitions. ThenA value is needed on entry if the block itself first reads it, or if a successor needs it and the block does not replace it.[ref]
The LLVM Target-Independent Code Generator. Live Variable Analysis and Live Intervals
For a block
x = y + 1; return x;, y is live on entry but the old x is not. Iterating the equations over a finite control-flow graph yields a conservative answer useful for register allocation. Syntactically possible paths may include paths that execution can never take, so computed liveness need not prove that a use actually occurs.Static single-assignment form is an intermediate representation in which each named value has one static definition. Repeated source assignments receive different names:
x=1; x=x+2 becomes definitions such as x1=1; x2=x1+2. This makes def-use relationships explicit without requiring a search backward for which assignment supplied a value.At a join in a control-flow graph, a phi node selects the value associated with the edge actually taken. If one branch defines
x1=1 and another defines x2=2, the join defines x3=phi(x1,left; x2,right). The node selects an incoming value, not their arithmetic average. Loop-carried values similarly use entry and back-edge arguments. LLVM specifies that phi instructions occur first in a basic block, with an incoming value for each predecessor.[ref] Static uniqueness concerns program definitions, not the number of times a loop instruction executes.A phi node supplies the value at a join in static single-assignment form by selecting among values associated with incoming edges. In LLVM, it lists a value and predecessor basic block for each incoming edge, and phi nodes occur before ordinary operations in their block.[ref]
For example, if the left branch defines
x1=10 and the right defines x2=20, the join can define x3=phi(x1,left; x2,right). Arriving from the left gives ten; arriving from the right gives twenty. It does not average the arguments or evaluate both branches. At a loop header, another phi node can select an initial value on first entry and the updated value on later iterations. The node has one static definition even though its selected value can change across executions.Choosing target-machine instructions to implement an intermediate representation. A memory operand using register-offset addressing can cover both an address addition and a load or store; computing the full address into a temporary variable can prevent that covering and add an unnecessary instruction.
Analysis of whether two accesses may designate the same storage location. Common subexpression elimination must not reuse a previously loaded value after a store that might change that location, unless an additional argument justifies it. A saved memory address can remain valid even though a value previously loaded at that address is invalidated.
A transformation that computes a repeated program expression once and reuses its saved result when the value is known not to have changed. A repeated load can be reused only when intervening stores, calls or other changes cannot alter the relevant location. Alias analysis helps establish that fact. Maximal address sharing can be counterproductive if instruction selection could otherwise fold an address addition into register-offset addressing.
Compilation is the translation process performed by a compiler, which may include checking and transforming an abstract syntax tree. Translation can finish before execution, or happen during execution through just-in-time compilation. Reusing the translated representation can avoid repeated parsing and repeated constant folding when only the inputs change. This does not guarantee a speedup: translation itself costs work, and the choice of representation and execution mechanism matters.
One possible compilation pipeline for
. Details. x*(2+3)-4, with execution from an abstract syntax tree, a stack machine instruction sequence, or machine codeA linker (computing) is a program that combines compiled or assembled components and connects references to their definitions. It reads object files and libraries, resolves named symbols, and applies relocation (computing) when locations become known. A typical output is an executable program or a shared software library.[ref]
Overview in the GNU ld documentation. §1 Overview: object/archive inputs, relocation and symbol references
Suppose one source file calls
square and another defines it. Their object files can be produced separately; the linker (computing) matches the call's unresolved symbol to the definition and arranges the final reference. A missing definition can therefore cause a link-time failure even when each source file compiled successfully. Some references can instead be resolved when a shared software library is loaded.An object file stores program components produced by a compiler or assembler, together with information needed to combine or load them. A relocatable object file commonly contains machine instructions and data divided into sections, named symbols, and relocation records for references whose final locations are not yet known.[ref]
Sections and Relocation in the GNU Assembler manual. §4.1 Background: sections and address adjustments; assembler relocation information
For example, compiling a file that calls
square can produce an object file containing the call-site instruction and an unresolved reference to that symbol. The linker (computing) later supplies its definition from another input. The file thus contains more than the bytes of a self-contained runnable program: its metadata describes how incomplete components fit together.Linking combines separately produced program components and resolves references between them. A linker (computing) reads object files and library archives, assigns or adjusts locations through relocation (computing), and connects references to their definitions. GNU
ld describes these as its central operations.[ref]Overview in the GNU ld documentation. §1, combining object/archive files, relocating data and resolving symbol references
For example, one object file contains a call to a procedure defined in a second object file. The first compiler invocation can leave a symbolic reference; linking supplies the connection once both components are available. A missing definition or conflicting definitions can cause an error even when both source files compiled separately. Depending on the toolchain, some connections are completed before execution and others when a shared software library is loaded.
Relocation (computing) adjusts references in program components to match the addresses assigned during linking or loading. A relocation record identifies a place to patch, a target symbol and an architecture-dependent rule for computing the replacement. Moving a section changes the addresses associated with its contents, even when their relative arrangement stays fixed.[ref]
Sections and Relocation in the GNU Assembler manual. §4.1 Background: assigning section addresses and adjusting references
In an illustrative absolute-address rule, a symbol address and addend produce . In a relative rule defined using reference address , they may produce . If , and , the latter gives an offset of . Actual instruction encodings specify the precise reference point, scaling and allowed range, so a linker (computing) must apply the relocation type's rule rather than blindly adding one constant everywhere.
Consider the program expression
x*(2+3)-4 in a deliberately small programming language. Its only program identifier is x, supplied as an integer input. Its literal values are nonnegative decimal numerals, interpreted as integers. Whitespace is ignored between lexical tokens. Its context-free grammar is:expression ::= term (("+" | "-") term)*
term ::= factor ("*" factor)*
factor ::= numeral | "x" | "(" expression ")"
numeral ::= digit digit*
digit ::= "0" | "1" | "2" | "3" | "4"
| "5" | "6" | "7" | "8" | "9"Here
* outside quotation marks means zero or more repetitions. Repeated operators are grouped to the left, specifying operator associativity; term gives multiplication higher operator precedence than addition and subtraction. Parentheses override that grouping. There is no unary minus, variable assignment, function call, or side effect in this language. Evaluation obtains each left operand before its right operand and uses exact integer arithmetic, with no fixed-width overflow.Lexical analysis recognizes
x, *, (, 2, +, 3, ), -, 4. Parsing constructs the concrete abstract syntax tree Sub(Mul(Name(x), Add(Int(2), Int(3))), Int(4)). Parentheses have done their work by making Add a child of Mul; they need not survive as nodes. Constant folding changes this to Sub(Mul(Name(x), Int(5)), Int(4)). It cannot replace Name(x) by a literal value because the input is supplied at execution. The resulting function of the input is .A compiler for our stack machine emits
LOAD x; PUSH 5; MUL; PUSH 4; SUB. LOAD x pushes the current input; PUSH n pushes the integer literal value n. Each binary instruction removes the top item as its right operand, then the next item as its left operand, and pushes the result. The instruction sequence is an intermediate representation that an interpreter can execute; no machine code has been emitted. A compact binary encoding could make it bytecode, but these printed instruction names are only a readable notation.Why does this compilation preserve the result? A structural induction supplies a short proof outline. Translating a literal value or
x appends its value to any initial stack. For a binary abstract syntax tree node, first translating the left child and then the right child appends the two operand values; the matching instruction replaces them by exactly the original operation's result. Previously present stack items remain intact. Constant folding also preserves the result because in the specified integer arithmetic. Together these facts explain agreement for every integer input, rather than merely agreement for one trial.Compilation performed during execution, often producing machine code for subsequent execution.
A program representation used between input and final output, convenient for analysis, transformation or execution. An abstract syntax tree and bytecode can each serve this role.
A fresh internal name introduced during compilation to hold an intermediate result. Its lifetime and uses can be exposed to instruction selection and allocation of processor registers; it need not correspond to a variable named in the source.
An encoded instruction representation for a software execution mechanism. Compilation can produce bytecode that an interpreter executes.
LLVM is a collection of reusable compiler infrastructure built around a typed intermediate representation. Its static single-assignment form gives each register-like value one definition, making data dependencies explicit for compiler optimization. The same intermediate representation has an in-memory form, a compact bitcode form and a readable textual form.[ref]
LLVM Language Reference Manual. Abstract, Introduction and Well-Formedness
A compiler front end translates a source programming language into the intermediate representation; optimization passes transform it while preserving the required semantics; a compiler back end produces code for a target computer architecture. Sharing the middle stages lets several source programming languages reuse the same analyses and target support. For a small textual example,
%y = add i32 %x, 1 defines a new 32-bit integer value from an earlier one. The value %y is defined once even if the source program repeatedly assigns to a source variable.