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/Target/TargetInstrInfo.h"
22 #include "llvm/ADT/ScopedHashTable.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Support/Debug.h"
28 STATISTIC(NumCoalesces, "Number of copies coalesced");
29 STATISTIC(NumCSEs, "Number of common subexpression eliminated");
32 class MachineCSE : public MachineFunctionPass {
33 const TargetInstrInfo *TII;
34 const TargetRegisterInfo *TRI;
35 MachineRegisterInfo *MRI;
36 MachineDominatorTree *DT;
38 static char ID; // Pass identification
39 MachineCSE() : MachineFunctionPass(&ID), CurrVN(0) {}
41 virtual bool runOnMachineFunction(MachineFunction &MF);
43 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
45 MachineFunctionPass::getAnalysisUsage(AU);
46 AU.addRequired<MachineDominatorTree>();
47 AU.addPreserved<MachineDominatorTree>();
52 ScopedHashTable<MachineInstr*, unsigned, MachineInstrExpressionTrait> VNT;
53 SmallVector<MachineInstr*, 64> Exps;
55 bool hasLivePhysRegDefUse(MachineInstr *MI, MachineBasicBlock *MBB);
56 bool isPhysDefTriviallyDead(unsigned Reg,
57 MachineBasicBlock::const_iterator I,
58 MachineBasicBlock::const_iterator E);
59 bool PerformTrivialCoalescing(MachineInstr *MI, MachineBasicBlock *MBB);
60 bool ProcessBlock(MachineDomTreeNode *Node);
62 } // end anonymous namespace
64 char MachineCSE::ID = 0;
65 static RegisterPass<MachineCSE>
66 X("machine-cse", "Machine Common Subexpression Elimination");
68 FunctionPass *llvm::createMachineCSEPass() { return new MachineCSE(); }
70 bool MachineCSE::PerformTrivialCoalescing(MachineInstr *MI,
71 MachineBasicBlock *MBB) {
73 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
74 MachineOperand &MO = MI->getOperand(i);
75 if (!MO.isReg() || !MO.isUse())
77 unsigned Reg = MO.getReg();
78 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
80 if (!MRI->hasOneUse(Reg))
81 // Only coalesce single use copies. This ensure the copy will be
84 MachineInstr *DefMI = MRI->getVRegDef(Reg);
85 if (DefMI->getParent() != MBB)
87 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
88 if (TII->isMoveInstr(*DefMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx) &&
89 TargetRegisterInfo::isVirtualRegister(SrcReg) &&
90 !SrcSubIdx && !DstSubIdx) {
92 DefMI->eraseFromParent();
101 bool MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
102 MachineBasicBlock::const_iterator I,
103 MachineBasicBlock::const_iterator E) {
104 unsigned LookAheadLeft = 5;
105 while (LookAheadLeft--) {
107 // Reached end of block, register is obviously dead.
110 if (I->isDebugValue())
112 bool SeenDef = false;
113 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
114 const MachineOperand &MO = I->getOperand(i);
115 if (!MO.isReg() || !MO.getReg())
117 if (!TRI->regsOverlap(MO.getReg(), Reg))
124 // See a def of Reg (or an alias) before encountering any use, it's
132 bool MachineCSE::hasLivePhysRegDefUse(MachineInstr *MI, MachineBasicBlock *MBB){
133 unsigned PhysDef = 0;
134 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
135 MachineOperand &MO = MI->getOperand(i);
138 unsigned Reg = MO.getReg();
141 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
143 // Can't touch anything to read a physical register.
146 // If the def is dead, it's ok.
148 // Ok, this is a physical register def that's not marked "dead". That's
149 // common since this pass is run before livevariables. We can scan
150 // forward a few instructions and check if it is obviously dead.
152 // Multiple physical register defs. These are rare, forget about it.
159 MachineBasicBlock::iterator I = MI; I = llvm::next(I);
160 if (!isPhysDefTriviallyDead(PhysDef, I, MBB->end()))
166 bool MachineCSE::ProcessBlock(MachineDomTreeNode *Node) {
167 bool Changed = false;
169 ScopedHashTableScope<MachineInstr*, unsigned,
170 MachineInstrExpressionTrait> VNTS(VNT);
171 MachineBasicBlock *MBB = Node->getBlock();
172 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
173 MachineInstr *MI = &*I;
175 bool SawStore = false;
176 if (!MI->isSafeToMove(TII, 0, SawStore))
178 // 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())
185 bool FoundCSE = VNT.count(MI);
187 // Look for trivial copy coalescing opportunities.
188 if (PerformTrivialCoalescing(MI, MBB))
189 FoundCSE = VNT.count(MI);
191 // FIXME: commute commutable instructions?
193 // If the instruction defines a physical register and the value *may* be
194 // used, then it's not safe to replace it with a common subexpression.
195 if (FoundCSE && hasLivePhysRegDefUse(MI, MBB))
199 VNT.insert(MI, CurrVN++);
204 // Found a common subexpression, eliminate it.
205 unsigned CSVN = VNT.lookup(MI);
206 MachineInstr *CSMI = Exps[CSVN];
207 DEBUG(dbgs() << "Examining: " << *MI);
208 DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
209 unsigned NumDefs = MI->getDesc().getNumDefs();
210 for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
211 MachineOperand &MO = MI->getOperand(i);
212 if (!MO.isReg() || !MO.isDef())
214 unsigned OldReg = MO.getReg();
215 unsigned NewReg = CSMI->getOperand(i).getReg();
216 assert(OldReg != NewReg &&
217 TargetRegisterInfo::isVirtualRegister(OldReg) &&
218 TargetRegisterInfo::isVirtualRegister(NewReg) &&
219 "Do not CSE physical register defs!");
220 MRI->replaceRegWith(OldReg, NewReg);
223 MI->eraseFromParent();
227 // Recursively call ProcessBlock with childred.
228 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
229 for (unsigned i = 0, e = Children.size(); i != e; ++i)
230 Changed |= ProcessBlock(Children[i]);
235 bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
236 TII = MF.getTarget().getInstrInfo();
237 TRI = MF.getTarget().getRegisterInfo();
238 MRI = &MF.getRegInfo();
239 DT = &getAnalysis<MachineDominatorTree>();
240 return ProcessBlock(DT->getRootNode());