1 //===-- MachineCSE.cpp - Machine Common Subexpression Elimination Pass ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs global common subexpression elimination on machine
11 // instructions using a scoped hash table based value numbering scheme. It
12 // must be run while the machine function is still in SSA form.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "machine-cse"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/MachineDominators.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/ScopedHashTable.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
31 STATISTIC(NumCoalesces, "Number of copies coalesced");
32 STATISTIC(NumCSEs, "Number of common subexpression eliminated");
33 STATISTIC(NumPhysCSEs, "Number of phyreg defining common subexpr eliminated");
36 class MachineCSE : public MachineFunctionPass {
37 const TargetInstrInfo *TII;
38 const TargetRegisterInfo *TRI;
40 MachineDominatorTree *DT;
41 MachineRegisterInfo *MRI;
43 static char ID; // Pass identification
44 MachineCSE() : MachineFunctionPass(&ID), LookAheadLimit(5), CurrVN(0) {}
46 virtual bool runOnMachineFunction(MachineFunction &MF);
48 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
50 MachineFunctionPass::getAnalysisUsage(AU);
51 AU.addRequired<AliasAnalysis>();
52 AU.addRequired<MachineDominatorTree>();
53 AU.addPreserved<MachineDominatorTree>();
57 const unsigned LookAheadLimit;
58 typedef ScopedHashTableScope<MachineInstr*, unsigned,
59 MachineInstrExpressionTrait> ScopeType;
60 DenseMap<MachineBasicBlock*, ScopeType*> ScopeMap;
61 ScopedHashTable<MachineInstr*, unsigned, MachineInstrExpressionTrait> VNT;
62 SmallVector<MachineInstr*, 64> Exps;
65 bool PerformTrivialCoalescing(MachineInstr *MI, MachineBasicBlock *MBB);
66 bool isPhysDefTriviallyDead(unsigned Reg,
67 MachineBasicBlock::const_iterator I,
68 MachineBasicBlock::const_iterator E) const ;
69 bool hasLivePhysRegDefUse(const MachineInstr *MI,
70 const MachineBasicBlock *MBB,
71 unsigned &PhysDef) const;
72 bool PhysRegDefReaches(MachineInstr *CSMI, MachineInstr *MI,
73 unsigned PhysDef) const;
74 bool isCSECandidate(MachineInstr *MI);
75 bool isProfitableToCSE(unsigned CSReg, unsigned Reg,
76 MachineInstr *CSMI, MachineInstr *MI);
77 void EnterScope(MachineBasicBlock *MBB);
78 void ExitScope(MachineBasicBlock *MBB);
79 bool ProcessBlock(MachineBasicBlock *MBB);
80 void ExitScopeIfDone(MachineDomTreeNode *Node,
81 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
82 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
83 bool PerformCSE(MachineDomTreeNode *Node);
85 } // end anonymous namespace
87 char MachineCSE::ID = 0;
88 static RegisterPass<MachineCSE>
89 X("machine-cse", "Machine Common Subexpression Elimination");
91 FunctionPass *llvm::createMachineCSEPass() { return new MachineCSE(); }
93 bool MachineCSE::PerformTrivialCoalescing(MachineInstr *MI,
94 MachineBasicBlock *MBB) {
96 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
97 MachineOperand &MO = MI->getOperand(i);
98 if (!MO.isReg() || !MO.isUse())
100 unsigned Reg = MO.getReg();
101 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
103 if (!MRI->hasOneUse(Reg))
104 // Only coalesce single use copies. This ensure the copy will be
107 MachineInstr *DefMI = MRI->getVRegDef(Reg);
108 if (DefMI->getParent() != MBB)
110 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
111 if (TII->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
112 TargetRegisterInfo::isVirtualRegister(SrcReg) &&
113 !SrcSubIdx && !DstSubIdx) {
114 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
115 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
116 const TargetRegisterClass *NewRC = getCommonSubClass(RC, SRC);
119 DEBUG(dbgs() << "Coalescing: " << *DefMI);
120 DEBUG(dbgs() << "*** to: " << *MI);
122 MRI->clearKillFlags(SrcReg);
124 MRI->setRegClass(SrcReg, NewRC);
125 DefMI->eraseFromParent();
130 if (!DefMI->isCopy())
132 SrcReg = DefMI->getOperand(1).getReg();
133 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
135 if (DefMI->getOperand(0).getSubReg() || DefMI->getOperand(1).getSubReg())
137 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
138 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
139 const TargetRegisterClass *NewRC = getCommonSubClass(RC, SRC);
142 DEBUG(dbgs() << "Coalescing: " << *DefMI);
143 DEBUG(dbgs() << "*** to: " << *MI);
145 MRI->clearKillFlags(SrcReg);
147 MRI->setRegClass(SrcReg, NewRC);
148 DefMI->eraseFromParent();
157 MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
158 MachineBasicBlock::const_iterator I,
159 MachineBasicBlock::const_iterator E) const {
160 unsigned LookAheadLeft = LookAheadLimit;
161 while (LookAheadLeft) {
162 // Skip over dbg_value's.
163 while (I != E && I->isDebugValue())
167 // Reached end of block, register is obviously dead.
170 bool SeenDef = false;
171 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
172 const MachineOperand &MO = I->getOperand(i);
173 if (!MO.isReg() || !MO.getReg())
175 if (!TRI->regsOverlap(MO.getReg(), Reg))
183 // See a def of Reg (or an alias) before encountering any use, it's
193 /// hasLivePhysRegDefUse - Return true if the specified instruction read / write
194 /// physical registers (except for dead defs of physical registers). It also
195 /// returns the physical register def by reference if it's the only one and the
196 /// instruction does not uses a physical register.
197 bool MachineCSE::hasLivePhysRegDefUse(const MachineInstr *MI,
198 const MachineBasicBlock *MBB,
199 unsigned &PhysDef) const {
201 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
202 const MachineOperand &MO = MI->getOperand(i);
205 unsigned Reg = MO.getReg();
208 if (TargetRegisterInfo::isVirtualRegister(Reg))
211 // Can't touch anything to read a physical register.
216 // If the def is dead, it's ok.
218 // Ok, this is a physical register def that's not marked "dead". That's
219 // common since this pass is run before livevariables. We can scan
220 // forward a few instructions and check if it is obviously dead.
222 // Multiple physical register defs. These are rare, forget about it.
230 MachineBasicBlock::const_iterator I = MI; I = llvm::next(I);
231 if (!isPhysDefTriviallyDead(PhysDef, I, MBB->end()))
237 bool MachineCSE::PhysRegDefReaches(MachineInstr *CSMI, MachineInstr *MI,
238 unsigned PhysDef) const {
239 // For now conservatively returns false if the common subexpression is
240 // not in the same basic block as the given instruction.
241 MachineBasicBlock *MBB = MI->getParent();
242 if (CSMI->getParent() != MBB)
244 MachineBasicBlock::const_iterator I = CSMI; I = llvm::next(I);
245 MachineBasicBlock::const_iterator E = MI;
246 unsigned LookAheadLeft = LookAheadLimit;
247 while (LookAheadLeft) {
248 // Skip over dbg_value's.
249 while (I != E && I->isDebugValue())
254 if (I->modifiesRegister(PhysDef, TRI))
264 static bool isCopy(const MachineInstr *MI, const TargetInstrInfo *TII) {
265 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
266 return MI->isCopyLike() ||
267 TII->isMoveInstr(*MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
270 bool MachineCSE::isCSECandidate(MachineInstr *MI) {
271 if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
272 MI->isKill() || MI->isInlineAsm() || MI->isDebugValue())
279 // Ignore stuff that we obviously can't move.
280 const TargetInstrDesc &TID = MI->getDesc();
281 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
282 TID.hasUnmodeledSideEffects())
286 // Okay, this instruction does a load. As a refinement, we allow the target
287 // to decide whether the loaded value is actually a constant. If so, we can
288 // actually use it as a load.
289 if (!MI->isInvariantLoad(AA))
290 // FIXME: we should be able to hoist loads with no other side effects if
291 // there are no other instructions which can change memory in this loop.
292 // This is a trivial form of alias analysis.
298 /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
299 /// common expression that defines Reg.
300 bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
301 MachineInstr *CSMI, MachineInstr *MI) {
302 // FIXME: Heuristics that works around the lack the live range splitting.
304 // Heuristics #1: Don't cse "cheap" computating if the def is not local or in an
305 // immediate predecessor. We don't want to increase register pressure and end up
306 // causing other computation to be spilled.
307 if (MI->getDesc().isAsCheapAsAMove()) {
308 MachineBasicBlock *CSBB = CSMI->getParent();
309 MachineBasicBlock *BB = MI->getParent();
311 find(CSBB->succ_begin(), CSBB->succ_end(), BB) == CSBB->succ_end())
315 // Heuristics #2: If the expression doesn't not use a vr and the only use
316 // of the redundant computation are copies, do not cse.
317 bool HasVRegUse = false;
318 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
319 const MachineOperand &MO = MI->getOperand(i);
320 if (MO.isReg() && MO.isUse() && MO.getReg() &&
321 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
327 bool HasNonCopyUse = false;
328 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
329 E = MRI->use_nodbg_end(); I != E; ++I) {
330 MachineInstr *Use = &*I;
332 if (!isCopy(Use, TII)) {
333 HasNonCopyUse = true;
341 // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
342 // it unless the defined value is already used in the BB of the new use.
344 SmallPtrSet<MachineBasicBlock*, 4> CSBBs;
345 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(CSReg),
346 E = MRI->use_nodbg_end(); I != E; ++I) {
347 MachineInstr *Use = &*I;
348 HasPHI |= Use->isPHI();
349 CSBBs.insert(Use->getParent());
354 return CSBBs.count(MI->getParent());
357 void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
358 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
359 ScopeType *Scope = new ScopeType(VNT);
360 ScopeMap[MBB] = Scope;
363 void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
364 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
365 DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
366 assert(SI != ScopeMap.end());
371 bool MachineCSE::ProcessBlock(MachineBasicBlock *MBB) {
372 bool Changed = false;
374 SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
375 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
376 MachineInstr *MI = &*I;
379 if (!isCSECandidate(MI))
382 bool DefPhys = false;
383 bool FoundCSE = VNT.count(MI);
385 // Look for trivial copy coalescing opportunities.
386 if (PerformTrivialCoalescing(MI, MBB)) {
387 // After coalescing MI itself may become a copy.
390 FoundCSE = VNT.count(MI);
393 // FIXME: commute commutable instructions?
395 // If the instruction defines a physical register and the value *may* be
396 // used, then it's not safe to replace it with a common subexpression.
397 unsigned PhysDef = 0;
398 if (FoundCSE && hasLivePhysRegDefUse(MI, MBB, PhysDef)) {
401 // ... Unless the CS is local and it also defines the physical register
402 // which is not clobbered in between.
404 unsigned CSVN = VNT.lookup(MI);
405 MachineInstr *CSMI = Exps[CSVN];
406 if (PhysRegDefReaches(CSMI, MI, PhysDef)) {
414 VNT.insert(MI, CurrVN++);
419 // Found a common subexpression, eliminate it.
420 unsigned CSVN = VNT.lookup(MI);
421 MachineInstr *CSMI = Exps[CSVN];
422 DEBUG(dbgs() << "Examining: " << *MI);
423 DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
425 // Check if it's profitable to perform this CSE.
427 unsigned NumDefs = MI->getDesc().getNumDefs();
428 for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
429 MachineOperand &MO = MI->getOperand(i);
430 if (!MO.isReg() || !MO.isDef())
432 unsigned OldReg = MO.getReg();
433 unsigned NewReg = CSMI->getOperand(i).getReg();
434 if (OldReg == NewReg)
436 assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
437 TargetRegisterInfo::isVirtualRegister(NewReg) &&
438 "Do not CSE physical register defs!");
439 if (!isProfitableToCSE(NewReg, OldReg, CSMI, MI)) {
443 CSEPairs.push_back(std::make_pair(OldReg, NewReg));
447 // Actually perform the elimination.
449 for (unsigned i = 0, e = CSEPairs.size(); i != e; ++i) {
450 MRI->replaceRegWith(CSEPairs[i].first, CSEPairs[i].second);
451 MRI->clearKillFlags(CSEPairs[i].second);
453 MI->eraseFromParent();
458 DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
459 VNT.insert(MI, CurrVN++);
468 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
469 /// dominator tree node if its a leaf or all of its children are done. Walk
470 /// up the dominator tree to destroy ancestors which are now done.
472 MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
473 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
474 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
475 if (OpenChildren[Node])
479 ExitScope(Node->getBlock());
481 // Now traverse upwards to pop ancestors whose offsprings are all done.
482 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
483 unsigned Left = --OpenChildren[Parent];
486 ExitScope(Parent->getBlock());
491 bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
492 SmallVector<MachineDomTreeNode*, 32> Scopes;
493 SmallVector<MachineDomTreeNode*, 8> WorkList;
494 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
495 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
497 // Perform a DFS walk to determine the order of visit.
498 WorkList.push_back(Node);
500 Node = WorkList.pop_back_val();
501 Scopes.push_back(Node);
502 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
503 unsigned NumChildren = Children.size();
504 OpenChildren[Node] = NumChildren;
505 for (unsigned i = 0; i != NumChildren; ++i) {
506 MachineDomTreeNode *Child = Children[i];
507 ParentMap[Child] = Node;
508 WorkList.push_back(Child);
510 } while (!WorkList.empty());
513 bool Changed = false;
514 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
515 MachineDomTreeNode *Node = Scopes[i];
516 MachineBasicBlock *MBB = Node->getBlock();
518 Changed |= ProcessBlock(MBB);
519 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
520 ExitScopeIfDone(Node, OpenChildren, ParentMap);
526 bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
527 TII = MF.getTarget().getInstrInfo();
528 TRI = MF.getTarget().getRegisterInfo();
529 MRI = &MF.getRegInfo();
530 AA = &getAnalysis<AliasAnalysis>();
531 DT = &getAnalysis<MachineDominatorTree>();
532 return PerformCSE(DT->getRootNode());