Repository navigation
SelectionDAG 01 overview
Relevant source files
The following files were used as context for generating this wiki page:
- llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp
- llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp
- llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
- llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp
- llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp
- llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp
- llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp
- llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp
- llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
- llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp
- llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
This wiki explains the SelectionDAG instruction selector in llvm/lib/CodeGen/SelectionDAG/, using the AArch64 backend (llvm/lib/Target/AArch64/) as the worked example. It covers the data structures, every phase from DAG construction to MIR emission, the TableGen pattern matcher, and how PHI nodes are resolved.
It does not cover GlobalISel or FastISel in depth; see Selector Comparison and Glossary for how they differ.
SelectionDAG runs once per function, after the IR-level code generation preparation passes and before any machine-level optimisation. Its output is MIR in SSA form: MachineBasicBlocks holding MachineInstrs in linear order that use virtual registers, with PHI instructions still present.
flowchart LR
IR["LLVM IR<br/>Function in SSA form"] --> PREP["IR passes<br/>CodeGenPrepare, LSR, AtomicExpand"]
PREP --> ISEL["Instruction selection<br/>SelectionDAGISel"]
ISEL --> MIR["MachineFunction<br/>SSA MIR, virtual registers, PHIs"]
MIR --> PRE["Pre-RA MIR passes<br/>machine-combiner, CSE, LICM"]
PRE --> PHIE["PHIElimination<br/>TwoAddressInstruction"]
PHIE --> RA["Register allocation"]
RA --> POST["Frame lowering, ldst-opt,<br/>post-RA passes"]
POST --> MC["AsmPrinter and MC layer"]
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:947-1200, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:766-776
| Description | |
|---|---|
| Input | One LLVM IR Function in SSA form, already cleaned by IR passes such as CodeGenPrepare
|
| Output | A MachineFunction whose blocks hold MachineInstrs in linear order, using virtual registers (MIR before register allocation) |
| Unit of work | One IR basic block at a time. One IR block can become several machine blocks (switch lowering, stack-protector checks), and with FastISel enabled the DAG covers only the tail that FastISel could not select |
| Cross-block values | Never DAG edges. They travel through virtual registers using CopyToReg and CopyFromReg nodes |
SelectionDAGISel::SelectAllBasicBlocks walks the function's blocks in reverse post-order and calls SelectBasicBlock for each, which builds the DAG and runs the phases in CodeGenAndEmitDAG.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1656-1971, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:884-908
| Component | Class or function | File | Role |
|---|---|---|---|
| Driver |
SelectionDAGISel, CodeGenAndEmitDAG
|
SelectionDAGISel.cpp |
Runs the phases for each block |
| IR to DAG | SelectionDAGBuilder::visit* |
SelectionDAGBuilder.cpp |
One visitor per IR instruction |
| Optimiser | DAGCombiner::Run |
DAGCombiner.cpp |
Worklist peephole optimiser, run up to four times |
| Type legalizer | DAGTypeLegalizer::run |
LegalizeTypes.cpp and siblings |
Promote, expand, split, widen types |
| Operation legalizer |
SelectionDAG::Legalize, SelectionDAGLegalize
|
LegalizeDAG.cpp |
Legal, Custom, Expand, LibCall, Promote |
| Vector legalizer | VectorLegalizer::Run |
LegalizeVectorOps.cpp |
Make vector operations supported |
| Matcher |
SelectCodeCommon plus generated tables |
SelectionDAGISel.cpp, AArch64GenDAGISel.inc
|
Pattern matching and node creation |
| Scheduler |
ScheduleDAGRRList and friends |
ScheduleDAGRRList.cpp |
Order machine nodes |
| Emitter | InstrEmitter |
InstrEmitter.cpp |
Create MachineInstrs and virtual registers |
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:947-1200, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:1372-1418, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:1846-1963, llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp:200-487, llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:6328-6375, llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp:207-247, llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp:848-1093
| Role | Class or file | What it provides |
|---|---|---|
| Lowering |
AArch64TargetLowering in AArch64ISelLowering.cpp
|
Legal types and operations (setOperationAction), LowerOperation, ReplaceNodeResults, PerformDAGCombine, argument, call and return lowering |
| Selector |
AArch64DAGToDAGISel in AArch64ISelDAGToDAG.cpp
|
Custom Select, ComplexPattern implementations, tryIndexedLoad, tryBitfieldExtractOp
|
| Patterns |
AArch64InstrInfo.td, AArch64InstrFormats.td
|
Instruction definitions with embedded patterns, standalone Pat<> records, AArch64ISD:: node definitions |
| Node info | AArch64SelectionDAGInfo.h |
In current LLVM the AArch64ISD:: enum is generated into AArch64GenSDNodeInfo.inc from the SDNode records; older releases declare it by hand |
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:460-554, llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:5096-5173, llvm/lib/Target/AArch64/AArch64SelectionDAGInfo.h:10-25
On AArch64 the selector depends on the optimisation level. AArch64TargetMachine enables GlobalISel when the optimisation level is at or below -aarch64-enable-global-isel-at-O (default 0, so -O0), and otherwise the pipeline uses SelectionDAG through AArch64PassConfig::addInstSelector, which adds the AArch64ISelDag pass.
Observed with llc 23.1.4 (-debug-pass=Structure): at -O2 the pass list contains the GlobalISel passes (IRTranslator, Legalizer, RegBankSelect, InstructionSelect) followed by AArch64 Instruction Selection, but the IRTranslator immediately marks the function as failed, so the SelectionDAG pass does the work and -global-isel-abort=2 reports "Instruction selection used fallback path". At -O0, -global-isel-abort=1 produces no error, so GlobalISel selects the function.
Sources: llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:159-162, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:404-418, llvm/lib/Target/AArch64/AArch64TargetMachine.cpp:766-776
| # | Phase | Result | Page |
|---|---|---|---|
| 1 | Build the DAG from IR | Generic ISD:: nodes, any type |
DAG Construction |
| 2 | DAG Combine 1 | Simplified DAG | DAG Combiner |
| 3 | Type legalization (then Combine 2) | Every value type is legal | Type Legalization |
| 4 | Vector legalization (then types and Combine 3 if it changed anything) | Vector operations supported | Operation and Vector Legalization |
| 5 | Operation legalization | Every operation Legal or custom-lowered | Operation and Vector Legalization |
| 6 | DAG Combine 4 | Legal DAG, cleaned up | DAG Combiner |
| 7 | Instruction selection | Machine nodes | Instruction Selection |
| 8 | Scheduling and emission | Linear MachineInstrs |
Scheduling and MIR Emission |
The exact order, the traversal each phase uses and a sequence diagram are on Pipeline, Phases and Traversal Orders. PHI handling spans several phases and has its own page: PHI Node Resolution.
- New to the codebase: Core Data Structures, then follow the pages in order.
- Interested in AArch64 behaviour: AArch64 Walkthroughs, starting with the End-to-End Example.
- Adding a pattern, combine or lowering: Tooling, Debugging and Extending.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look