Repository navigation
SelectionDAG 07 scheduling emission
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/ScheduleDAGSDNodes.cpp
- llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp
- llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp
- llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
- llvm/lib/Target/AArch64/AArch64Subtarget.h
- llvm/include/llvm/CodeGen/TargetSubtargetInfo.h
This page covers phases 6 and 7 of the pipeline: choosing the scheduler, building the scheduling graph, list scheduling, and InstrEmitter. It is the step where the graph becomes the linear MIR you see in -stop-after dumps.
CodeGenAndEmitDAG calls CreateScheduler(), which honours the -pre-RA-sched= option (default: createDefaultScheduler). That function decides in this order:
- If the subtarget supplies its own DAG scheduler (
getDAGScheduler), use it. - If the optimisation level is
-O0, or the subtarget enables the MachineScheduler and lets it be the default (enableMachineScheduler() && enableMachineSchedDefaultSched()), or the target's preference isSched::Source: use the source-order list scheduler. - Otherwise pick by
TLI->getSchedulingPreference():RegPressuregives the bottom-up register-pressure scheduler, thenHybrid,VLIW,Fast,Linearize, or by defaultILP.
On AArch64, AArch64Subtarget::enableMachineScheduler() returns true and the base class returns true for enableMachineSchedDefaultSched(), so rule 2 applies even though the constructor calls setSchedulingPreference(Sched::Hybrid). The DAG scheduler on AArch64 therefore keeps instructions in roughly the original IR order, and the performance scheduling is left to the MachineScheduler that runs later on MIR with real latency and resource models.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:301-330, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1164-1183, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:1276, llvm/lib/Target/AArch64/AArch64Subtarget.h:160, llvm/include/llvm/CodeGen/TargetSubtargetInfo.h:210-214
flowchart LR
R["ScheduleDAGSDNodes::Run"] --> S["Schedule"]
S --> U["BuildSchedUnits<br/>one SUnit per node, glued nodes merged"]
U --> E["AddSchedEdges<br/>data, order, physreg edges"]
E --> L["ListScheduleBottomUp<br/>priority queue from the exit node"]
L --> V["Reverse the sequence"]
V --> EM["EmitSchedule<br/>InstrEmitter per SUnit"]
-
BuildSchedUnitscreates anSUnitper node, but nodes joined by glue are merged into one unit, since glue means "emit these back to back". For example, theCopyToRegnodes that place outgoing arguments in registers and theBLthat reads them form one unit. -
AddSchedEdgesadds dependency edges (SDep): data edges for operands, order edges for chains, and physical-register edges where an instruction implicitly defines or uses a register (such asNZCV). Latencies come from the target's itineraries or scheduling model when available. - Each
SUnitrecords a source-order number (SDNodeOrderfrom the builder), used as the tie-breaker.
Sources: llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp:55-65, llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp:324-439, llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp:441-530
ScheduleDAGRRList::ListScheduleBottomUp builds the order from the bottom: it starts at the exit unit (the root) and repeatedly picks one available unit (one whose users have all been scheduled) from a priority queue, schedules it, then makes its operands available. The priority function for the source-order variant (src_ls_rr_sort) prefers the node with the higher source order, so the bottom-up walk reproduces the program order. At the end the sequence is reversed (std::reverse(Sequence...)) to get top-down order. The other variants add heuristics for register pressure, ILP, and two-address and physical-register constraints.
Sources: llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp:1580-1621, llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp:1662-1673
ScheduleDAGSDNodes::EmitSchedule creates an InstrEmitter positioned in the MachineBasicBlock, then for each SUnit in Sequence emits its node(s) with Emitter.EmitNode. What each node kind becomes:
| Node | Emitted as |
|---|---|
Machine node (ADDWrr, LDRWui, BL, ...) |
EmitMachineNode: a MachineInstr built from the instruction's descriptor. Defs get a new virtual register whose register class comes from the instruction's operand constraint (gpr32, gpr64, fpr128); uses come from VRBaseMap (a map from (SDNode, result number) to its vreg); constants become immediate operands; MachineMemOperands and IR flags are attached |
CopyToReg dst, src |
A COPY into dst (a physical register such as $w0, or a virtual register for a value that leaves the block). If the source is IMPLICIT_DEF, an IMPLICIT_DEF instruction instead |
CopyFromReg src |
If src is virtual: no instruction; the node's result aliases that vreg in VRBaseMap. If physical: a COPY from it into a fresh vreg |
COPY_TO_REGCLASS, EXTRACT_SUBREG, INSERT_SUBREG, SUBREG_TO_REG, REG_SEQUENCE
|
COPY with subregister indices or the right register class (special-cased in EmitSubregNode, EmitRegSequence) |
EntryToken, TokenFactor
|
Nothing: they only carried ordering |
Two details explain visible features of MIR (as produced by the 23.1.4 llc the examples use):
-
Kill flags. In
AddRegisterOperanda use is markedkilledwhen its defining node has a single use, is not aCopyFromReg, and the instruction operand is not tied. That is why%3iskilledinADDWrr killed %3, %2below while%0and%1, which come fromCopyFromReg, never are. -
Register class constraints. For each virtual-register use the emitter calls
MRI->constrainRegClassto narrow the class of the vreg to what the instruction accepts, or inserts aCOPYinto a new vreg if narrowing is impossible. This is why an incoming pointer becomes%0:gpr64common(a class that excludesxzr, which cannot be a base address) in load examples, while ani64argument that is only added staysgpr64.
Sources: llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp:848-1093, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:88-183, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:185-263, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:340-392, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:503-634, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:1003-1258, llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp:1263-1310
After all blocks of the function have been selected, SelectionDAGISel::runOnMachineFunction calls MachineRegisterInfo::EmitLiveInCopies for the entry block. It inserts one COPY per live-in physical register at the very top, each placed at the block's beginning, which is why they appear in reverse (%2 = COPY $w2, %1 = COPY $w1, %0 = COPY $w0). A later pass, finalize-isel ("Finalize ISel and expand pseudo-instructions"), handles instructions that need a custom inserter and applies post-ISel hooks.
Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:688
The DAG from Core Data Structures after selection, scheduling and emission produces exactly this MIR (real output from llc -mtriple=aarch64 -O2 -stop-after=finalize-isel):
bb.0 (%ir-block.0):
liveins: $w0, $w1, $w2
%2:gpr32 = COPY $w2 ; live-in copies, inserted at the top, in reverse
%1:gpr32 = COPY $w1
%0:gpr32 = COPY $w0
%3:gpr32 = MADDWrrr %0, %1, $wzr ; mul a, b (a multiply is a MADD with the zero register)
%4:gpr32 = ADDWrr killed %3, %2 ; add, %3 is single-use so it is killed
$w0 = COPY %4 ; CopyToReg $w0
RET_ReallyLR implicit $w0 ; AArch64ISD::RET_GLUE, glued to the copy
Every MIR instruction maps back to one DAG node: three CopyFromReg (which became no instruction; the COPYs at the top are the live-in copies of the physical registers, and %0..%2 are the vregs they alias), the mul, the add, the CopyToReg, and the glued return.
- 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