Inside swiftc: How Swift Turns Source into SIL, LLVM IR and Machine Code
Source → Lexer → Parser → AST → Type checker → SIL → SIL optimizer → LLVM IR → LLVM optimizer → Machine code → Object file → Linker → Binary
Last year I lost most of an afternoon to a single line of arithmetic. It was in a geometry helper, nothing clever, a handful of numbers, a couple of Double(...) conversions and some parentheses.
Every clean build took noticeably longer than it should have, and when I finally ran the compiler with type-checking timers switched on, that one line was the culprit.
That sent me down a path I'd been avoiding for years: actually reading what swiftc produces between my source file and the binary. This article is the write-up I wish I'd had at the start.
We'll follow one tiny function through every stage of the pipeline. We'll look at real SIL, real LLVM IR and real assembly. Then we'll use what we learn to explain some performance results that surprise most people.
About the output in this article
Every listing labelled compiler output was produced on my machine with:
$ swiftc -version
swift-driver version: 1.127.15 Apple Swift version 6.2.4 ( swiftlang-6.2.4.1.4 clang-1700.6.4.2 ) Target: x86_64-apple-macosx15.0
That's Xcode 26.3 on an Intel MacBook Pro. ARM64 listings were produced by the same compiler with -target arm64-apple-macos14.
Listings labelled illustrative are simplified by hand. Compiler output changes between Swift versions, sometimes a lot, so if you run these commands on a different toolchain, expect the details to differ while the overall shape stays the same.
1. The question
Here's the function we'll follow through the pipeline:
func calculateTotal ( price : Int , quantity : Int ) -> Int { return price * quantity }
A processor has no idea what Int means, or *, or what a function with argument labels is. It executes a fixed set of instructions on registers and memory.
Somewhere between this text and the CPU, something has to settle a long list of questions. Which * is this, out of dozens? What happens on overflow? How are the two arguments passed? Where does the result go? Can any of it be skipped?
An interpreter answers those questions while the program runs, every time the line runs. A compiler answers them once, ahead of time, and writes the answers down as machine code.
Swift is mostly used the second way, but not exclusively. swift file.swift runs a script in immediate mode through an LLVM JIT, which is why scripting with Swift feels interpreted even though it isn't really.
The interesting part of Swift's design is how many layers sit between the language and the CPU. Swift doesn't hand your code straight to LLVM. It first lowers it into its own intermediate language, SIL, where it can reason about Swift-specific things LLVM has no vocabulary for: value ownership, reference counting, protocol witness tables, generic specialization. Only after that does LLVM get a much lower-level program and do the work it's good at.
For our function, the whole journey compresses to about 17 bytes of x86-64 code: one multiply, one overflow check, one return. Let's see how it gets there.
2. The pipeline from 10,000 feet
Conceptually, a Swift file goes through these stages:
- Swift source
- ↓ Lexer characters → tokens
- ↓ Parser tokens → untyped AST
- ↓ Sema name lookup, type checking → typed AST
- ↓ SILGen typed AST → raw SIL (ownership SSA)
- ↓ Mandatory passes diagnostics + required transforms → canonical SIL
- ↓ SIL optimizer (only with
-O/-Osize) - ↓ IRGen SIL → LLVM IR
- ↓ LLVM optimizer
- ↓ LLVM codegen IR → target machine code
- ↓ Object file (.o)
- ↓ Linker .o files + libraries → executable / dylib
Each layer of the compiler lives in its own directory of the swiftlang/swift repository. Parsing is in lib/Parse, semantic analysis in lib/Sema, SIL generation in lib/SILGen, the SIL optimizer in lib/SILOptimizer and LLVM IR generation in lib/IRGen. If you want to read the code behind a stage, those directory names are the map.
The diagram is honest about order but hides orchestration. swiftc is a driver, not the compiler itself. You can ask it what it would do with -###:
$ swiftc -### Example.swift main2.swift
# compiler output, trimmed
.../swift-frontend -frontend -c -primary-file Example.swift main2.swift ... -o .../Example-1.o
.../swift-frontend -frontend -c Example.swift -primary-file main2.swift ... -o .../main2-1.o
.../clang .../Example-1.o .../main2-1.o ... -o main
There are two frontend processes, one per primary file. Each one parses every file in the module, because it has to know about declarations in the others, but it only generates code for its primary file. Then clang is invoked as the link driver.
This is the incremental, per-file mode Xcode uses for Debug builds. Release builds default to whole-module optimization (WMO): one frontend job sees the whole module at once, which matters a lot for the optimizations in section 8.
Xcode adds its own layer on top, scheduling module dependencies, asset compilation, code signing and packaging. Keep that in mind: "the compiler" and "the build" are different things.
3. Lexing: characters to tokens
The lexer (lib/Parse/Lexer.cpp) walks the raw bytes and groups them into tokens: keywords (func, return), identifiers (calculateTotal, price), punctuation ((, :, ->, {), operators (*) and literals.
illustrative token stream
kw_func identifier(calculateTotal) l_paren identifier(price) colon identifier(Int) comma identifier(quantity) colon identifier(Int) r_paren arrow identifier(Int) l_brace kw_return identifier(price) oper_binary_spaced(*) identifier(quantity) r_brace eof
Two details are more Swift-specific than they look.
First, whitespace is semantically meaningful around operators. The lexer records whether an operator has whitespace on its left, right, both sides or neither, and that decides whether it's a prefix, postfix or binary operator. That's why a - b and a -b mean different things, and why a -b usually produces a diagnostic.
Comments and other whitespace are kept as trivia attached to tokens rather than thrown away, which tooling such as formatters and refactoring engines relies on.
Second, string interpolation is lexed as a single string literal token. In "Total: \(price * quantity)", the lexer does not produce separate tokens for the embedded expression. It produces one string literal and records where the interpolated segments are.
The parser later lexes those segments again as ordinary Swift code, and the type checker eventually turns the whole thing into a series of appendLiteral and appendInterpolation calls on a DefaultStringInterpolation value, via ExpressibleByStringInterpolation. That's why you can define custom appendInterpolation overloads: interpolation is just code after a certain point in the pipeline.
4. Parsing and the AST
The parser consumes tokens and builds an abstract syntax tree. "Abstract" means the tree keeps meaning and drops syntax that only existed to delimit things. Parentheses, commas and braces don't appear as nodes. What remains are declarations (func_decl, var_decl), statements (return_stmt, brace_stmt) and expressions.
You don't have to imagine what it looks like. -dump-parse prints the AST straight after parsing, before any type checking (source ranges removed for width):
$ swiftc -dump-parse Example.swift
# compiler output
( source_file "Example.swift"
( func_decl "calculateTotal(price:quantity:)"
( result = type_unqualified_ident id = "Int" unbound ) thrown_type = "<null>"
( parameter_list ( parameter "price" apiName = "price" ) ( parameter "quantity" apiName = "quantity" ) )
( brace_stmt ( return_stmt ( sequence_expr type = "<null>"
( unresolved_decl_ref_expr type = "<null>" name = "price" function_ref = unapplied )
( unresolved_decl_ref_expr type = "<null>" name = "*" function_ref = unapplied )
( unresolved_decl_ref_expr type = "<null>" name = "quantity" function_ref = unapplied ) ) ) ) ) )
Three things in this output say a lot about how Swift works:
type="<null>"everywhere. The parser doesn't know types. It doesn't even know whatIntrefers to, which is why it saysunbound.unresolved_decl_ref_expr.priceis just a name at this point, not yet linked to the parameter.sequence_expr. The parser does not know operator precedence. Swift lets you declare your own operators and precedence groups, possibly in another file or module, so the parser can't builda + b * cinto the right tree shape on its own. It produces a flat sequence[price, *, quantity]and leaves "folding" it into a tree to semantic analysis, which can look up the precedence groups.
That last point is the clearest difference between a parse tree and Swift's AST in practice: the AST that comes out of the parser is deliberately incomplete and gets filled in later.
When the parser hits invalid syntax, it emits a diagnostic, tries to recover (skipping to the next statement or closing brace, for example) and keeps going. That's how you get several syntax errors from one build instead of just the first.
Closures and nested functions are ordinary nodes in the tree. A closure becomes a closure_expr with its own parameter list and body, nested inside whichever expression contains it. Which outer variables it captures isn't recorded until semantic analysis.
5. Semantic analysis and type checking
This is where Swift does most of its thinking and, not coincidentally, where most compile time goes in many codebases. Semantic analysis (lib/Sema) resolves names to declarations, folds operator sequences using precedence groups, checks protocol conformances and access control, and type-checks every expression.
Take two lines:
let value = 100
let result = value + 20
The typed AST, via -dump-ast (trimmed):
$ swiftc -dump-ast Infer.swift
# compiler output, trimmed
( pattern_named type = "Int" "value" )
( original_init = integer_literal_expr type = "Int" value = "100" builtin_initializer = "Swift.(file).Int.init(_builtinIntegerLiteral:)" )
...
( original_init = sequence_expr type = "<null>"
( unresolved_decl_ref_expr type = "<null>" name = "value" function_ref = unapplied )
( overloaded_decl_ref_expr type = "<null>" name = "+" number_of_decls = 36 function_ref = single apply )
( integer_literal_expr type = "Int" value = "20" ... ) )
( processed_init = binary_expr type = "Int"
( dot_syntax_call_expr implicit type = "(Int, Int) -> Int"
( declref_expr type = "(Int.Type) -> (Int, Int) -> Int" decl = "Swift.(file).Int extension.+" ... ) )
( argument_list implicit
( argument ( declref_expr type = "Int" decl = "Infer.(file).v****@Infer.swift:1:5" ... ) )
( argument ( integer_literal_expr type = "Int" value = "20" ... ) ) ) )
Look at number_of_decls=36. When the type checker met +, there were 36 visible declarations named +: for Int, Double, String, Array, the SIMD types, Strideable and so on. Its job was to pick exactly one.
Swift's type checker does this by building a constraint system. Every subexpression gets a type variable. Every relationship becomes a constraint: "the literal 100 must be some type that conforms to ExpressibleByIntegerLiteral", "the argument types must be convertible to the parameter types of whichever + we pick", and so on. A solver then searches for an assignment that satisfies all constraints.
Literals have default types (Int for integer literals, Double for float literals) that the solver prefers when nothing else forces a choice. So value becomes Int, and once it's Int, value + 20 strongly favors the (Int, Int) -> Int overload.
The output also shows that the literal 20 is turned into an Int through Int.init(_builtinIntegerLiteral:). Literals aren't magic: they're initializer calls the compiler inserts for you.
The same solver handles generic constraints (T: Comparable plus everything implied by T's associated types), overload resolution and closure parameter inference.
Once types are settled, other checks run against the now-typed AST. Does this type actually provide every requirement of the protocols it claims to conform to? Is this private member visible from here? Is this let being assigned twice? Each failure becomes a compile-time diagnostic instead of a runtime crash, which is the point of the exercise.
When the solver gets expensive
Constraint solving can be exponential in the worst case. Each overloaded operator multiplies the number of candidate combinations, and literals can be many types. The solver uses a lot of heuristics to prune the search, and most expressions are solved in microseconds. But you can still fall off a cliff.
Here is a real expression and the real result:
// Slow.swift
let a = 1 , b = 2.0 , c = 3
let slow = - ( 1 + 2 ) * a - Double ( c ) / 4 + b * 5 - ( 6 + 7.5 ) * Double ( a + c ) + 8
$ swiftc -typecheck -Xfrontend -warn-long-expression-type-checking=20 Slow.swift
# compiler output
Slow.swift:2:12: warning: expression took 9369ms to type-check ( limit: 20ms )
Slow.swift:2:5: error: the compiler is unable to type-check this expression in reasonable time ; try breaking up the expression into distinct sub-expressions
It took about twenty seconds of wall-clock time and then gave up. The expression is also wrong: -(1 + 2) * a is an Int and everything else is Double, so there is no valid solution. That's the worst case, because the solver has to rule out every combination before it can say no. Mixed literals, many overloaded operators and a type error together are the classic recipe.
The fix is to give the solver fewer choices:
// Fast.swift
let a = 1 , b = 2.0 , c = 3
let ad = Double ( a ) , cd = Double ( c )
let left : Double = - 3 * ad - cd / 4
let right : Double = b * 5 - 13.5 * ( ad + cd ) + 8
let fast = left + right
swiftc -typecheck Fast.swift finishes in 0.24 seconds of wall-clock time on the same machine, and almost all of that is process startup.
Splitting expressions and a
Comments
No comments yet. Start the discussion.