LLVM 24.0.0git
OptimizePHIs.cpp
Go to the documentation of this file.
1//===- OptimizePHIs.cpp - Optimize machine instruction PHIs ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass optimizes machine instruction PHIs to take advantage of
10// opportunities created during DAG legalization.
11//
12//===----------------------------------------------------------------------===//
13
16#include "llvm/ADT/Statistic.h"
24#include "llvm/Pass.h"
25#include <cassert>
26
27using namespace llvm;
28
29#define DEBUG_TYPE "opt-phis"
30
31STATISTIC(NumPHICycles, "Number of PHI cycles replaced");
32STATISTIC(NumDeadPHICycles, "Number of dead PHI cycles");
33
34namespace {
35
36class OptimizePHIs {
37 MachineRegisterInfo *MRI = nullptr;
38
39public:
40 bool run(MachineFunction &Fn);
41
42private:
43 using InstrSet = SmallPtrSet<MachineInstr *, 16>;
44
45 bool IsSingleValuePHICycle(MachineInstr *MI, Register &SingleValReg,
46 InstrSet &PHIsInCycle);
47 bool IsDeadPHICycle(MachineInstr *MI, InstrSet &PHIsInCycle);
48 bool OptimizeBB(MachineBasicBlock &MBB);
49};
50
51class OptimizePHIsLegacy : public MachineFunctionPass {
52public:
53 static char ID;
54 OptimizePHIsLegacy() : MachineFunctionPass(ID) {}
55
56 bool runOnMachineFunction(MachineFunction &MF) override {
57 if (skipFunction(MF.getFunction()))
58 return false;
59 OptimizePHIs OP;
60 return OP.run(MF);
61 }
62
63 void getAnalysisUsage(AnalysisUsage &AU) const override {
64 AU.setPreservesCFG();
65 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
67 }
68};
69} // end anonymous namespace
70
71char OptimizePHIsLegacy::ID = 0;
72
73char &llvm::OptimizePHIsLegacyID = OptimizePHIsLegacy::ID;
74
75INITIALIZE_PASS(OptimizePHIsLegacy, DEBUG_TYPE,
76 "Optimize machine instruction PHIs", false, false)
77
80 OptimizePHIs OP;
81 if (!OP.run(MF))
84 PA.preserveSet<CFGAnalyses>();
85 PA.preserve<MachineRegisterClassAnalysis>();
86 return PA;
87}
88
89bool OptimizePHIs::run(MachineFunction &Fn) {
90 MRI = &Fn.getRegInfo();
91
92 // Find dead PHI cycles and PHI cycles that can be replaced by a single
93 // value. InstCombine does these optimizations, but DAG legalization may
94 // introduce new opportunities, e.g., when i64 values are split up for
95 // 32-bit targets.
96 bool Changed = false;
97 for (MachineBasicBlock &MBB : Fn)
98 Changed |= OptimizeBB(MBB);
99
100 return Changed;
101}
102
103/// IsSingleValuePHICycle - Check if MI is a PHI where all the source operands
104/// are copies of SingleValReg, possibly via copies through other PHIs. If
105/// SingleValReg is zero on entry, it is set to the register with the single
106/// non-copy value. PHIsInCycle is a set used to keep track of the PHIs that
107/// have been scanned. PHIs may be grouped by cycle, several cycles or chains.
108bool OptimizePHIs::IsSingleValuePHICycle(MachineInstr *MI,
109 Register &SingleValReg,
110 InstrSet &PHIsInCycle) {
111 assert(MI->isPHI() && "IsSingleValuePHICycle expects a PHI instruction");
112 Register DstReg = MI->getOperand(0).getReg();
113
114 // See if we already saw this register.
115 if (!PHIsInCycle.insert(MI).second)
116 return true;
117
118 // Don't scan crazily complex things.
119 if (PHIsInCycle.size() == 16)
120 return false;
121
122 // Scan the PHI operands.
123 for (unsigned i = 1; i != MI->getNumOperands(); i += 2) {
124 Register SrcReg = MI->getOperand(i).getReg();
125 if (SrcReg == DstReg)
126 continue;
127 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg);
128
129 // Skip over register-to-register moves.
130 if (SrcMI && SrcMI->isCopy() && !SrcMI->getOperand(0).getSubReg() &&
131 !SrcMI->getOperand(1).getSubReg() &&
132 SrcMI->getOperand(1).getReg().isVirtual()) {
133 SrcReg = SrcMI->getOperand(1).getReg();
134 SrcMI = MRI->getVRegDef(SrcReg);
135 }
136 if (!SrcMI)
137 return false;
138
139 if (SrcMI->isPHI()) {
140 if (!IsSingleValuePHICycle(SrcMI, SingleValReg, PHIsInCycle))
141 return false;
142 } else {
143 // Fail if there is more than one non-phi/non-move register.
144 if (SingleValReg && SingleValReg != SrcReg)
145 return false;
146 SingleValReg = SrcReg;
147 }
148 }
149 return true;
150}
151
152/// IsDeadPHICycle - Check if the register defined by a PHI is only used by
153/// other PHIs in a cycle.
154bool OptimizePHIs::IsDeadPHICycle(MachineInstr *MI, InstrSet &PHIsInCycle) {
155 assert(MI->isPHI() && "IsDeadPHICycle expects a PHI instruction");
156 Register DstReg = MI->getOperand(0).getReg();
157 assert(DstReg.isVirtual() && "PHI destination is not a virtual register");
158
159 // See if we already saw this register.
160 if (!PHIsInCycle.insert(MI).second)
161 return true;
162
163 // Don't scan crazily complex things.
164 if (PHIsInCycle.size() == 16)
165 return false;
166
167 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DstReg)) {
168 if (!UseMI.isPHI() || !IsDeadPHICycle(&UseMI, PHIsInCycle))
169 return false;
170 }
171
172 return true;
173}
174
175/// OptimizeBB - Remove dead PHI cycles and PHI cycles that can be replaced by
176/// a single value.
177bool OptimizePHIs::OptimizeBB(MachineBasicBlock &MBB) {
178 bool Changed = false;
180 MII = MBB.begin(), E = MBB.end(); MII != E; ) {
181 MachineInstr *MI = &*MII++;
182 if (!MI->isPHI())
183 break;
184
185 // Check for single-value PHI cycles.
186 Register SingleValReg;
187 InstrSet PHIsInCycle;
188 if (IsSingleValuePHICycle(MI, SingleValReg, PHIsInCycle) && SingleValReg) {
189 Register OldReg = MI->getOperand(0).getReg();
190 if (!MRI->constrainRegClass(SingleValReg, MRI->getRegClass(OldReg)))
191 continue;
192
193 MRI->replaceRegWith(OldReg, SingleValReg);
194 MI->eraseFromParent();
195
196 ++NumPHICycles;
197 Changed = true;
198 continue;
199 }
200
201 // Check for dead PHI cycles.
202 PHIsInCycle.clear();
203 if (IsDeadPHICycle(MI, PHIsInCycle)) {
204 for (MachineInstr *PhiMI : PHIsInCycle) {
205 if (MII == PhiMI)
206 ++MII;
207 PhiMI->eraseFromParent();
208 }
209 ++NumDeadPHICycles;
210 Changed = true;
211 }
212 }
213 return Changed;
214}
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define DEBUG_TYPE
IRTranslator LLVM IR MI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
#define OP(OPC)
Definition Instruction.h:46
This file defines the SmallPtrSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
bool isCopy() const
const MachineOperand & getOperand(unsigned i) const
unsigned getSubReg() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This is an optimization pass for GlobalISel generic memory operations.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI char & OptimizePHIsLegacyID
OptimizePHIs - This pass optimizes machine instruction PHIs to take advantage of opportunities create...