1 //===-- 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
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.
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"
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"
28
29 using namespace llvm;
30
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");
34
35 namespace {
36 class MachineCSE : public MachineFunctionPass {
37 const TargetInstrInfo *TII;
38 const TargetRegisterInfo *TRI;
39 AliasAnalysis *AA;
40 MachineDominatorTree *DT;
41 MachineRegisterInfo *MRI;
42 public:
43 static char ID; // Pass identification
MachineCSE()44 MachineCSE() : MachineFunctionPass(ID), LookAheadLimit(5), CurrVN(0) {}
45
46 virtual bool runOnMachineFunction(MachineFunction &MF);
47
getAnalysisUsage(AnalysisUsage & AU) const48 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
49 AU.setPreservesCFG();
50 MachineFunctionPass::getAnalysisUsage(AU);
51 AU.addRequired<AliasAnalysis>();
52 AU.addPreservedID(MachineLoopInfoID);
53 AU.addRequired<MachineDominatorTree>();
54 AU.addPreserved<MachineDominatorTree>();
55 }
56
releaseMemory()57 virtual void releaseMemory() {
58 ScopeMap.clear();
59 Exps.clear();
60 }
61
62 private:
63 const unsigned LookAheadLimit;
64 typedef ScopedHashTableScope<MachineInstr*, unsigned,
65 MachineInstrExpressionTrait> ScopeType;
66 DenseMap<MachineBasicBlock*, ScopeType*> ScopeMap;
67 ScopedHashTable<MachineInstr*, unsigned, MachineInstrExpressionTrait> VNT;
68 SmallVector<MachineInstr*, 64> Exps;
69 unsigned CurrVN;
70
71 bool PerformTrivialCoalescing(MachineInstr *MI, MachineBasicBlock *MBB);
72 bool isPhysDefTriviallyDead(unsigned Reg,
73 MachineBasicBlock::const_iterator I,
74 MachineBasicBlock::const_iterator E) const ;
75 bool hasLivePhysRegDefUse(const MachineInstr *MI,
76 const MachineBasicBlock *MBB,
77 unsigned &PhysDef) const;
78 bool PhysRegDefReaches(MachineInstr *CSMI, MachineInstr *MI,
79 unsigned PhysDef) const;
80 bool isCSECandidate(MachineInstr *MI);
81 bool isProfitableToCSE(unsigned CSReg, unsigned Reg,
82 MachineInstr *CSMI, MachineInstr *MI);
83 void EnterScope(MachineBasicBlock *MBB);
84 void ExitScope(MachineBasicBlock *MBB);
85 bool ProcessBlock(MachineBasicBlock *MBB);
86 void ExitScopeIfDone(MachineDomTreeNode *Node,
87 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
88 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
89 bool PerformCSE(MachineDomTreeNode *Node);
90 };
91 } // end anonymous namespace
92
93 char MachineCSE::ID = 0;
94 INITIALIZE_PASS(MachineCSE, "machine-cse",
95 "Machine Common Subexpression Elimination", false, false);
96
createMachineCSEPass()97 FunctionPass *llvm::createMachineCSEPass() { return new MachineCSE(); }
98
PerformTrivialCoalescing(MachineInstr * MI,MachineBasicBlock * MBB)99 bool MachineCSE::PerformTrivialCoalescing(MachineInstr *MI,
100 MachineBasicBlock *MBB) {
101 bool Changed = false;
102 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
103 MachineOperand &MO = MI->getOperand(i);
104 if (!MO.isReg() || !MO.isUse())
105 continue;
106 unsigned Reg = MO.getReg();
107 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
108 continue;
109 if (!MRI->hasOneNonDBGUse(Reg))
110 // Only coalesce single use copies. This ensure the copy will be
111 // deleted.
112 continue;
113 MachineInstr *DefMI = MRI->getVRegDef(Reg);
114 if (DefMI->getParent() != MBB)
115 continue;
116 if (!DefMI->isCopy())
117 continue;
118 unsigned SrcReg = DefMI->getOperand(1).getReg();
119 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
120 continue;
121 if (DefMI->getOperand(0).getSubReg() || DefMI->getOperand(1).getSubReg())
122 continue;
123 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg);
124 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
125 const TargetRegisterClass *NewRC = getCommonSubClass(RC, SRC);
126 if (!NewRC)
127 continue;
128 DEBUG(dbgs() << "Coalescing: " << *DefMI);
129 DEBUG(dbgs() << "*** to: " << *MI);
130 MO.setReg(SrcReg);
131 MRI->clearKillFlags(SrcReg);
132 if (NewRC != SRC)
133 MRI->setRegClass(SrcReg, NewRC);
134 DefMI->eraseFromParent();
135 ++NumCoalesces;
136 Changed = true;
137 }
138
139 return Changed;
140 }
141
142 bool
isPhysDefTriviallyDead(unsigned Reg,MachineBasicBlock::const_iterator I,MachineBasicBlock::const_iterator E) const143 MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
144 MachineBasicBlock::const_iterator I,
145 MachineBasicBlock::const_iterator E) const {
146 unsigned LookAheadLeft = LookAheadLimit;
147 while (LookAheadLeft) {
148 // Skip over dbg_value's.
149 while (I != E && I->isDebugValue())
150 ++I;
151
152 if (I == E)
153 // Reached end of block, register is obviously dead.
154 return true;
155
156 bool SeenDef = false;
157 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
158 const MachineOperand &MO = I->getOperand(i);
159 if (!MO.isReg() || !MO.getReg())
160 continue;
161 if (!TRI->regsOverlap(MO.getReg(), Reg))
162 continue;
163 if (MO.isUse())
164 // Found a use!
165 return false;
166 SeenDef = true;
167 }
168 if (SeenDef)
169 // See a def of Reg (or an alias) before encountering any use, it's
170 // trivially dead.
171 return true;
172
173 --LookAheadLeft;
174 ++I;
175 }
176 return false;
177 }
178
179 /// hasLivePhysRegDefUse - Return true if the specified instruction read / write
180 /// physical registers (except for dead defs of physical registers). It also
181 /// returns the physical register def by reference if it's the only one and the
182 /// instruction does not uses a physical register.
hasLivePhysRegDefUse(const MachineInstr * MI,const MachineBasicBlock * MBB,unsigned & PhysDef) const183 bool MachineCSE::hasLivePhysRegDefUse(const MachineInstr *MI,
184 const MachineBasicBlock *MBB,
185 unsigned &PhysDef) const {
186 PhysDef = 0;
187 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
188 const MachineOperand &MO = MI->getOperand(i);
189 if (!MO.isReg())
190 continue;
191 unsigned Reg = MO.getReg();
192 if (!Reg)
193 continue;
194 if (TargetRegisterInfo::isVirtualRegister(Reg))
195 continue;
196 if (MO.isUse()) {
197 // Can't touch anything to read a physical register.
198 PhysDef = 0;
199 return true;
200 }
201 if (MO.isDead())
202 // If the def is dead, it's ok.
203 continue;
204 // Ok, this is a physical register def that's not marked "dead". That's
205 // common since this pass is run before livevariables. We can scan
206 // forward a few instructions and check if it is obviously dead.
207 if (PhysDef) {
208 // Multiple physical register defs. These are rare, forget about it.
209 PhysDef = 0;
210 return true;
211 }
212 PhysDef = Reg;
213 }
214
215 if (PhysDef) {
216 MachineBasicBlock::const_iterator I = MI; I = llvm::next(I);
217 if (!isPhysDefTriviallyDead(PhysDef, I, MBB->end()))
218 return true;
219 }
220 return false;
221 }
222
PhysRegDefReaches(MachineInstr * CSMI,MachineInstr * MI,unsigned PhysDef) const223 bool MachineCSE::PhysRegDefReaches(MachineInstr *CSMI, MachineInstr *MI,
224 unsigned PhysDef) const {
225 // For now conservatively returns false if the common subexpression is
226 // not in the same basic block as the given instruction.
227 MachineBasicBlock *MBB = MI->getParent();
228 if (CSMI->getParent() != MBB)
229 return false;
230 MachineBasicBlock::const_iterator I = CSMI; I = llvm::next(I);
231 MachineBasicBlock::const_iterator E = MI;
232 unsigned LookAheadLeft = LookAheadLimit;
233 while (LookAheadLeft) {
234 // Skip over dbg_value's.
235 while (I != E && I->isDebugValue())
236 ++I;
237
238 if (I == E)
239 return true;
240 if (I->modifiesRegister(PhysDef, TRI))
241 return false;
242
243 --LookAheadLeft;
244 ++I;
245 }
246
247 return false;
248 }
249
isCSECandidate(MachineInstr * MI)250 bool MachineCSE::isCSECandidate(MachineInstr *MI) {
251 if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
252 MI->isKill() || MI->isInlineAsm() || MI->isDebugValue())
253 return false;
254
255 // Ignore copies.
256 if (MI->isCopyLike())
257 return false;
258
259 // Ignore stuff that we obviously can't move.
260 const TargetInstrDesc &TID = MI->getDesc();
261 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
262 TID.hasUnmodeledSideEffects())
263 return false;
264
265 if (TID.mayLoad()) {
266 // Okay, this instruction does a load. As a refinement, we allow the target
267 // to decide whether the loaded value is actually a constant. If so, we can
268 // actually use it as a load.
269 if (!MI->isInvariantLoad(AA))
270 // FIXME: we should be able to hoist loads with no other side effects if
271 // there are no other instructions which can change memory in this loop.
272 // This is a trivial form of alias analysis.
273 return false;
274 }
275 return true;
276 }
277
278 /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
279 /// common expression that defines Reg.
isProfitableToCSE(unsigned CSReg,unsigned Reg,MachineInstr * CSMI,MachineInstr * MI)280 bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
281 MachineInstr *CSMI, MachineInstr *MI) {
282 // FIXME: Heuristics that works around the lack the live range splitting.
283
284 // Heuristics #1: Don't cse "cheap" computating if the def is not local or in an
285 // immediate predecessor. We don't want to increase register pressure and end up
286 // causing other computation to be spilled.
287 if (MI->getDesc().isAsCheapAsAMove()) {
288 MachineBasicBlock *CSBB = CSMI->getParent();
289 MachineBasicBlock *BB = MI->getParent();
290 if (CSBB != BB &&
291 find(CSBB->succ_begin(), CSBB->succ_end(), BB) == CSBB->succ_end())
292 return false;
293 }
294
295 // Heuristics #2: If the expression doesn't not use a vr and the only use
296 // of the redundant computation are copies, do not cse.
297 bool HasVRegUse = false;
298 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
299 const MachineOperand &MO = MI->getOperand(i);
300 if (MO.isReg() && MO.isUse() && MO.getReg() &&
301 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
302 HasVRegUse = true;
303 break;
304 }
305 }
306 if (!HasVRegUse) {
307 bool HasNonCopyUse = false;
308 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
309 E = MRI->use_nodbg_end(); I != E; ++I) {
310 MachineInstr *Use = &*I;
311 // Ignore copies.
312 if (!Use->isCopyLike()) {
313 HasNonCopyUse = true;
314 break;
315 }
316 }
317 if (!HasNonCopyUse)
318 return false;
319 }
320
321 // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
322 // it unless the defined value is already used in the BB of the new use.
323 bool HasPHI = false;
324 SmallPtrSet<MachineBasicBlock*, 4> CSBBs;
325 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(CSReg),
326 E = MRI->use_nodbg_end(); I != E; ++I) {
327 MachineInstr *Use = &*I;
328 HasPHI |= Use->isPHI();
329 CSBBs.insert(Use->getParent());
330 }
331
332 if (!HasPHI)
333 return true;
334 return CSBBs.count(MI->getParent());
335 }
336
EnterScope(MachineBasicBlock * MBB)337 void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
338 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
339 ScopeType *Scope = new ScopeType(VNT);
340 ScopeMap[MBB] = Scope;
341 }
342
ExitScope(MachineBasicBlock * MBB)343 void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
344 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
345 DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
346 assert(SI != ScopeMap.end());
347 ScopeMap.erase(SI);
348 delete SI->second;
349 }
350
ProcessBlock(MachineBasicBlock * MBB)351 bool MachineCSE::ProcessBlock(MachineBasicBlock *MBB) {
352 bool Changed = false;
353
354 SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
355 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
356 MachineInstr *MI = &*I;
357 ++I;
358
359 if (!isCSECandidate(MI))
360 continue;
361
362 bool DefPhys = false;
363 bool FoundCSE = VNT.count(MI);
364 if (!FoundCSE) {
365 // Look for trivial copy coalescing opportunities.
366 if (PerformTrivialCoalescing(MI, MBB)) {
367 // After coalescing MI itself may become a copy.
368 if (MI->isCopyLike())
369 continue;
370 FoundCSE = VNT.count(MI);
371 }
372 }
373 // FIXME: commute commutable instructions?
374
375 // If the instruction defines a physical register and the value *may* be
376 // used, then it's not safe to replace it with a common subexpression.
377 unsigned PhysDef = 0;
378 if (FoundCSE && hasLivePhysRegDefUse(MI, MBB, PhysDef)) {
379 FoundCSE = false;
380
381 // ... Unless the CS is local and it also defines the physical register
382 // which is not clobbered in between.
383 if (PhysDef) {
384 unsigned CSVN = VNT.lookup(MI);
385 MachineInstr *CSMI = Exps[CSVN];
386 if (PhysRegDefReaches(CSMI, MI, PhysDef)) {
387 FoundCSE = true;
388 DefPhys = true;
389 }
390 }
391 }
392
393 if (!FoundCSE) {
394 VNT.insert(MI, CurrVN++);
395 Exps.push_back(MI);
396 continue;
397 }
398
399 // Found a common subexpression, eliminate it.
400 unsigned CSVN = VNT.lookup(MI);
401 MachineInstr *CSMI = Exps[CSVN];
402 DEBUG(dbgs() << "Examining: " << *MI);
403 DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
404
405 // Check if it's profitable to perform this CSE.
406 bool DoCSE = true;
407 unsigned NumDefs = MI->getDesc().getNumDefs();
408 for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
409 MachineOperand &MO = MI->getOperand(i);
410 if (!MO.isReg() || !MO.isDef())
411 continue;
412 unsigned OldReg = MO.getReg();
413 unsigned NewReg = CSMI->getOperand(i).getReg();
414 if (OldReg == NewReg)
415 continue;
416 assert(TargetRegisterInfo::isVirtualRegister(OldReg) &&
417 TargetRegisterInfo::isVirtualRegister(NewReg) &&
418 "Do not CSE physical register defs!");
419 if (!isProfitableToCSE(NewReg, OldReg, CSMI, MI)) {
420 DoCSE = false;
421 break;
422 }
423 CSEPairs.push_back(std::make_pair(OldReg, NewReg));
424 --NumDefs;
425 }
426
427 // Actually perform the elimination.
428 if (DoCSE) {
429 for (unsigned i = 0, e = CSEPairs.size(); i != e; ++i) {
430 MRI->replaceRegWith(CSEPairs[i].first, CSEPairs[i].second);
431 MRI->clearKillFlags(CSEPairs[i].second);
432 }
433 MI->eraseFromParent();
434 ++NumCSEs;
435 if (DefPhys)
436 ++NumPhysCSEs;
437 } else {
438 DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
439 VNT.insert(MI, CurrVN++);
440 Exps.push_back(MI);
441 }
442 CSEPairs.clear();
443 }
444
445 return Changed;
446 }
447
448 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
449 /// dominator tree node if its a leaf or all of its children are done. Walk
450 /// up the dominator tree to destroy ancestors which are now done.
451 void
ExitScopeIfDone(MachineDomTreeNode * Node,DenseMap<MachineDomTreeNode *,unsigned> & OpenChildren,DenseMap<MachineDomTreeNode *,MachineDomTreeNode * > & ParentMap)452 MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
453 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
454 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
455 if (OpenChildren[Node])
456 return;
457
458 // Pop scope.
459 ExitScope(Node->getBlock());
460
461 // Now traverse upwards to pop ancestors whose offsprings are all done.
462 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
463 unsigned Left = --OpenChildren[Parent];
464 if (Left != 0)
465 break;
466 ExitScope(Parent->getBlock());
467 Node = Parent;
468 }
469 }
470
PerformCSE(MachineDomTreeNode * Node)471 bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
472 SmallVector<MachineDomTreeNode*, 32> Scopes;
473 SmallVector<MachineDomTreeNode*, 8> WorkList;
474 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
475 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
476
477 CurrVN = 0;
478
479 // Perform a DFS walk to determine the order of visit.
480 WorkList.push_back(Node);
481 do {
482 Node = WorkList.pop_back_val();
483 Scopes.push_back(Node);
484 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
485 unsigned NumChildren = Children.size();
486 OpenChildren[Node] = NumChildren;
487 for (unsigned i = 0; i != NumChildren; ++i) {
488 MachineDomTreeNode *Child = Children[i];
489 ParentMap[Child] = Node;
490 WorkList.push_back(Child);
491 }
492 } while (!WorkList.empty());
493
494 // Now perform CSE.
495 bool Changed = false;
496 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
497 MachineDomTreeNode *Node = Scopes[i];
498 MachineBasicBlock *MBB = Node->getBlock();
499 EnterScope(MBB);
500 Changed |= ProcessBlock(MBB);
501 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
502 ExitScopeIfDone(Node, OpenChildren, ParentMap);
503 }
504
505 return Changed;
506 }
507
runOnMachineFunction(MachineFunction & MF)508 bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
509 TII = MF.getTarget().getInstrInfo();
510 TRI = MF.getTarget().getRegisterInfo();
511 MRI = &MF.getRegInfo();
512 AA = &getAnalysis<AliasAnalysis>();
513 DT = &getAnalysis<MachineDominatorTree>();
514 return PerformCSE(DT->getRootNode());
515 }
516