10b57cec5SDimitry Andric //===- MachineCSE.cpp - Machine Common Subexpression Elimination Pass -----===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This pass performs global common subexpression elimination on machine 100b57cec5SDimitry Andric // instructions using a scoped hash table based value numbering scheme. It 110b57cec5SDimitry Andric // must be run while the machine function is still in SSA form. 120b57cec5SDimitry Andric // 130b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 140b57cec5SDimitry Andric 150b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h" 160b57cec5SDimitry Andric #include "llvm/ADT/ScopedHashTable.h" 170b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 180b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h" 190b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 200b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h" 210b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h" 220b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h" 230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h" 240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h" 260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h" 270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h" 280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h" 290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h" 300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h" 310b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h" 320b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h" 330b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h" 340b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h" 350b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h" 36480093f4SDimitry Andric #include "llvm/InitializePasses.h" 37e8d8bef9SDimitry Andric #include "llvm/MC/MCRegister.h" 380b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h" 390b57cec5SDimitry Andric #include "llvm/Pass.h" 400b57cec5SDimitry Andric #include "llvm/Support/Allocator.h" 410b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 420b57cec5SDimitry Andric #include "llvm/Support/RecyclingAllocator.h" 430b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 440b57cec5SDimitry Andric #include <cassert> 450b57cec5SDimitry Andric #include <iterator> 460b57cec5SDimitry Andric #include <utility> 470b57cec5SDimitry Andric 480b57cec5SDimitry Andric using namespace llvm; 490b57cec5SDimitry Andric 500b57cec5SDimitry Andric #define DEBUG_TYPE "machine-cse" 510b57cec5SDimitry Andric 520b57cec5SDimitry Andric STATISTIC(NumCoalesces, "Number of copies coalesced"); 530b57cec5SDimitry Andric STATISTIC(NumCSEs, "Number of common subexpression eliminated"); 540b57cec5SDimitry Andric STATISTIC(NumPREs, "Number of partial redundant expression" 550b57cec5SDimitry Andric " transformed to fully redundant"); 560b57cec5SDimitry Andric STATISTIC(NumPhysCSEs, 570b57cec5SDimitry Andric "Number of physreg referencing common subexpr eliminated"); 580b57cec5SDimitry Andric STATISTIC(NumCrossBBCSEs, 590b57cec5SDimitry Andric "Number of cross-MBB physreg referencing CS eliminated"); 600b57cec5SDimitry Andric STATISTIC(NumCommutes, "Number of copies coalesced after commuting"); 610b57cec5SDimitry Andric 62bdd1243dSDimitry Andric // Threshold to avoid excessive cost to compute isProfitableToCSE. 63bdd1243dSDimitry Andric static cl::opt<int> 64bdd1243dSDimitry Andric CSUsesThreshold("csuses-threshold", cl::Hidden, cl::init(1024), 65bdd1243dSDimitry Andric cl::desc("Threshold for the size of CSUses")); 66bdd1243dSDimitry Andric 675f757f3fSDimitry Andric static cl::opt<bool> AggressiveMachineCSE( 685f757f3fSDimitry Andric "aggressive-machine-cse", cl::Hidden, cl::init(false), 695f757f3fSDimitry Andric cl::desc("Override the profitability heuristics for Machine CSE")); 705f757f3fSDimitry Andric 710b57cec5SDimitry Andric namespace { 720b57cec5SDimitry Andric 730b57cec5SDimitry Andric class MachineCSE : public MachineFunctionPass { 7406c3fb27SDimitry Andric const TargetInstrInfo *TII = nullptr; 7506c3fb27SDimitry Andric const TargetRegisterInfo *TRI = nullptr; 7606c3fb27SDimitry Andric AliasAnalysis *AA = nullptr; 7706c3fb27SDimitry Andric MachineDominatorTree *DT = nullptr; 7806c3fb27SDimitry Andric MachineRegisterInfo *MRI = nullptr; 7906c3fb27SDimitry Andric MachineBlockFrequencyInfo *MBFI = nullptr; 800b57cec5SDimitry Andric 810b57cec5SDimitry Andric public: 820b57cec5SDimitry Andric static char ID; // Pass identification 830b57cec5SDimitry Andric 840b57cec5SDimitry Andric MachineCSE() : MachineFunctionPass(ID) { 850b57cec5SDimitry Andric initializeMachineCSEPass(*PassRegistry::getPassRegistry()); 860b57cec5SDimitry Andric } 870b57cec5SDimitry Andric 880b57cec5SDimitry Andric bool runOnMachineFunction(MachineFunction &MF) override; 890b57cec5SDimitry Andric 900b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 910b57cec5SDimitry Andric AU.setPreservesCFG(); 920b57cec5SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU); 930b57cec5SDimitry Andric AU.addRequired<AAResultsWrapperPass>(); 940b57cec5SDimitry Andric AU.addPreservedID(MachineLoopInfoID); 95*0fca6ea1SDimitry Andric AU.addRequired<MachineDominatorTreeWrapperPass>(); 96*0fca6ea1SDimitry Andric AU.addPreserved<MachineDominatorTreeWrapperPass>(); 97*0fca6ea1SDimitry Andric AU.addRequired<MachineBlockFrequencyInfoWrapperPass>(); 98*0fca6ea1SDimitry Andric AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>(); 990b57cec5SDimitry Andric } 1000b57cec5SDimitry Andric 10181ad6265SDimitry Andric MachineFunctionProperties getRequiredProperties() const override { 10281ad6265SDimitry Andric return MachineFunctionProperties() 10381ad6265SDimitry Andric .set(MachineFunctionProperties::Property::IsSSA); 10481ad6265SDimitry Andric } 10581ad6265SDimitry Andric 1060b57cec5SDimitry Andric void releaseMemory() override { 1070b57cec5SDimitry Andric ScopeMap.clear(); 1080b57cec5SDimitry Andric PREMap.clear(); 1090b57cec5SDimitry Andric Exps.clear(); 1100b57cec5SDimitry Andric } 1110b57cec5SDimitry Andric 1120b57cec5SDimitry Andric private: 1130b57cec5SDimitry Andric using AllocatorTy = RecyclingAllocator<BumpPtrAllocator, 1140b57cec5SDimitry Andric ScopedHashTableVal<MachineInstr *, unsigned>>; 1150b57cec5SDimitry Andric using ScopedHTType = 1160b57cec5SDimitry Andric ScopedHashTable<MachineInstr *, unsigned, MachineInstrExpressionTrait, 1170b57cec5SDimitry Andric AllocatorTy>; 1180b57cec5SDimitry Andric using ScopeType = ScopedHTType::ScopeTy; 1190b57cec5SDimitry Andric using PhysDefVector = SmallVector<std::pair<unsigned, unsigned>, 2>; 1200b57cec5SDimitry Andric 1210b57cec5SDimitry Andric unsigned LookAheadLimit = 0; 1220b57cec5SDimitry Andric DenseMap<MachineBasicBlock *, ScopeType *> ScopeMap; 1230b57cec5SDimitry Andric DenseMap<MachineInstr *, MachineBasicBlock *, MachineInstrExpressionTrait> 1240b57cec5SDimitry Andric PREMap; 1250b57cec5SDimitry Andric ScopedHTType VNT; 1260b57cec5SDimitry Andric SmallVector<MachineInstr *, 64> Exps; 1270b57cec5SDimitry Andric unsigned CurrVN = 0; 1280b57cec5SDimitry Andric 1290b57cec5SDimitry Andric bool PerformTrivialCopyPropagation(MachineInstr *MI, 1300b57cec5SDimitry Andric MachineBasicBlock *MBB); 131e8d8bef9SDimitry Andric bool isPhysDefTriviallyDead(MCRegister Reg, 1320b57cec5SDimitry Andric MachineBasicBlock::const_iterator I, 1330b57cec5SDimitry Andric MachineBasicBlock::const_iterator E) const; 1340b57cec5SDimitry Andric bool hasLivePhysRegDefUses(const MachineInstr *MI, 1350b57cec5SDimitry Andric const MachineBasicBlock *MBB, 136e8d8bef9SDimitry Andric SmallSet<MCRegister, 8> &PhysRefs, 1370b57cec5SDimitry Andric PhysDefVector &PhysDefs, bool &PhysUseDef) const; 1380b57cec5SDimitry Andric bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI, 139e8d8bef9SDimitry Andric SmallSet<MCRegister, 8> &PhysRefs, 1400b57cec5SDimitry Andric PhysDefVector &PhysDefs, bool &NonLocal) const; 1410b57cec5SDimitry Andric bool isCSECandidate(MachineInstr *MI); 142e8d8bef9SDimitry Andric bool isProfitableToCSE(Register CSReg, Register Reg, 1430b57cec5SDimitry Andric MachineBasicBlock *CSBB, MachineInstr *MI); 1440b57cec5SDimitry Andric void EnterScope(MachineBasicBlock *MBB); 1450b57cec5SDimitry Andric void ExitScope(MachineBasicBlock *MBB); 1460b57cec5SDimitry Andric bool ProcessBlockCSE(MachineBasicBlock *MBB); 1470b57cec5SDimitry Andric void ExitScopeIfDone(MachineDomTreeNode *Node, 1480b57cec5SDimitry Andric DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren); 1490b57cec5SDimitry Andric bool PerformCSE(MachineDomTreeNode *Node); 1500b57cec5SDimitry Andric 151bdd1243dSDimitry Andric bool isPRECandidate(MachineInstr *MI, SmallSet<MCRegister, 8> &PhysRefs); 1520b57cec5SDimitry Andric bool ProcessBlockPRE(MachineDominatorTree *MDT, MachineBasicBlock *MBB); 1530b57cec5SDimitry Andric bool PerformSimplePRE(MachineDominatorTree *DT); 1548bcb0991SDimitry Andric /// Heuristics to see if it's profitable to move common computations of MBB 1550b57cec5SDimitry Andric /// and MBB1 to CandidateBB. 1568bcb0991SDimitry Andric bool isProfitableToHoistInto(MachineBasicBlock *CandidateBB, 1570b57cec5SDimitry Andric MachineBasicBlock *MBB, 1580b57cec5SDimitry Andric MachineBasicBlock *MBB1); 1590b57cec5SDimitry Andric }; 1600b57cec5SDimitry Andric 1610b57cec5SDimitry Andric } // end anonymous namespace 1620b57cec5SDimitry Andric 1630b57cec5SDimitry Andric char MachineCSE::ID = 0; 1640b57cec5SDimitry Andric 1650b57cec5SDimitry Andric char &llvm::MachineCSEID = MachineCSE::ID; 1660b57cec5SDimitry Andric 1670b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MachineCSE, DEBUG_TYPE, 1680b57cec5SDimitry Andric "Machine Common Subexpression Elimination", false, false) 169*0fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass) 1700b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1710b57cec5SDimitry Andric INITIALIZE_PASS_END(MachineCSE, DEBUG_TYPE, 1720b57cec5SDimitry Andric "Machine Common Subexpression Elimination", false, false) 1730b57cec5SDimitry Andric 1740b57cec5SDimitry Andric /// The source register of a COPY machine instruction can be propagated to all 1750b57cec5SDimitry Andric /// its users, and this propagation could increase the probability of finding 1760b57cec5SDimitry Andric /// common subexpressions. If the COPY has only one user, the COPY itself can 1770b57cec5SDimitry Andric /// be removed. 1780b57cec5SDimitry Andric bool MachineCSE::PerformTrivialCopyPropagation(MachineInstr *MI, 1790b57cec5SDimitry Andric MachineBasicBlock *MBB) { 1800b57cec5SDimitry Andric bool Changed = false; 18106c3fb27SDimitry Andric for (MachineOperand &MO : MI->all_uses()) { 1828bcb0991SDimitry Andric Register Reg = MO.getReg(); 183bdd1243dSDimitry Andric if (!Reg.isVirtual()) 1840b57cec5SDimitry Andric continue; 1850b57cec5SDimitry Andric bool OnlyOneUse = MRI->hasOneNonDBGUse(Reg); 1860b57cec5SDimitry Andric MachineInstr *DefMI = MRI->getVRegDef(Reg); 187*0fca6ea1SDimitry Andric if (!DefMI || !DefMI->isCopy()) 1880b57cec5SDimitry Andric continue; 1898bcb0991SDimitry Andric Register SrcReg = DefMI->getOperand(1).getReg(); 190bdd1243dSDimitry Andric if (!SrcReg.isVirtual()) 1910b57cec5SDimitry Andric continue; 1920b57cec5SDimitry Andric if (DefMI->getOperand(0).getSubReg()) 1930b57cec5SDimitry Andric continue; 1940b57cec5SDimitry Andric // FIXME: We should trivially coalesce subregister copies to expose CSE 1950b57cec5SDimitry Andric // opportunities on instructions with truncated operands (see 1960b57cec5SDimitry Andric // cse-add-with-overflow.ll). This can be done here as follows: 1970b57cec5SDimitry Andric // if (SrcSubReg) 1980b57cec5SDimitry Andric // RC = TRI->getMatchingSuperRegClass(MRI->getRegClass(SrcReg), RC, 1990b57cec5SDimitry Andric // SrcSubReg); 2000b57cec5SDimitry Andric // MO.substVirtReg(SrcReg, SrcSubReg, *TRI); 2010b57cec5SDimitry Andric // 2020b57cec5SDimitry Andric // The 2-addr pass has been updated to handle coalesced subregs. However, 2030b57cec5SDimitry Andric // some machine-specific code still can't handle it. 2040b57cec5SDimitry Andric // To handle it properly we also need a way find a constrained subregister 2050b57cec5SDimitry Andric // class given a super-reg class and subreg index. 2060b57cec5SDimitry Andric if (DefMI->getOperand(1).getSubReg()) 2070b57cec5SDimitry Andric continue; 2080b57cec5SDimitry Andric if (!MRI->constrainRegAttrs(SrcReg, Reg)) 2090b57cec5SDimitry Andric continue; 2100b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI); 2110b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "*** to: " << *MI); 2120b57cec5SDimitry Andric 2130b57cec5SDimitry Andric // Propagate SrcReg of copies to MI. 2140b57cec5SDimitry Andric MO.setReg(SrcReg); 2150b57cec5SDimitry Andric MRI->clearKillFlags(SrcReg); 2160b57cec5SDimitry Andric // Coalesce single use copies. 2170b57cec5SDimitry Andric if (OnlyOneUse) { 2188bcb0991SDimitry Andric // If (and only if) we've eliminated all uses of the copy, also 2198bcb0991SDimitry Andric // copy-propagate to any debug-users of MI, or they'll be left using 2208bcb0991SDimitry Andric // an undefined value. 2218bcb0991SDimitry Andric DefMI->changeDebugValuesDefReg(SrcReg); 2228bcb0991SDimitry Andric 2230b57cec5SDimitry Andric DefMI->eraseFromParent(); 2240b57cec5SDimitry Andric ++NumCoalesces; 2250b57cec5SDimitry Andric } 2260b57cec5SDimitry Andric Changed = true; 2270b57cec5SDimitry Andric } 2280b57cec5SDimitry Andric 2290b57cec5SDimitry Andric return Changed; 2300b57cec5SDimitry Andric } 2310b57cec5SDimitry Andric 232e8d8bef9SDimitry Andric bool MachineCSE::isPhysDefTriviallyDead( 233e8d8bef9SDimitry Andric MCRegister Reg, MachineBasicBlock::const_iterator I, 2340b57cec5SDimitry Andric MachineBasicBlock::const_iterator E) const { 2350b57cec5SDimitry Andric unsigned LookAheadLeft = LookAheadLimit; 2360b57cec5SDimitry Andric while (LookAheadLeft) { 2370b57cec5SDimitry Andric // Skip over dbg_value's. 2380b57cec5SDimitry Andric I = skipDebugInstructionsForward(I, E); 2390b57cec5SDimitry Andric 2400b57cec5SDimitry Andric if (I == E) 2410b57cec5SDimitry Andric // Reached end of block, we don't know if register is dead or not. 2420b57cec5SDimitry Andric return false; 2430b57cec5SDimitry Andric 2440b57cec5SDimitry Andric bool SeenDef = false; 2450b57cec5SDimitry Andric for (const MachineOperand &MO : I->operands()) { 2460b57cec5SDimitry Andric if (MO.isRegMask() && MO.clobbersPhysReg(Reg)) 2470b57cec5SDimitry Andric SeenDef = true; 2480b57cec5SDimitry Andric if (!MO.isReg() || !MO.getReg()) 2490b57cec5SDimitry Andric continue; 2500b57cec5SDimitry Andric if (!TRI->regsOverlap(MO.getReg(), Reg)) 2510b57cec5SDimitry Andric continue; 2520b57cec5SDimitry Andric if (MO.isUse()) 2530b57cec5SDimitry Andric // Found a use! 2540b57cec5SDimitry Andric return false; 2550b57cec5SDimitry Andric SeenDef = true; 2560b57cec5SDimitry Andric } 2570b57cec5SDimitry Andric if (SeenDef) 2580b57cec5SDimitry Andric // See a def of Reg (or an alias) before encountering any use, it's 2590b57cec5SDimitry Andric // trivially dead. 2600b57cec5SDimitry Andric return true; 2610b57cec5SDimitry Andric 2620b57cec5SDimitry Andric --LookAheadLeft; 2630b57cec5SDimitry Andric ++I; 2640b57cec5SDimitry Andric } 2650b57cec5SDimitry Andric return false; 2660b57cec5SDimitry Andric } 2670b57cec5SDimitry Andric 268e8d8bef9SDimitry Andric static bool isCallerPreservedOrConstPhysReg(MCRegister Reg, 269bdd1243dSDimitry Andric const MachineOperand &MO, 2700b57cec5SDimitry Andric const MachineFunction &MF, 271bdd1243dSDimitry Andric const TargetRegisterInfo &TRI, 272bdd1243dSDimitry Andric const TargetInstrInfo &TII) { 2730b57cec5SDimitry Andric // MachineRegisterInfo::isConstantPhysReg directly called by 2740b57cec5SDimitry Andric // MachineRegisterInfo::isCallerPreservedOrConstPhysReg expects the 2750b57cec5SDimitry Andric // reserved registers to be frozen. That doesn't cause a problem post-ISel as 2760b57cec5SDimitry Andric // most (if not all) targets freeze reserved registers right after ISel. 2770b57cec5SDimitry Andric // 2780b57cec5SDimitry Andric // It does cause issues mid-GlobalISel, however, hence the additional 2790b57cec5SDimitry Andric // reservedRegsFrozen check. 2800b57cec5SDimitry Andric const MachineRegisterInfo &MRI = MF.getRegInfo(); 281bdd1243dSDimitry Andric return TRI.isCallerPreservedPhysReg(Reg, MF) || TII.isIgnorableUse(MO) || 2820b57cec5SDimitry Andric (MRI.reservedRegsFrozen() && MRI.isConstantPhysReg(Reg)); 2830b57cec5SDimitry Andric } 2840b57cec5SDimitry Andric 2850b57cec5SDimitry Andric /// hasLivePhysRegDefUses - Return true if the specified instruction read/write 2860b57cec5SDimitry Andric /// physical registers (except for dead defs of physical registers). It also 2870b57cec5SDimitry Andric /// returns the physical register def by reference if it's the only one and the 2880b57cec5SDimitry Andric /// instruction does not uses a physical register. 2890b57cec5SDimitry Andric bool MachineCSE::hasLivePhysRegDefUses(const MachineInstr *MI, 2900b57cec5SDimitry Andric const MachineBasicBlock *MBB, 291e8d8bef9SDimitry Andric SmallSet<MCRegister, 8> &PhysRefs, 2920b57cec5SDimitry Andric PhysDefVector &PhysDefs, 2930b57cec5SDimitry Andric bool &PhysUseDef) const { 2940b57cec5SDimitry Andric // First, add all uses to PhysRefs. 29506c3fb27SDimitry Andric for (const MachineOperand &MO : MI->all_uses()) { 2968bcb0991SDimitry Andric Register Reg = MO.getReg(); 2970b57cec5SDimitry Andric if (!Reg) 2980b57cec5SDimitry Andric continue; 299bdd1243dSDimitry Andric if (Reg.isVirtual()) 3000b57cec5SDimitry Andric continue; 3010b57cec5SDimitry Andric // Reading either caller preserved or constant physregs is ok. 302bdd1243dSDimitry Andric if (!isCallerPreservedOrConstPhysReg(Reg.asMCReg(), MO, *MI->getMF(), *TRI, 303bdd1243dSDimitry Andric *TII)) 3040b57cec5SDimitry Andric for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) 3050b57cec5SDimitry Andric PhysRefs.insert(*AI); 3060b57cec5SDimitry Andric } 3070b57cec5SDimitry Andric 3080b57cec5SDimitry Andric // Next, collect all defs into PhysDefs. If any is already in PhysRefs 3090b57cec5SDimitry Andric // (which currently contains only uses), set the PhysUseDef flag. 3100b57cec5SDimitry Andric PhysUseDef = false; 3110b57cec5SDimitry Andric MachineBasicBlock::const_iterator I = MI; I = std::next(I); 3120b57cec5SDimitry Andric for (const auto &MOP : llvm::enumerate(MI->operands())) { 3130b57cec5SDimitry Andric const MachineOperand &MO = MOP.value(); 3140b57cec5SDimitry Andric if (!MO.isReg() || !MO.isDef()) 3150b57cec5SDimitry Andric continue; 3168bcb0991SDimitry Andric Register Reg = MO.getReg(); 3170b57cec5SDimitry Andric if (!Reg) 3180b57cec5SDimitry Andric continue; 319bdd1243dSDimitry Andric if (Reg.isVirtual()) 3200b57cec5SDimitry Andric continue; 3210b57cec5SDimitry Andric // Check against PhysRefs even if the def is "dead". 322e8d8bef9SDimitry Andric if (PhysRefs.count(Reg.asMCReg())) 3230b57cec5SDimitry Andric PhysUseDef = true; 3240b57cec5SDimitry Andric // If the def is dead, it's ok. But the def may not marked "dead". That's 3250b57cec5SDimitry Andric // common since this pass is run before livevariables. We can scan 3260b57cec5SDimitry Andric // forward a few instructions and check if it is obviously dead. 327e8d8bef9SDimitry Andric if (!MO.isDead() && !isPhysDefTriviallyDead(Reg.asMCReg(), I, MBB->end())) 3280b57cec5SDimitry Andric PhysDefs.push_back(std::make_pair(MOP.index(), Reg)); 3290b57cec5SDimitry Andric } 3300b57cec5SDimitry Andric 3310b57cec5SDimitry Andric // Finally, add all defs to PhysRefs as well. 3320b57cec5SDimitry Andric for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) 3330b57cec5SDimitry Andric for (MCRegAliasIterator AI(PhysDefs[i].second, TRI, true); AI.isValid(); 3340b57cec5SDimitry Andric ++AI) 3350b57cec5SDimitry Andric PhysRefs.insert(*AI); 3360b57cec5SDimitry Andric 3370b57cec5SDimitry Andric return !PhysRefs.empty(); 3380b57cec5SDimitry Andric } 3390b57cec5SDimitry Andric 3400b57cec5SDimitry Andric bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI, 341e8d8bef9SDimitry Andric SmallSet<MCRegister, 8> &PhysRefs, 3420b57cec5SDimitry Andric PhysDefVector &PhysDefs, 3430b57cec5SDimitry Andric bool &NonLocal) const { 3440b57cec5SDimitry Andric // For now conservatively returns false if the common subexpression is 3450b57cec5SDimitry Andric // not in the same basic block as the given instruction. The only exception 3460b57cec5SDimitry Andric // is if the common subexpression is in the sole predecessor block. 3470b57cec5SDimitry Andric const MachineBasicBlock *MBB = MI->getParent(); 3480b57cec5SDimitry Andric const MachineBasicBlock *CSMBB = CSMI->getParent(); 3490b57cec5SDimitry Andric 3500b57cec5SDimitry Andric bool CrossMBB = false; 3510b57cec5SDimitry Andric if (CSMBB != MBB) { 3520b57cec5SDimitry Andric if (MBB->pred_size() != 1 || *MBB->pred_begin() != CSMBB) 3530b57cec5SDimitry Andric return false; 3540b57cec5SDimitry Andric 3550b57cec5SDimitry Andric for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) { 3560b57cec5SDimitry Andric if (MRI->isAllocatable(PhysDefs[i].second) || 3570b57cec5SDimitry Andric MRI->isReserved(PhysDefs[i].second)) 3580b57cec5SDimitry Andric // Avoid extending live range of physical registers if they are 3590b57cec5SDimitry Andric //allocatable or reserved. 3600b57cec5SDimitry Andric return false; 3610b57cec5SDimitry Andric } 3620b57cec5SDimitry Andric CrossMBB = true; 3630b57cec5SDimitry Andric } 3640b57cec5SDimitry Andric MachineBasicBlock::const_iterator I = CSMI; I = std::next(I); 3650b57cec5SDimitry Andric MachineBasicBlock::const_iterator E = MI; 3660b57cec5SDimitry Andric MachineBasicBlock::const_iterator EE = CSMBB->end(); 3670b57cec5SDimitry Andric unsigned LookAheadLeft = LookAheadLimit; 3680b57cec5SDimitry Andric while (LookAheadLeft) { 3690b57cec5SDimitry Andric // Skip over dbg_value's. 3700b57cec5SDimitry Andric while (I != E && I != EE && I->isDebugInstr()) 3710b57cec5SDimitry Andric ++I; 3720b57cec5SDimitry Andric 3730b57cec5SDimitry Andric if (I == EE) { 3740b57cec5SDimitry Andric assert(CrossMBB && "Reaching end-of-MBB without finding MI?"); 3750b57cec5SDimitry Andric (void)CrossMBB; 3760b57cec5SDimitry Andric CrossMBB = false; 3770b57cec5SDimitry Andric NonLocal = true; 3780b57cec5SDimitry Andric I = MBB->begin(); 3790b57cec5SDimitry Andric EE = MBB->end(); 3800b57cec5SDimitry Andric continue; 3810b57cec5SDimitry Andric } 3820b57cec5SDimitry Andric 3830b57cec5SDimitry Andric if (I == E) 3840b57cec5SDimitry Andric return true; 3850b57cec5SDimitry Andric 3860b57cec5SDimitry Andric for (const MachineOperand &MO : I->operands()) { 3870b57cec5SDimitry Andric // RegMasks go on instructions like calls that clobber lots of physregs. 3880b57cec5SDimitry Andric // Don't attempt to CSE across such an instruction. 3890b57cec5SDimitry Andric if (MO.isRegMask()) 3900b57cec5SDimitry Andric return false; 3910b57cec5SDimitry Andric if (!MO.isReg() || !MO.isDef()) 3920b57cec5SDimitry Andric continue; 3938bcb0991SDimitry Andric Register MOReg = MO.getReg(); 394bdd1243dSDimitry Andric if (MOReg.isVirtual()) 3950b57cec5SDimitry Andric continue; 396e8d8bef9SDimitry Andric if (PhysRefs.count(MOReg.asMCReg())) 3970b57cec5SDimitry Andric return false; 3980b57cec5SDimitry Andric } 3990b57cec5SDimitry Andric 4000b57cec5SDimitry Andric --LookAheadLeft; 4010b57cec5SDimitry Andric ++I; 4020b57cec5SDimitry Andric } 4030b57cec5SDimitry Andric 4040b57cec5SDimitry Andric return false; 4050b57cec5SDimitry Andric } 4060b57cec5SDimitry Andric 4070b57cec5SDimitry Andric bool MachineCSE::isCSECandidate(MachineInstr *MI) { 4080b57cec5SDimitry Andric if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() || MI->isKill() || 4095f757f3fSDimitry Andric MI->isInlineAsm() || MI->isDebugInstr() || MI->isJumpTableDebugInfo()) 4100b57cec5SDimitry Andric return false; 4110b57cec5SDimitry Andric 4120b57cec5SDimitry Andric // Ignore copies. 4130b57cec5SDimitry Andric if (MI->isCopyLike()) 4140b57cec5SDimitry Andric return false; 4150b57cec5SDimitry Andric 4160b57cec5SDimitry Andric // Ignore stuff that we obviously can't move. 4170b57cec5SDimitry Andric if (MI->mayStore() || MI->isCall() || MI->isTerminator() || 4180b57cec5SDimitry Andric MI->mayRaiseFPException() || MI->hasUnmodeledSideEffects()) 4190b57cec5SDimitry Andric return false; 4200b57cec5SDimitry Andric 4210b57cec5SDimitry Andric if (MI->mayLoad()) { 4220b57cec5SDimitry Andric // Okay, this instruction does a load. As a refinement, we allow the target 4230b57cec5SDimitry Andric // to decide whether the loaded value is actually a constant. If so, we can 4240b57cec5SDimitry Andric // actually use it as a load. 425fcaf7f86SDimitry Andric if (!MI->isDereferenceableInvariantLoad()) 4260b57cec5SDimitry Andric // FIXME: we should be able to hoist loads with no other side effects if 4270b57cec5SDimitry Andric // there are no other instructions which can change memory in this loop. 4280b57cec5SDimitry Andric // This is a trivial form of alias analysis. 4290b57cec5SDimitry Andric return false; 4300b57cec5SDimitry Andric } 4310b57cec5SDimitry Andric 4320b57cec5SDimitry Andric // Ignore stack guard loads, otherwise the register that holds CSEed value may 4330b57cec5SDimitry Andric // be spilled and get loaded back with corrupted data. 4340b57cec5SDimitry Andric if (MI->getOpcode() == TargetOpcode::LOAD_STACK_GUARD) 4350b57cec5SDimitry Andric return false; 4360b57cec5SDimitry Andric 4370b57cec5SDimitry Andric return true; 4380b57cec5SDimitry Andric } 4390b57cec5SDimitry Andric 4400b57cec5SDimitry Andric /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a 4410b57cec5SDimitry Andric /// common expression that defines Reg. CSBB is basic block where CSReg is 4420b57cec5SDimitry Andric /// defined. 443e8d8bef9SDimitry Andric bool MachineCSE::isProfitableToCSE(Register CSReg, Register Reg, 4440b57cec5SDimitry Andric MachineBasicBlock *CSBB, MachineInstr *MI) { 4455f757f3fSDimitry Andric if (AggressiveMachineCSE) 4465f757f3fSDimitry Andric return true; 4475f757f3fSDimitry Andric 4480b57cec5SDimitry Andric // FIXME: Heuristics that works around the lack the live range splitting. 4490b57cec5SDimitry Andric 4500b57cec5SDimitry Andric // If CSReg is used at all uses of Reg, CSE should not increase register 4510b57cec5SDimitry Andric // pressure of CSReg. 4520b57cec5SDimitry Andric bool MayIncreasePressure = true; 453bdd1243dSDimitry Andric if (CSReg.isVirtual() && Reg.isVirtual()) { 4540b57cec5SDimitry Andric MayIncreasePressure = false; 4550b57cec5SDimitry Andric SmallPtrSet<MachineInstr*, 8> CSUses; 456bdd1243dSDimitry Andric int NumOfUses = 0; 4570b57cec5SDimitry Andric for (MachineInstr &MI : MRI->use_nodbg_instructions(CSReg)) { 4580b57cec5SDimitry Andric CSUses.insert(&MI); 459bdd1243dSDimitry Andric // Too costly to compute if NumOfUses is very large. Conservatively assume 460bdd1243dSDimitry Andric // MayIncreasePressure to avoid spending too much time here. 461bdd1243dSDimitry Andric if (++NumOfUses > CSUsesThreshold) { 462bdd1243dSDimitry Andric MayIncreasePressure = true; 463bdd1243dSDimitry Andric break; 4640b57cec5SDimitry Andric } 465bdd1243dSDimitry Andric } 466bdd1243dSDimitry Andric if (!MayIncreasePressure) 4670b57cec5SDimitry Andric for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) { 4680b57cec5SDimitry Andric if (!CSUses.count(&MI)) { 4690b57cec5SDimitry Andric MayIncreasePressure = true; 4700b57cec5SDimitry Andric break; 4710b57cec5SDimitry Andric } 4720b57cec5SDimitry Andric } 4730b57cec5SDimitry Andric } 4740b57cec5SDimitry Andric if (!MayIncreasePressure) return true; 4750b57cec5SDimitry Andric 4760b57cec5SDimitry Andric // Heuristics #1: Don't CSE "cheap" computation if the def is not local or in 4770b57cec5SDimitry Andric // an immediate predecessor. We don't want to increase register pressure and 4780b57cec5SDimitry Andric // end up causing other computation to be spilled. 4790b57cec5SDimitry Andric if (TII->isAsCheapAsAMove(*MI)) { 4800b57cec5SDimitry Andric MachineBasicBlock *BB = MI->getParent(); 4810b57cec5SDimitry Andric if (CSBB != BB && !CSBB->isSuccessor(BB)) 4820b57cec5SDimitry Andric return false; 4830b57cec5SDimitry Andric } 4840b57cec5SDimitry Andric 4850b57cec5SDimitry Andric // Heuristics #2: If the expression doesn't not use a vr and the only use 4860b57cec5SDimitry Andric // of the redundant computation are copies, do not cse. 4870b57cec5SDimitry Andric bool HasVRegUse = false; 48806c3fb27SDimitry Andric for (const MachineOperand &MO : MI->all_uses()) { 48906c3fb27SDimitry Andric if (MO.getReg().isVirtual()) { 4900b57cec5SDimitry Andric HasVRegUse = true; 4910b57cec5SDimitry Andric break; 4920b57cec5SDimitry Andric } 4930b57cec5SDimitry Andric } 4940b57cec5SDimitry Andric if (!HasVRegUse) { 4950b57cec5SDimitry Andric bool HasNonCopyUse = false; 4960b57cec5SDimitry Andric for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) { 4970b57cec5SDimitry Andric // Ignore copies. 4980b57cec5SDimitry Andric if (!MI.isCopyLike()) { 4990b57cec5SDimitry Andric HasNonCopyUse = true; 5000b57cec5SDimitry Andric break; 5010b57cec5SDimitry Andric } 5020b57cec5SDimitry Andric } 5030b57cec5SDimitry Andric if (!HasNonCopyUse) 5040b57cec5SDimitry Andric return false; 5050b57cec5SDimitry Andric } 5060b57cec5SDimitry Andric 5070b57cec5SDimitry Andric // Heuristics #3: If the common subexpression is used by PHIs, do not reuse 5080b57cec5SDimitry Andric // it unless the defined value is already used in the BB of the new use. 5090b57cec5SDimitry Andric bool HasPHI = false; 5100b57cec5SDimitry Andric for (MachineInstr &UseMI : MRI->use_nodbg_instructions(CSReg)) { 5110b57cec5SDimitry Andric HasPHI |= UseMI.isPHI(); 5120b57cec5SDimitry Andric if (UseMI.getParent() == MI->getParent()) 5130b57cec5SDimitry Andric return true; 5140b57cec5SDimitry Andric } 5150b57cec5SDimitry Andric 5160b57cec5SDimitry Andric return !HasPHI; 5170b57cec5SDimitry Andric } 5180b57cec5SDimitry Andric 5190b57cec5SDimitry Andric void MachineCSE::EnterScope(MachineBasicBlock *MBB) { 5200b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n'); 5210b57cec5SDimitry Andric ScopeType *Scope = new ScopeType(VNT); 5220b57cec5SDimitry Andric ScopeMap[MBB] = Scope; 5230b57cec5SDimitry Andric } 5240b57cec5SDimitry Andric 5250b57cec5SDimitry Andric void MachineCSE::ExitScope(MachineBasicBlock *MBB) { 5260b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n'); 5270b57cec5SDimitry Andric DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB); 5280b57cec5SDimitry Andric assert(SI != ScopeMap.end()); 5290b57cec5SDimitry Andric delete SI->second; 5300b57cec5SDimitry Andric ScopeMap.erase(SI); 5310b57cec5SDimitry Andric } 5320b57cec5SDimitry Andric 5330b57cec5SDimitry Andric bool MachineCSE::ProcessBlockCSE(MachineBasicBlock *MBB) { 5340b57cec5SDimitry Andric bool Changed = false; 5350b57cec5SDimitry Andric 5360b57cec5SDimitry Andric SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs; 5370b57cec5SDimitry Andric SmallVector<unsigned, 2> ImplicitDefsToUpdate; 5380b57cec5SDimitry Andric SmallVector<unsigned, 2> ImplicitDefs; 539349cc55cSDimitry Andric for (MachineInstr &MI : llvm::make_early_inc_range(*MBB)) { 540349cc55cSDimitry Andric if (!isCSECandidate(&MI)) 5410b57cec5SDimitry Andric continue; 5420b57cec5SDimitry Andric 543349cc55cSDimitry Andric bool FoundCSE = VNT.count(&MI); 5440b57cec5SDimitry Andric if (!FoundCSE) { 5450b57cec5SDimitry Andric // Using trivial copy propagation to find more CSE opportunities. 546349cc55cSDimitry Andric if (PerformTrivialCopyPropagation(&MI, MBB)) { 5470b57cec5SDimitry Andric Changed = true; 5480b57cec5SDimitry Andric 5490b57cec5SDimitry Andric // After coalescing MI itself may become a copy. 550349cc55cSDimitry Andric if (MI.isCopyLike()) 5510b57cec5SDimitry Andric continue; 5520b57cec5SDimitry Andric 5530b57cec5SDimitry Andric // Try again to see if CSE is possible. 554349cc55cSDimitry Andric FoundCSE = VNT.count(&MI); 5550b57cec5SDimitry Andric } 5560b57cec5SDimitry Andric } 5570b57cec5SDimitry Andric 5580b57cec5SDimitry Andric // Commute commutable instructions. 5590b57cec5SDimitry Andric bool Commuted = false; 560349cc55cSDimitry Andric if (!FoundCSE && MI.isCommutable()) { 561349cc55cSDimitry Andric if (MachineInstr *NewMI = TII->commuteInstruction(MI)) { 5620b57cec5SDimitry Andric Commuted = true; 5630b57cec5SDimitry Andric FoundCSE = VNT.count(NewMI); 564349cc55cSDimitry Andric if (NewMI != &MI) { 5650b57cec5SDimitry Andric // New instruction. It doesn't need to be kept. 5660b57cec5SDimitry Andric NewMI->eraseFromParent(); 5670b57cec5SDimitry Andric Changed = true; 5680b57cec5SDimitry Andric } else if (!FoundCSE) 5690b57cec5SDimitry Andric // MI was changed but it didn't help, commute it back! 570349cc55cSDimitry Andric (void)TII->commuteInstruction(MI); 5710b57cec5SDimitry Andric } 5720b57cec5SDimitry Andric } 5730b57cec5SDimitry Andric 5740b57cec5SDimitry Andric // If the instruction defines physical registers and the values *may* be 5750b57cec5SDimitry Andric // used, then it's not safe to replace it with a common subexpression. 5760b57cec5SDimitry Andric // It's also not safe if the instruction uses physical registers. 5770b57cec5SDimitry Andric bool CrossMBBPhysDef = false; 578e8d8bef9SDimitry Andric SmallSet<MCRegister, 8> PhysRefs; 5790b57cec5SDimitry Andric PhysDefVector PhysDefs; 5800b57cec5SDimitry Andric bool PhysUseDef = false; 581349cc55cSDimitry Andric if (FoundCSE && 582349cc55cSDimitry Andric hasLivePhysRegDefUses(&MI, MBB, PhysRefs, PhysDefs, PhysUseDef)) { 5830b57cec5SDimitry Andric FoundCSE = false; 5840b57cec5SDimitry Andric 5850b57cec5SDimitry Andric // ... Unless the CS is local or is in the sole predecessor block 5860b57cec5SDimitry Andric // and it also defines the physical register which is not clobbered 5870b57cec5SDimitry Andric // in between and the physical register uses were not clobbered. 5880b57cec5SDimitry Andric // This can never be the case if the instruction both uses and 5890b57cec5SDimitry Andric // defines the same physical register, which was detected above. 5900b57cec5SDimitry Andric if (!PhysUseDef) { 591349cc55cSDimitry Andric unsigned CSVN = VNT.lookup(&MI); 5920b57cec5SDimitry Andric MachineInstr *CSMI = Exps[CSVN]; 593349cc55cSDimitry Andric if (PhysRegDefsReach(CSMI, &MI, PhysRefs, PhysDefs, CrossMBBPhysDef)) 5940b57cec5SDimitry Andric FoundCSE = true; 5950b57cec5SDimitry Andric } 5960b57cec5SDimitry Andric } 5970b57cec5SDimitry Andric 5980b57cec5SDimitry Andric if (!FoundCSE) { 599349cc55cSDimitry Andric VNT.insert(&MI, CurrVN++); 600349cc55cSDimitry Andric Exps.push_back(&MI); 6010b57cec5SDimitry Andric continue; 6020b57cec5SDimitry Andric } 6030b57cec5SDimitry Andric 6040b57cec5SDimitry Andric // Found a common subexpression, eliminate it. 605349cc55cSDimitry Andric unsigned CSVN = VNT.lookup(&MI); 6060b57cec5SDimitry Andric MachineInstr *CSMI = Exps[CSVN]; 607349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Examining: " << MI); 6080b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI); 6090b57cec5SDimitry Andric 610fe6060f1SDimitry Andric // Prevent CSE-ing non-local convergent instructions. 611fe6060f1SDimitry Andric // LLVM's current definition of `isConvergent` does not necessarily prove 612fe6060f1SDimitry Andric // that non-local CSE is illegal. The following check extends the definition 613fe6060f1SDimitry Andric // of `isConvergent` to assume a convergent instruction is dependent not 614fe6060f1SDimitry Andric // only on additional conditions, but also on fewer conditions. LLVM does 615fe6060f1SDimitry Andric // not have a MachineInstr attribute which expresses this extended 616fe6060f1SDimitry Andric // definition, so it's necessary to use `isConvergent` to prevent illegally 617fe6060f1SDimitry Andric // CSE-ing the subset of `isConvergent` instructions which do fall into this 618fe6060f1SDimitry Andric // extended definition. 619349cc55cSDimitry Andric if (MI.isConvergent() && MI.getParent() != CSMI->getParent()) { 620fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "*** Convergent MI and subexpression exist in " 621fe6060f1SDimitry Andric "different BBs, avoid CSE!\n"); 622349cc55cSDimitry Andric VNT.insert(&MI, CurrVN++); 623349cc55cSDimitry Andric Exps.push_back(&MI); 624fe6060f1SDimitry Andric continue; 625fe6060f1SDimitry Andric } 626fe6060f1SDimitry Andric 6270b57cec5SDimitry Andric // Check if it's profitable to perform this CSE. 6280b57cec5SDimitry Andric bool DoCSE = true; 629349cc55cSDimitry Andric unsigned NumDefs = MI.getNumDefs(); 6300b57cec5SDimitry Andric 631349cc55cSDimitry Andric for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) { 632349cc55cSDimitry Andric MachineOperand &MO = MI.getOperand(i); 6330b57cec5SDimitry Andric if (!MO.isReg() || !MO.isDef()) 6340b57cec5SDimitry Andric continue; 6358bcb0991SDimitry Andric Register OldReg = MO.getReg(); 6368bcb0991SDimitry Andric Register NewReg = CSMI->getOperand(i).getReg(); 6370b57cec5SDimitry Andric 6380b57cec5SDimitry Andric // Go through implicit defs of CSMI and MI, if a def is not dead at MI, 6390b57cec5SDimitry Andric // we should make sure it is not dead at CSMI. 6400b57cec5SDimitry Andric if (MO.isImplicit() && !MO.isDead() && CSMI->getOperand(i).isDead()) 6410b57cec5SDimitry Andric ImplicitDefsToUpdate.push_back(i); 6420b57cec5SDimitry Andric 6430b57cec5SDimitry Andric // Keep track of implicit defs of CSMI and MI, to clear possibly 6440b57cec5SDimitry Andric // made-redundant kill flags. 6450b57cec5SDimitry Andric if (MO.isImplicit() && !MO.isDead() && OldReg == NewReg) 6460b57cec5SDimitry Andric ImplicitDefs.push_back(OldReg); 6470b57cec5SDimitry Andric 6480b57cec5SDimitry Andric if (OldReg == NewReg) { 6490b57cec5SDimitry Andric --NumDefs; 6500b57cec5SDimitry Andric continue; 6510b57cec5SDimitry Andric } 6520b57cec5SDimitry Andric 653bdd1243dSDimitry Andric assert(OldReg.isVirtual() && NewReg.isVirtual() && 6540b57cec5SDimitry Andric "Do not CSE physical register defs!"); 6550b57cec5SDimitry Andric 656349cc55cSDimitry Andric if (!isProfitableToCSE(NewReg, OldReg, CSMI->getParent(), &MI)) { 6570b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n"); 6580b57cec5SDimitry Andric DoCSE = false; 6590b57cec5SDimitry Andric break; 6600b57cec5SDimitry Andric } 6610b57cec5SDimitry Andric 6620b57cec5SDimitry Andric // Don't perform CSE if the result of the new instruction cannot exist 6630b57cec5SDimitry Andric // within the constraints (register class, bank, or low-level type) of 6640b57cec5SDimitry Andric // the old instruction. 6650b57cec5SDimitry Andric if (!MRI->constrainRegAttrs(NewReg, OldReg)) { 6660b57cec5SDimitry Andric LLVM_DEBUG( 6670b57cec5SDimitry Andric dbgs() << "*** Not the same register constraints, avoid CSE!\n"); 6680b57cec5SDimitry Andric DoCSE = false; 6690b57cec5SDimitry Andric break; 6700b57cec5SDimitry Andric } 6710b57cec5SDimitry Andric 6720b57cec5SDimitry Andric CSEPairs.push_back(std::make_pair(OldReg, NewReg)); 6730b57cec5SDimitry Andric --NumDefs; 6740b57cec5SDimitry Andric } 6750b57cec5SDimitry Andric 6760b57cec5SDimitry Andric // Actually perform the elimination. 6770b57cec5SDimitry Andric if (DoCSE) { 678e8d8bef9SDimitry Andric for (const std::pair<unsigned, unsigned> &CSEPair : CSEPairs) { 6790b57cec5SDimitry Andric unsigned OldReg = CSEPair.first; 6800b57cec5SDimitry Andric unsigned NewReg = CSEPair.second; 6810b57cec5SDimitry Andric // OldReg may have been unused but is used now, clear the Dead flag 6820b57cec5SDimitry Andric MachineInstr *Def = MRI->getUniqueVRegDef(NewReg); 6830b57cec5SDimitry Andric assert(Def != nullptr && "CSEd register has no unique definition?"); 6840b57cec5SDimitry Andric Def->clearRegisterDeads(NewReg); 6850b57cec5SDimitry Andric // Replace with NewReg and clear kill flags which may be wrong now. 6860b57cec5SDimitry Andric MRI->replaceRegWith(OldReg, NewReg); 6870b57cec5SDimitry Andric MRI->clearKillFlags(NewReg); 6880b57cec5SDimitry Andric } 6890b57cec5SDimitry Andric 6900b57cec5SDimitry Andric // Go through implicit defs of CSMI and MI, if a def is not dead at MI, 6910b57cec5SDimitry Andric // we should make sure it is not dead at CSMI. 6920b57cec5SDimitry Andric for (unsigned ImplicitDefToUpdate : ImplicitDefsToUpdate) 6930b57cec5SDimitry Andric CSMI->getOperand(ImplicitDefToUpdate).setIsDead(false); 694e8d8bef9SDimitry Andric for (const auto &PhysDef : PhysDefs) 695349cc55cSDimitry Andric if (!MI.getOperand(PhysDef.first).isDead()) 6960b57cec5SDimitry Andric CSMI->getOperand(PhysDef.first).setIsDead(false); 6970b57cec5SDimitry Andric 6980b57cec5SDimitry Andric // Go through implicit defs of CSMI and MI, and clear the kill flags on 6990b57cec5SDimitry Andric // their uses in all the instructions between CSMI and MI. 7000b57cec5SDimitry Andric // We might have made some of the kill flags redundant, consider: 7010b57cec5SDimitry Andric // subs ... implicit-def %nzcv <- CSMI 7020b57cec5SDimitry Andric // csinc ... implicit killed %nzcv <- this kill flag isn't valid anymore 7030b57cec5SDimitry Andric // subs ... implicit-def %nzcv <- MI, to be eliminated 7040b57cec5SDimitry Andric // csinc ... implicit killed %nzcv 7050b57cec5SDimitry Andric // Since we eliminated MI, and reused a register imp-def'd by CSMI 7060b57cec5SDimitry Andric // (here %nzcv), that register, if it was killed before MI, should have 7070b57cec5SDimitry Andric // that kill flag removed, because it's lifetime was extended. 708349cc55cSDimitry Andric if (CSMI->getParent() == MI.getParent()) { 709349cc55cSDimitry Andric for (MachineBasicBlock::iterator II = CSMI, IE = &MI; II != IE; ++II) 7100b57cec5SDimitry Andric for (auto ImplicitDef : ImplicitDefs) 7110b57cec5SDimitry Andric if (MachineOperand *MO = II->findRegisterUseOperand( 712*0fca6ea1SDimitry Andric ImplicitDef, TRI, /*isKill=*/true)) 7130b57cec5SDimitry Andric MO->setIsKill(false); 7140b57cec5SDimitry Andric } else { 7150b57cec5SDimitry Andric // If the instructions aren't in the same BB, bail out and clear the 7160b57cec5SDimitry Andric // kill flag on all uses of the imp-def'd register. 7170b57cec5SDimitry Andric for (auto ImplicitDef : ImplicitDefs) 7180b57cec5SDimitry Andric MRI->clearKillFlags(ImplicitDef); 7190b57cec5SDimitry Andric } 7200b57cec5SDimitry Andric 7210b57cec5SDimitry Andric if (CrossMBBPhysDef) { 7220b57cec5SDimitry Andric // Add physical register defs now coming in from a predecessor to MBB 7230b57cec5SDimitry Andric // livein list. 7240b57cec5SDimitry Andric while (!PhysDefs.empty()) { 7250b57cec5SDimitry Andric auto LiveIn = PhysDefs.pop_back_val(); 7260b57cec5SDimitry Andric if (!MBB->isLiveIn(LiveIn.second)) 7270b57cec5SDimitry Andric MBB->addLiveIn(LiveIn.second); 7280b57cec5SDimitry Andric } 7290b57cec5SDimitry Andric ++NumCrossBBCSEs; 7300b57cec5SDimitry Andric } 7310b57cec5SDimitry Andric 732349cc55cSDimitry Andric MI.eraseFromParent(); 7330b57cec5SDimitry Andric ++NumCSEs; 7340b57cec5SDimitry Andric if (!PhysRefs.empty()) 7350b57cec5SDimitry Andric ++NumPhysCSEs; 7360b57cec5SDimitry Andric if (Commuted) 7370b57cec5SDimitry Andric ++NumCommutes; 7380b57cec5SDimitry Andric Changed = true; 7390b57cec5SDimitry Andric } else { 740349cc55cSDimitry Andric VNT.insert(&MI, CurrVN++); 741349cc55cSDimitry Andric Exps.push_back(&MI); 7420b57cec5SDimitry Andric } 7430b57cec5SDimitry Andric CSEPairs.clear(); 7440b57cec5SDimitry Andric ImplicitDefsToUpdate.clear(); 7450b57cec5SDimitry Andric ImplicitDefs.clear(); 7460b57cec5SDimitry Andric } 7470b57cec5SDimitry Andric 7480b57cec5SDimitry Andric return Changed; 7490b57cec5SDimitry Andric } 7500b57cec5SDimitry Andric 7510b57cec5SDimitry Andric /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given 7520b57cec5SDimitry Andric /// dominator tree node if its a leaf or all of its children are done. Walk 7530b57cec5SDimitry Andric /// up the dominator tree to destroy ancestors which are now done. 7540b57cec5SDimitry Andric void 7550b57cec5SDimitry Andric MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node, 7560b57cec5SDimitry Andric DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren) { 7570b57cec5SDimitry Andric if (OpenChildren[Node]) 7580b57cec5SDimitry Andric return; 7590b57cec5SDimitry Andric 7600b57cec5SDimitry Andric // Pop scope. 7610b57cec5SDimitry Andric ExitScope(Node->getBlock()); 7620b57cec5SDimitry Andric 7630b57cec5SDimitry Andric // Now traverse upwards to pop ancestors whose offsprings are all done. 7640b57cec5SDimitry Andric while (MachineDomTreeNode *Parent = Node->getIDom()) { 7650b57cec5SDimitry Andric unsigned Left = --OpenChildren[Parent]; 7660b57cec5SDimitry Andric if (Left != 0) 7670b57cec5SDimitry Andric break; 7680b57cec5SDimitry Andric ExitScope(Parent->getBlock()); 7690b57cec5SDimitry Andric Node = Parent; 7700b57cec5SDimitry Andric } 7710b57cec5SDimitry Andric } 7720b57cec5SDimitry Andric 7730b57cec5SDimitry Andric bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) { 7740b57cec5SDimitry Andric SmallVector<MachineDomTreeNode*, 32> Scopes; 7750b57cec5SDimitry Andric SmallVector<MachineDomTreeNode*, 8> WorkList; 7760b57cec5SDimitry Andric DenseMap<MachineDomTreeNode*, unsigned> OpenChildren; 7770b57cec5SDimitry Andric 7780b57cec5SDimitry Andric CurrVN = 0; 7790b57cec5SDimitry Andric 7800b57cec5SDimitry Andric // Perform a DFS walk to determine the order of visit. 7810b57cec5SDimitry Andric WorkList.push_back(Node); 7820b57cec5SDimitry Andric do { 7830b57cec5SDimitry Andric Node = WorkList.pop_back_val(); 7840b57cec5SDimitry Andric Scopes.push_back(Node); 7855ffd83dbSDimitry Andric OpenChildren[Node] = Node->getNumChildren(); 786e8d8bef9SDimitry Andric append_range(WorkList, Node->children()); 7870b57cec5SDimitry Andric } while (!WorkList.empty()); 7880b57cec5SDimitry Andric 7890b57cec5SDimitry Andric // Now perform CSE. 7900b57cec5SDimitry Andric bool Changed = false; 7910b57cec5SDimitry Andric for (MachineDomTreeNode *Node : Scopes) { 7920b57cec5SDimitry Andric MachineBasicBlock *MBB = Node->getBlock(); 7930b57cec5SDimitry Andric EnterScope(MBB); 7940b57cec5SDimitry Andric Changed |= ProcessBlockCSE(MBB); 7950b57cec5SDimitry Andric // If it's a leaf node, it's done. Traverse upwards to pop ancestors. 7960b57cec5SDimitry Andric ExitScopeIfDone(Node, OpenChildren); 7970b57cec5SDimitry Andric } 7980b57cec5SDimitry Andric 7990b57cec5SDimitry Andric return Changed; 8000b57cec5SDimitry Andric } 8010b57cec5SDimitry Andric 8020b57cec5SDimitry Andric // We use stronger checks for PRE candidate rather than for CSE ones to embrace 8030b57cec5SDimitry Andric // checks inside ProcessBlockCSE(), not only inside isCSECandidate(). This helps 8040b57cec5SDimitry Andric // to exclude instrs created by PRE that won't be CSEed later. 805bdd1243dSDimitry Andric bool MachineCSE::isPRECandidate(MachineInstr *MI, 806bdd1243dSDimitry Andric SmallSet<MCRegister, 8> &PhysRefs) { 8070b57cec5SDimitry Andric if (!isCSECandidate(MI) || 8080b57cec5SDimitry Andric MI->isNotDuplicable() || 8090b57cec5SDimitry Andric MI->mayLoad() || 810bdd1243dSDimitry Andric TII->isAsCheapAsAMove(*MI) || 8110b57cec5SDimitry Andric MI->getNumDefs() != 1 || 8120b57cec5SDimitry Andric MI->getNumExplicitDefs() != 1) 8130b57cec5SDimitry Andric return false; 8140b57cec5SDimitry Andric 815bdd1243dSDimitry Andric for (const MachineOperand &MO : MI->operands()) { 816bdd1243dSDimitry Andric if (MO.isReg() && !MO.getReg().isVirtual()) { 817bdd1243dSDimitry Andric if (MO.isDef()) 8180b57cec5SDimitry Andric return false; 819bdd1243dSDimitry Andric else 820bdd1243dSDimitry Andric PhysRefs.insert(MO.getReg()); 821bdd1243dSDimitry Andric } 822bdd1243dSDimitry Andric } 8230b57cec5SDimitry Andric 8240b57cec5SDimitry Andric return true; 8250b57cec5SDimitry Andric } 8260b57cec5SDimitry Andric 8270b57cec5SDimitry Andric bool MachineCSE::ProcessBlockPRE(MachineDominatorTree *DT, 8280b57cec5SDimitry Andric MachineBasicBlock *MBB) { 8290b57cec5SDimitry Andric bool Changed = false; 830349cc55cSDimitry Andric for (MachineInstr &MI : llvm::make_early_inc_range(*MBB)) { 831bdd1243dSDimitry Andric SmallSet<MCRegister, 8> PhysRefs; 832bdd1243dSDimitry Andric if (!isPRECandidate(&MI, PhysRefs)) 8330b57cec5SDimitry Andric continue; 8340b57cec5SDimitry Andric 835349cc55cSDimitry Andric if (!PREMap.count(&MI)) { 836349cc55cSDimitry Andric PREMap[&MI] = MBB; 8370b57cec5SDimitry Andric continue; 8380b57cec5SDimitry Andric } 8390b57cec5SDimitry Andric 840349cc55cSDimitry Andric auto MBB1 = PREMap[&MI]; 8410b57cec5SDimitry Andric assert( 8420b57cec5SDimitry Andric !DT->properlyDominates(MBB, MBB1) && 8430b57cec5SDimitry Andric "MBB cannot properly dominate MBB1 while DFS through dominators tree!"); 8440b57cec5SDimitry Andric auto CMBB = DT->findNearestCommonDominator(MBB, MBB1); 8450b57cec5SDimitry Andric if (!CMBB->isLegalToHoistInto()) 8460b57cec5SDimitry Andric continue; 8470b57cec5SDimitry Andric 8488bcb0991SDimitry Andric if (!isProfitableToHoistInto(CMBB, MBB, MBB1)) 8490b57cec5SDimitry Andric continue; 8500b57cec5SDimitry Andric 8510b57cec5SDimitry Andric // Two instrs are partial redundant if their basic blocks are reachable 8520b57cec5SDimitry Andric // from one to another but one doesn't dominate another. 8530b57cec5SDimitry Andric if (CMBB != MBB1) { 8540b57cec5SDimitry Andric auto BB = MBB->getBasicBlock(), BB1 = MBB1->getBasicBlock(); 8550b57cec5SDimitry Andric if (BB != nullptr && BB1 != nullptr && 8560b57cec5SDimitry Andric (isPotentiallyReachable(BB1, BB) || 8570b57cec5SDimitry Andric isPotentiallyReachable(BB, BB1))) { 858fe6060f1SDimitry Andric // The following check extends the definition of `isConvergent` to 859fe6060f1SDimitry Andric // assume a convergent instruction is dependent not only on additional 860fe6060f1SDimitry Andric // conditions, but also on fewer conditions. LLVM does not have a 861fe6060f1SDimitry Andric // MachineInstr attribute which expresses this extended definition, so 862fe6060f1SDimitry Andric // it's necessary to use `isConvergent` to prevent illegally PRE-ing the 863fe6060f1SDimitry Andric // subset of `isConvergent` instructions which do fall into this 864fe6060f1SDimitry Andric // extended definition. 865349cc55cSDimitry Andric if (MI.isConvergent() && CMBB != MBB) 866fe6060f1SDimitry Andric continue; 8670b57cec5SDimitry Andric 868bdd1243dSDimitry Andric // If this instruction uses physical registers then we can only do PRE 869bdd1243dSDimitry Andric // if it's using the value that is live at the place we're hoisting to. 870bdd1243dSDimitry Andric bool NonLocal; 871bdd1243dSDimitry Andric PhysDefVector PhysDefs; 872bdd1243dSDimitry Andric if (!PhysRefs.empty() && 873bdd1243dSDimitry Andric !PhysRegDefsReach(&*(CMBB->getFirstTerminator()), &MI, PhysRefs, 874bdd1243dSDimitry Andric PhysDefs, NonLocal)) 875bdd1243dSDimitry Andric continue; 876bdd1243dSDimitry Andric 877349cc55cSDimitry Andric assert(MI.getOperand(0).isDef() && 8780b57cec5SDimitry Andric "First operand of instr with one explicit def must be this def"); 879349cc55cSDimitry Andric Register VReg = MI.getOperand(0).getReg(); 8808bcb0991SDimitry Andric Register NewReg = MRI->cloneVirtualRegister(VReg); 881349cc55cSDimitry Andric if (!isProfitableToCSE(NewReg, VReg, CMBB, &MI)) 8820b57cec5SDimitry Andric continue; 8830b57cec5SDimitry Andric MachineInstr &NewMI = 884349cc55cSDimitry Andric TII->duplicate(*CMBB, CMBB->getFirstTerminator(), MI); 8855ffd83dbSDimitry Andric 8865ffd83dbSDimitry Andric // When hoisting, make sure we don't carry the debug location of 8875ffd83dbSDimitry Andric // the original instruction, as that's not correct and can cause 8885ffd83dbSDimitry Andric // unexpected jumps when debugging optimized code. 8895ffd83dbSDimitry Andric auto EmptyDL = DebugLoc(); 8905ffd83dbSDimitry Andric NewMI.setDebugLoc(EmptyDL); 8915ffd83dbSDimitry Andric 8920b57cec5SDimitry Andric NewMI.getOperand(0).setReg(NewReg); 8930b57cec5SDimitry Andric 894349cc55cSDimitry Andric PREMap[&MI] = CMBB; 8950b57cec5SDimitry Andric ++NumPREs; 8960b57cec5SDimitry Andric Changed = true; 8970b57cec5SDimitry Andric } 8980b57cec5SDimitry Andric } 8990b57cec5SDimitry Andric } 9000b57cec5SDimitry Andric return Changed; 9010b57cec5SDimitry Andric } 9020b57cec5SDimitry Andric 9030b57cec5SDimitry Andric // This simple PRE (partial redundancy elimination) pass doesn't actually 9040b57cec5SDimitry Andric // eliminate partial redundancy but transforms it to full redundancy, 9050b57cec5SDimitry Andric // anticipating that the next CSE step will eliminate this created redundancy. 9060b57cec5SDimitry Andric // If CSE doesn't eliminate this, than created instruction will remain dead 9070b57cec5SDimitry Andric // and eliminated later by Remove Dead Machine Instructions pass. 9080b57cec5SDimitry Andric bool MachineCSE::PerformSimplePRE(MachineDominatorTree *DT) { 9090b57cec5SDimitry Andric SmallVector<MachineDomTreeNode *, 32> BBs; 9100b57cec5SDimitry Andric 9110b57cec5SDimitry Andric PREMap.clear(); 9120b57cec5SDimitry Andric bool Changed = false; 9130b57cec5SDimitry Andric BBs.push_back(DT->getRootNode()); 9140b57cec5SDimitry Andric do { 9150b57cec5SDimitry Andric auto Node = BBs.pop_back_val(); 916e8d8bef9SDimitry Andric append_range(BBs, Node->children()); 9170b57cec5SDimitry Andric 9180b57cec5SDimitry Andric MachineBasicBlock *MBB = Node->getBlock(); 9190b57cec5SDimitry Andric Changed |= ProcessBlockPRE(DT, MBB); 9200b57cec5SDimitry Andric 9210b57cec5SDimitry Andric } while (!BBs.empty()); 9220b57cec5SDimitry Andric 9230b57cec5SDimitry Andric return Changed; 9240b57cec5SDimitry Andric } 9250b57cec5SDimitry Andric 9268bcb0991SDimitry Andric bool MachineCSE::isProfitableToHoistInto(MachineBasicBlock *CandidateBB, 9270b57cec5SDimitry Andric MachineBasicBlock *MBB, 9280b57cec5SDimitry Andric MachineBasicBlock *MBB1) { 9290b57cec5SDimitry Andric if (CandidateBB->getParent()->getFunction().hasMinSize()) 9300b57cec5SDimitry Andric return true; 9310b57cec5SDimitry Andric assert(DT->dominates(CandidateBB, MBB) && "CandidateBB should dominate MBB"); 9320b57cec5SDimitry Andric assert(DT->dominates(CandidateBB, MBB1) && 9330b57cec5SDimitry Andric "CandidateBB should dominate MBB1"); 9340b57cec5SDimitry Andric return MBFI->getBlockFreq(CandidateBB) <= 9350b57cec5SDimitry Andric MBFI->getBlockFreq(MBB) + MBFI->getBlockFreq(MBB1); 9360b57cec5SDimitry Andric } 9370b57cec5SDimitry Andric 9380b57cec5SDimitry Andric bool MachineCSE::runOnMachineFunction(MachineFunction &MF) { 9390b57cec5SDimitry Andric if (skipFunction(MF.getFunction())) 9400b57cec5SDimitry Andric return false; 9410b57cec5SDimitry Andric 9420b57cec5SDimitry Andric TII = MF.getSubtarget().getInstrInfo(); 9430b57cec5SDimitry Andric TRI = MF.getSubtarget().getRegisterInfo(); 9440b57cec5SDimitry Andric MRI = &MF.getRegInfo(); 9450b57cec5SDimitry Andric AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 946*0fca6ea1SDimitry Andric DT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree(); 947*0fca6ea1SDimitry Andric MBFI = &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI(); 9480b57cec5SDimitry Andric LookAheadLimit = TII->getMachineCSELookAheadLimit(); 9490b57cec5SDimitry Andric bool ChangedPRE, ChangedCSE; 9500b57cec5SDimitry Andric ChangedPRE = PerformSimplePRE(DT); 9510b57cec5SDimitry Andric ChangedCSE = PerformCSE(DT->getRootNode()); 9520b57cec5SDimitry Andric return ChangedPRE || ChangedCSE; 9530b57cec5SDimitry Andric } 954