Repository navigation
SelectionDAG 03 dag construction
Relevant source files
The following files were used as context for generating this wiki page:
This page covers phase 1: the driver loop, the translation of each IR instruction, chain handling while building, cross-block values and function arguments. PHI handling during construction is summarised here and detailed in PHI Node Resolution.
flowchart TD
A["runOnMachineFunction"] --> B["FunctionLoweringInfo::set<br/>vregs, MBBs, empty machine PHIs"]
B --> C["SelectAllBasicBlocks"]
C --> D["LowerArguments<br/>entry block only"]
C --> E["for each block in reverse post-order"]
E --> F["SelectBasicBlock"]
F --> G["SDB visit for each instruction"]
G --> H["CodeGenAndEmitDAG"]
E --> I["FinishBasicBlock<br/>patch successor PHIs, switch extras"]
-
FunctionLoweringInfo::setcreates oneMachineBasicBlockper IR block, assigns virtual registers to values used outside their block or by a PHI, and creates an empty machinePHIfor every live IR PHI. -
SelectAllBasicBlocksvisits blocks in reverse post-order. For the entry block it first callsLowerArguments, which calls the target'sLowerFormalArguments. -
SelectBasicBlock(Begin, End)callsSDB->visit(*I)for each instruction, sets the DAG root togetControlRoot(), and callsCodeGenAndEmitDAG(). -
FinishBasicBlockattaches PHI operands, handles switch-lowering extras (jump tables, bit tests, stack-protector blocks) and runsCodeGenAndEmitDAGagain for any extra machine block it created.
One IR block normally yields one DAG, but it can become several machine blocks, and with FastISel only the part FastISel could not select is built as a DAG.
Sources: llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:86-335, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1656-1971, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:884-908, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1974-2227
SelectionDAGBuilder::visit(const Instruction&) dispatches on the IR opcode. After visiting a non-terminator it calls CopyToExportRegsIfNeeded, and just before a terminator it calls HandlePHINodesInSuccessorBlocks.
| LLVM IR | Builder function | Initial DAG node(s) |
|---|---|---|
add, sub, mul, and, or, xor, shl, lshr, ashr
|
visitBinary |
ISD::ADD, SUB, MUL, AND, OR, XOR, SHL, SRL, SRA; nsw/nuw/exact become node flags |
sdiv, udiv, srem, urem
|
visitBinary |
ISD::SDIV, UDIV, SREM, UREM
|
icmp |
visitICmp |
ISD::SETCC with result type i1 and a CondCodeSDNode
|
select |
visitSelect |
ISD::SELECT (VSELECT for vectors) |
zext, sext, trunc, bitcast
|
visitZExt ... |
ZERO_EXTEND, SIGN_EXTEND, TRUNCATE, BITCAST
|
getelementptr |
visitGetElementPtr |
ADD ptr, (MUL idx, size); constant indices fold into one offset; a power-of-two size becomes SHL
|
load |
visitLoad |
ISD::LOAD chain, ptr, undef, results (value, chain)
|
store |
visitStore |
ISD::STORE chain, value, ptr, undef, result chain
|
phi |
none | No node. The PHI's virtual register is read with CopyFromReg when used |
br |
visitCondBr, visitUncondBr
|
ISD::BR, or ISD::BRCOND chain, cond, BasicBlock plus ISD::BR
|
call |
visitCall, LowerCallTo
|
The target's LowerCall: CALLSEQ_START, CopyToReg per argument, AArch64ISD::CALL, CALLSEQ_END, CopyFromReg per result |
ret |
visitRet |
The target's LowerReturn: CopyToReg $w0/$x0/$q0 and AArch64ISD::RET_GLUE
|
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:1372-1418, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:3738-3756, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:3808-3833, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:3863-4007, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:4497-4666, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:4740-4862, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:4920-4993, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:2217-2379, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:2840-2926, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:9316-9437
The builder keeps a current root chain and a few pending lists so independent memory operations do not get a false order.
-
Loads are collected in
PendingLoads. A load takes the current chain as input but does not become the new root; the chains are merged with aTokenFactoronly when something needs a full ordering. Two loads can therefore be reordered freely. -
Stores, calls and ABI register copies (return values, outgoing arguments) ask for the root with
getRoot()(stores usegetMemoryRoot()), which first flushesPendingLoadsinto aTokenFactor. They chain on top of the result and become the new root. -
Exports (
CopyToRegfor values leaving the block) are collected inPendingExportsand joined bygetControlRoot(), which becomes the DAG'sRoot.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:1206-1229
getValue(V) checks NodeMap first, then getCopyFromRegs (is there a virtual register for V in FuncInfo.ValueMap?), then builds a constant or other leaf. A value is therefore a direct SDValue in its defining block and a CopyFromReg in any other block.
After each non-terminator, CopyToExportRegsIfNeeded emits a CopyToReg into the value's virtual register if one was assigned. FunctionLoweringInfo::set assigns registers to every value that is used outside its block or by a PHI.
sequenceDiagram
participant FLI as FunctionLoweringInfo
participant SDB as SelectionDAGBuilder
participant DAG as SelectionDAG
FLI->>FLI: InitializeRegForValue for exported values
SDB->>DAG: visit(add) creates the ADD node
SDB->>DAG: CopyToExportRegsIfNeeded emits CopyToReg to vreg
Note over SDB,DAG: another block later
SDB->>DAG: getValue finds vreg in ValueMap, emits CopyFromReg
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:1798-1815, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:2384-2395, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:11860-11884, llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:46-55, llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:392-400
AArch64TargetLowering::LowerFormalArguments runs the calling-convention rules from AArch64CallingConvention.td over the IR argument types. For an argument passed in $w0 it registers a live-in (MF.addLiveIn, returning a vreg such as %0) and creates CopyFromReg Chain, Register:i32 %0. In the final MIR this appears as liveins: $w0 on the block and %0:gpr32 = COPY $w0 at its top; the copies are inserted by MachineRegisterInfo::EmitLiveInCopies after all blocks are selected (see Scheduling and MIR Emission).
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9059-9520, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:12077-12441
define i32 @smin(i32 %a, i32 %b) {
%c = icmp slt i32 %a, %b
%r = select i1 %c, i32 %a, i32 %b
ret i32 %r
}Initial DAG (reconstructed in -debug-only=isel format; node numbers are illustrative):
t0: ch,glue = EntryToken
t2: i32,ch = CopyFromReg t0, Register:i32 %0
t4: i32,ch = CopyFromReg t0, Register:i32 %1
t5: i1 = setcc t2, t4, setlt:ch
t6: i32 = select t5, t2, t4
t8: ch,glue = CopyToReg t0, Register:i32 $w0, t6
t9: ch = AArch64ISD::RET_GLUE t8, Register:i32 $w0, t8:1
AArch64 has no 1-bit registers, so i1 is an illegal type. Here the problem disappears early, because the combiner rewrites select (setcc ...) as select_cc before type legalization starts (see DAG Combiner). A setcc whose i1 result survives is promoted by the type legalizer (see Type Legalization). The example continues on Operation and Vector Legalization.
- 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