xref: /src/contrib/llvm-project/llvm/lib/CodeGen/MachineCSE.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1044eb2f6SDimitry Andric //===- MachineCSE.cpp - Machine Common Subexpression Elimination Pass -----===//
267a71b31SRoman Divacky //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
667a71b31SRoman Divacky //
767a71b31SRoman Divacky //===----------------------------------------------------------------------===//
867a71b31SRoman Divacky //
967a71b31SRoman Divacky // This pass performs global common subexpression elimination on machine
1067a71b31SRoman Divacky // instructions using a scoped hash table based value numbering scheme. It
1167a71b31SRoman Divacky // must be run while the machine function is still in SSA form.
1267a71b31SRoman Divacky //
1367a71b31SRoman Divacky //===----------------------------------------------------------------------===//
1467a71b31SRoman Divacky 
15d7f7719eSRoman Divacky #include "llvm/ADT/DenseMap.h"
1667a71b31SRoman Divacky #include "llvm/ADT/ScopedHashTable.h"
17044eb2f6SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
18cf099d11SDimitry Andric #include "llvm/ADT/SmallSet.h"
19044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
2067a71b31SRoman Divacky #include "llvm/ADT/Statistic.h"
214a16efa3SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
22e6d15924SDimitry Andric #include "llvm/Analysis/CFG.h"
23044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
241d5ae102SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
254a16efa3SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
26044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
27044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
284a16efa3SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
29044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
304a16efa3SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
317ab83427SDimitry Andric #include "llvm/CodeGen/Passes.h"
32044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
33044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
34044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
35044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
36706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
37b60736ecSDimitry Andric #include "llvm/MC/MCRegister.h"
38044eb2f6SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
39044eb2f6SDimitry Andric #include "llvm/Pass.h"
40044eb2f6SDimitry Andric #include "llvm/Support/Allocator.h"
4167a71b31SRoman Divacky #include "llvm/Support/Debug.h"
42cf099d11SDimitry Andric #include "llvm/Support/RecyclingAllocator.h"
435a5ac124SDimitry Andric #include "llvm/Support/raw_ostream.h"
44044eb2f6SDimitry Andric #include <cassert>
45044eb2f6SDimitry Andric #include <iterator>
46044eb2f6SDimitry Andric #include <utility>
47044eb2f6SDimitry Andric 
4867a71b31SRoman Divacky using namespace llvm;
4967a71b31SRoman Divacky 
505ca98fd9SDimitry Andric #define DEBUG_TYPE "machine-cse"
515ca98fd9SDimitry Andric 
52f5a3459aSRoman Divacky STATISTIC(NumCoalesces, "Number of copies coalesced");
53f5a3459aSRoman Divacky STATISTIC(NumCSEs,      "Number of common subexpression eliminated");
54e6d15924SDimitry Andric STATISTIC(NumPREs,      "Number of partial redundant expression"
55e6d15924SDimitry Andric                         " transformed to fully redundant");
56cf099d11SDimitry Andric STATISTIC(NumPhysCSEs,
57cf099d11SDimitry Andric           "Number of physreg referencing common subexpr eliminated");
5863faed5bSDimitry Andric STATISTIC(NumCrossBBCSEs,
5963faed5bSDimitry Andric           "Number of cross-MBB physreg referencing CS eliminated");
60cf099d11SDimitry Andric STATISTIC(NumCommutes,  "Number of copies coalesced after commuting");
61abdf259dSRoman Divacky 
62e3b55780SDimitry Andric // Threshold to avoid excessive cost to compute isProfitableToCSE.
63e3b55780SDimitry Andric static cl::opt<int>
64e3b55780SDimitry Andric     CSUsesThreshold("csuses-threshold", cl::Hidden, cl::init(1024),
65e3b55780SDimitry Andric                     cl::desc("Threshold for the size of CSUses"));
66e3b55780SDimitry Andric 
67b1c73532SDimitry Andric static cl::opt<bool> AggressiveMachineCSE(
68b1c73532SDimitry Andric     "aggressive-machine-cse", cl::Hidden, cl::init(false),
69b1c73532SDimitry Andric     cl::desc("Override the profitability heuristics for Machine CSE"));
70b1c73532SDimitry Andric 
7167a71b31SRoman Divacky namespace {
72044eb2f6SDimitry Andric 
7367a71b31SRoman Divacky   class MachineCSE : public MachineFunctionPass {
747fa27ce4SDimitry Andric     const TargetInstrInfo *TII = nullptr;
757fa27ce4SDimitry Andric     const TargetRegisterInfo *TRI = nullptr;
767fa27ce4SDimitry Andric     AliasAnalysis *AA = nullptr;
777fa27ce4SDimitry Andric     MachineDominatorTree *DT = nullptr;
787fa27ce4SDimitry Andric     MachineRegisterInfo *MRI = nullptr;
797fa27ce4SDimitry Andric     MachineBlockFrequencyInfo *MBFI = nullptr;
80044eb2f6SDimitry Andric 
8167a71b31SRoman Divacky   public:
8267a71b31SRoman Divacky     static char ID; // Pass identification
83044eb2f6SDimitry Andric 
MachineCSE()84044eb2f6SDimitry Andric     MachineCSE() : MachineFunctionPass(ID) {
85cf099d11SDimitry Andric       initializeMachineCSEPass(*PassRegistry::getPassRegistry());
86cf099d11SDimitry Andric     }
8767a71b31SRoman Divacky 
885ca98fd9SDimitry Andric     bool runOnMachineFunction(MachineFunction &MF) override;
8967a71b31SRoman Divacky 
getAnalysisUsage(AnalysisUsage & AU) const905ca98fd9SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
9167a71b31SRoman Divacky       AU.setPreservesCFG();
9267a71b31SRoman Divacky       MachineFunctionPass::getAnalysisUsage(AU);
93dd58ef01SDimitry Andric       AU.addRequired<AAResultsWrapperPass>();
94d39c594dSDimitry Andric       AU.addPreservedID(MachineLoopInfoID);
95ac9a064cSDimitry Andric       AU.addRequired<MachineDominatorTreeWrapperPass>();
96ac9a064cSDimitry Andric       AU.addPreserved<MachineDominatorTreeWrapperPass>();
97ac9a064cSDimitry Andric       AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
98ac9a064cSDimitry Andric       AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
9967a71b31SRoman Divacky     }
10067a71b31SRoman Divacky 
getRequiredProperties() const101145449b1SDimitry Andric     MachineFunctionProperties getRequiredProperties() const override {
102145449b1SDimitry Andric       return MachineFunctionProperties()
103145449b1SDimitry Andric         .set(MachineFunctionProperties::Property::IsSSA);
104145449b1SDimitry Andric     }
105145449b1SDimitry Andric 
releaseMemory()1065ca98fd9SDimitry Andric     void releaseMemory() override {
10749011b52SDimitry Andric       ScopeMap.clear();
108e6d15924SDimitry Andric       PREMap.clear();
10949011b52SDimitry Andric       Exps.clear();
11049011b52SDimitry Andric     }
11149011b52SDimitry Andric 
11267a71b31SRoman Divacky   private:
113044eb2f6SDimitry Andric     using AllocatorTy = RecyclingAllocator<BumpPtrAllocator,
114044eb2f6SDimitry Andric                             ScopedHashTableVal<MachineInstr *, unsigned>>;
115044eb2f6SDimitry Andric     using ScopedHTType =
116044eb2f6SDimitry Andric         ScopedHashTable<MachineInstr *, unsigned, MachineInstrExpressionTrait,
117044eb2f6SDimitry Andric                         AllocatorTy>;
118044eb2f6SDimitry Andric     using ScopeType = ScopedHTType::ScopeTy;
119e6d15924SDimitry Andric     using PhysDefVector = SmallVector<std::pair<unsigned, unsigned>, 2>;
120044eb2f6SDimitry Andric 
121044eb2f6SDimitry Andric     unsigned LookAheadLimit = 0;
122d7f7719eSRoman Divacky     DenseMap<MachineBasicBlock *, ScopeType *> ScopeMap;
123e6d15924SDimitry Andric     DenseMap<MachineInstr *, MachineBasicBlock *, MachineInstrExpressionTrait>
124e6d15924SDimitry Andric         PREMap;
125cf099d11SDimitry Andric     ScopedHTType VNT;
126f5a3459aSRoman Divacky     SmallVector<MachineInstr *, 64> Exps;
127044eb2f6SDimitry Andric     unsigned CurrVN = 0;
128f5a3459aSRoman Divacky 
12967c32a98SDimitry Andric     bool PerformTrivialCopyPropagation(MachineInstr *MI,
13067c32a98SDimitry Andric                                        MachineBasicBlock *MBB);
131b60736ecSDimitry Andric     bool isPhysDefTriviallyDead(MCRegister Reg,
132f5a3459aSRoman Divacky                                 MachineBasicBlock::const_iterator I,
133abdf259dSRoman Divacky                                 MachineBasicBlock::const_iterator E) const;
134cf099d11SDimitry Andric     bool hasLivePhysRegDefUses(const MachineInstr *MI,
135abdf259dSRoman Divacky                                const MachineBasicBlock *MBB,
136b60736ecSDimitry Andric                                SmallSet<MCRegister, 8> &PhysRefs,
137e6d15924SDimitry Andric                                PhysDefVector &PhysDefs, bool &PhysUseDef) const;
138cf099d11SDimitry Andric     bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
139b60736ecSDimitry Andric                           SmallSet<MCRegister, 8> &PhysRefs,
140e6d15924SDimitry Andric                           PhysDefVector &PhysDefs, bool &NonLocal) const;
141f5a3459aSRoman Divacky     bool isCSECandidate(MachineInstr *MI);
142b60736ecSDimitry Andric     bool isProfitableToCSE(Register CSReg, Register Reg,
143e6d15924SDimitry Andric                            MachineBasicBlock *CSBB, MachineInstr *MI);
144d7f7719eSRoman Divacky     void EnterScope(MachineBasicBlock *MBB);
145d7f7719eSRoman Divacky     void ExitScope(MachineBasicBlock *MBB);
146e6d15924SDimitry Andric     bool ProcessBlockCSE(MachineBasicBlock *MBB);
147d7f7719eSRoman Divacky     void ExitScopeIfDone(MachineDomTreeNode *Node,
14858b69754SDimitry Andric                          DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren);
149d7f7719eSRoman Divacky     bool PerformCSE(MachineDomTreeNode *Node);
150e6d15924SDimitry Andric 
151e3b55780SDimitry Andric     bool isPRECandidate(MachineInstr *MI, SmallSet<MCRegister, 8> &PhysRefs);
152e6d15924SDimitry Andric     bool ProcessBlockPRE(MachineDominatorTree *MDT, MachineBasicBlock *MBB);
153e6d15924SDimitry Andric     bool PerformSimplePRE(MachineDominatorTree *DT);
1541d5ae102SDimitry Andric     /// Heuristics to see if it's profitable to move common computations of MBB
1551d5ae102SDimitry Andric     /// and MBB1 to CandidateBB.
1561d5ae102SDimitry Andric     bool isProfitableToHoistInto(MachineBasicBlock *CandidateBB,
1571d5ae102SDimitry Andric                                  MachineBasicBlock *MBB,
1581d5ae102SDimitry Andric                                  MachineBasicBlock *MBB1);
15967a71b31SRoman Divacky   };
160044eb2f6SDimitry Andric 
16167a71b31SRoman Divacky } // end anonymous namespace
16267a71b31SRoman Divacky 
16367a71b31SRoman Divacky char MachineCSE::ID = 0;
164044eb2f6SDimitry Andric 
16563faed5bSDimitry Andric char &llvm::MachineCSEID = MachineCSE::ID;
166044eb2f6SDimitry Andric 
167ab44ce3dSDimitry Andric INITIALIZE_PASS_BEGIN(MachineCSE, DEBUG_TYPE,
168cf099d11SDimitry Andric                       "Machine Common Subexpression Elimination", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)169ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
170dd58ef01SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
171ab44ce3dSDimitry Andric INITIALIZE_PASS_END(MachineCSE, DEBUG_TYPE,
172cf099d11SDimitry Andric                     "Machine Common Subexpression Elimination", false, false)
17367a71b31SRoman Divacky 
17467c32a98SDimitry Andric /// The source register of a COPY machine instruction can be propagated to all
17567c32a98SDimitry Andric /// its users, and this propagation could increase the probability of finding
17667c32a98SDimitry Andric /// common subexpressions. If the COPY has only one user, the COPY itself can
17767c32a98SDimitry Andric /// be removed.
17867c32a98SDimitry Andric bool MachineCSE::PerformTrivialCopyPropagation(MachineInstr *MI,
17967a71b31SRoman Divacky                                                MachineBasicBlock *MBB) {
18067a71b31SRoman Divacky   bool Changed = false;
1817fa27ce4SDimitry Andric   for (MachineOperand &MO : MI->all_uses()) {
1821d5ae102SDimitry Andric     Register Reg = MO.getReg();
183e3b55780SDimitry Andric     if (!Reg.isVirtual())
18467a71b31SRoman Divacky       continue;
18567c32a98SDimitry Andric     bool OnlyOneUse = MRI->hasOneNonDBGUse(Reg);
18667a71b31SRoman Divacky     MachineInstr *DefMI = MRI->getVRegDef(Reg);
187ac9a064cSDimitry Andric     if (!DefMI || !DefMI->isCopy())
18866e41e3cSRoman Divacky       continue;
1891d5ae102SDimitry Andric     Register SrcReg = DefMI->getOperand(1).getReg();
190e3b55780SDimitry Andric     if (!SrcReg.isVirtual())
19166e41e3cSRoman Divacky       continue;
1925ca98fd9SDimitry Andric     if (DefMI->getOperand(0).getSubReg())
19366e41e3cSRoman Divacky       continue;
1945ca98fd9SDimitry Andric     // FIXME: We should trivially coalesce subregister copies to expose CSE
1955ca98fd9SDimitry Andric     // opportunities on instructions with truncated operands (see
1965ca98fd9SDimitry Andric     // cse-add-with-overflow.ll). This can be done here as follows:
1975ca98fd9SDimitry Andric     // if (SrcSubReg)
1985ca98fd9SDimitry Andric     //  RC = TRI->getMatchingSuperRegClass(MRI->getRegClass(SrcReg), RC,
1995ca98fd9SDimitry Andric     //                                     SrcSubReg);
2005ca98fd9SDimitry Andric     // MO.substVirtReg(SrcReg, SrcSubReg, *TRI);
2015ca98fd9SDimitry Andric     //
2025ca98fd9SDimitry Andric     // The 2-addr pass has been updated to handle coalesced subregs. However,
2035ca98fd9SDimitry Andric     // some machine-specific code still can't handle it.
2045ca98fd9SDimitry Andric     // To handle it properly we also need a way find a constrained subregister
2055ca98fd9SDimitry Andric     // class given a super-reg class and subreg index.
2065ca98fd9SDimitry Andric     if (DefMI->getOperand(1).getSubReg())
2075ca98fd9SDimitry Andric       continue;
208eb11fae6SDimitry Andric     if (!MRI->constrainRegAttrs(SrcReg, Reg))
20966e41e3cSRoman Divacky       continue;
210eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
211eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "***     to: " << *MI);
212d8e91e46SDimitry Andric 
21367c32a98SDimitry Andric     // Propagate SrcReg of copies to MI.
21466e41e3cSRoman Divacky     MO.setReg(SrcReg);
21566e41e3cSRoman Divacky     MRI->clearKillFlags(SrcReg);
21667c32a98SDimitry Andric     // Coalesce single use copies.
21767c32a98SDimitry Andric     if (OnlyOneUse) {
2181d5ae102SDimitry Andric       // If (and only if) we've eliminated all uses of the copy, also
2191d5ae102SDimitry Andric       // copy-propagate to any debug-users of MI, or they'll be left using
2201d5ae102SDimitry Andric       // an undefined value.
2211d5ae102SDimitry Andric       DefMI->changeDebugValuesDefReg(SrcReg);
2221d5ae102SDimitry Andric 
22366e41e3cSRoman Divacky       DefMI->eraseFromParent();
22466e41e3cSRoman Divacky       ++NumCoalesces;
22567c32a98SDimitry Andric     }
22666e41e3cSRoman Divacky     Changed = true;
22767a71b31SRoman Divacky   }
22867a71b31SRoman Divacky 
22967a71b31SRoman Divacky   return Changed;
23067a71b31SRoman Divacky }
23167a71b31SRoman Divacky 
isPhysDefTriviallyDead(MCRegister Reg,MachineBasicBlock::const_iterator I,MachineBasicBlock::const_iterator E) const232b60736ecSDimitry Andric bool MachineCSE::isPhysDefTriviallyDead(
233b60736ecSDimitry Andric     MCRegister Reg, MachineBasicBlock::const_iterator I,
234abdf259dSRoman Divacky     MachineBasicBlock::const_iterator E) const {
235abdf259dSRoman Divacky   unsigned LookAheadLeft = LookAheadLimit;
236104bd817SRoman Divacky   while (LookAheadLeft) {
237104bd817SRoman Divacky     // Skip over dbg_value's.
238b915e9e0SDimitry Andric     I = skipDebugInstructionsForward(I, E);
239104bd817SRoman Divacky 
240f5a3459aSRoman Divacky     if (I == E)
241ab44ce3dSDimitry Andric       // Reached end of block, we don't know if register is dead or not.
242ab44ce3dSDimitry Andric       return false;
243f5a3459aSRoman Divacky 
244f5a3459aSRoman Divacky     bool SeenDef = false;
2458a6c1c25SDimitry Andric     for (const MachineOperand &MO : I->operands()) {
24663faed5bSDimitry Andric       if (MO.isRegMask() && MO.clobbersPhysReg(Reg))
24763faed5bSDimitry Andric         SeenDef = true;
248f5a3459aSRoman Divacky       if (!MO.isReg() || !MO.getReg())
249f5a3459aSRoman Divacky         continue;
250f5a3459aSRoman Divacky       if (!TRI->regsOverlap(MO.getReg(), Reg))
251f5a3459aSRoman Divacky         continue;
252f5a3459aSRoman Divacky       if (MO.isUse())
253abdf259dSRoman Divacky         // Found a use!
254f5a3459aSRoman Divacky         return false;
255f5a3459aSRoman Divacky       SeenDef = true;
256f5a3459aSRoman Divacky     }
257f5a3459aSRoman Divacky     if (SeenDef)
258f5a3459aSRoman Divacky       // See a def of Reg (or an alias) before encountering any use, it's
259f5a3459aSRoman Divacky       // trivially dead.
260f5a3459aSRoman Divacky       return true;
261104bd817SRoman Divacky 
262104bd817SRoman Divacky     --LookAheadLeft;
263f5a3459aSRoman Divacky     ++I;
264f5a3459aSRoman Divacky   }
265f5a3459aSRoman Divacky   return false;
266f5a3459aSRoman Divacky }
267f5a3459aSRoman Divacky 
isCallerPreservedOrConstPhysReg(MCRegister Reg,const MachineOperand & MO,const MachineFunction & MF,const TargetRegisterInfo & TRI,const TargetInstrInfo & TII)268b60736ecSDimitry Andric static bool isCallerPreservedOrConstPhysReg(MCRegister Reg,
269e3b55780SDimitry Andric                                             const MachineOperand &MO,
270d8e91e46SDimitry Andric                                             const MachineFunction &MF,
271e3b55780SDimitry Andric                                             const TargetRegisterInfo &TRI,
272e3b55780SDimitry Andric                                             const TargetInstrInfo &TII) {
273d8e91e46SDimitry Andric   // MachineRegisterInfo::isConstantPhysReg directly called by
274d8e91e46SDimitry Andric   // MachineRegisterInfo::isCallerPreservedOrConstPhysReg expects the
275d8e91e46SDimitry Andric   // reserved registers to be frozen. That doesn't cause a problem  post-ISel as
276d8e91e46SDimitry Andric   // most (if not all) targets freeze reserved registers right after ISel.
277d8e91e46SDimitry Andric   //
278d8e91e46SDimitry Andric   // It does cause issues mid-GlobalISel, however, hence the additional
279d8e91e46SDimitry Andric   // reservedRegsFrozen check.
280d8e91e46SDimitry Andric   const MachineRegisterInfo &MRI = MF.getRegInfo();
281e3b55780SDimitry Andric   return TRI.isCallerPreservedPhysReg(Reg, MF) || TII.isIgnorableUse(MO) ||
282d8e91e46SDimitry Andric          (MRI.reservedRegsFrozen() && MRI.isConstantPhysReg(Reg));
283d8e91e46SDimitry Andric }
284d8e91e46SDimitry Andric 
285cf099d11SDimitry Andric /// hasLivePhysRegDefUses - Return true if the specified instruction read/write
286abdf259dSRoman Divacky /// physical registers (except for dead defs of physical registers). It also
28766e41e3cSRoman Divacky /// returns the physical register def by reference if it's the only one and the
28866e41e3cSRoman Divacky /// instruction does not uses a physical register.
hasLivePhysRegDefUses(const MachineInstr * MI,const MachineBasicBlock * MBB,SmallSet<MCRegister,8> & PhysRefs,PhysDefVector & PhysDefs,bool & PhysUseDef) const289cf099d11SDimitry Andric bool MachineCSE::hasLivePhysRegDefUses(const MachineInstr *MI,
290abdf259dSRoman Divacky                                        const MachineBasicBlock *MBB,
291b60736ecSDimitry Andric                                        SmallSet<MCRegister, 8> &PhysRefs,
292e6d15924SDimitry Andric                                        PhysDefVector &PhysDefs,
293522600a2SDimitry Andric                                        bool &PhysUseDef) const {
294522600a2SDimitry Andric   // First, add all uses to PhysRefs.
2957fa27ce4SDimitry Andric   for (const MachineOperand &MO : MI->all_uses()) {
2961d5ae102SDimitry Andric     Register Reg = MO.getReg();
29767a71b31SRoman Divacky     if (!Reg)
29867a71b31SRoman Divacky       continue;
299e3b55780SDimitry Andric     if (Reg.isVirtual())
300abdf259dSRoman Divacky       continue;
301044eb2f6SDimitry Andric     // Reading either caller preserved or constant physregs is ok.
302e3b55780SDimitry Andric     if (!isCallerPreservedOrConstPhysReg(Reg.asMCReg(), MO, *MI->getMF(), *TRI,
303e3b55780SDimitry Andric                                          *TII))
30458b69754SDimitry Andric       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
30558b69754SDimitry Andric         PhysRefs.insert(*AI);
306522600a2SDimitry Andric   }
307522600a2SDimitry Andric 
308522600a2SDimitry Andric   // Next, collect all defs into PhysDefs.  If any is already in PhysRefs
309522600a2SDimitry Andric   // (which currently contains only uses), set the PhysUseDef flag.
310522600a2SDimitry Andric   PhysUseDef = false;
3115ca98fd9SDimitry Andric   MachineBasicBlock::const_iterator I = MI; I = std::next(I);
312e6d15924SDimitry Andric   for (const auto &MOP : llvm::enumerate(MI->operands())) {
313e6d15924SDimitry Andric     const MachineOperand &MO = MOP.value();
314522600a2SDimitry Andric     if (!MO.isReg() || !MO.isDef())
315522600a2SDimitry Andric       continue;
3161d5ae102SDimitry Andric     Register Reg = MO.getReg();
317522600a2SDimitry Andric     if (!Reg)
318522600a2SDimitry Andric       continue;
319e3b55780SDimitry Andric     if (Reg.isVirtual())
320522600a2SDimitry Andric       continue;
321522600a2SDimitry Andric     // Check against PhysRefs even if the def is "dead".
322b60736ecSDimitry Andric     if (PhysRefs.count(Reg.asMCReg()))
323522600a2SDimitry Andric       PhysUseDef = true;
324522600a2SDimitry Andric     // If the def is dead, it's ok. But the def may not marked "dead". That's
325522600a2SDimitry Andric     // common since this pass is run before livevariables. We can scan
326522600a2SDimitry Andric     // forward a few instructions and check if it is obviously dead.
327b60736ecSDimitry Andric     if (!MO.isDead() && !isPhysDefTriviallyDead(Reg.asMCReg(), I, MBB->end()))
328e6d15924SDimitry Andric       PhysDefs.push_back(std::make_pair(MOP.index(), Reg));
329f5a3459aSRoman Divacky   }
330f5a3459aSRoman Divacky 
331522600a2SDimitry Andric   // Finally, add all defs to PhysRefs as well.
332522600a2SDimitry Andric   for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i)
333e6d15924SDimitry Andric     for (MCRegAliasIterator AI(PhysDefs[i].second, TRI, true); AI.isValid();
334e6d15924SDimitry Andric          ++AI)
335522600a2SDimitry Andric       PhysRefs.insert(*AI);
336522600a2SDimitry Andric 
337cf099d11SDimitry Andric   return !PhysRefs.empty();
33867a71b31SRoman Divacky }
33967a71b31SRoman Divacky 
PhysRegDefsReach(MachineInstr * CSMI,MachineInstr * MI,SmallSet<MCRegister,8> & PhysRefs,PhysDefVector & PhysDefs,bool & NonLocal) const340cf099d11SDimitry Andric bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
341b60736ecSDimitry Andric                                   SmallSet<MCRegister, 8> &PhysRefs,
342e6d15924SDimitry Andric                                   PhysDefVector &PhysDefs,
34363faed5bSDimitry Andric                                   bool &NonLocal) const {
344abdf259dSRoman Divacky   // For now conservatively returns false if the common subexpression is
34563faed5bSDimitry Andric   // not in the same basic block as the given instruction. The only exception
34663faed5bSDimitry Andric   // is if the common subexpression is in the sole predecessor block.
34763faed5bSDimitry Andric   const MachineBasicBlock *MBB = MI->getParent();
34863faed5bSDimitry Andric   const MachineBasicBlock *CSMBB = CSMI->getParent();
34963faed5bSDimitry Andric 
35063faed5bSDimitry Andric   bool CrossMBB = false;
35163faed5bSDimitry Andric   if (CSMBB != MBB) {
35263faed5bSDimitry Andric     if (MBB->pred_size() != 1 || *MBB->pred_begin() != CSMBB)
353abdf259dSRoman Divacky       return false;
35463faed5bSDimitry Andric 
35563faed5bSDimitry Andric     for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
356e6d15924SDimitry Andric       if (MRI->isAllocatable(PhysDefs[i].second) ||
357e6d15924SDimitry Andric           MRI->isReserved(PhysDefs[i].second))
35863faed5bSDimitry Andric         // Avoid extending live range of physical registers if they are
35963faed5bSDimitry Andric         //allocatable or reserved.
36063faed5bSDimitry Andric         return false;
36163faed5bSDimitry Andric     }
36263faed5bSDimitry Andric     CrossMBB = true;
36363faed5bSDimitry Andric   }
3645ca98fd9SDimitry Andric   MachineBasicBlock::const_iterator I = CSMI; I = std::next(I);
365abdf259dSRoman Divacky   MachineBasicBlock::const_iterator E = MI;
36663faed5bSDimitry Andric   MachineBasicBlock::const_iterator EE = CSMBB->end();
367abdf259dSRoman Divacky   unsigned LookAheadLeft = LookAheadLimit;
368abdf259dSRoman Divacky   while (LookAheadLeft) {
369abdf259dSRoman Divacky     // Skip over dbg_value's.
370eb11fae6SDimitry Andric     while (I != E && I != EE && I->isDebugInstr())
371abdf259dSRoman Divacky       ++I;
372abdf259dSRoman Divacky 
37363faed5bSDimitry Andric     if (I == EE) {
37463faed5bSDimitry Andric       assert(CrossMBB && "Reaching end-of-MBB without finding MI?");
37563faed5bSDimitry Andric       (void)CrossMBB;
37663faed5bSDimitry Andric       CrossMBB = false;
37763faed5bSDimitry Andric       NonLocal = true;
37863faed5bSDimitry Andric       I = MBB->begin();
37963faed5bSDimitry Andric       EE = MBB->end();
38063faed5bSDimitry Andric       continue;
38163faed5bSDimitry Andric     }
38263faed5bSDimitry Andric 
383abdf259dSRoman Divacky     if (I == E)
384abdf259dSRoman Divacky       return true;
385cf099d11SDimitry Andric 
3868a6c1c25SDimitry Andric     for (const MachineOperand &MO : I->operands()) {
38763faed5bSDimitry Andric       // RegMasks go on instructions like calls that clobber lots of physregs.
38863faed5bSDimitry Andric       // Don't attempt to CSE across such an instruction.
38963faed5bSDimitry Andric       if (MO.isRegMask())
39063faed5bSDimitry Andric         return false;
391cf099d11SDimitry Andric       if (!MO.isReg() || !MO.isDef())
392cf099d11SDimitry Andric         continue;
3931d5ae102SDimitry Andric       Register MOReg = MO.getReg();
394e3b55780SDimitry Andric       if (MOReg.isVirtual())
395cf099d11SDimitry Andric         continue;
396b60736ecSDimitry Andric       if (PhysRefs.count(MOReg.asMCReg()))
397abdf259dSRoman Divacky         return false;
398cf099d11SDimitry Andric     }
399abdf259dSRoman Divacky 
400abdf259dSRoman Divacky     --LookAheadLeft;
401abdf259dSRoman Divacky     ++I;
402abdf259dSRoman Divacky   }
403abdf259dSRoman Divacky 
404abdf259dSRoman Divacky   return false;
405abdf259dSRoman Divacky }
406abdf259dSRoman Divacky 
isCSECandidate(MachineInstr * MI)407ea5b2dd1SRoman Divacky bool MachineCSE::isCSECandidate(MachineInstr *MI) {
4085ca98fd9SDimitry Andric   if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() || MI->isKill() ||
409b1c73532SDimitry Andric       MI->isInlineAsm() || MI->isDebugInstr() || MI->isJumpTableDebugInfo())
410ea5b2dd1SRoman Divacky     return false;
411ea5b2dd1SRoman Divacky 
412ea5b2dd1SRoman Divacky   // Ignore copies.
413d39c594dSDimitry Andric   if (MI->isCopyLike())
414f5a3459aSRoman Divacky     return false;
415f5a3459aSRoman Divacky 
416f5a3459aSRoman Divacky   // Ignore stuff that we obviously can't move.
41763faed5bSDimitry Andric   if (MI->mayStore() || MI->isCall() || MI->isTerminator() ||
418e6d15924SDimitry Andric       MI->mayRaiseFPException() || MI->hasUnmodeledSideEffects())
419f5a3459aSRoman Divacky     return false;
420f5a3459aSRoman Divacky 
42163faed5bSDimitry Andric   if (MI->mayLoad()) {
422f5a3459aSRoman Divacky     // Okay, this instruction does a load. As a refinement, we allow the target
423f5a3459aSRoman Divacky     // to decide whether the loaded value is actually a constant. If so, we can
424f5a3459aSRoman Divacky     // actually use it as a load.
4254b4fe385SDimitry Andric     if (!MI->isDereferenceableInvariantLoad())
426f5a3459aSRoman Divacky       // FIXME: we should be able to hoist loads with no other side effects if
427f5a3459aSRoman Divacky       // there are no other instructions which can change memory in this loop.
428f5a3459aSRoman Divacky       // This is a trivial form of alias analysis.
429f5a3459aSRoman Divacky       return false;
430f5a3459aSRoman Divacky   }
43101095a5dSDimitry Andric 
43201095a5dSDimitry Andric   // Ignore stack guard loads, otherwise the register that holds CSEed value may
43301095a5dSDimitry Andric   // be spilled and get loaded back with corrupted data.
43401095a5dSDimitry Andric   if (MI->getOpcode() == TargetOpcode::LOAD_STACK_GUARD)
43501095a5dSDimitry Andric     return false;
43601095a5dSDimitry Andric 
437f5a3459aSRoman Divacky   return true;
438f5a3459aSRoman Divacky }
439f5a3459aSRoman Divacky 
440ea5b2dd1SRoman Divacky /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
441e6d15924SDimitry Andric /// common expression that defines Reg. CSBB is basic block where CSReg is
442e6d15924SDimitry Andric /// defined.
isProfitableToCSE(Register CSReg,Register Reg,MachineBasicBlock * CSBB,MachineInstr * MI)443b60736ecSDimitry Andric bool MachineCSE::isProfitableToCSE(Register CSReg, Register Reg,
444e6d15924SDimitry Andric                                    MachineBasicBlock *CSBB, MachineInstr *MI) {
445b1c73532SDimitry Andric   if (AggressiveMachineCSE)
446b1c73532SDimitry Andric     return true;
447b1c73532SDimitry Andric 
448ea5b2dd1SRoman Divacky   // FIXME: Heuristics that works around the lack the live range splitting.
449ea5b2dd1SRoman Divacky 
45058b69754SDimitry Andric   // If CSReg is used at all uses of Reg, CSE should not increase register
45158b69754SDimitry Andric   // pressure of CSReg.
45258b69754SDimitry Andric   bool MayIncreasePressure = true;
453e3b55780SDimitry Andric   if (CSReg.isVirtual() && Reg.isVirtual()) {
45458b69754SDimitry Andric     MayIncreasePressure = false;
45558b69754SDimitry Andric     SmallPtrSet<MachineInstr*, 8> CSUses;
456e3b55780SDimitry Andric     int NumOfUses = 0;
4575ca98fd9SDimitry Andric     for (MachineInstr &MI : MRI->use_nodbg_instructions(CSReg)) {
4585ca98fd9SDimitry Andric       CSUses.insert(&MI);
459e3b55780SDimitry Andric       // Too costly to compute if NumOfUses is very large. Conservatively assume
460e3b55780SDimitry Andric       // MayIncreasePressure to avoid spending too much time here.
461e3b55780SDimitry Andric       if (++NumOfUses > CSUsesThreshold) {
462e3b55780SDimitry Andric         MayIncreasePressure = true;
463e3b55780SDimitry Andric         break;
46458b69754SDimitry Andric       }
465e3b55780SDimitry Andric     }
466e3b55780SDimitry Andric     if (!MayIncreasePressure)
4675ca98fd9SDimitry Andric       for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
4685ca98fd9SDimitry Andric         if (!CSUses.count(&MI)) {
46958b69754SDimitry Andric           MayIncreasePressure = true;
47058b69754SDimitry Andric           break;
47158b69754SDimitry Andric         }
47258b69754SDimitry Andric       }
47358b69754SDimitry Andric   }
47458b69754SDimitry Andric   if (!MayIncreasePressure) return true;
47558b69754SDimitry Andric 
476cf099d11SDimitry Andric   // Heuristics #1: Don't CSE "cheap" computation if the def is not local or in
477cf099d11SDimitry Andric   // an immediate predecessor. We don't want to increase register pressure and
478cf099d11SDimitry Andric   // end up causing other computation to be spilled.
47901095a5dSDimitry Andric   if (TII->isAsCheapAsAMove(*MI)) {
480ea5b2dd1SRoman Divacky     MachineBasicBlock *BB = MI->getParent();
481cf099d11SDimitry Andric     if (CSBB != BB && !CSBB->isSuccessor(BB))
482ea5b2dd1SRoman Divacky       return false;
483ea5b2dd1SRoman Divacky   }
484ea5b2dd1SRoman Divacky 
485ea5b2dd1SRoman Divacky   // Heuristics #2: If the expression doesn't not use a vr and the only use
486ea5b2dd1SRoman Divacky   // of the redundant computation are copies, do not cse.
487ea5b2dd1SRoman Divacky   bool HasVRegUse = false;
4887fa27ce4SDimitry Andric   for (const MachineOperand &MO : MI->all_uses()) {
4897fa27ce4SDimitry Andric     if (MO.getReg().isVirtual()) {
490ea5b2dd1SRoman Divacky       HasVRegUse = true;
491ea5b2dd1SRoman Divacky       break;
492ea5b2dd1SRoman Divacky     }
493ea5b2dd1SRoman Divacky   }
494ea5b2dd1SRoman Divacky   if (!HasVRegUse) {
495ea5b2dd1SRoman Divacky     bool HasNonCopyUse = false;
4965ca98fd9SDimitry Andric     for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
497ea5b2dd1SRoman Divacky       // Ignore copies.
4985ca98fd9SDimitry Andric       if (!MI.isCopyLike()) {
499ea5b2dd1SRoman Divacky         HasNonCopyUse = true;
500ea5b2dd1SRoman Divacky         break;
501ea5b2dd1SRoman Divacky       }
502ea5b2dd1SRoman Divacky     }
503ea5b2dd1SRoman Divacky     if (!HasNonCopyUse)
504ea5b2dd1SRoman Divacky       return false;
505ea5b2dd1SRoman Divacky   }
506ea5b2dd1SRoman Divacky 
507ea5b2dd1SRoman Divacky   // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
508ea5b2dd1SRoman Divacky   // it unless the defined value is already used in the BB of the new use.
509ea5b2dd1SRoman Divacky   bool HasPHI = false;
510eb11fae6SDimitry Andric   for (MachineInstr &UseMI : MRI->use_nodbg_instructions(CSReg)) {
511eb11fae6SDimitry Andric     HasPHI |= UseMI.isPHI();
512eb11fae6SDimitry Andric     if (UseMI.getParent() == MI->getParent())
513eb11fae6SDimitry Andric       return true;
514ea5b2dd1SRoman Divacky   }
515ea5b2dd1SRoman Divacky 
516eb11fae6SDimitry Andric   return !HasPHI;
517ea5b2dd1SRoman Divacky }
518ea5b2dd1SRoman Divacky 
EnterScope(MachineBasicBlock * MBB)519d7f7719eSRoman Divacky void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
520eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
521d7f7719eSRoman Divacky   ScopeType *Scope = new ScopeType(VNT);
522d7f7719eSRoman Divacky   ScopeMap[MBB] = Scope;
523d7f7719eSRoman Divacky }
524d7f7719eSRoman Divacky 
ExitScope(MachineBasicBlock * MBB)525d7f7719eSRoman Divacky void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
526eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
527d7f7719eSRoman Divacky   DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
528d7f7719eSRoman Divacky   assert(SI != ScopeMap.end());
529d7f7719eSRoman Divacky   delete SI->second;
530522600a2SDimitry Andric   ScopeMap.erase(SI);
531d7f7719eSRoman Divacky }
532d7f7719eSRoman Divacky 
ProcessBlockCSE(MachineBasicBlock * MBB)533e6d15924SDimitry Andric bool MachineCSE::ProcessBlockCSE(MachineBasicBlock *MBB) {
534f5a3459aSRoman Divacky   bool Changed = false;
535f5a3459aSRoman Divacky 
536ea5b2dd1SRoman Divacky   SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
53758b69754SDimitry Andric   SmallVector<unsigned, 2> ImplicitDefsToUpdate;
53867c32a98SDimitry Andric   SmallVector<unsigned, 2> ImplicitDefs;
539c0981da4SDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(*MBB)) {
540c0981da4SDimitry Andric     if (!isCSECandidate(&MI))
54167a71b31SRoman Divacky       continue;
54267a71b31SRoman Divacky 
543c0981da4SDimitry Andric     bool FoundCSE = VNT.count(&MI);
54467a71b31SRoman Divacky     if (!FoundCSE) {
54567c32a98SDimitry Andric       // Using trivial copy propagation to find more CSE opportunities.
546c0981da4SDimitry Andric       if (PerformTrivialCopyPropagation(&MI, MBB)) {
5476b943ff3SDimitry Andric         Changed = true;
5486b943ff3SDimitry Andric 
549104bd817SRoman Divacky         // After coalescing MI itself may become a copy.
550c0981da4SDimitry Andric         if (MI.isCopyLike())
551104bd817SRoman Divacky           continue;
55267c32a98SDimitry Andric 
55367c32a98SDimitry Andric         // Try again to see if CSE is possible.
554c0981da4SDimitry Andric         FoundCSE = VNT.count(&MI);
55567a71b31SRoman Divacky       }
556104bd817SRoman Divacky     }
55767a71b31SRoman Divacky 
558cf099d11SDimitry Andric     // Commute commutable instructions.
559cf099d11SDimitry Andric     bool Commuted = false;
560c0981da4SDimitry Andric     if (!FoundCSE && MI.isCommutable()) {
561c0981da4SDimitry Andric       if (MachineInstr *NewMI = TII->commuteInstruction(MI)) {
562cf099d11SDimitry Andric         Commuted = true;
563cf099d11SDimitry Andric         FoundCSE = VNT.count(NewMI);
564c0981da4SDimitry Andric         if (NewMI != &MI) {
565cf099d11SDimitry Andric           // New instruction. It doesn't need to be kept.
566cf099d11SDimitry Andric           NewMI->eraseFromParent();
5676b943ff3SDimitry Andric           Changed = true;
5686b943ff3SDimitry Andric         } else if (!FoundCSE)
569cf099d11SDimitry Andric           // MI was changed but it didn't help, commute it back!
570c0981da4SDimitry Andric           (void)TII->commuteInstruction(MI);
571cf099d11SDimitry Andric       }
572cf099d11SDimitry Andric     }
573cf099d11SDimitry Andric 
574cf099d11SDimitry Andric     // If the instruction defines physical registers and the values *may* be
575f5a3459aSRoman Divacky     // used, then it's not safe to replace it with a common subexpression.
576cf099d11SDimitry Andric     // It's also not safe if the instruction uses physical registers.
57763faed5bSDimitry Andric     bool CrossMBBPhysDef = false;
578b60736ecSDimitry Andric     SmallSet<MCRegister, 8> PhysRefs;
579e6d15924SDimitry Andric     PhysDefVector PhysDefs;
580522600a2SDimitry Andric     bool PhysUseDef = false;
581c0981da4SDimitry Andric     if (FoundCSE &&
582c0981da4SDimitry Andric         hasLivePhysRegDefUses(&MI, MBB, PhysRefs, PhysDefs, PhysUseDef)) {
583f5a3459aSRoman Divacky       FoundCSE = false;
584f5a3459aSRoman Divacky 
58563faed5bSDimitry Andric       // ... Unless the CS is local or is in the sole predecessor block
58663faed5bSDimitry Andric       // and it also defines the physical register which is not clobbered
58763faed5bSDimitry Andric       // in between and the physical register uses were not clobbered.
588522600a2SDimitry Andric       // This can never be the case if the instruction both uses and
589522600a2SDimitry Andric       // defines the same physical register, which was detected above.
590522600a2SDimitry Andric       if (!PhysUseDef) {
591c0981da4SDimitry Andric         unsigned CSVN = VNT.lookup(&MI);
592abdf259dSRoman Divacky         MachineInstr *CSMI = Exps[CSVN];
593c0981da4SDimitry Andric         if (PhysRegDefsReach(CSMI, &MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
594abdf259dSRoman Divacky           FoundCSE = true;
595abdf259dSRoman Divacky       }
596522600a2SDimitry Andric     }
597abdf259dSRoman Divacky 
598f5a3459aSRoman Divacky     if (!FoundCSE) {
599c0981da4SDimitry Andric       VNT.insert(&MI, CurrVN++);
600c0981da4SDimitry Andric       Exps.push_back(&MI);
601f5a3459aSRoman Divacky       continue;
602f5a3459aSRoman Divacky     }
603f5a3459aSRoman Divacky 
604f5a3459aSRoman Divacky     // Found a common subexpression, eliminate it.
605c0981da4SDimitry Andric     unsigned CSVN = VNT.lookup(&MI);
606f5a3459aSRoman Divacky     MachineInstr *CSMI = Exps[CSVN];
607c0981da4SDimitry Andric     LLVM_DEBUG(dbgs() << "Examining: " << MI);
608eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
609ea5b2dd1SRoman Divacky 
610344a3780SDimitry Andric     // Prevent CSE-ing non-local convergent instructions.
611344a3780SDimitry Andric     // LLVM's current definition of `isConvergent` does not necessarily prove
612344a3780SDimitry Andric     // that non-local CSE is illegal. The following check extends the definition
613344a3780SDimitry Andric     // of `isConvergent` to assume a convergent instruction is dependent not
614344a3780SDimitry Andric     // only on additional conditions, but also on fewer conditions. LLVM does
615344a3780SDimitry Andric     // not have a MachineInstr attribute which expresses this extended
616344a3780SDimitry Andric     // definition, so it's necessary to use `isConvergent` to prevent illegally
617344a3780SDimitry Andric     // CSE-ing the subset of `isConvergent` instructions which do fall into this
618344a3780SDimitry Andric     // extended definition.
619c0981da4SDimitry Andric     if (MI.isConvergent() && MI.getParent() != CSMI->getParent()) {
620344a3780SDimitry Andric       LLVM_DEBUG(dbgs() << "*** Convergent MI and subexpression exist in "
621344a3780SDimitry Andric                            "different BBs, avoid CSE!\n");
622c0981da4SDimitry Andric       VNT.insert(&MI, CurrVN++);
623c0981da4SDimitry Andric       Exps.push_back(&MI);
624344a3780SDimitry Andric       continue;
625344a3780SDimitry Andric     }
626344a3780SDimitry Andric 
627ea5b2dd1SRoman Divacky     // Check if it's profitable to perform this CSE.
628ea5b2dd1SRoman Divacky     bool DoCSE = true;
629c0981da4SDimitry Andric     unsigned NumDefs = MI.getNumDefs();
63058b69754SDimitry Andric 
631c0981da4SDimitry Andric     for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
632c0981da4SDimitry Andric       MachineOperand &MO = MI.getOperand(i);
633f5a3459aSRoman Divacky       if (!MO.isReg() || !MO.isDef())
634f5a3459aSRoman Divacky         continue;
6351d5ae102SDimitry Andric       Register OldReg = MO.getReg();
6361d5ae102SDimitry Andric       Register NewReg = CSMI->getOperand(i).getReg();
63758b69754SDimitry Andric 
63858b69754SDimitry Andric       // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
63958b69754SDimitry Andric       // we should make sure it is not dead at CSMI.
64058b69754SDimitry Andric       if (MO.isImplicit() && !MO.isDead() && CSMI->getOperand(i).isDead())
64158b69754SDimitry Andric         ImplicitDefsToUpdate.push_back(i);
64267c32a98SDimitry Andric 
64367c32a98SDimitry Andric       // Keep track of implicit defs of CSMI and MI, to clear possibly
64467c32a98SDimitry Andric       // made-redundant kill flags.
64567c32a98SDimitry Andric       if (MO.isImplicit() && !MO.isDead() && OldReg == NewReg)
64667c32a98SDimitry Andric         ImplicitDefs.push_back(OldReg);
64767c32a98SDimitry Andric 
64858b69754SDimitry Andric       if (OldReg == NewReg) {
64958b69754SDimitry Andric         --NumDefs;
650f5a3459aSRoman Divacky         continue;
65158b69754SDimitry Andric       }
65230815c53SDimitry Andric 
653e3b55780SDimitry Andric       assert(OldReg.isVirtual() && NewReg.isVirtual() &&
654f5a3459aSRoman Divacky              "Do not CSE physical register defs!");
65530815c53SDimitry Andric 
656c0981da4SDimitry Andric       if (!isProfitableToCSE(NewReg, OldReg, CSMI->getParent(), &MI)) {
657eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
658ea5b2dd1SRoman Divacky         DoCSE = false;
659ea5b2dd1SRoman Divacky         break;
660ea5b2dd1SRoman Divacky       }
66130815c53SDimitry Andric 
662eb11fae6SDimitry Andric       // Don't perform CSE if the result of the new instruction cannot exist
663eb11fae6SDimitry Andric       // within the constraints (register class, bank, or low-level type) of
664eb11fae6SDimitry Andric       // the old instruction.
665eb11fae6SDimitry Andric       if (!MRI->constrainRegAttrs(NewReg, OldReg)) {
666eb11fae6SDimitry Andric         LLVM_DEBUG(
667eb11fae6SDimitry Andric             dbgs() << "*** Not the same register constraints, avoid CSE!\n");
66830815c53SDimitry Andric         DoCSE = false;
66930815c53SDimitry Andric         break;
67030815c53SDimitry Andric       }
67130815c53SDimitry Andric 
672ea5b2dd1SRoman Divacky       CSEPairs.push_back(std::make_pair(OldReg, NewReg));
673f5a3459aSRoman Divacky       --NumDefs;
674f5a3459aSRoman Divacky     }
675ea5b2dd1SRoman Divacky 
676ea5b2dd1SRoman Divacky     // Actually perform the elimination.
677ea5b2dd1SRoman Divacky     if (DoCSE) {
678b60736ecSDimitry Andric       for (const std::pair<unsigned, unsigned> &CSEPair : CSEPairs) {
6798a6c1c25SDimitry Andric         unsigned OldReg = CSEPair.first;
6808a6c1c25SDimitry Andric         unsigned NewReg = CSEPair.second;
6815a5ac124SDimitry Andric         // OldReg may have been unused but is used now, clear the Dead flag
6825a5ac124SDimitry Andric         MachineInstr *Def = MRI->getUniqueVRegDef(NewReg);
6835a5ac124SDimitry Andric         assert(Def != nullptr && "CSEd register has no unique definition?");
6845a5ac124SDimitry Andric         Def->clearRegisterDeads(NewReg);
6855a5ac124SDimitry Andric         // Replace with NewReg and clear kill flags which may be wrong now.
6865a5ac124SDimitry Andric         MRI->replaceRegWith(OldReg, NewReg);
6875a5ac124SDimitry Andric         MRI->clearKillFlags(NewReg);
688abdf259dSRoman Divacky       }
68963faed5bSDimitry Andric 
69058b69754SDimitry Andric       // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
69158b69754SDimitry Andric       // we should make sure it is not dead at CSMI.
6928a6c1c25SDimitry Andric       for (unsigned ImplicitDefToUpdate : ImplicitDefsToUpdate)
6938a6c1c25SDimitry Andric         CSMI->getOperand(ImplicitDefToUpdate).setIsDead(false);
694b60736ecSDimitry Andric       for (const auto &PhysDef : PhysDefs)
695c0981da4SDimitry Andric         if (!MI.getOperand(PhysDef.first).isDead())
696e6d15924SDimitry Andric           CSMI->getOperand(PhysDef.first).setIsDead(false);
69758b69754SDimitry Andric 
69867c32a98SDimitry Andric       // Go through implicit defs of CSMI and MI, and clear the kill flags on
69967c32a98SDimitry Andric       // their uses in all the instructions between CSMI and MI.
70067c32a98SDimitry Andric       // We might have made some of the kill flags redundant, consider:
701044eb2f6SDimitry Andric       //   subs  ... implicit-def %nzcv    <- CSMI
702044eb2f6SDimitry Andric       //   csinc ... implicit killed %nzcv <- this kill flag isn't valid anymore
703044eb2f6SDimitry Andric       //   subs  ... implicit-def %nzcv    <- MI, to be eliminated
704044eb2f6SDimitry Andric       //   csinc ... implicit killed %nzcv
70567c32a98SDimitry Andric       // Since we eliminated MI, and reused a register imp-def'd by CSMI
706044eb2f6SDimitry Andric       // (here %nzcv), that register, if it was killed before MI, should have
70767c32a98SDimitry Andric       // that kill flag removed, because it's lifetime was extended.
708c0981da4SDimitry Andric       if (CSMI->getParent() == MI.getParent()) {
709c0981da4SDimitry Andric         for (MachineBasicBlock::iterator II = CSMI, IE = &MI; II != IE; ++II)
71067c32a98SDimitry Andric           for (auto ImplicitDef : ImplicitDefs)
71167c32a98SDimitry Andric             if (MachineOperand *MO = II->findRegisterUseOperand(
712ac9a064cSDimitry Andric                     ImplicitDef, TRI, /*isKill=*/true))
71367c32a98SDimitry Andric               MO->setIsKill(false);
71467c32a98SDimitry Andric       } else {
71567c32a98SDimitry Andric         // If the instructions aren't in the same BB, bail out and clear the
71667c32a98SDimitry Andric         // kill flag on all uses of the imp-def'd register.
71767c32a98SDimitry Andric         for (auto ImplicitDef : ImplicitDefs)
71867c32a98SDimitry Andric           MRI->clearKillFlags(ImplicitDef);
71967c32a98SDimitry Andric       }
72067c32a98SDimitry Andric 
72163faed5bSDimitry Andric       if (CrossMBBPhysDef) {
72263faed5bSDimitry Andric         // Add physical register defs now coming in from a predecessor to MBB
72363faed5bSDimitry Andric         // livein list.
72463faed5bSDimitry Andric         while (!PhysDefs.empty()) {
725e6d15924SDimitry Andric           auto LiveIn = PhysDefs.pop_back_val();
726e6d15924SDimitry Andric           if (!MBB->isLiveIn(LiveIn.second))
727e6d15924SDimitry Andric             MBB->addLiveIn(LiveIn.second);
72863faed5bSDimitry Andric         }
72963faed5bSDimitry Andric         ++NumCrossBBCSEs;
73063faed5bSDimitry Andric       }
73163faed5bSDimitry Andric 
732c0981da4SDimitry Andric       MI.eraseFromParent();
733f5a3459aSRoman Divacky       ++NumCSEs;
734cf099d11SDimitry Andric       if (!PhysRefs.empty())
73566e41e3cSRoman Divacky         ++NumPhysCSEs;
736cf099d11SDimitry Andric       if (Commuted)
737cf099d11SDimitry Andric         ++NumCommutes;
7386b943ff3SDimitry Andric       Changed = true;
739ea5b2dd1SRoman Divacky     } else {
740c0981da4SDimitry Andric       VNT.insert(&MI, CurrVN++);
741c0981da4SDimitry Andric       Exps.push_back(&MI);
742ea5b2dd1SRoman Divacky     }
743ea5b2dd1SRoman Divacky     CSEPairs.clear();
74458b69754SDimitry Andric     ImplicitDefsToUpdate.clear();
74567c32a98SDimitry Andric     ImplicitDefs.clear();
74667a71b31SRoman Divacky   }
74767a71b31SRoman Divacky 
748d7f7719eSRoman Divacky   return Changed;
749d7f7719eSRoman Divacky }
750d7f7719eSRoman Divacky 
751d7f7719eSRoman Divacky /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
752d7f7719eSRoman Divacky /// dominator tree node if its a leaf or all of its children are done. Walk
753d7f7719eSRoman Divacky /// up the dominator tree to destroy ancestors which are now done.
754d7f7719eSRoman Divacky void
ExitScopeIfDone(MachineDomTreeNode * Node,DenseMap<MachineDomTreeNode *,unsigned> & OpenChildren)755d7f7719eSRoman Divacky MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
75658b69754SDimitry Andric                         DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren) {
757d7f7719eSRoman Divacky   if (OpenChildren[Node])
758d7f7719eSRoman Divacky     return;
759d7f7719eSRoman Divacky 
760d7f7719eSRoman Divacky   // Pop scope.
761d7f7719eSRoman Divacky   ExitScope(Node->getBlock());
762d7f7719eSRoman Divacky 
763d7f7719eSRoman Divacky   // Now traverse upwards to pop ancestors whose offsprings are all done.
76458b69754SDimitry Andric   while (MachineDomTreeNode *Parent = Node->getIDom()) {
765d7f7719eSRoman Divacky     unsigned Left = --OpenChildren[Parent];
766d7f7719eSRoman Divacky     if (Left != 0)
767d7f7719eSRoman Divacky       break;
768d7f7719eSRoman Divacky     ExitScope(Parent->getBlock());
769d7f7719eSRoman Divacky     Node = Parent;
770d7f7719eSRoman Divacky   }
771d7f7719eSRoman Divacky }
772d7f7719eSRoman Divacky 
PerformCSE(MachineDomTreeNode * Node)773d7f7719eSRoman Divacky bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
774d7f7719eSRoman Divacky   SmallVector<MachineDomTreeNode*, 32> Scopes;
775d7f7719eSRoman Divacky   SmallVector<MachineDomTreeNode*, 8> WorkList;
776d7f7719eSRoman Divacky   DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
777d7f7719eSRoman Divacky 
77849011b52SDimitry Andric   CurrVN = 0;
77949011b52SDimitry Andric 
780d7f7719eSRoman Divacky   // Perform a DFS walk to determine the order of visit.
781d7f7719eSRoman Divacky   WorkList.push_back(Node);
782d7f7719eSRoman Divacky   do {
783d7f7719eSRoman Divacky     Node = WorkList.pop_back_val();
784d7f7719eSRoman Divacky     Scopes.push_back(Node);
785cfca06d7SDimitry Andric     OpenChildren[Node] = Node->getNumChildren();
786b60736ecSDimitry Andric     append_range(WorkList, Node->children());
787d7f7719eSRoman Divacky   } while (!WorkList.empty());
788d7f7719eSRoman Divacky 
789d7f7719eSRoman Divacky   // Now perform CSE.
790d7f7719eSRoman Divacky   bool Changed = false;
7918a6c1c25SDimitry Andric   for (MachineDomTreeNode *Node : Scopes) {
792d7f7719eSRoman Divacky     MachineBasicBlock *MBB = Node->getBlock();
793d7f7719eSRoman Divacky     EnterScope(MBB);
794e6d15924SDimitry Andric     Changed |= ProcessBlockCSE(MBB);
795d7f7719eSRoman Divacky     // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
79658b69754SDimitry Andric     ExitScopeIfDone(Node, OpenChildren);
797d7f7719eSRoman Divacky   }
79867a71b31SRoman Divacky 
79967a71b31SRoman Divacky   return Changed;
80067a71b31SRoman Divacky }
80167a71b31SRoman Divacky 
802e6d15924SDimitry Andric // We use stronger checks for PRE candidate rather than for CSE ones to embrace
803e6d15924SDimitry Andric // checks inside ProcessBlockCSE(), not only inside isCSECandidate(). This helps
804e6d15924SDimitry Andric // to exclude instrs created by PRE that won't be CSEed later.
isPRECandidate(MachineInstr * MI,SmallSet<MCRegister,8> & PhysRefs)805e3b55780SDimitry Andric bool MachineCSE::isPRECandidate(MachineInstr *MI,
806e3b55780SDimitry Andric                                 SmallSet<MCRegister, 8> &PhysRefs) {
807e6d15924SDimitry Andric   if (!isCSECandidate(MI) ||
808e6d15924SDimitry Andric       MI->isNotDuplicable() ||
809e6d15924SDimitry Andric       MI->mayLoad() ||
810e3b55780SDimitry Andric       TII->isAsCheapAsAMove(*MI) ||
811e6d15924SDimitry Andric       MI->getNumDefs() != 1 ||
812e6d15924SDimitry Andric       MI->getNumExplicitDefs() != 1)
813e6d15924SDimitry Andric     return false;
814e6d15924SDimitry Andric 
815e3b55780SDimitry Andric   for (const MachineOperand &MO : MI->operands()) {
816e3b55780SDimitry Andric     if (MO.isReg() && !MO.getReg().isVirtual()) {
817e3b55780SDimitry Andric       if (MO.isDef())
818e6d15924SDimitry Andric         return false;
819e3b55780SDimitry Andric       else
820e3b55780SDimitry Andric         PhysRefs.insert(MO.getReg());
821e3b55780SDimitry Andric     }
822e3b55780SDimitry Andric   }
823e6d15924SDimitry Andric 
824e6d15924SDimitry Andric   return true;
825e6d15924SDimitry Andric }
826e6d15924SDimitry Andric 
ProcessBlockPRE(MachineDominatorTree * DT,MachineBasicBlock * MBB)827e6d15924SDimitry Andric bool MachineCSE::ProcessBlockPRE(MachineDominatorTree *DT,
828e6d15924SDimitry Andric                                  MachineBasicBlock *MBB) {
829e6d15924SDimitry Andric   bool Changed = false;
830c0981da4SDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(*MBB)) {
831e3b55780SDimitry Andric     SmallSet<MCRegister, 8> PhysRefs;
832e3b55780SDimitry Andric     if (!isPRECandidate(&MI, PhysRefs))
833e6d15924SDimitry Andric       continue;
834e6d15924SDimitry Andric 
835c0981da4SDimitry Andric     if (!PREMap.count(&MI)) {
836c0981da4SDimitry Andric       PREMap[&MI] = MBB;
837e6d15924SDimitry Andric       continue;
838e6d15924SDimitry Andric     }
839e6d15924SDimitry Andric 
840c0981da4SDimitry Andric     auto MBB1 = PREMap[&MI];
841e6d15924SDimitry Andric     assert(
842e6d15924SDimitry Andric         !DT->properlyDominates(MBB, MBB1) &&
843e6d15924SDimitry Andric         "MBB cannot properly dominate MBB1 while DFS through dominators tree!");
844e6d15924SDimitry Andric     auto CMBB = DT->findNearestCommonDominator(MBB, MBB1);
845e6d15924SDimitry Andric     if (!CMBB->isLegalToHoistInto())
846e6d15924SDimitry Andric       continue;
847e6d15924SDimitry Andric 
8481d5ae102SDimitry Andric     if (!isProfitableToHoistInto(CMBB, MBB, MBB1))
8491d5ae102SDimitry Andric       continue;
8501d5ae102SDimitry Andric 
851e6d15924SDimitry Andric     // Two instrs are partial redundant if their basic blocks are reachable
852e6d15924SDimitry Andric     // from one to another but one doesn't dominate another.
853e6d15924SDimitry Andric     if (CMBB != MBB1) {
854e6d15924SDimitry Andric       auto BB = MBB->getBasicBlock(), BB1 = MBB1->getBasicBlock();
855e6d15924SDimitry Andric       if (BB != nullptr && BB1 != nullptr &&
856e6d15924SDimitry Andric           (isPotentiallyReachable(BB1, BB) ||
857e6d15924SDimitry Andric            isPotentiallyReachable(BB, BB1))) {
858344a3780SDimitry Andric         // The following check extends the definition of `isConvergent` to
859344a3780SDimitry Andric         // assume a convergent instruction is dependent not only on additional
860344a3780SDimitry Andric         // conditions, but also on fewer conditions. LLVM does not have a
861344a3780SDimitry Andric         // MachineInstr attribute which expresses this extended definition, so
862344a3780SDimitry Andric         // it's necessary to use `isConvergent` to prevent illegally PRE-ing the
863344a3780SDimitry Andric         // subset of `isConvergent` instructions which do fall into this
864344a3780SDimitry Andric         // extended definition.
865c0981da4SDimitry Andric         if (MI.isConvergent() && CMBB != MBB)
866344a3780SDimitry Andric           continue;
867e6d15924SDimitry Andric 
868e3b55780SDimitry Andric         // If this instruction uses physical registers then we can only do PRE
869e3b55780SDimitry Andric         // if it's using the value that is live at the place we're hoisting to.
870e3b55780SDimitry Andric         bool NonLocal;
871e3b55780SDimitry Andric         PhysDefVector PhysDefs;
872e3b55780SDimitry Andric         if (!PhysRefs.empty() &&
873e3b55780SDimitry Andric             !PhysRegDefsReach(&*(CMBB->getFirstTerminator()), &MI, PhysRefs,
874e3b55780SDimitry Andric                               PhysDefs, NonLocal))
875e3b55780SDimitry Andric           continue;
876e3b55780SDimitry Andric 
877c0981da4SDimitry Andric         assert(MI.getOperand(0).isDef() &&
878e6d15924SDimitry Andric                "First operand of instr with one explicit def must be this def");
879c0981da4SDimitry Andric         Register VReg = MI.getOperand(0).getReg();
8801d5ae102SDimitry Andric         Register NewReg = MRI->cloneVirtualRegister(VReg);
881c0981da4SDimitry Andric         if (!isProfitableToCSE(NewReg, VReg, CMBB, &MI))
882e6d15924SDimitry Andric           continue;
883e6d15924SDimitry Andric         MachineInstr &NewMI =
884c0981da4SDimitry Andric             TII->duplicate(*CMBB, CMBB->getFirstTerminator(), MI);
885cfca06d7SDimitry Andric 
886cfca06d7SDimitry Andric         // When hoisting, make sure we don't carry the debug location of
887cfca06d7SDimitry Andric         // the original instruction, as that's not correct and can cause
888cfca06d7SDimitry Andric         // unexpected jumps when debugging optimized code.
889cfca06d7SDimitry Andric         auto EmptyDL = DebugLoc();
890cfca06d7SDimitry Andric         NewMI.setDebugLoc(EmptyDL);
891cfca06d7SDimitry Andric 
892e6d15924SDimitry Andric         NewMI.getOperand(0).setReg(NewReg);
893e6d15924SDimitry Andric 
894c0981da4SDimitry Andric         PREMap[&MI] = CMBB;
895e6d15924SDimitry Andric         ++NumPREs;
896e6d15924SDimitry Andric         Changed = true;
897e6d15924SDimitry Andric       }
898e6d15924SDimitry Andric     }
899e6d15924SDimitry Andric   }
900e6d15924SDimitry Andric   return Changed;
901e6d15924SDimitry Andric }
902e6d15924SDimitry Andric 
903e6d15924SDimitry Andric // This simple PRE (partial redundancy elimination) pass doesn't actually
904e6d15924SDimitry Andric // eliminate partial redundancy but transforms it to full redundancy,
905e6d15924SDimitry Andric // anticipating that the next CSE step will eliminate this created redundancy.
906e6d15924SDimitry Andric // If CSE doesn't eliminate this, than created instruction will remain dead
907e6d15924SDimitry Andric // and eliminated later by Remove Dead Machine Instructions pass.
PerformSimplePRE(MachineDominatorTree * DT)908e6d15924SDimitry Andric bool MachineCSE::PerformSimplePRE(MachineDominatorTree *DT) {
909e6d15924SDimitry Andric   SmallVector<MachineDomTreeNode *, 32> BBs;
910e6d15924SDimitry Andric 
911e6d15924SDimitry Andric   PREMap.clear();
912e6d15924SDimitry Andric   bool Changed = false;
913e6d15924SDimitry Andric   BBs.push_back(DT->getRootNode());
914e6d15924SDimitry Andric   do {
915e6d15924SDimitry Andric     auto Node = BBs.pop_back_val();
916b60736ecSDimitry Andric     append_range(BBs, Node->children());
917e6d15924SDimitry Andric 
918e6d15924SDimitry Andric     MachineBasicBlock *MBB = Node->getBlock();
919e6d15924SDimitry Andric     Changed |= ProcessBlockPRE(DT, MBB);
920e6d15924SDimitry Andric 
921e6d15924SDimitry Andric   } while (!BBs.empty());
922e6d15924SDimitry Andric 
923e6d15924SDimitry Andric   return Changed;
924e6d15924SDimitry Andric }
925e6d15924SDimitry Andric 
isProfitableToHoistInto(MachineBasicBlock * CandidateBB,MachineBasicBlock * MBB,MachineBasicBlock * MBB1)9261d5ae102SDimitry Andric bool MachineCSE::isProfitableToHoistInto(MachineBasicBlock *CandidateBB,
9271d5ae102SDimitry Andric                                          MachineBasicBlock *MBB,
9281d5ae102SDimitry Andric                                          MachineBasicBlock *MBB1) {
9291d5ae102SDimitry Andric   if (CandidateBB->getParent()->getFunction().hasMinSize())
9301d5ae102SDimitry Andric     return true;
9311d5ae102SDimitry Andric   assert(DT->dominates(CandidateBB, MBB) && "CandidateBB should dominate MBB");
9321d5ae102SDimitry Andric   assert(DT->dominates(CandidateBB, MBB1) &&
9331d5ae102SDimitry Andric          "CandidateBB should dominate MBB1");
9341d5ae102SDimitry Andric   return MBFI->getBlockFreq(CandidateBB) <=
9351d5ae102SDimitry Andric          MBFI->getBlockFreq(MBB) + MBFI->getBlockFreq(MBB1);
9361d5ae102SDimitry Andric }
9371d5ae102SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)93867a71b31SRoman Divacky bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
939044eb2f6SDimitry Andric   if (skipFunction(MF.getFunction()))
9405ca98fd9SDimitry Andric     return false;
9415ca98fd9SDimitry Andric 
94267c32a98SDimitry Andric   TII = MF.getSubtarget().getInstrInfo();
94367c32a98SDimitry Andric   TRI = MF.getSubtarget().getRegisterInfo();
94467a71b31SRoman Divacky   MRI = &MF.getRegInfo();
945dd58ef01SDimitry Andric   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
946ac9a064cSDimitry Andric   DT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
947ac9a064cSDimitry Andric   MBFI = &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
9485a5ac124SDimitry Andric   LookAheadLimit = TII->getMachineCSELookAheadLimit();
949e6d15924SDimitry Andric   bool ChangedPRE, ChangedCSE;
950e6d15924SDimitry Andric   ChangedPRE = PerformSimplePRE(DT);
951e6d15924SDimitry Andric   ChangedCSE = PerformCSE(DT->getRootNode());
952e6d15924SDimitry Andric   return ChangedPRE || ChangedCSE;
95367a71b31SRoman Divacky }
954