Repository navigation
Register Allocation 04.1 phi two address
Relevant source files
The following files were used as context for generating this wiki page:
This page explains what each pass produces, why, and which target hooks affect it. The SelectionDAG side of PHIs (how they are created) is not covered here.
A PHI picks a value depending on which predecessor block control came from:
bb.1.loop:
%0:gpr64all = PHI %6, %bb.0, %3, %bb.1
No CPU has such an instruction. The value has to be placed in one agreed register before control reaches bb.1, on every incoming edge.
For each PHI result %d, PHIEliminationImpl::LowerPHINode:
- creates a new virtual register
%t(the "incoming" register); - at the end of each predecessor (before its terminator), inserts
%t = COPY <value from that predecessor>; - replaces the
PHIwith%d = COPY %tat the top of the block; - updates
LiveVariableskill flags (andLiveIntervals, if it already exists).
In the loop from Preparing Code for Allocation, the result is exactly what the two-address dump shows:
bb.0.entry:
...
%15:gpr64common = COPY killed %6 ; incoming copy on edge bb.0 -> bb.1
%16:gpr32 = COPY killed %7
bb.1.loop:
%1:gpr32 = COPY killed %16 ; PHI replaced by a copy
%0:gpr64common = COPY killed %15
...
%15:gpr64common = COPY killed %3 ; incoming copy on edge bb.1 -> bb.1
%16:gpr32 = COPY %2
%15 and %16 now have two definitions each, one per incoming edge. This is the point where MIR stops being SSA.
If a predecessor has several successors and the PHI's block has several predecessors, the edge between them is critical. A copy placed at the end of the predecessor would also run on its other outgoing edges, extending a live range where it is not needed. PHIEliminationImpl::SplitPHIEdges may split such edges (insert a new block) so copies go only where they are needed. It uses MachineLoopInfo to decide, which is why addOptimizedRegAlloc adds MachineLoopInfo just before PHI elimination ("Edge splitting is smarter with machine loop info").
None directly. PHI elimination uses only target-independent COPYs; turning a COPY into a real move instruction happens much later through TargetInstrInfo::copyPhysReg (see TargetInstrInfo Hooks).
Sources: llvm/lib/CodeGen/PHIElimination.cpp:236, llvm/lib/CodeGen/PHIElimination.cpp:319, llvm/lib/CodeGen/PHIElimination.cpp:367, llvm/lib/CodeGen/PHIElimination.cpp:803, llvm/lib/CodeGen/TargetPassConfig.cpp:1513-1515
Many instruction sets (x86 most famously, and some instructions on every target) have two-address instructions: the destination register must be the same as one of the sources. add eax, ebx computes eax = eax + ebx; there is no way to write the result elsewhere.
TableGen expresses this as a constraint on the instruction definition:
let Constraints = "$dst = $src1" in
def ADD32rr : ... (outs GR32:$dst), (ins GR32:$src1, GR32:$src2) ...
In SSA MIR, the result and the tied input are still different virtual registers, and the tie is shown with tied-def:
%2:gr32 = ADD32rr %0(tied-def 0), %1
On AArch64 this is rarer: most instructions are three-address. Tied operands appear on instructions such as MOVK (insert 16 bits into an existing register), BFM/BFI (bitfield insert), many NEON accumulate forms (MLA, FMLA) and SVE destructive operations.
The example below is illustrative (x86-style), not llc output. Given
%2 = ADD32rr %0(tied-def 0), %1
... %0 used later ...
the allocator cannot simply give %2 and %0 the same register, because %0 is still needed afterwards. Two-address lowering rewrites it to
%2 = COPY %0
%2 = ADD32rr %2(tied-def 0), %1
After this, the instruction reads and writes the same virtual register, the constraint holds by construction, and the code is no longer SSA (%2 has two definitions). This is the TiedOpsRewritten property printed in MIR dumps.
If %0 is killed at the instruction (not used afterwards), the copy is still inserted, but the coalescer will almost always remove it, because %0 and %2 do not overlap.
Before falling back to a copy, TwoAddressInstructionImpl::tryInstructionTransform tries cheaper options:
| Trick | Function | Target hook it needs |
|---|---|---|
| Commute the instruction so the tied operand is a source that dies here |
tryInstructionCommute, isProfitableToCommute
|
TargetInstrInfo::findCommutedOpIndices, commuteInstructionImpl (instruction marked isCommutable = 1) |
Convert to three-address form (e.g. x86 ADD to LEA) |
convertInstTo3Addr |
TargetInstrInfo::convertToThreeAddress (instruction marked isConvertibleToThreeAddress = 1) |
| Reschedule the instruction below the last use of the source, so the source dies at it | rescheduleMIBelowKill |
none |
Then processTiedPairs inserts whatever copies are still needed.
- Declare tied operands with
Constraints = "$dst = $src"in the instruction definition. Do not try to enforce the constraint yourself in instruction selection. - Mark commutable instructions
isCommutable = 1. If the commutable operands are not simply operands 1 and 2, overridefindCommutedOpIndices. - If your target has a three-address equivalent for some two-address instruction, set
isConvertibleToThreeAddress = 1and implementconvertToThreeAddress. - Use
@earlyclobber $dst(in theConstraintsstring) for results that must not share a register with any input. This is the opposite constraint and is handled by liveness, not by this pass (see Liveness).
Sources: llvm/lib/CodeGen/TwoAddressInstructionPass.cpp:647, llvm/lib/CodeGen/TwoAddressInstructionPass.cpp:800, llvm/lib/CodeGen/TwoAddressInstructionPass.cpp:927, llvm/lib/CodeGen/TwoAddressInstructionPass.cpp:1284, llvm/lib/CodeGen/TwoAddressInstructionPass.cpp:1349, llvm/lib/CodeGen/TwoAddressInstructionPass.cpp:1592, llvm/lib/CodeGen/TwoAddressInstructionPass.cpp:1878, llvm/include/llvm/CodeGen/TargetInstrInfo.h:235, llvm/include/llvm/CodeGen/TargetInstrInfo.h:519, llvm/include/llvm/CodeGen/TargetInstrInfo.h:569
| PHI elimination | Two-address lowering | |
|---|---|---|
| Input | SSA MIR with PHIs |
SSA MIR with tied operands |
| Output |
COPYs on incoming edges; registers with several definitions |
Tied def and use are the same register; COPY before the instruction when needed |
| Ends SSA? | Yes | Yes |
| Target hooks | None | Commute, convert-to-three-address |
| Cleaned up by | Register coalescer | Register coalescer |
- 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