Skip to content

SelectionDAG 04 dag combiner

Mugundan edited this page Nov 27, 2026 · 1 revision

DAG Combiner

Relevant source files

The following files were used as context for generating this wiki page:

DAGCombiner is the DAG's peephole optimiser: a worklist algorithm that rewrites nodes until nothing more fires. It runs up to four times during selection, each time with different rules about what it may create.

Purpose and Scope

This page describes the DAGCombiner::Run algorithm, the four combine levels, the categories of folds, the AArch64 target hooks, and three worked examples. It is not a single top-to-bottom pass, and not a fixed-point loop over the whole graph either: only nodes touched by a change are revisited.

The Algorithm

flowchart TD
  S["Seed worklist with every node in AllNodes order"] --> P["Pop node N from the back"]
  P --> D{"N has no users?"}
  D -- yes --> DEL["Delete N and re-queue its operands"]
  DEL --> P
  D -- no --> LG{"Level is AfterLegalizeDAG?"}
  LG -- yes --> RL["Re-legalize N"]
  RL --> Q
  LG -- no --> Q["Queue N's operands that were not combined before"]
  Q --> C["combine of N"]
  C --> R{"Replacement found?"}
  R -- no --> P
  R -- yes --> REP["ReplaceAllUsesWith, queue the new node and all its users"]
  REP --> P
Loading
  1. Seed. Every node in DAG.allnodes() is pushed on a worklist. With -combiner-topological-sorting (or when the target's useTopologicalSorting() says so) the DAG is first sorted and pushed in reverse. Each node stores its worklist index in the node itself; -2 means already combined once.
  2. Pop from the back. The worklist is a vector used as a stack, so the node created last (normally the root) is processed first.
  3. Dead node? A popped node with no users is deleted and its operands are queued again.
  4. After legalization only: at AfterLegalizeDAG the node is first re-legalized with DAG.LegalizeOp, so combines never see an illegal node.
  5. Queue the operands that have not been combined yet. Because the list is last-in-first-out, the operands are visited next: the walk descends from users toward operands.
  6. combine(N), stopping at the first success:
    1. the generic visit(N), one visitXxx per opcode;
    2. the target hook TLI.PerformDAGCombine(N, DCI), called only if the target registered the opcode with setTargetDAGCombine (or N is a target opcode);
    3. operation promotion (PromoteIntBinOp and friends);
    4. for commutative operations, reuse of an existing operand-swapped node.
  7. Replace. If a replacement RV came back, ReplaceAllUsesWith(N, RV) rewires every user, and the new node and all its users go on the worklist. A dead N is deleted.

Two consequences follow. A pattern rooted at a user sees its operands in their original shape, and when an operand later simplifies the user is re-queued for a second look. And termination relies on every fold making the DAG better by some measure: two folds that undo each other make llc hang.

Uniquing (see Core Data Structures) makes common-subexpression elimination implicit.

Sources: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:1846-1963, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:235-252, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:274-294, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:2152-2222

The Four Invocations

The CombineLevel enum is in DAGCombine.h. Run derives LegalTypes, LegalOperations and LegalDAG from it (see the table on Pipeline, Phases and Traversal Orders).

Run Level Runs Illegal types allowed? Illegal operations allowed?
1 BeforeLegalizeTypes always yes yes
2 AfterLegalizeTypes only if type legalization changed the DAG no yes
3 AfterLegalizeVectorOps only if vector legalization changed the DAG no no
4 AfterLegalizeDAG always no no

Combines guard themselves with the flags, for example if (!LegalOperations || TLI.isOperationLegal(ISD::ROTL, VT)), so a fold never introduces something the target cannot select. TargetLowering::DAGCombinerInfo exposes isBeforeLegalize(), isBeforeLegalizeOps() (true for levels 1 and 2) and isAfterLegalizeDAG() to target code.

Sources: llvm/include/llvm/CodeGen/DAGCombine.h:15-20, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:1846-1851, llvm/include/llvm/CodeGen/TargetLowering.h:4574-4587

What the Combines Do

Category Example fold Where
Constant folding add 3, 4 becomes 7 getNode folds on creation
Identities x + 0, x * 1, x & -1, x ^ x visitADD, visitMUL, ...
Reassociation (x + c1) + c2 becomes x + (c1 + c2) reassociateOps
Strength reduction mul x, 8 becomes shl x, 3; udiv x, c becomes multiply-high and shifts visitMUL, visitUDIV
Extension folding zext (load i8) becomes a ZEXTLOAD; trunc (zext x) becomes x visitZERO_EXTEND, visitTRUNCATE
Demanded bits Remove masks or extensions whose bits no user reads SimplifyDemandedBits
Compare and select select (setcc a, b, cc), x, y becomes select_cc a, b, x, y, cc when SELECT_CC is legal or Custom; brcond (setcc ...) becomes br_cc visitSELECT, visitBRCOND
Memory Store-to-load forwarding, store merging, load narrowing, forming pre/post-indexed loads and stores visitLOAD, visitSTORE, CombineToPreIndexedLoadStore, CombineToPostIndexedLoadStore
Vectors Fold extract_vector_elt (build_vector ...), merge shuffles, detect splats visitEXTRACT_VECTOR_ELT, visitVECTOR_SHUFFLE

Sources: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:13243-13440, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:376-377, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:4868

AArch64 Target Combines

AArch64TargetLowering registers the opcodes it wants with setTargetDAGCombine in its constructor, and PerformDAGCombine is a switch over N->getOpcode() that dispatches to specialised functions: performAddSubCombine, performMulCombine, performANDCombine, performORCombine, performSelectCombine, performSETCCCombine, performLOADCombine, performSTORECombine, performExtendCombine, performBRCONDCombine, performTBZCombine and more. They match target-aware shapes the generic combiner cannot know, such as turning mul x, (2^n + 1) into add (shl x, n), x.

Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:1188-1205, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:30803-31168

Example 1: x * 9

performMulCombine returns early while DCI.isBeforeLegalizeOps() is true, so the fold fires in the later runs. It sees that 9 is 2^3 + 1 and rewrites:

before:  t5: i32 = mul t2, Constant:i32<9>
after:   t6: i32 = shl t2, Constant:i64<3>
         t7: i32 = add t2, t6            ; replaces t5 for all users

Instruction Selection then matches the add plus shl to a single ADDWrs. Real llc output confirms it: the MIR contains only ADDWrs %0, %0, 3 and the assembly is add w0, w0, w0, lsl #3.

Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:21202-21213, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:21266-21306

Example 2: x / 10 (unsigned 32-bit)

The generic visitUDIV replaces division by a constant with multiplication by a magic reciprocal (TargetLowering::BuildUDIV). AArch64 has a fast 32 by 32 to 64 multiply, so the result is a widening multiply and a shift:

t3: i32 = udiv t2, Constant:i32<10>
  ==>
t7: i64 = zero_extend t2
t9: i64 = mul t7, Constant:i64<3435973837>      ; 0xCCCCCCCD
t10: i64 = srl t9, Constant:i64<35>
t11: i32 = truncate t10

The real post-selection MIR matches: MOVi32imm -858993459 (the same constant as a signed 32-bit value), UMADDLrrr %0, killed %1, $xzr, UBFMXri killed %2, 35, 63, then a sub_32 copy for the truncate.

Example 3: Post-Indexed Load Formation

In the loop of PHI Node Resolution the IR is a load i32, ptr %p followed in the same iteration by getelementptr i8, ptr %p, i64 4. CombineToPostIndexedLoadStore asks the target getPostIndexedAddressParts; AArch64 answers yes for a small constant offset, so the load and the pointer add merge into one indexed load node that produces both the loaded value and the incremented pointer. AArch64 Instruction Selection shows it selected as LDRWpost.

Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:31289-31350

Switches That Help When Debugging

-combiner-disabled turns the generic combiner off (a quick check for whether a miscompile comes from a combine), -combiner-topological-sorting changes the visit order, -combiner-global-alias-analysis lets store and load combines use IR alias analysis, and -combiner-store-merging=false disables store merging. -debug-counter=dagcombine-skip=N,dagcombine-count=M bisects combines in assertion builds. See Tooling, Debugging and Extending.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally