DEV Community

Cover image for Inside swiftc: How Swift Turns Source into SIL, LLVM IR and Machine Code
Dheerendra Chaturvedi
Dheerendra Chaturvedi

Posted on

Inside swiftc: How Swift Turns Source into SIL, LLVM IR and Machine Code

One small function followed through every stage of the Swift compiler, with real SIL, LLVM IR and x86-64 / ARM64 assembly, and a measured look at how optimization changes the cost of protocols, generics, closures and classes.

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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))))))
Enter fullscreen mode Exit fullscreen mode

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 what Int refers to, which is why it says unbound.

  • unresolved_decl_ref_expr. price is 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 build a + b * c into 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
Enter fullscreen mode Exit fullscreen mode

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).value@Infer.swift:1:5" ...))
    (argument (integer_literal_expr type="Int" value="20" ...))))
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
$ 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 adding a type annotation in the right place doesn't make your code less "Swifty". It turns a search problem into a lookup. Section 14 shows how to find these hot spots in a real project.

6. SIL: Swift's own intermediate language

If you take one thing from this article, take this section. SIL, the Swift Intermediate Language, is the reason Swift's optimizer can do things a generic C-family compiler can't.

Why another IR?

The AST is good for representing what the programmer wrote and terrible for analysis: it's a tree, there's no explicit control flow and the semantics are implicit. LLVM IR is great for analysis but too low-level for Swift. By the time something is LLVM IR, a call to a protocol requirement is just a load from a table and an indirect call, and a retain is just an opaque runtime function call. LLVM can't know that a particular retain pairs with a particular release because of Swift's ownership rules, or that a witness table lookup can be skipped because the concrete type is known.

SIL sits in between. Like LLVM IR, it's a control-flow graph of basic blocks in SSA form. Every value is defined exactly once, and blocks end in explicit branches. Unlike LLVM IR, it still has Swift's types, generics, protocols, classes, ownership and method dispatch as first-class concepts. The design documents in the docs directory of the Swift repository are the authoritative reference for every instruction.

Raw SIL from SILGen

-emit-silgen shows SIL straight out of SILGen, before any mandatory pass:

$ swiftc -emit-silgen -parse-as-library Example.swift        # compiler output
// calculateTotal(price:quantity:)
// Isolation: unspecified
sil hidden [ossa] @$s7Example14calculateTotal5price8quantityS2i_SitF : $@convention(thin) (Int, Int) -> Int {
// %0 "price"                                     // users: %6, %2
// %1 "quantity"                                  // users: %6, %3
bb0(%0 : $Int, %1 : $Int):
  debug_value %0, let, name "price", argno 1      // id: %2
  debug_value %1, let, name "quantity", argno 2   // id: %3
  %4 = metatype $@thin Int.Type                   // user: %6
  // function_ref static Int.* infix(_:_:)
  %5 = function_ref @$sSi1moiyS2i_SitFZ : $@convention(method) (Int, Int, @thin Int.Type) -> Int // user: %6
  %6 = apply %5(%0, %1, %4) : $@convention(method) (Int, Int, @thin Int.Type) -> Int // user: %7
  return %6                                       // id: %7
} // end sil function '$s7Example14calculateTotal5price8quantityS2i_SitF'
Enter fullscreen mode Exit fullscreen mode

Line by line:

  • $s7Example14calculateTotal5price8quantityS2i_SitF is the mangled name, a unique symbol that encodes the module, name, argument labels and types. xcrun swift-demangle turns it back into Example.calculateTotal(price: Swift.Int, quantity: Swift.Int) -> Swift.Int.

  • hidden is SIL's linkage for internal. [ossa] means the function is in Ownership SSA form, which we'll get to in a moment.

  • @convention(thin) means a plain function with no context. A closure would be @callee_guaranteed and carry a context pointer.

  • bb0(%0 : $Int, %1 : $Int) is the entry block. Arguments are block arguments, SIL's version of phi nodes.

  • debug_value only exists for the debugger. It generates no code.

  • metatype $@thin Int.Type: * is a static method on Int, so it needs a self, and for a static method self is the metatype.

  • function_ref takes a direct reference to a known function. apply calls it. Note that SILGen does not inline Int.*. It emits a normal call to the standard library's implementation, exactly as it would for your own function.

  • return %6. No surprises.

Canonical SIL: mandatory passes

Now -emit-sil with optimization off:

$ swiftc -emit-sil -Onone -parse-as-library Example.swift    # compiler output
sil hidden @$s7Example14calculateTotal5price8quantityS2i_SitF : $@convention(thin) (Int, Int) -> Int {
bb0(%0 : $Int, %1 : $Int):
  debug_value %0, let, name "price", argno 1
  debug_value %1, let, name "quantity", argno 2
  %4 = struct_extract %0, #Int._value
  %5 = struct_extract %1, #Int._value
  %6 = integer_literal $Builtin.Int1, -1
  %7 = builtin "smul_with_overflow_Int64"(%4, %5, %6) : $(Builtin.Int64, Builtin.Int1)
  %8 = tuple_extract %7, 0
  %9 = tuple_extract %7, 1
  cond_fail %9, "arithmetic overflow"
  %11 = struct $Int (%8)
  return %11
}
Enter fullscreen mode Exit fullscreen mode

Even at -Onone, the call to Int.* is gone. That's not optimization in the usual sense. Int.* is marked @_transparent in the standard library, and the mandatory inlining pass always inlines transparent functions, at every optimization level. It has to, because diagnostics such as "this constant expression overflows" can only be produced once the arithmetic is visible.

What we see after inlining is the real structure of Int. Int is a struct with a single stored property, _value, of type Builtin.Int64. struct_extract pulls that raw 64-bit value out, builtin "smul_with_overflow_Int64" multiplies it and returns a (result, overflowed) tuple, cond_fail traps with "arithmetic overflow" if the flag is set, and struct $Int (%8) wraps the raw result back up. Swift's overflow checking isn't a runtime library feature. It's two SIL instructions that survive all the way to machine code.

Also note what disappeared: the [ossa] marker. In this build, ownership information is stripped by a pass called OwnershipModelEliminator before the SIL is printed. You can list every pass the compiler runs with -Xllvm -sil-print-pass-name. On this toolchain, the mandatory stage includes, among many others:

AllocBoxToStack  DefiniteInitialization  DiagnoseStaticExclusivity  MandatoryInlining
DiagnosticConstantPropagation  DiagnoseUnreachable  MoveOnlyChecker  SendNonSendable
Enter fullscreen mode Exit fullscreen mode

Several of those are the reason Swift feels safe. DefiniteInitialization is what reports "variable used before being initialized". DiagnoseStaticExclusivity finds overlapping access to the same variable. SendNonSendable produces many of the Swift 6 data-race diagnostics. These are compile errors that are implemented as SIL passes. Raw SIL that comes out of these passes successfully is canonical SIL, the form the optimizer and IRGen expect.

Ownership and ARC, visibly

Int is trivial: no reference counting, no ownership. To see the instructions that matter for classes, here's a slightly richer example:

final class Cart {
    var items: [String] = []
}

func firstItem(of cart: Cart) -> String? {
    let copy = cart
    return copy.items.first
}
Enter fullscreen mode Exit fullscreen mode

Raw SIL:

$ swiftc -emit-silgen -parse-as-library Ownership.swift      # compiler output
sil hidden [ossa] @$s9Ownership9firstItem2ofSSSgAA4CartC_tF : $@convention(thin) (@guaranteed Cart) -> @owned Optional<String> {
bb0(%0 : @guaranteed $Cart):
  debug_value %0, let, name "cart", argno 1
  %2 = copy_value %0
  %3 = move_value [lexical] [var_decl] %2
  debug_value %3, let, name "copy"
  %5 = begin_borrow %3
  %6 = ref_element_addr %5, #Cart.items
  %7 = begin_access [read] [dynamic] %6
  %8 = load [copy] %7
  end_access %7
  %10 = begin_borrow %8
  %11 = alloc_stack $Array<String>
  %12 = store_borrow %10 to %11
  %13 = alloc_stack $Optional<String>
  // function_ref Collection.first.getter
  %14 = function_ref @$sSlsE5first7ElementQzSgvg : $@convention(method) <τ_0_0 where τ_0_0 : Collection> (@in_guaranteed τ_0_0) -> @out Optional<τ_0_0.Element>
  %15 = apply %14<[String]>(%13, %12) : ...
  %16 = load [take] %13
  end_borrow %12
  end_borrow %10
  destroy_value %8
  dealloc_stack %13
  dealloc_stack %11
  end_borrow %5
  destroy_value %3
  return %16
}
Enter fullscreen mode Exit fullscreen mode

This is the ownership model on display, so it's worth going slowly.

The signature says (@guaranteed Cart) -> @owned Optional<String>. @guaranteed means the caller keeps the Cart alive for the duration of the call, so the callee may use it but must not destroy it. @owned means the caller receives a value it's responsible for destroying.

let copy = cart becomes copy_value %0: a new owned reference to the same object, conceptually a retain. move_value [lexical] marks the start of the variable's lifetime. At the end of the function, the matching destroy_value %3, conceptually a release, ends it. In OSSA, every owned value must be consumed exactly once on every path. The SIL verifier checks this, which is how the compiler catches its own ARC bugs before they become yours.

begin_borrow / end_borrow form a borrow scope: "I'm using this value without taking ownership, and it must stay alive until end_borrow." ref_element_addr computes the address of the items property inside the object. begin_access [read] [dynamic] is exclusivity enforcement: class properties can't always be proven exclusive at compile time, so this access is checked at runtime. load [copy] loads the array and copies it, so %8 is an owned array that must later be destroy_valued.

alloc_stack / dealloc_stack allocate and free stack slots. They're needed here because Collection.first is a generic function called through its unspecialized form, so its argument and result are passed indirectly by address (@in_guaranteed, @out). store_borrow puts a borrowed value into such a slot, and load [take] moves the result out of one. apply %14<[String]>(...) is a generic call with an explicit substitution: τ_0_0 = [String].

That's a lot of machinery for copy.items.first. Here is the same function after the optimizer, at -O:

$ swiftc -emit-sil -O -parse-as-library Ownership.swift      # compiler output, trimmed
sil hidden @$s9Ownership9firstItem2ofSSSgAA4CartC_tF : $@convention(thin) (@guaranteed Cart) -> @owned Optional<String> {
bb0(%0 : $Cart):
  %2 = ref_element_addr %0, #Cart.items
  %3 = begin_access [read] [dynamic] [no_nested_conflict] %2
  ...
  %7 = load %6
  end_access %3
  ...
  %15 = load %14                                  // the array's count
  %17 = builtin "cmp_eq_Int64"(%16, %9) : $Builtin.Int1
  cond_br %17, bb1, bb2
bb1:
  %19 = enum $Optional<String>, #Optional.none!enumelt
  br bb3(%19)
bb2:
  ...
  %26 = load %25                                  // the first String
  %27 = enum $Optional<String>, #Optional.some!enumelt, %26
  ...
  strong_retain %30
  br bb3(%27)
bb3(%33 : $Optional<String>):
  return %33
}
Enter fullscreen mode Exit fullscreen mode

The copy_value / destroy_value pair for the local copy is gone. The array is no longer copied. The generic Collection.first getter has been inlined and specialized into a count check and a load from the array's storage. The alloc_stack slots have disappeared. Exactly one retain remains: strong_retain on the string's storage object, because the function returns an owned String and the caller will eventually release it. That retain is semantically required, and the optimizer is right to keep it.

SILGen vs. mandatory passes vs. optimization

The three phases are easy to blur, so here is the distinction:

Phase Runs at -Onone? Purpose Examples
SILGen Yes Faithful, naive lowering of the typed AST Every let copy becomes copy_value
Mandatory passes Yes Required for correctness and diagnostics DefiniteInitialization, MandatoryInlining of @_transparent, AllocBoxToStack
Performance optimizer No (-O, -Osize only) Make it fast or small GenericSpecializer, Devirtualizer, ARCSequenceOpts, ExistentialSpecializer, DeadObjectElimination

Two quick commands make the difference concrete. swiftc -emit-silgen gives you the first row. swiftc -emit-sil -Onone gives you the first two. swiftc -emit-sil -O gives you all three. On this toolchain, the -O pipeline ran tens of thousands of pass invocations (most of them on standard library code pulled in for inlining) across stages the compiler names HighLevel, MidLevel, LowLevel and LateLoopOpt.

If you modify the compiler, or you're investigating a suspected miscompile, -Xfrontend -sil-verify-all runs the SIL verifier after every pass instead of only at key points. It's slow, but it pinpoints which pass first produced invalid SIL.

7. LLVM IR: handing off to LLVM

IRGen lowers canonical SIL to LLVM IR. By now, the Swift-specific concepts have to be expressed in terms LLVM understands. Structs become LLVM aggregates or scalars. Classes become pointers. Retains and releases become calls to runtime functions such as swift_retain and swift_release. Protocol method calls become loads from witness tables followed by indirect calls. Generic code that wasn't specialized gets metadata and witness table parameters it passes around at runtime.

Here is our function at -O:

; swiftc -emit-ir -O -parse-as-library Example.swift        ; compiler output
define hidden swiftcc i64 @"$s7Example14calculateTotal5price8quantityS2i_SitF"(i64 %0, i64 %1) local_unnamed_addr #0 {
entry:
  %2 = tail call { i64, i1 } @llvm.smul.with.overflow.i64(i64 %0, i64 %1)
  %3 = extractvalue { i64, i1 } %2, 1
  br i1 %3, label %6, label %4, !prof !17

4:                                                ; preds = %entry
  %5 = extractvalue { i64, i1 } %2, 0
  ret i64 %5

6:                                                ; preds = %entry
  tail call void asm sideeffect "", "n"(i32 0) #3
  tail call void @llvm.trap()
  unreachable
}
Enter fullscreen mode Exit fullscreen mode

Reading it:

  • define hidden swiftcc i64 @"..."(i64 %0, i64 %1). Int has become plain i64. The wrapper struct is gone entirely. swiftcc is the Swift calling convention, which LLVM knows about. For two integers it looks just like C, but it reserves dedicated registers for things like a method's self and a thrown error.

  • @llvm.smul.with.overflow.i64 is an LLVM intrinsic that returns {product, overflowed}. It's the direct counterpart of the SIL builtin.

  • br i1 %3, label %6, label %4, !prof !17 branches to the trap block if the multiplication overflowed. !prof is branch-weight metadata telling LLVM this path is cold, so the normal path gets laid out as the fall-through.

  • Block 4 returns the product.

  • Block 6 is what cond_fail turned into: @llvm.trap() followed by unreachable. The empty inline asm sideeffect marker in front of it keeps LLVM from merging separate trap sites into one, so that a crash still points at the right check.

Compare the same function at -Onone:

; swiftc -emit-ir -Onone -parse-as-library Example.swift    ; compiler output
define hidden swiftcc i64 @"$s7Example14calculateTotal5price8quantityS2i_SitF"(i64 %0, i64 %1) #0 {
entry:
  %price.debug = alloca i64, align 8
  call void @llvm.memset.p0.i64(ptr align 8 %price.debug, i8 0, i64 8, i1 false)
  %quantity.debug = alloca i64, align 8
  call void @llvm.memset.p0.i64(ptr align 8 %quantity.debug, i8 0, i64 8, i1 false)
  store i64 %0, ptr %price.debug, align 8
  store i64 %1, ptr %quantity.debug, align 8
  %2 = call { i64, i1 } @llvm.smul.with.overflow.i64(i64 %0, i64 %1)
  ...
Enter fullscreen mode Exit fullscreen mode

The arithmetic is identical. The extra work is entirely for you, in the debugger: each parameter gets a stack slot (%price.debug) so LLDB can always find and display it, even after the register holding it has been reused. That's a large part of why Debug builds are slower. It isn't that the math is worse. Every value is kept somewhere the debugger can see it.

The attributes block hides one more interesting fact:

attributes #0 = { "frame-pointer"="all" ... "target-cpu"="penryn" ... }
Enter fullscreen mode Exit fullscreen mode

The default x86-64 macOS target CPU is penryn, an old Core 2 generation chip, so the compiler won't use AVX unless you ask it to. "frame-pointer"="all" keeps frame pointers in every function so that profilers and crash reporters can walk the stack cheaply. You'll see both of these effects in the assembly.

After IRGen, the normal LLVM optimization pipeline runs (instcombine, GVN, loop passes, inlining at the LLVM level and so on), plus some Swift-specific LLVM passes for ARC. The important design point is that most Swift-semantic optimization has already happened in SIL. LLVM's job is mostly classic scalar and loop optimization.

8. Optimizations that matter in practice

None of these happen on every function. They're attempts, each limited by what the compiler can prove. Here are the ones that most affect real Swift code.

Inlining replaces a call with the callee's body. It removes call overhead, but more importantly it gives every other optimization more to work with: once Collection.first was inlined into firstItem, the optimizer could see there was no need to copy the array. The trade-off is code size. Inlining a large function into many callers bloats the binary and can hurt instruction-cache behavior, which is what -Osize is designed to rein in. Across module boundaries, the optimizer can only inline what it can see, which is what @inlinable is for.

Constant folding and propagation evaluate expressions whose inputs are known at compile time and substitute the results. let seconds = 60 * 60 * 24 becomes 86400 early, in SIL. In Swift, this pass also has a diagnostic role: DiagnosticConstantPropagation is how let x: Int8 = 100 + 100 becomes a compile error instead of a trap.

Dead code elimination removes code whose result is unused and that has no side effects. It's also why naive benchmarks lie: if you never use a result, the optimizer can delete the computation you meant to measure. The benchmark below takes its inputs from the command line and prints a checksum for exactly this reason.

Allocation promotion is one of my favorite examples of SIL doing language-specific work. Look at what SILGen produces for an ordinary local var that's mutated in a loop:

// swiftc -emit-silgen, function runningTotal(_:)      ; compiler output, excerpt
%2 = alloc_box ${ var Int }, var, name "total"
Enter fullscreen mode Exit fullscreen mode

alloc_box is a heap-allocated, reference-counted box. SILGen boxes every mutable local by default, because if a closure captured total, the variable would have to outlive the stack frame. The AllocBoxToStack pass then proves nothing escapes and turns the box into a stack slot. At -O, swiftc -emit-sil -O Ownership.swift | grep -c alloc_box prints 0: total is just an SSA value in a register. This is the first counterexample to "structs live on the stack". Where a value lives is decided by escape analysis, not by its kind.

Generic specialization. Unspecialized generic code is compiled once and works for every type by passing type metadata and witness tables at runtime. Every protocol requirement call becomes an indirect call through a table. Specialization clones the function for a concrete type, after which those calls become direct and inlinable. The compiler can only specialize when it can see both the generic function's body and a call site with concrete types, which is why whole-module optimization and @inlinable matter so much for generics. We'll see this happen for real in section 12.

Devirtualization turns a dynamic call (through a class vtable or a protocol witness table) into a direct call when the compiler can prove which implementation will run. The easiest proofs come from final classes and methods, private / fileprivate members, which can't be overridden outside the file, and internal members under WMO, where the compiler sees every subclass in the module. When it can't prove it, the call stays dynamic.

ARC optimization removes retain/release pairs the compiler can prove are redundant. In OSSA, passes like CopyPropagation shorten lifetimes and remove copies. Later, ARCSequenceOpts matches up retain/release pairs on the lowered code. We saw this in firstItem, where only the one semantically required retain survived. Its limits are calls the optimizer can't see into and values that genuinely escape.

Loop optimizations include hoisting invariant code (LICM), removing bounds checks the compiler can prove safe (BoundsCheckOpts), and copy-on-write checks for arrays (COWArrayOpts). LLVM then adds its own unrolling and vectorization.

Whole-module optimization is less a single optimization than an enabling condition. Every optimization above that needs to see "the other file" works better under WMO. The trade-off is incremental build time, because a change anywhere means optimizing the whole module again. That's why Xcode defaults Debug to incremental mode and Release to WMO.

Debug vs. Release, in one table

Debug (-Onone) Release (-O)
SIL optimizer Mandatory passes only Full pipeline
Compilation mode (Xcode default) Incremental Whole module
Debug shadow copies Every variable Mostly gone, so the debugger may show "optimized out"
Overflow and bounds checks Present Still present (only -Ounchecked removes them)
assert() Evaluated Removed (precondition() stays)
Specialization, devirtualization Rare (prespecialized stdlib entry points only) Wherever provable

The overflow row is one that people get wrong surprisingly often. Release builds of Swift still check for overflow. If you compile calculateTotal with -Ounchecked, the cond_fail disappears from the SIL. With -O, it stays, as the assembly below shows.

9. Machine code

LLVM's backend turns IR into instructions for a specific target. It selects instructions (matching IR patterns to the cheapest machine instructions), allocates registers (mapping unlimited SSA values onto a handful of physical registers and spilling to the stack when needed), schedules instructions around pipeline latencies, and builds the stack frame according to the platform's calling convention.

Here's our function on x86-64:

; swiftc -S -O -parse-as-library Example.swift          ; compiler output, CFI directives removed
_$s7Example14calculateTotal5price8quantityS2i_SitF:
    pushq   %rbp            ; save caller's frame pointer
    movq    %rsp, %rbp      ; set up our frame pointer
    imulq   %rsi, %rdi      ; rdi = price * quantity, sets OF on signed overflow
    jo      LBB0_2          ; overflow → trap
    movq    %rdi, %rax      ; return value goes in rax
    popq    %rbp
    retq
LBB0_2:
    ud2                     ; undefined instruction = trap (crash with "arithmetic overflow")
Enter fullscreen mode Exit fullscreen mode

The arguments arrive in rdi and rsi, and the result leaves in rax, standard System V x86-64 registers, which swiftcc matches for simple integer arguments. The frame-pointer push/pop is the "frame-pointer"="all" attribute in action: the function doesn't need a frame at all, but Darwin keeps one for reliable stack walking. x86 makes overflow detection cheap because imul sets the overflow flag, so the whole check is a single jo.

Same source, same compiler, -target arm64-apple-macos14:

; swiftc -S -O -parse-as-library -target arm64-apple-macos14 Example.swift   ; compiler output
_$s7Example14calculateTotal5price8quantityS2i_SitF:
    mov     x8, x0          ; keep a copy of price
    mul     x0, x0, x1      ; x0 = low 64 bits of price * quantity
    smulh   x8, x8, x1      ; x8 = high 64 bits of the signed 128-bit product
    cmp     x8, x0, asr #63 ; no overflow iff high bits == sign-extension of low bits
    b.ne    LBB0_2
    ret                     ; result already in x0
LBB0_2:
    brk     #0x1            ; trap
Enter fullscreen mode Exit fullscreen mode

ARM64's mul doesn't set flags, so LLVM computes the full 128-bit product's high half with smulh. If the high 64 bits aren't just copies of the low half's sign bit, the true product didn't fit. Arguments arrive in x0 and x1, and the result goes out in x0. No frame setup is emitted for this leaf function. There's no single "right" machine code for a Swift function, only the best code for a particular target, and the same SIL produces both of these.

This is also why a universal (fat) binary is literally two compilations: one pass through the backend per architecture, with the results combined into one Mach-O file.

10. Object files and linking

Each frontend job produces a Mach-O object file. It contains machine code, data, a symbol table (names this file defines and names it needs from elsewhere) and relocations (places in the code that must be patched once final addresses are known):

$ swiftc -c -O -parse-as-library Example.swift -o Example.o && nm -m Example.o    # compiler output
0000000000000000 (__TEXT,__text) private external _$s7Example14calculateTotal5price8quantityS2i_SitF
0000000000000012 (__TEXT,__const) weak private external [no dead strip] ___swift_reflection_version
0000000000000014 (__LLVM,__swift_modhash) non-external [no dead strip] l_llvm.swift_module_hash
Enter fullscreen mode Exit fullscreen mode

size -m Example.o reports 17 bytes in __TEXT,__text: the whole function. Real Swift object files also carry __swift5_* sections with type metadata, protocol conformance records and reflection data. The runtime reads those for dynamic casts, Mirror and the debugger.

The linker (ld, invoked through clang as we saw in the -### output) combines object files, resolves every undefined symbol against other objects, static libraries and dynamic libraries, applies relocations and writes the final executable. Static linking copies code into your binary. Dynamic linking records a dependency, and dyld binds the symbol at load time. The Swift runtime and standard library ship in the OS on Apple platforms, which is why your app links against them dynamically and doesn't bundle them. A framework is a dynamic library in a directory with headers, module maps and resources. Dead stripping (-dead_strip, controlled by Xcode's Dead Code Stripping setting, on by default in new projects) removes functions and data nothing references, which is what the [no dead strip] flags above opt out of. Link-time optimization lets LLVM optimize across object files at link time. Xcode's LTO setting applies to Clang-compiled code, while Swift relies primarily on WMO for cross-file optimization.

Building an app is much more than this. Xcode's build system compiles each target's Swift sources (and any C/Objective-C) into objects, links them into a binary, compiles asset catalogs and storyboards, processes Info.plist, embeds frameworks, signs everything and assembles the .app bundle. Compilation is one step in that graph.

11. Try it yourself

You need only a Swift toolchain. These all work with Xcode's swiftc or a toolchain from swift.org. Use -parse-as-library for files that don't have top-level code, so the output isn't cluttered with main.

swiftc -version                                                           # record it with any output
swiftc -dump-parse  Example.swift                                         # untyped AST
swiftc -dump-ast    Example.swift                                         # typed AST
swiftc -emit-silgen -parse-as-library Example.swift                       # raw SIL (OSSA)
swiftc -emit-sil -Onone -parse-as-library Example.swift                   # canonical SIL (no -O)
swiftc -emit-sil -O     -parse-as-library Example.swift                   # optimized SIL
swiftc -emit-ir  -O     -parse-as-library Example.swift                   # LLVM IR
swiftc -S        -O     -parse-as-library Example.swift                   # assembly for the host
swiftc -S -O -parse-as-library -target arm64-apple-macos14 Example.swift  # assembly for ARM64
xcrun swift-demangle '$s7Example14calculateTotal5price8quantityS2i_SitF'   # decode a symbol
Enter fullscreen mode Exit fullscreen mode

Some reading tips that save time:

  • SIL output includes all the standard library code that was pulled in. Search for // yourFunctionName to jump to your own function.

  • In SIL, look for apply of a witness_method or class_method: those are dynamic calls. function_ref + apply is a direct call. alloc_ref and alloc_box are heap allocations. strong_retain / strong_release (or copy_value / destroy_value in OSSA) are ARC.

  • In optimized SIL, look for function names containing Tg5, which marks a generic specialization (the demangler shows these as generic specialization <...> of ...).

  • Compare -Onone and -O with a plain diff. The differences tell you what the optimizer could prove.

  • For multi-file experiments, add -wmo (and a -module-name that doesn't collide with a system module such as Dispatch, as I found out the hard way) to see what whole-module optimization does.

12. Case study: four ways to apply a discount

Here's an experiment I find more instructive than any microbenchmark blog post I've read. One task, implemented four ways:

// Pricing.swift
protocol PriceRule { func apply(_ price: Int) -> Int }

struct Discount: PriceRule {
    let percent: Int
    func apply(_ price: Int) -> Int { price - price * percent / 100 }
}

class BaseRule { func apply(_ price: Int) -> Int { price } }
final class DiscountRule: BaseRule {
    let percent: Int
    init(percent: Int) { self.percent = percent }
    override func apply(_ price: Int) -> Int { price - price * percent / 100 }
}

@inline(never)
func totalExistential(_ prices: [Int], rule: any PriceRule) -> Int {
    var sum = 0
    for p in prices { sum &+= rule.apply(p) }
    return sum
}

@inline(never)
func totalGeneric<R: PriceRule>(_ prices: [Int], rule: R) -> Int {
    var sum = 0
    for p in prices { sum &+= rule.apply(p) }
    return sum
}

@inline(never)
func totalClosure(_ prices: [Int], rule: (Int) -> Int) -> Int {
    var sum = 0
    for p in prices { sum &+= rule(p) }
    return sum
}

@inline(never)
func totalClass(_ prices: [Int], rule: BaseRule) -> Int {
    var sum = 0
    for p in prices { sum &+= rule.apply(p) }
    return sum
}
Enter fullscreen mode Exit fullscreen mode

@inline(never) keeps each function as a separate unit so we can inspect and time it. Without it, the optimizer could inline everything into the caller and the comparison would be meaningless.

What the compiler does with each

First, compile only Pricing.swift with -O and look at the dispatch instructions left in each function:

compiler output, counted with grep
totalExistential   open_existential_addr ×1, witness_method ×3
totalGeneric       witness_method ×3
totalClosure       indirect apply of the closure value
totalClass         class_method ×1
Enter fullscreen mode Exit fullscreen mode

The generic version is no faster than the existential here: without a call site, there is no concrete type to specialize for, so it is compiled as true generic code that dispatches through the witness table.

Now add a main.swift that calls each function with concrete values, and compile both files together with -O -wmo. The optimized SIL now contains these functions:

compiler output
sil shared [noinline] @$s7Pricing12totalGeneric_4ruleSiSaySiG_xtAA9PriceRuleRzlFAA8DiscountV_Tg5
        : $@convention(thin) (@guaranteed Array<Int>, Discount) -> Int
sil hidden [noinline] @$s7Pricing12totalClosure_4ruleSiSaySiG_S2iXEtF
        : $@convention(thin) (@guaranteed Array<Int>, @guaranteed @noescape @callee_guaranteed (Int) -> Int) -> Int
sil hidden [noinline] @$s7Pricing10totalClass_4ruleSiSaySiG_AA8BaseRuleCtF
        : $@convention(thin) (@guaranteed Array<Int>, @guaranteed BaseRule) -> Int
sil shared [noinline] @$s7Pricing16totalExistential_4ruleSiSaySiG_AA9PriceRule_ptFTf4ne_nAA8DiscountV_Tg5
        : $@convention(thin) (@guaranteed Array<Int>, Discount) -> Int
Enter fullscreen mode Exit fullscreen mode

Read the signatures, they tell the story:

  • Generic: the Tg5 suffix and the parameter type Discount show that GenericSpecializer made a copy just for Discount. The witness table is gone, and Discount.apply is inlined into the loop.

  • Existential: this one surprised me. The Tf4ne_n suffix is ExistentialSpecializer at work: under WMO, the compiler saw that the only thing ever passed as rule was a Discount, so it made a version that takes Discount directly. Inside, it still builds an existential box on the stack (alloc_stack $any PriceRule, init_existential_addr), and inside the loop it reopens it with open_existential_addr followed by an unchecked_addr_cast to Discount. There's no witness table call anymore, but the box shuffling stays in the loop.

  • Closure: still an indirect call to a function value. The closure is non-escaping, so there's no heap allocation and no retain/release, but the call can't be inlined into this function.

  • Class: still class_method, a vtable call. In the assembly, the loop body contains callq *-48(%rbp), an indirect call through a function pointer loaded from the vtable.

Measuring it

The harness (main.swift) reads the iteration count and discount percent from the command line so nothing can be constant-folded. It runs one warm-up pass, then takes the best of five timed runs using ContinuousClock and prints a checksum so that nothing gets eliminated as dead code. Each run processes a 100,000-element array 200 times.

Measured on an Intel Core i7-8850H (2.6 GHz), macOS 15.7.4, Swift 6.2.4, three runs, ns per array element:

Implementation -O -wmo run 1 run 2 run 3
Existential (any PriceRule) 2.74 2.65 2.54
Generic (specialized) 1.48 1.48 1.24
Closure 1.80 1.81 2.00
Class (vtable) 2.13 2.07 2.08

And the same code at -Onone: roughly 200–210 ns per element for all four.

These numbers come from one machine, one compiler and one tiny workload. Your numbers will be different, especially on Apple Silicon. What I'd take from them is the shape, not the values:

  1. At -Onone, the dispatch style barely matters. Everything is about 100 times slower, and the differences between the styles disappear into the noise. Profiling a Debug build to choose between protocols and generics is measuring the wrong thing.

  2. At -O, specialization wins when it can happen. The generic version compiles to the tightest loop because the compiler was allowed to see through it.

  3. "Protocols are slow" is too blunt. The existential version wasn't doing a witness-table call at all in this build. Its remaining cost is existential-box handling that the optimizer didn't fully remove. Change the program so that rule can be one of several types and the specializer can't apply, and the result will be different again.

  4. The gaps are a couple of nanoseconds per call. That's important in a hot inner loop over millions of elements and irrelevant in a function that runs once per button tap.

To reproduce this properly in a project, put each variant in an XCTest measure {} block (or use the community package-benchmark package, which reports statistics and can count allocations and ARC traffic). Build in Release, keep inputs opaque to the optimizer, consume every result, and inspect the SIL to check that you're measuring what you think you are. If you skip that last step, it's easy to end up benchmarking a loop the optimizer already deleted.

13. Myths the compiler output disproves

"Swift is always compiled ahead of time." Usually, yes. But swift script.swift runs in immediate mode via JIT, and the REPL works the same way. Swift Playgrounds and Xcode previews add their own machinery on top.

"Structs always live on the stack." We watched SILGen put a plain var total = 0 into a heap box (alloc_box), which the optimizer then moved back to the stack. A struct stored in a class property lives in that object on the heap. A struct captured by an escaping closure lives in a heap box. An existential whose value doesn't fit in its three-word inline buffer stores the value in a separate heap allocation. Placement is decided by escape analysis, not by struct vs. class.

"Every function call costs a stack frame." Our calculateTotal at -O on ARM64 had no frame setup at all, and once it's inlined into a caller, it doesn't even exist as a call. @_transparent standard library functions such as Int.* are inlined even in Debug builds.

"Generics are slower than concrete types." Specialized generics are concrete code. In the case study, the generic version was the fastest of the four. Unspecialized generics, as in a library that isn't @inlinable or a call site the optimizer can't see, really do pay for metadata and witness-table dispatch.

"Protocols always mean dynamic dispatch." Protocol constraints on generics are resolved statically after specialization, and as we saw, even an any parameter can be specialized under WMO when the compiler can prove what flows into it.

"Release builds remove all unnecessary code." They remove what the optimizer can prove is unnecessary. Overflow checks, bounds checks and preconditions stay by design. Calls into code the optimizer can't see (other modules without @inlinable, Objective-C, dynamic members) stay.

"ARC always adds expensive runtime overhead." Int, Double and structs of trivial types involve no reference counting at all. For references, the optimizer removes the copies it can prove redundant: our firstItem went from four ARC operations at -Onone to one required retain at -O. ARC overhead is real in code that creates and passes around many references across opaque boundaries. It isn't a constant tax on every line.

"LLVM does all the optimizing." The most Swift-specific transformations, including generic and existential specialization, devirtualization, ownership-based ARC optimization, box-to-stack promotion and closure specialization, happen in SIL, before LLVM ever sees the code. LLVM never had the information to do them.

14. When the compiler pushes back

Type-checking errors usually point at the right expression but not always the right sub-expression. When a message mentions a type you didn't expect, add explicit annotations progressively from the inside out until the error moves. The point where it moves is where your intent and the solver's inference diverged.

"Ambiguous use of …" means more than one overload fits equally well. Add a type annotation, use an explicit argument label, or write as SomeType on one argument to break the tie.

Generic constraint failures ("global function 'f' requires that 'T' conform to 'Hashable'") are worth reading from the bottom of the note chain upwards. The most specific note usually names the requirement that actually failed.

Slow builds. Two frontend flags find type-checker hot spots, and both work in Xcode's Other Swift Flags:

-Xfrontend -warn-long-expression-type-checking=100
-Xfrontend -warn-long-function-bodies=100
Enter fullscreen mode Exit fullscreen mode

They warn about any expression or function body that took longer than the given number of milliseconds. Start at a high threshold and lower it gradually. -Xfrontend -debug-time-function-bodies prints a time for every function, and -driver-time-compilation prints a time for each driver job. Xcode's Build Timeline (Product → Perform Action → Build With Timing Summary) shows where the wall-clock time actually goes across the whole build, which is often not where you'd guess.

Compiler crashes. If swift-frontend crashes, the log includes a stack trace and, usually, the pass or declaration being processed. Narrow the crash to the smallest file that reproduces it (deleting code until it stops crashing works surprisingly well) and report it on the swiftlang/swift issue tracker along with your swiftc -version. A SIL verification failure is a compiler bug by definition, not a mistake in your code. Running with -Xfrontend -sil-verify-all helps maintainers find which pass broke the invariant. A workaround in the meantime is often to rewrite the construct that triggers it, or to mark the function @_optimize(none), an underscored, unofficial attribute that disables optimization for one function. Treat it as a temporary escape hatch, not a fix.

15. The whole trip

Our function went from text to tokens, to an untyped AST with a flat operator sequence, to a typed AST with one specific * chosen out of many, to raw SIL with an ordinary call to Int.*, to canonical SIL where that call was inlined into an overflow-checked builtin, to LLVM IR with a swiftcc signature and an overflow intrinsic, to 17 bytes of x86-64 or a handful of ARM64 instructions, into an object file and finally through the linker into a binary.

Swift source → AST → SIL → LLVM IR → machine code → object file → executable
Enter fullscreen mode Exit fullscreen mode

Knowing that path changes how I write Swift in small, practical ways. I split long mixed-type expressions without thinking twice, because I've watched the solver struggle with them. I make classes final and members private by default, because that's free information for the devirtualizer. I don't trust a performance claim about generics or protocols until I've checked whether specialization actually happened, and the SIL tells me that in seconds. And when a Debug build is slow, I no longer conclude the code is slow.

The compiler is not a black box. It's a pipeline with good tooling for looking inside, and every stage prints its work if you ask. Next time you're unsure what something costs, don't guess: run -emit-sil -O and read the output.

References: the Swift compiler source, including the SIL documentation in its docs/ directory; the Swift documentation; the LLVM Language Reference and LLVM documentation. All compiler output was generated with Apple Swift 6.2.4 (Xcode 26.3).

Top comments (0)