Repository navigation
SelectionDAG 06 instruction selection
Relevant source files
The following files were used as context for generating this wiki page:
This page covers the traversal and the per-node dispatch of DoInstructionSelection. The pattern language and the build-time generator are on TableGen Pattern Language; the interpreter that runs the generated matcher and the folding rules are on Matcher Interpreter and Folding; AArch64's hand-written parts are on AArch64 Instruction Selection.
SelectionDAGISel::DoInstructionSelection does the following (verified in SelectionDAGISel.cpp):
flowchart TD
A["PreprocessISelDAG"] --> B["AssignTopologicalOrder<br/>number every node"]
B --> C["HandleSDNode keeps the root alive"]
C --> D["Start at the last node of AllNodes, the root"]
D --> E{"Node has users?"}
E -- no --> F["Skip, it is dead"]
E -- yes --> G["Select of Node"]
F --> H{"More nodes toward the entry?"}
G --> H
H -- yes --> D
H -- no --> I["PostprocessISelDAG"]
-
PreprocessISelDAG(): an optional target hook. -
CurDAG->AssignTopologicalOrder(): number every node so operands have smaller ids than users. - Walk
AllNodesbackward from the root toEntryToken. Skip a node with no users (dead; nodes folded into an earlier selection become dead this way), lower strict-FP nodes to plain ones if the target lacks them, then callSelect(Node). -
PostprocessISelDAG(): another optional hook.
The backward order is deliberate. When add is selected first, its operand shl is still a generic node, so the pattern add x, (shl y, 3) can see it and absorb it into a single ADDWrs. If operands were selected first, the shl would already be a separate UBFM instruction. An ISelUpdater keeps the iterator valid while nodes are deleted or replaced, and node ids are a safety net: a selected node gets id -1, and the code asserts that no unselected node has a selected predecessor.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1287-1392, llvm/include/llvm/CodeGen/SelectionDAGISel.h:143
AArch64DAGToDAGISel::Select(SDNode *Node) runs three tiers:
flowchart TD
N["Select of Node"] --> M{"Already a machine node?"}
M -- yes --> M1["Mark selected, done"]
M -- no --> S{"Opcode handled in the C++ switch?"}
S -- yes --> T["tryXxx helper"]
T --> TR{"Helper succeeded?"}
TR -- yes --> DONE["Replaced, done"]
TR -- no --> G
S -- no --> G["SelectCode of Node<br/>generated matcher"]
G --> GM{"Pattern matched?"}
GM -- yes --> DONE
GM -- no --> ERR["Cannot select error"]
-
Already machine? If
Node->isMachineOpcode(), the node was created pre-selected, so it is marked done. -
Hand-written selection in a C++
switchfor cases the pattern language cannot express well:ISD::LOADcallstryIndexedLoad;SRL,AND,SRA,SIGN_EXTEND_INREGtrytryBitfieldExtractOp;ORtriestryBitfieldInsertOp; atomics, system registers,EXTRACT_SUBVECTORand NEON/SVE load-store intrinsics have their own helpers. -
Generated matcher. Anything left goes to
SelectCode(Node)at the end of the switch.
SelectCodeCommon first accepts, without patterns, node kinds that are already in final form: EntryToken, Register, CopyFromReg, CopyToReg, TokenFactor, TargetConstant, TargetGlobalAddress, BasicBlock and similar. It turns UNDEF into IMPLICIT_DEF and handles INLINEASM specially.
Sources: llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:5096-5173, llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:7754, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:3354-3443
When the backward sweep ends the DAG consists of machine nodes plus the structural nodes (CopyToReg, CopyFromReg, TokenFactor, EntryToken). -debug-only=isel prints it as Selected selection DAG. It is still a graph: nothing says in which order independent instructions must appear. That is the scheduler's job; see Scheduling and MIR Emission.
Some familiar AArch64 optimisations are not SelectionDAG decisions. In real output the fused multiply-add and load/store pairs appear only later:
-
a*b + cis selected asMADDWrrr %0, %1, $wzr(a plain multiply) followed byADDWrr. The MachineCombiner pass later fuses them intomadd w0, w0, w1, w2. The source ofperformMulCombinesays so in a comment: "in MachineCombiner pass, add+mul will be combined into madd". - Two adjacent
LDRXuibecomeldp(and twoSTRXuibecomestp) inAArch64LoadStoreOptimizer, after register allocation.
The split is intentional: those fusions depend on register pressure, scheduling and pairing rules that the DAG cannot see.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:21215-21217, llvm/lib/Target/AArch64/AArch64InstrInfo.td:2911-2921
- 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