blob: 199885d8b3bd87be3c638d0834f10c71debded30 [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 Cheng31156982010-04-21 00:21:07 +000023#include "llvm/ADT/DenseMap.h"
Evan Chengc6fe3332010-03-02 02:38:24 +000024#include "llvm/ADT/ScopedHashTable.h"
25#include "llvm/ADT/Statistic.h"
Evan Cheng835810b2010-05-21 21:22:19 +000026#include "llvm/Support/CommandLine.h"
Evan Chengc6fe3332010-03-02 02:38:24 +000027#include "llvm/Support/Debug.h"
28
29using namespace llvm;
30
Evan Cheng16b48b82010-03-03 21:20:05 +000031STATISTIC(NumCoalesces, "Number of copies coalesced");
32STATISTIC(NumCSEs, "Number of common subexpression eliminated");
Evan Cheng2b4e7272010-06-04 23:28:13 +000033STATISTIC(NumPhysCSEs, "Number of phyreg defining common subexpr eliminated");
Bob Wilson38441732010-06-03 18:28:31 +000034
Evan Chengc6fe3332010-03-02 02:38:24 +000035namespace {
36 class MachineCSE : public MachineFunctionPass {
Evan Cheng6ba95542010-03-03 02:48:20 +000037 const TargetInstrInfo *TII;
Evan Chengb3958e82010-03-04 01:33:55 +000038 const TargetRegisterInfo *TRI;
Evan Chenga5f32cb2010-03-04 21:18:08 +000039 AliasAnalysis *AA;
Evan Cheng31f94c72010-03-09 03:21:12 +000040 MachineDominatorTree *DT;
41 MachineRegisterInfo *MRI;
Evan Chengc6fe3332010-03-02 02:38:24 +000042 public:
43 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +000044 MachineCSE() : MachineFunctionPass(ID), LookAheadLimit(5), CurrVN(0) {
45 initializeMachineCSEPass(*PassRegistry::getPassRegistry());
46 }
Evan Chengc6fe3332010-03-02 02:38:24 +000047
48 virtual bool runOnMachineFunction(MachineFunction &MF);
49
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51 AU.setPreservesCFG();
52 MachineFunctionPass::getAnalysisUsage(AU);
Evan Chenga5f32cb2010-03-04 21:18:08 +000053 AU.addRequired<AliasAnalysis>();
Evan Cheng65424162010-08-17 20:57:42 +000054 AU.addPreservedID(MachineLoopInfoID);
Evan Chengc6fe3332010-03-02 02:38:24 +000055 AU.addRequired<MachineDominatorTree>();
56 AU.addPreserved<MachineDominatorTree>();
57 }
58
Evan Chengc2b768f2010-09-17 21:59:42 +000059 virtual void releaseMemory() {
60 ScopeMap.clear();
61 Exps.clear();
62 }
63
Evan Chengc6fe3332010-03-02 02:38:24 +000064 private:
Evan Cheng835810b2010-05-21 21:22:19 +000065 const unsigned LookAheadLimit;
Evan Cheng31156982010-04-21 00:21:07 +000066 typedef ScopedHashTableScope<MachineInstr*, unsigned,
67 MachineInstrExpressionTrait> ScopeType;
68 DenseMap<MachineBasicBlock*, ScopeType*> ScopeMap;
Evan Cheng05bdcbb2010-03-03 23:27:36 +000069 ScopedHashTable<MachineInstr*, unsigned, MachineInstrExpressionTrait> VNT;
Evan Cheng16b48b82010-03-03 21:20:05 +000070 SmallVector<MachineInstr*, 64> Exps;
Evan Cheng31156982010-04-21 00:21:07 +000071 unsigned CurrVN;
Evan Cheng16b48b82010-03-03 21:20:05 +000072
Evan Chenga5f32cb2010-03-04 21:18:08 +000073 bool PerformTrivialCoalescing(MachineInstr *MI, MachineBasicBlock *MBB);
Evan Chengb3958e82010-03-04 01:33:55 +000074 bool isPhysDefTriviallyDead(unsigned Reg,
75 MachineBasicBlock::const_iterator I,
Evan Cheng835810b2010-05-21 21:22:19 +000076 MachineBasicBlock::const_iterator E) const ;
77 bool hasLivePhysRegDefUse(const MachineInstr *MI,
78 const MachineBasicBlock *MBB,
79 unsigned &PhysDef) const;
80 bool PhysRegDefReaches(MachineInstr *CSMI, MachineInstr *MI,
81 unsigned PhysDef) const;
Evan Chenga5f32cb2010-03-04 21:18:08 +000082 bool isCSECandidate(MachineInstr *MI);
Evan Cheng2938a002010-03-10 02:12:03 +000083 bool isProfitableToCSE(unsigned CSReg, unsigned Reg,
84 MachineInstr *CSMI, MachineInstr *MI);
Evan Cheng31156982010-04-21 00:21:07 +000085 void EnterScope(MachineBasicBlock *MBB);
86 void ExitScope(MachineBasicBlock *MBB);
87 bool ProcessBlock(MachineBasicBlock *MBB);
88 void ExitScopeIfDone(MachineDomTreeNode *Node,
89 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
90 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
91 bool PerformCSE(MachineDomTreeNode *Node);
Evan Chengc6fe3332010-03-02 02:38:24 +000092 };
93} // end anonymous namespace
94
95char MachineCSE::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000096INITIALIZE_PASS_BEGIN(MachineCSE, "machine-cse",
97 "Machine Common Subexpression Elimination", false, false)
98INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
99INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
100INITIALIZE_PASS_END(MachineCSE, "machine-cse",
Owen Andersonce665bd2010-10-07 22:25:06 +0000101 "Machine Common Subexpression Elimination", false, false)
Evan Chengc6fe3332010-03-02 02:38:24 +0000102
103FunctionPass *llvm::createMachineCSEPass() { return new MachineCSE(); }
104
Evan Cheng6ba95542010-03-03 02:48:20 +0000105bool MachineCSE::PerformTrivialCoalescing(MachineInstr *MI,
106 MachineBasicBlock *MBB) {
107 bool Changed = false;
108 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
109 MachineOperand &MO = MI->getOperand(i);
Evan Cheng16b48b82010-03-03 21:20:05 +0000110 if (!MO.isReg() || !MO.isUse())
111 continue;
112 unsigned Reg = MO.getReg();
113 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
114 continue;
Evan Chengf437f732010-09-17 21:56:26 +0000115 if (!MRI->hasOneNonDBGUse(Reg))
Evan Cheng16b48b82010-03-03 21:20:05 +0000116 // Only coalesce single use copies. This ensure the copy will be
117 // deleted.
118 continue;
119 MachineInstr *DefMI = MRI->getVRegDef(Reg);
120 if (DefMI->getParent() != MBB)
121 continue;
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +0000122 if (!DefMI->isCopy())
123 continue;
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000124 unsigned SrcReg = DefMI->getOperand(1).getReg();
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +0000125 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
126 continue;
127 if (DefMI->getOperand(0).getSubReg() || DefMI->getOperand(1).getSubReg())
128 continue;
Jakob Stoklund Olesenbf4699c2010-10-06 23:54:39 +0000129 if (!MRI->constrainRegClass(SrcReg, MRI->getRegClass(Reg)))
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +0000130 continue;
131 DEBUG(dbgs() << "Coalescing: " << *DefMI);
Jakob Stoklund Olesenbf4699c2010-10-06 23:54:39 +0000132 DEBUG(dbgs() << "*** to: " << *MI);
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +0000133 MO.setReg(SrcReg);
134 MRI->clearKillFlags(SrcReg);
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +0000135 DefMI->eraseFromParent();
136 ++NumCoalesces;
137 Changed = true;
Evan Cheng6ba95542010-03-03 02:48:20 +0000138 }
139
140 return Changed;
141}
142
Evan Cheng835810b2010-05-21 21:22:19 +0000143bool
144MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
145 MachineBasicBlock::const_iterator I,
146 MachineBasicBlock::const_iterator E) const {
Eric Christophere81d0102010-05-21 23:40:03 +0000147 unsigned LookAheadLeft = LookAheadLimit;
Evan Cheng112e5e72010-03-23 20:33:48 +0000148 while (LookAheadLeft) {
Evan Cheng22504252010-03-24 01:50:28 +0000149 // Skip over dbg_value's.
150 while (I != E && I->isDebugValue())
151 ++I;
152
Evan Chengb3958e82010-03-04 01:33:55 +0000153 if (I == E)
154 // Reached end of block, register is obviously dead.
155 return true;
156
Evan Chengb3958e82010-03-04 01:33:55 +0000157 bool SeenDef = false;
158 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
159 const MachineOperand &MO = I->getOperand(i);
160 if (!MO.isReg() || !MO.getReg())
161 continue;
162 if (!TRI->regsOverlap(MO.getReg(), Reg))
163 continue;
164 if (MO.isUse())
Evan Cheng835810b2010-05-21 21:22:19 +0000165 // Found a use!
Evan Chengb3958e82010-03-04 01:33:55 +0000166 return false;
167 SeenDef = true;
168 }
169 if (SeenDef)
170 // See a def of Reg (or an alias) before encountering any use, it's
171 // trivially dead.
172 return true;
Evan Cheng112e5e72010-03-23 20:33:48 +0000173
174 --LookAheadLeft;
Evan Chengb3958e82010-03-04 01:33:55 +0000175 ++I;
176 }
177 return false;
178}
179
Evan Cheng2938a002010-03-10 02:12:03 +0000180/// hasLivePhysRegDefUse - Return true if the specified instruction read / write
Evan Cheng835810b2010-05-21 21:22:19 +0000181/// physical registers (except for dead defs of physical registers). It also
Evan Cheng2b4e7272010-06-04 23:28:13 +0000182/// returns the physical register def by reference if it's the only one and the
183/// instruction does not uses a physical register.
Evan Cheng835810b2010-05-21 21:22:19 +0000184bool MachineCSE::hasLivePhysRegDefUse(const MachineInstr *MI,
185 const MachineBasicBlock *MBB,
186 unsigned &PhysDef) const {
187 PhysDef = 0;
Evan Cheng6ba95542010-03-03 02:48:20 +0000188 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Evan Cheng835810b2010-05-21 21:22:19 +0000189 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng6ba95542010-03-03 02:48:20 +0000190 if (!MO.isReg())
191 continue;
192 unsigned Reg = MO.getReg();
193 if (!Reg)
194 continue;
Evan Cheng835810b2010-05-21 21:22:19 +0000195 if (TargetRegisterInfo::isVirtualRegister(Reg))
196 continue;
Evan Cheng2b4e7272010-06-04 23:28:13 +0000197 if (MO.isUse()) {
Evan Cheng835810b2010-05-21 21:22:19 +0000198 // Can't touch anything to read a physical register.
Evan Cheng2b4e7272010-06-04 23:28:13 +0000199 PhysDef = 0;
Evan Cheng835810b2010-05-21 21:22:19 +0000200 return true;
Evan Cheng2b4e7272010-06-04 23:28:13 +0000201 }
Evan Cheng835810b2010-05-21 21:22:19 +0000202 if (MO.isDead())
203 // If the def is dead, it's ok.
204 continue;
205 // Ok, this is a physical register def that's not marked "dead". That's
206 // common since this pass is run before livevariables. We can scan
207 // forward a few instructions and check if it is obviously dead.
208 if (PhysDef) {
209 // Multiple physical register defs. These are rare, forget about it.
210 PhysDef = 0;
211 return true;
Evan Chengb3958e82010-03-04 01:33:55 +0000212 }
Evan Cheng835810b2010-05-21 21:22:19 +0000213 PhysDef = Reg;
Evan Chengb3958e82010-03-04 01:33:55 +0000214 }
215
216 if (PhysDef) {
Evan Cheng835810b2010-05-21 21:22:19 +0000217 MachineBasicBlock::const_iterator I = MI; I = llvm::next(I);
Evan Chengb3958e82010-03-04 01:33:55 +0000218 if (!isPhysDefTriviallyDead(PhysDef, I, MBB->end()))
Evan Cheng6ba95542010-03-03 02:48:20 +0000219 return true;
Evan Chengc6fe3332010-03-02 02:38:24 +0000220 }
221 return false;
222}
223
Evan Cheng835810b2010-05-21 21:22:19 +0000224bool MachineCSE::PhysRegDefReaches(MachineInstr *CSMI, MachineInstr *MI,
225 unsigned PhysDef) const {
226 // For now conservatively returns false if the common subexpression is
227 // not in the same basic block as the given instruction.
228 MachineBasicBlock *MBB = MI->getParent();
229 if (CSMI->getParent() != MBB)
230 return false;
231 MachineBasicBlock::const_iterator I = CSMI; I = llvm::next(I);
232 MachineBasicBlock::const_iterator E = MI;
233 unsigned LookAheadLeft = LookAheadLimit;
234 while (LookAheadLeft) {
235 // Skip over dbg_value's.
236 while (I != E && I->isDebugValue())
237 ++I;
238
239 if (I == E)
240 return true;
241 if (I->modifiesRegister(PhysDef, TRI))
242 return false;
243
244 --LookAheadLeft;
245 ++I;
246 }
247
248 return false;
249}
250
Evan Chenga5f32cb2010-03-04 21:18:08 +0000251bool MachineCSE::isCSECandidate(MachineInstr *MI) {
Evan Cheng51960182010-03-08 23:49:12 +0000252 if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
Dale Johannesene68ea062010-03-11 02:10:24 +0000253 MI->isKill() || MI->isInlineAsm() || MI->isDebugValue())
Evan Cheng51960182010-03-08 23:49:12 +0000254 return false;
255
Evan Cheng2938a002010-03-10 02:12:03 +0000256 // Ignore copies.
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000257 if (MI->isCopyLike())
Evan Chenga5f32cb2010-03-04 21:18:08 +0000258 return false;
259
260 // Ignore stuff that we obviously can't move.
261 const TargetInstrDesc &TID = MI->getDesc();
262 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
263 TID.hasUnmodeledSideEffects())
264 return false;
265
266 if (TID.mayLoad()) {
267 // Okay, this instruction does a load. As a refinement, we allow the target
268 // to decide whether the loaded value is actually a constant. If so, we can
269 // actually use it as a load.
270 if (!MI->isInvariantLoad(AA))
271 // FIXME: we should be able to hoist loads with no other side effects if
272 // there are no other instructions which can change memory in this loop.
273 // This is a trivial form of alias analysis.
274 return false;
275 }
276 return true;
277}
278
Evan Cheng31f94c72010-03-09 03:21:12 +0000279/// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
280/// common expression that defines Reg.
Evan Cheng2938a002010-03-10 02:12:03 +0000281bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
282 MachineInstr *CSMI, MachineInstr *MI) {
283 // FIXME: Heuristics that works around the lack the live range splitting.
284
285 // Heuristics #1: Don't cse "cheap" computating if the def is not local or in an
286 // immediate predecessor. We don't want to increase register pressure and end up
287 // causing other computation to be spilled.
288 if (MI->getDesc().isAsCheapAsAMove()) {
289 MachineBasicBlock *CSBB = CSMI->getParent();
290 MachineBasicBlock *BB = MI->getParent();
291 if (CSBB != BB &&
292 find(CSBB->succ_begin(), CSBB->succ_end(), BB) == CSBB->succ_end())
293 return false;
294 }
295
296 // Heuristics #2: If the expression doesn't not use a vr and the only use
297 // of the redundant computation are copies, do not cse.
298 bool HasVRegUse = false;
299 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
300 const MachineOperand &MO = MI->getOperand(i);
301 if (MO.isReg() && MO.isUse() && MO.getReg() &&
302 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
303 HasVRegUse = true;
304 break;
305 }
306 }
307 if (!HasVRegUse) {
308 bool HasNonCopyUse = false;
309 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
310 E = MRI->use_nodbg_end(); I != E; ++I) {
311 MachineInstr *Use = &*I;
312 // Ignore copies.
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000313 if (!Use->isCopyLike()) {
Evan Cheng2938a002010-03-10 02:12:03 +0000314 HasNonCopyUse = true;
315 break;
316 }
317 }
318 if (!HasNonCopyUse)
319 return false;
320 }
321
322 // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
323 // it unless the defined value is already used in the BB of the new use.
Evan Cheng31f94c72010-03-09 03:21:12 +0000324 bool HasPHI = false;
325 SmallPtrSet<MachineBasicBlock*, 4> CSBBs;
Evan Cheng2938a002010-03-10 02:12:03 +0000326 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(CSReg),
Evan Cheng31f94c72010-03-09 03:21:12 +0000327 E = MRI->use_nodbg_end(); I != E; ++I) {
328 MachineInstr *Use = &*I;
329 HasPHI |= Use->isPHI();
330 CSBBs.insert(Use->getParent());
331 }
332
333 if (!HasPHI)
334 return true;
335 return CSBBs.count(MI->getParent());
336}
337
Evan Cheng31156982010-04-21 00:21:07 +0000338void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
339 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
340 ScopeType *Scope = new ScopeType(VNT);
341 ScopeMap[MBB] = Scope;
342}
343
344void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
345 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
346 DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
347 assert(SI != ScopeMap.end());
348 ScopeMap.erase(SI);
349 delete SI->second;
350}
351
352bool MachineCSE::ProcessBlock(MachineBasicBlock *MBB) {
Evan Cheng6ba95542010-03-03 02:48:20 +0000353 bool Changed = false;
354
Evan Cheng31f94c72010-03-09 03:21:12 +0000355 SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
Evan Cheng16b48b82010-03-03 21:20:05 +0000356 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
Evan Cheng6ba95542010-03-03 02:48:20 +0000357 MachineInstr *MI = &*I;
Evan Cheng16b48b82010-03-03 21:20:05 +0000358 ++I;
Evan Chenga5f32cb2010-03-04 21:18:08 +0000359
360 if (!isCSECandidate(MI))
Evan Cheng6ba95542010-03-03 02:48:20 +0000361 continue;
Evan Cheng6ba95542010-03-03 02:48:20 +0000362
Evan Cheng2b4e7272010-06-04 23:28:13 +0000363 bool DefPhys = false;
Evan Cheng6ba95542010-03-03 02:48:20 +0000364 bool FoundCSE = VNT.count(MI);
365 if (!FoundCSE) {
366 // Look for trivial copy coalescing opportunities.
Evan Chengdb8771a2010-04-02 02:21:24 +0000367 if (PerformTrivialCoalescing(MI, MBB)) {
368 // After coalescing MI itself may become a copy.
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000369 if (MI->isCopyLike())
Evan Chengdb8771a2010-04-02 02:21:24 +0000370 continue;
Evan Cheng6ba95542010-03-03 02:48:20 +0000371 FoundCSE = VNT.count(MI);
Evan Chengdb8771a2010-04-02 02:21:24 +0000372 }
Evan Cheng6ba95542010-03-03 02:48:20 +0000373 }
Evan Chengb3958e82010-03-04 01:33:55 +0000374 // FIXME: commute commutable instructions?
Evan Cheng6ba95542010-03-03 02:48:20 +0000375
Evan Cheng67bda722010-03-03 23:59:08 +0000376 // If the instruction defines a physical register and the value *may* be
377 // used, then it's not safe to replace it with a common subexpression.
Evan Cheng835810b2010-05-21 21:22:19 +0000378 unsigned PhysDef = 0;
379 if (FoundCSE && hasLivePhysRegDefUse(MI, MBB, PhysDef)) {
Evan Cheng67bda722010-03-03 23:59:08 +0000380 FoundCSE = false;
381
Evan Cheng835810b2010-05-21 21:22:19 +0000382 // ... Unless the CS is local and it also defines the physical register
383 // which is not clobbered in between.
Evan Cheng2b4e7272010-06-04 23:28:13 +0000384 if (PhysDef) {
Evan Cheng835810b2010-05-21 21:22:19 +0000385 unsigned CSVN = VNT.lookup(MI);
386 MachineInstr *CSMI = Exps[CSVN];
Evan Cheng2b4e7272010-06-04 23:28:13 +0000387 if (PhysRegDefReaches(CSMI, MI, PhysDef)) {
Evan Cheng835810b2010-05-21 21:22:19 +0000388 FoundCSE = true;
Evan Cheng2b4e7272010-06-04 23:28:13 +0000389 DefPhys = true;
390 }
Evan Cheng835810b2010-05-21 21:22:19 +0000391 }
392 }
393
Evan Cheng16b48b82010-03-03 21:20:05 +0000394 if (!FoundCSE) {
395 VNT.insert(MI, CurrVN++);
396 Exps.push_back(MI);
397 continue;
398 }
399
400 // Found a common subexpression, eliminate it.
401 unsigned CSVN = VNT.lookup(MI);
402 MachineInstr *CSMI = Exps[CSVN];
403 DEBUG(dbgs() << "Examining: " << *MI);
404 DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
Evan Cheng31f94c72010-03-09 03:21:12 +0000405
406 // Check if it's profitable to perform this CSE.
407 bool DoCSE = true;
Evan Cheng16b48b82010-03-03 21:20:05 +0000408 unsigned NumDefs = MI->getDesc().getNumDefs();
409 for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
410 MachineOperand &MO = MI->getOperand(i);
411 if (!MO.isReg() || !MO.isDef())
412 continue;
413 unsigned OldReg = MO.getReg();
414 unsigned NewReg = CSMI->getOperand(i).getReg();
Evan Cheng6cc1aea2010-03-06 01:14:19 +0000415 if (OldReg == NewReg)
416 continue;
417 assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
Evan Cheng16b48b82010-03-03 21:20:05 +0000418 TargetRegisterInfo::isVirtualRegister(NewReg) &&
419 "Do not CSE physical register defs!");
Evan Cheng2938a002010-03-10 02:12:03 +0000420 if (!isProfitableToCSE(NewReg, OldReg, CSMI, MI)) {
Evan Cheng31f94c72010-03-09 03:21:12 +0000421 DoCSE = false;
422 break;
423 }
424 CSEPairs.push_back(std::make_pair(OldReg, NewReg));
Evan Cheng16b48b82010-03-03 21:20:05 +0000425 --NumDefs;
426 }
Evan Cheng31f94c72010-03-09 03:21:12 +0000427
428 // Actually perform the elimination.
429 if (DoCSE) {
Dan Gohman49b45892010-05-13 19:24:00 +0000430 for (unsigned i = 0, e = CSEPairs.size(); i != e; ++i) {
Evan Cheng31f94c72010-03-09 03:21:12 +0000431 MRI->replaceRegWith(CSEPairs[i].first, CSEPairs[i].second);
Dan Gohman49b45892010-05-13 19:24:00 +0000432 MRI->clearKillFlags(CSEPairs[i].second);
433 }
Evan Cheng31f94c72010-03-09 03:21:12 +0000434 MI->eraseFromParent();
435 ++NumCSEs;
Evan Cheng2b4e7272010-06-04 23:28:13 +0000436 if (DefPhys)
437 ++NumPhysCSEs;
Evan Cheng31f94c72010-03-09 03:21:12 +0000438 } else {
439 DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
440 VNT.insert(MI, CurrVN++);
441 Exps.push_back(MI);
442 }
443 CSEPairs.clear();
Evan Cheng6ba95542010-03-03 02:48:20 +0000444 }
445
Evan Cheng31156982010-04-21 00:21:07 +0000446 return Changed;
447}
448
449/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
450/// dominator tree node if its a leaf or all of its children are done. Walk
451/// up the dominator tree to destroy ancestors which are now done.
452void
453MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
454 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
455 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
456 if (OpenChildren[Node])
457 return;
458
459 // Pop scope.
460 ExitScope(Node->getBlock());
461
462 // Now traverse upwards to pop ancestors whose offsprings are all done.
463 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
464 unsigned Left = --OpenChildren[Parent];
465 if (Left != 0)
466 break;
467 ExitScope(Parent->getBlock());
468 Node = Parent;
469 }
470}
471
472bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
473 SmallVector<MachineDomTreeNode*, 32> Scopes;
474 SmallVector<MachineDomTreeNode*, 8> WorkList;
475 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
476 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
477
Evan Chengc2b768f2010-09-17 21:59:42 +0000478 CurrVN = 0;
479
Evan Cheng31156982010-04-21 00:21:07 +0000480 // Perform a DFS walk to determine the order of visit.
481 WorkList.push_back(Node);
482 do {
483 Node = WorkList.pop_back_val();
484 Scopes.push_back(Node);
485 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
486 unsigned NumChildren = Children.size();
487 OpenChildren[Node] = NumChildren;
488 for (unsigned i = 0; i != NumChildren; ++i) {
489 MachineDomTreeNode *Child = Children[i];
490 ParentMap[Child] = Node;
491 WorkList.push_back(Child);
492 }
493 } while (!WorkList.empty());
494
495 // Now perform CSE.
496 bool Changed = false;
497 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
498 MachineDomTreeNode *Node = Scopes[i];
499 MachineBasicBlock *MBB = Node->getBlock();
500 EnterScope(MBB);
501 Changed |= ProcessBlock(MBB);
502 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
503 ExitScopeIfDone(Node, OpenChildren, ParentMap);
504 }
Evan Cheng6ba95542010-03-03 02:48:20 +0000505
506 return Changed;
507}
508
Evan Chengc6fe3332010-03-02 02:38:24 +0000509bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
Evan Cheng6ba95542010-03-03 02:48:20 +0000510 TII = MF.getTarget().getInstrInfo();
Evan Chengb3958e82010-03-04 01:33:55 +0000511 TRI = MF.getTarget().getRegisterInfo();
Evan Cheng6ba95542010-03-03 02:48:20 +0000512 MRI = &MF.getRegInfo();
Evan Chenga5f32cb2010-03-04 21:18:08 +0000513 AA = &getAnalysis<AliasAnalysis>();
Evan Cheng31f94c72010-03-09 03:21:12 +0000514 DT = &getAnalysis<MachineDominatorTree>();
Evan Cheng31156982010-04-21 00:21:07 +0000515 return PerformCSE(DT->getRootNode());
Evan Chengc6fe3332010-03-02 02:38:24 +0000516}