apple/swift
SwiftCompilerSources
Active contributors: eeckstein, atrick, meg-gupta, kavon
Purpose
SwiftCompilerSources/ is the part of the Swift compiler implemented in Swift. Today it covers SIL utilities, optimizer passes, and a Swift-side wrapper around the AST. New SIL passes are written here whenever feasible. The directory is the bridge that lets the compiler benefit from the very language it compiles.
Directory layout
SwiftCompilerSources/
├── README.md
├── Package.swift # SwiftPM manifest for editor tooling
├── stubs.cpp # C++ stubs for Swift→C++ bridge
├── force_lib.c
└── Sources/
├── AST/ # Swift AST module (wraps lib/AST C++)
├── Basic/ # shared utility types
├── SIL/ # Swift wrappers around lib/SIL
└── Optimizer/ # Swift-side optimizer
├── PassManager/
├── FunctionPasses/ # 30+ Swift-implemented function passes
├── ModulePasses/
├── InstructionSimplification/
├── Analysis/
├── DataStructures/
└── Utilities/The corresponding C++ side lives in include/swift/Bridging/, include/swift/SIL/SILBridging.h, and so on. Each Swift module here has a paired C++ "Bridging" header that declares the FFI surface.
Key abstractions
| Swift type | Wraps | File |
|---|---|---|
Function |
C++ SILFunction |
SwiftCompilerSources/Sources/SIL/Function.swift |
Instruction |
C++ SILInstruction |
SwiftCompilerSources/Sources/SIL/Instruction.swift |
Value |
C++ SILValue |
SwiftCompilerSources/Sources/SIL/Value.swift |
BasicBlock |
C++ SILBasicBlock |
SwiftCompilerSources/Sources/SIL/BasicBlock.swift |
Type |
C++ swift::Type |
SwiftCompilerSources/Sources/AST/Type.swift |
Decl |
C++ swift::Decl |
SwiftCompilerSources/Sources/AST/Decl.swift |
FunctionPassContext |
passes' analysis/mutation handle | SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift |
How it works
graph LR
CPP[C++ pass driver] -->|invoke| Bridge[OptimizerBridging]
Bridge -->|"call Swift @_cdecl"| SwiftPass["Swift pass body"]
SwiftPass -->|reads| BridgedSIL["BridgedFunction wraps SILFunction *"]
SwiftPass -->|mutates via builder| Bridge
Bridge -->|"manipulates"| SILModule["lib/SIL data structures"]Build
SwiftCompilerSources/CMakeLists.txt builds the Swift sources with the just-built compiler (a bootstrap stage). The output is a static library (libswiftCompilerSources etc.) that the C++ compiler links against. The Swift libraries here use -parse-stdlib-style minimalism: they import only Swift, _SwiftSyntax, and the bridging modules.
Bridging mechanics
C++ exposes opaque structs (BridgedFunction, BridgedInstruction, BridgedSILType, ...) declared in include/swift/SIL/SILBridging.h. Swift wraps them in safe types (Function, Instruction, Type).
A simplified example of a Swift pass:
// SwiftCompilerSources/Sources/Optimizer/FunctionPasses/AssumeSingleThreaded.swift
let assumeSingleThreadedPass = FunctionPass(name: "assume-single-threaded") {
(function: Function, context: FunctionPassContext) in
for inst in function.instructions {
if let builtin = inst as? BuiltinInst, builtin.id == .swift_isUniquelyReferenced {
context.replaceAllUsesAndErase(builtin, with: ...)
}
}
}Pass registration uses OptimizerBridging: the Swift module exports a list of (name, body) pairs that the C++ pass manager registers and runs identically to native C++ passes.
Memory ownership
The C++ side owns SIL memory. Swift wrappers are value-typed handles; the wrapped pointers are guaranteed to outlive the Swift pass execution. Swift code uses precondition/fatalError instead of throwing; the C++ runtime is -fno-exceptions.
Selected Swift-implemented passes
A non-exhaustive sample from SwiftCompilerSources/Sources/Optimizer/FunctionPasses/:
| Pass | What it does |
|---|---|
AllocBoxToStack |
Promote heap-allocated boxes to stack when ownership allows. |
DeadStoreElimination |
Remove writes whose result is overwritten or dead. |
LoopInvariantCodeMotion |
Hoist invariant computations out of loops. |
StackProtection |
Insert stack canaries. |
LifetimeDependenceDiagnostics |
Validate @lifetime annotations. |
LifetimeDependenceInsertion |
Insert mark_dependence instructions for lifetime-dep. |
BooleanLiteralFolding |
Fold known-true/false branches. |
CleanupDebugSteps |
Drop redundant debug_step instructions. |
DiagnoseInfiniteRecursion |
Static detection of infinitely recursive functions. |
ObjCBridgingOptimization |
Eliminate redundant _bridgeFromObjectiveC round trips. |
SwiftCompilerSources/Sources/Optimizer/ModulePasses/:
| Pass | What it does |
|---|---|
MandatoryPerformanceOptimizations |
The mandatory pipeline pass. |
EmbeddedSwiftDiagnostics |
Embedded-Swift specific checks. |
StackProtection |
Module-level stack-protector setup. |
ReadOnlyGlobalVariables |
Mark globals that are never written. |
ConformanceCheckOptimization |
Specialize generic conformance lookups. |
Integration points
- The pass manager (
lib/SILOptimizer/PassManager/) treats Swift-implemented passes the same as C++ ones. - Bridging headers (
include/swift/Bridging/,include/swift/SIL/SILBridging.h) are the contract; they evolve alongside Swift wrappers. - Tests for Swift passes live in
test/SILOptimizer/. - The
Package.swiftallows runningswift buildonSwiftCompilerSources/for IDE tooling, but the real build is CMake-driven from the host build system.
Entry points for modification
- Adding a new Swift pass: create
SwiftCompilerSources/Sources/Optimizer/FunctionPasses/MyPass.swiftexporting aFunctionPass. Register the name in the C++ pass list (include/swift/SILOptimizer/PassManager/Passes.def) plus the Swift registration inOptimizer/PassManager/PassRegistration.swift. - Wrapping a new SIL utility for Swift: add the C++ bridging declaration in
include/swift/SIL/SILBridging.h, then a Swift wrapper inSources/SIL/. - Investigating a Swift-side compile error: most issues are missing bridging declarations; the C++ side compile error usually points at the offender.
Related pages
- SIL and the SIL optimizer -- the C++ counterpart.
- AST -- the C++ side of the AST that Swift wraps.
- Patterns and conventions -- bridging idioms.
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.
Previous
Runtime
Next
IDE support and SourceKit