blob: a0023feb986cd980021c91fb36f5585a3976e89f [file] [log] [blame]
Evan Chengc6fe3332010-03-02 02:38:24 +00001//===-- MachineCSE.cpp - Machine Common Subexpression Elimination Pass ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs global common subexpression elimination on machine
Evan Chengc5bbba12010-03-02 19:02:27 +000011// instructions using a scoped hash table based value numbering scheme. It
Evan Chengc6fe3332010-03-02 02:38:24 +000012// must be run while the machine function is still in SSA form.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "machine-cse"
17#include "llvm/CodeGen/Passes.h"
18#include "llvm/CodeGen/MachineDominators.h"
19#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng6ba95542010-03-03 02:48:20 +000020#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Chenga5f32cb2010-03-04 21:18:08 +000021#include "llvm/Analysis/AliasAnalysis.h"
Evan Cheng6ba95542010-03-03 02:48:20 +000022#include "llvm/Target/TargetInstrInfo.h"
Evan Chengc6fe3332010-03-02 02:38:24 +000023#include "llvm/ADT/ScopedHashTable.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/Support/Debug.h"
26
27using namespace llvm;
28
Evan Cheng16b48b82010-03-03 21:20:05 +000029STATISTIC(NumCoalesces, "Number of copies coalesced");
30STATISTIC(NumCSEs, "Number of common subexpression eliminated");
31
Evan Chengc6fe3332010-03-02 02:38:24 +000032namespace {
33 class MachineCSE : public MachineFunctionPass {
Evan Cheng6ba95542010-03-03 02:48:20 +000034 const TargetInstrInfo *TII;
Evan Chengb3958e82010-03-04 01:33:55 +000035 const TargetRegisterInfo *TRI;
Evan Cheng6ba95542010-03-03 02:48:20 +000036 MachineRegisterInfo *MRI;
Evan Chengc6fe3332010-03-02 02:38:24 +000037 MachineDominatorTree *DT;
Evan Chenga5f32cb2010-03-04 21:18:08 +000038 AliasAnalysis *AA;
Evan Chengc6fe3332010-03-02 02:38:24 +000039 public:
40 static char ID; // Pass identification
Evan Cheng6ba95542010-03-03 02:48:20 +000041 MachineCSE() : MachineFunctionPass(&ID), CurrVN(0) {}
Evan Chengc6fe3332010-03-02 02:38:24 +000042
43 virtual bool runOnMachineFunction(MachineFunction &MF);
44
45 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46 AU.setPreservesCFG();
47 MachineFunctionPass::getAnalysisUsage(AU);
Evan Chenga5f32cb2010-03-04 21:18:08 +000048 AU.addRequired<AliasAnalysis>();
Evan Chengc6fe3332010-03-02 02:38:24 +000049 AU.addRequired<MachineDominatorTree>();
50 AU.addPreserved<MachineDominatorTree>();
51 }
52
53 private:
Evan Cheng16b48b82010-03-03 21:20:05 +000054 unsigned CurrVN;
Evan Cheng05bdcbb2010-03-03 23:27:36 +000055 ScopedHashTable<MachineInstr*, unsigned, MachineInstrExpressionTrait> VNT;
Evan Cheng16b48b82010-03-03 21:20:05 +000056 SmallVector<MachineInstr*, 64> Exps;
57
Evan Chenga5f32cb2010-03-04 21:18:08 +000058 bool PerformTrivialCoalescing(MachineInstr *MI, MachineBasicBlock *MBB);
Evan Chengb3958e82010-03-04 01:33:55 +000059 bool isPhysDefTriviallyDead(unsigned Reg,
60 MachineBasicBlock::const_iterator I,
61 MachineBasicBlock::const_iterator E);
Evan Chenga5f32cb2010-03-04 21:18:08 +000062 bool hasLivePhysRegDefUse(MachineInstr *MI, MachineBasicBlock *MBB);
63 bool isCSECandidate(MachineInstr *MI);
Evan Chengc6fe3332010-03-02 02:38:24 +000064 bool ProcessBlock(MachineDomTreeNode *Node);
65 };
66} // end anonymous namespace
67
68char MachineCSE::ID = 0;
69static RegisterPass<MachineCSE>
70X("machine-cse", "Machine Common Subexpression Elimination");
71
72FunctionPass *llvm::createMachineCSEPass() { return new MachineCSE(); }
73
Evan Cheng6ba95542010-03-03 02:48:20 +000074bool MachineCSE::PerformTrivialCoalescing(MachineInstr *MI,
75 MachineBasicBlock *MBB) {
76 bool Changed = false;
77 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
78 MachineOperand &MO = MI->getOperand(i);
Evan Cheng16b48b82010-03-03 21:20:05 +000079 if (!MO.isReg() || !MO.isUse())
80 continue;
81 unsigned Reg = MO.getReg();
82 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
83 continue;
84 if (!MRI->hasOneUse(Reg))
85 // Only coalesce single use copies. This ensure the copy will be
86 // deleted.
87 continue;
88 MachineInstr *DefMI = MRI->getVRegDef(Reg);
89 if (DefMI->getParent() != MBB)
90 continue;
91 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
92 if (TII->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
93 TargetRegisterInfo::isVirtualRegister(SrcReg) &&
Evan Cheng6c3b8ac2010-03-08 23:28:08 +000094 MRI->getRegClass(SrcReg) == MRI->getRegClass(Reg) &&
Evan Cheng16b48b82010-03-03 21:20:05 +000095 !SrcSubIdx && !DstSubIdx) {
Evan Cheng6c3b8ac2010-03-08 23:28:08 +000096 DEBUG(dbgs() << "Coalescing: " << *DefMI);
97 DEBUG(dbgs() << "*** to: " << *MI);
Evan Cheng16b48b82010-03-03 21:20:05 +000098 MO.setReg(SrcReg);
99 DefMI->eraseFromParent();
100 ++NumCoalesces;
101 Changed = true;
Evan Cheng6ba95542010-03-03 02:48:20 +0000102 }
103 }
104
105 return Changed;
106}
107
Evan Chengb3958e82010-03-04 01:33:55 +0000108bool MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
109 MachineBasicBlock::const_iterator I,
110 MachineBasicBlock::const_iterator E) {
111 unsigned LookAheadLeft = 5;
112 while (LookAheadLeft--) {
113 if (I == E)
114 // Reached end of block, register is obviously dead.
115 return true;
116
117 if (I->isDebugValue())
118 continue;
119 bool SeenDef = false;
120 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
121 const MachineOperand &MO = I->getOperand(i);
122 if (!MO.isReg() || !MO.getReg())
123 continue;
124 if (!TRI->regsOverlap(MO.getReg(), Reg))
125 continue;
126 if (MO.isUse())
127 return false;
128 SeenDef = true;
129 }
130 if (SeenDef)
131 // See a def of Reg (or an alias) before encountering any use, it's
132 // trivially dead.
133 return true;
134 ++I;
135 }
136 return false;
137}
138
139bool MachineCSE::hasLivePhysRegDefUse(MachineInstr *MI, MachineBasicBlock *MBB){
140 unsigned PhysDef = 0;
Evan Cheng6ba95542010-03-03 02:48:20 +0000141 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
142 MachineOperand &MO = MI->getOperand(i);
143 if (!MO.isReg())
144 continue;
145 unsigned Reg = MO.getReg();
146 if (!Reg)
147 continue;
Evan Chengb3958e82010-03-04 01:33:55 +0000148 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
149 if (MO.isUse())
150 // Can't touch anything to read a physical register.
151 return true;
152 if (MO.isDead())
153 // If the def is dead, it's ok.
154 continue;
155 // Ok, this is a physical register def that's not marked "dead". That's
156 // common since this pass is run before livevariables. We can scan
157 // forward a few instructions and check if it is obviously dead.
158 if (PhysDef)
159 // Multiple physical register defs. These are rare, forget about it.
160 return true;
161 PhysDef = Reg;
162 }
163 }
164
165 if (PhysDef) {
166 MachineBasicBlock::iterator I = MI; I = llvm::next(I);
167 if (!isPhysDefTriviallyDead(PhysDef, I, MBB->end()))
Evan Cheng6ba95542010-03-03 02:48:20 +0000168 return true;
Evan Chengc6fe3332010-03-02 02:38:24 +0000169 }
170 return false;
171}
172
Evan Chenga5f32cb2010-03-04 21:18:08 +0000173bool MachineCSE::isCSECandidate(MachineInstr *MI) {
Evan Cheng51960182010-03-08 23:49:12 +0000174 if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
175 MI->isKill() || MI->isInlineAsm())
176 return false;
177
Evan Chenga5f32cb2010-03-04 21:18:08 +0000178 // Ignore copies or instructions that read / write physical registers
179 // (except for dead defs of physical registers).
180 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
181 if (TII->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) ||
182 MI->isExtractSubreg() || MI->isInsertSubreg() || MI->isSubregToReg())
183 return false;
184
185 // Ignore stuff that we obviously can't move.
186 const TargetInstrDesc &TID = MI->getDesc();
187 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
188 TID.hasUnmodeledSideEffects())
189 return false;
190
191 if (TID.mayLoad()) {
192 // Okay, this instruction does a load. As a refinement, we allow the target
193 // to decide whether the loaded value is actually a constant. If so, we can
194 // actually use it as a load.
195 if (!MI->isInvariantLoad(AA))
196 // FIXME: we should be able to hoist loads with no other side effects if
197 // there are no other instructions which can change memory in this loop.
198 // This is a trivial form of alias analysis.
199 return false;
200 }
201 return true;
202}
203
Evan Cheng6ba95542010-03-03 02:48:20 +0000204bool MachineCSE::ProcessBlock(MachineDomTreeNode *Node) {
205 bool Changed = false;
206
Evan Cheng05bdcbb2010-03-03 23:27:36 +0000207 ScopedHashTableScope<MachineInstr*, unsigned,
208 MachineInstrExpressionTrait> VNTS(VNT);
Evan Cheng6ba95542010-03-03 02:48:20 +0000209 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng16b48b82010-03-03 21:20:05 +0000210 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
Evan Cheng6ba95542010-03-03 02:48:20 +0000211 MachineInstr *MI = &*I;
Evan Cheng16b48b82010-03-03 21:20:05 +0000212 ++I;
Evan Chenga5f32cb2010-03-04 21:18:08 +0000213
214 if (!isCSECandidate(MI))
Evan Cheng6ba95542010-03-03 02:48:20 +0000215 continue;
Evan Cheng6ba95542010-03-03 02:48:20 +0000216
217 bool FoundCSE = VNT.count(MI);
218 if (!FoundCSE) {
219 // Look for trivial copy coalescing opportunities.
220 if (PerformTrivialCoalescing(MI, MBB))
221 FoundCSE = VNT.count(MI);
222 }
Evan Chengb3958e82010-03-04 01:33:55 +0000223 // FIXME: commute commutable instructions?
Evan Cheng6ba95542010-03-03 02:48:20 +0000224
Evan Cheng67bda722010-03-03 23:59:08 +0000225 // If the instruction defines a physical register and the value *may* be
226 // used, then it's not safe to replace it with a common subexpression.
Evan Chengb3958e82010-03-04 01:33:55 +0000227 if (FoundCSE && hasLivePhysRegDefUse(MI, MBB))
Evan Cheng67bda722010-03-03 23:59:08 +0000228 FoundCSE = false;
229
Evan Cheng16b48b82010-03-03 21:20:05 +0000230 if (!FoundCSE) {
231 VNT.insert(MI, CurrVN++);
232 Exps.push_back(MI);
233 continue;
234 }
235
236 // Found a common subexpression, eliminate it.
237 unsigned CSVN = VNT.lookup(MI);
238 MachineInstr *CSMI = Exps[CSVN];
239 DEBUG(dbgs() << "Examining: " << *MI);
240 DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
241 unsigned NumDefs = MI->getDesc().getNumDefs();
242 for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
243 MachineOperand &MO = MI->getOperand(i);
244 if (!MO.isReg() || !MO.isDef())
245 continue;
246 unsigned OldReg = MO.getReg();
247 unsigned NewReg = CSMI->getOperand(i).getReg();
Evan Cheng6cc1aea2010-03-06 01:14:19 +0000248 if (OldReg == NewReg)
249 continue;
250 assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
Evan Cheng16b48b82010-03-03 21:20:05 +0000251 TargetRegisterInfo::isVirtualRegister(NewReg) &&
252 "Do not CSE physical register defs!");
253 MRI->replaceRegWith(OldReg, NewReg);
254 --NumDefs;
255 }
256 MI->eraseFromParent();
257 ++NumCSEs;
Evan Cheng6ba95542010-03-03 02:48:20 +0000258 }
259
260 // Recursively call ProcessBlock with childred.
261 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
262 for (unsigned i = 0, e = Children.size(); i != e; ++i)
263 Changed |= ProcessBlock(Children[i]);
264
265 return Changed;
266}
267
Evan Chengc6fe3332010-03-02 02:38:24 +0000268bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
Evan Cheng6ba95542010-03-03 02:48:20 +0000269 TII = MF.getTarget().getInstrInfo();
Evan Chengb3958e82010-03-04 01:33:55 +0000270 TRI = MF.getTarget().getRegisterInfo();
Evan Cheng6ba95542010-03-03 02:48:20 +0000271 MRI = &MF.getRegInfo();
Evan Chengc6fe3332010-03-02 02:38:24 +0000272 DT = &getAnalysis<MachineDominatorTree>();
Evan Chenga5f32cb2010-03-04 21:18:08 +0000273 AA = &getAnalysis<AliasAnalysis>();
Evan Chengc6fe3332010-03-02 02:38:24 +0000274 return ProcessBlock(DT->getRootNode());
275}