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