1 //===- MachineCSE.cpp - Machine Common Subexpression Elimination Pass -----===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This pass performs global common subexpression elimination on machine
10 // instructions using a scoped hash table based value numbering scheme. It
11 // must be run while the machine function is still in SSA form.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/ScopedHashTable.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/CFG.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/CodeGen/TargetInstrInfo.h"
33 #include "llvm/CodeGen/TargetOpcodes.h"
34 #include "llvm/CodeGen/TargetRegisterInfo.h"
35 #include "llvm/CodeGen/TargetSubtargetInfo.h"
36 #include "llvm/InitializePasses.h"
37 #include "llvm/MC/MCInstrDesc.h"
38 #include "llvm/MC/MCRegisterInfo.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/Allocator.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/RecyclingAllocator.h"
43 #include "llvm/Support/raw_ostream.h"
51 #define DEBUG_TYPE "machine-cse"
53 STATISTIC(NumCoalesces, "Number of copies coalesced");
54 STATISTIC(NumCSEs, "Number of common subexpression eliminated");
55 STATISTIC(NumPREs, "Number of partial redundant expression"
56 " transformed to fully redundant");
57 STATISTIC(NumPhysCSEs,
58 "Number of physreg referencing common subexpr eliminated");
59 STATISTIC(NumCrossBBCSEs,
60 "Number of cross-MBB physreg referencing CS eliminated");
61 STATISTIC(NumCommutes, "Number of copies coalesced after commuting");
65 class MachineCSE : public MachineFunctionPass {
66 const TargetInstrInfo *TII;
67 const TargetRegisterInfo *TRI;
69 MachineDominatorTree *DT;
70 MachineRegisterInfo *MRI;
71 MachineBlockFrequencyInfo *MBFI;
74 static char ID; // Pass identification
76 MachineCSE() : MachineFunctionPass(ID) {
77 initializeMachineCSEPass(*PassRegistry::getPassRegistry());
80 bool runOnMachineFunction(MachineFunction &MF) override;
82 void getAnalysisUsage(AnalysisUsage &AU) const override {
84 MachineFunctionPass::getAnalysisUsage(AU);
85 AU.addRequired<AAResultsWrapperPass>();
86 AU.addPreservedID(MachineLoopInfoID);
87 AU.addRequired<MachineDominatorTree>();
88 AU.addPreserved<MachineDominatorTree>();
89 AU.addRequired<MachineBlockFrequencyInfo>();
90 AU.addPreserved<MachineBlockFrequencyInfo>();
93 void releaseMemory() override {
100 using AllocatorTy = RecyclingAllocator<BumpPtrAllocator,
101 ScopedHashTableVal<MachineInstr *, unsigned>>;
103 ScopedHashTable<MachineInstr *, unsigned, MachineInstrExpressionTrait,
105 using ScopeType = ScopedHTType::ScopeTy;
106 using PhysDefVector = SmallVector<std::pair<unsigned, unsigned>, 2>;
108 unsigned LookAheadLimit = 0;
109 DenseMap<MachineBasicBlock *, ScopeType *> ScopeMap;
110 DenseMap<MachineInstr *, MachineBasicBlock *, MachineInstrExpressionTrait>
113 SmallVector<MachineInstr *, 64> Exps;
116 bool PerformTrivialCopyPropagation(MachineInstr *MI,
117 MachineBasicBlock *MBB);
118 bool isPhysDefTriviallyDead(unsigned Reg,
119 MachineBasicBlock::const_iterator I,
120 MachineBasicBlock::const_iterator E) const;
121 bool hasLivePhysRegDefUses(const MachineInstr *MI,
122 const MachineBasicBlock *MBB,
123 SmallSet<unsigned, 8> &PhysRefs,
124 PhysDefVector &PhysDefs, bool &PhysUseDef) const;
125 bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
126 SmallSet<unsigned, 8> &PhysRefs,
127 PhysDefVector &PhysDefs, bool &NonLocal) const;
128 bool isCSECandidate(MachineInstr *MI);
129 bool isProfitableToCSE(unsigned CSReg, unsigned Reg,
130 MachineBasicBlock *CSBB, MachineInstr *MI);
131 void EnterScope(MachineBasicBlock *MBB);
132 void ExitScope(MachineBasicBlock *MBB);
133 bool ProcessBlockCSE(MachineBasicBlock *MBB);
134 void ExitScopeIfDone(MachineDomTreeNode *Node,
135 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren);
136 bool PerformCSE(MachineDomTreeNode *Node);
138 bool isPRECandidate(MachineInstr *MI);
139 bool ProcessBlockPRE(MachineDominatorTree *MDT, MachineBasicBlock *MBB);
140 bool PerformSimplePRE(MachineDominatorTree *DT);
141 /// Heuristics to see if it's profitable to move common computations of MBB
142 /// and MBB1 to CandidateBB.
143 bool isProfitableToHoistInto(MachineBasicBlock *CandidateBB,
144 MachineBasicBlock *MBB,
145 MachineBasicBlock *MBB1);
148 } // end anonymous namespace
150 char MachineCSE::ID = 0;
152 char &llvm::MachineCSEID = MachineCSE::ID;
154 INITIALIZE_PASS_BEGIN(MachineCSE, DEBUG_TYPE,
155 "Machine Common Subexpression Elimination", false, false)
156 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
157 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
158 INITIALIZE_PASS_END(MachineCSE, DEBUG_TYPE,
159 "Machine Common Subexpression Elimination", false, false)
161 /// The source register of a COPY machine instruction can be propagated to all
162 /// its users, and this propagation could increase the probability of finding
163 /// common subexpressions. If the COPY has only one user, the COPY itself can
165 bool MachineCSE::PerformTrivialCopyPropagation(MachineInstr *MI,
166 MachineBasicBlock *MBB) {
167 bool Changed = false;
168 for (MachineOperand &MO : MI->operands()) {
169 if (!MO.isReg() || !MO.isUse())
171 Register Reg = MO.getReg();
172 if (!Register::isVirtualRegister(Reg))
174 bool OnlyOneUse = MRI->hasOneNonDBGUse(Reg);
175 MachineInstr *DefMI = MRI->getVRegDef(Reg);
176 if (!DefMI->isCopy())
178 Register SrcReg = DefMI->getOperand(1).getReg();
179 if (!Register::isVirtualRegister(SrcReg))
181 if (DefMI->getOperand(0).getSubReg())
183 // FIXME: We should trivially coalesce subregister copies to expose CSE
184 // opportunities on instructions with truncated operands (see
185 // cse-add-with-overflow.ll). This can be done here as follows:
187 // RC = TRI->getMatchingSuperRegClass(MRI->getRegClass(SrcReg), RC,
189 // MO.substVirtReg(SrcReg, SrcSubReg, *TRI);
191 // The 2-addr pass has been updated to handle coalesced subregs. However,
192 // some machine-specific code still can't handle it.
193 // To handle it properly we also need a way find a constrained subregister
194 // class given a super-reg class and subreg index.
195 if (DefMI->getOperand(1).getSubReg())
197 if (!MRI->constrainRegAttrs(SrcReg, Reg))
199 LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
200 LLVM_DEBUG(dbgs() << "*** to: " << *MI);
202 // Propagate SrcReg of copies to MI.
204 MRI->clearKillFlags(SrcReg);
205 // Coalesce single use copies.
207 // If (and only if) we've eliminated all uses of the copy, also
208 // copy-propagate to any debug-users of MI, or they'll be left using
209 // an undefined value.
210 DefMI->changeDebugValuesDefReg(SrcReg);
212 DefMI->eraseFromParent();
222 MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
223 MachineBasicBlock::const_iterator I,
224 MachineBasicBlock::const_iterator E) const {
225 unsigned LookAheadLeft = LookAheadLimit;
226 while (LookAheadLeft) {
227 // Skip over dbg_value's.
228 I = skipDebugInstructionsForward(I, E);
231 // Reached end of block, we don't know if register is dead or not.
234 bool SeenDef = false;
235 for (const MachineOperand &MO : I->operands()) {
236 if (MO.isRegMask() && MO.clobbersPhysReg(Reg))
238 if (!MO.isReg() || !MO.getReg())
240 if (!TRI->regsOverlap(MO.getReg(), Reg))
248 // See a def of Reg (or an alias) before encountering any use, it's
258 static bool isCallerPreservedOrConstPhysReg(unsigned Reg,
259 const MachineFunction &MF,
260 const TargetRegisterInfo &TRI) {
261 // MachineRegisterInfo::isConstantPhysReg directly called by
262 // MachineRegisterInfo::isCallerPreservedOrConstPhysReg expects the
263 // reserved registers to be frozen. That doesn't cause a problem post-ISel as
264 // most (if not all) targets freeze reserved registers right after ISel.
266 // It does cause issues mid-GlobalISel, however, hence the additional
267 // reservedRegsFrozen check.
268 const MachineRegisterInfo &MRI = MF.getRegInfo();
269 return TRI.isCallerPreservedPhysReg(Reg, MF) ||
270 (MRI.reservedRegsFrozen() && MRI.isConstantPhysReg(Reg));
273 /// hasLivePhysRegDefUses - Return true if the specified instruction read/write
274 /// physical registers (except for dead defs of physical registers). It also
275 /// returns the physical register def by reference if it's the only one and the
276 /// instruction does not uses a physical register.
277 bool MachineCSE::hasLivePhysRegDefUses(const MachineInstr *MI,
278 const MachineBasicBlock *MBB,
279 SmallSet<unsigned, 8> &PhysRefs,
280 PhysDefVector &PhysDefs,
281 bool &PhysUseDef) const {
282 // First, add all uses to PhysRefs.
283 for (const MachineOperand &MO : MI->operands()) {
284 if (!MO.isReg() || MO.isDef())
286 Register Reg = MO.getReg();
289 if (Register::isVirtualRegister(Reg))
291 // Reading either caller preserved or constant physregs is ok.
292 if (!isCallerPreservedOrConstPhysReg(Reg, *MI->getMF(), *TRI))
293 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
294 PhysRefs.insert(*AI);
297 // Next, collect all defs into PhysDefs. If any is already in PhysRefs
298 // (which currently contains only uses), set the PhysUseDef flag.
300 MachineBasicBlock::const_iterator I = MI; I = std::next(I);
301 for (const auto &MOP : llvm::enumerate(MI->operands())) {
302 const MachineOperand &MO = MOP.value();
303 if (!MO.isReg() || !MO.isDef())
305 Register Reg = MO.getReg();
308 if (Register::isVirtualRegister(Reg))
310 // Check against PhysRefs even if the def is "dead".
311 if (PhysRefs.count(Reg))
313 // If the def is dead, it's ok. But the def may not marked "dead". That's
314 // common since this pass is run before livevariables. We can scan
315 // forward a few instructions and check if it is obviously dead.
316 if (!MO.isDead() && !isPhysDefTriviallyDead(Reg, I, MBB->end()))
317 PhysDefs.push_back(std::make_pair(MOP.index(), Reg));
320 // Finally, add all defs to PhysRefs as well.
321 for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i)
322 for (MCRegAliasIterator AI(PhysDefs[i].second, TRI, true); AI.isValid();
324 PhysRefs.insert(*AI);
326 return !PhysRefs.empty();
329 bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
330 SmallSet<unsigned, 8> &PhysRefs,
331 PhysDefVector &PhysDefs,
332 bool &NonLocal) const {
333 // For now conservatively returns false if the common subexpression is
334 // not in the same basic block as the given instruction. The only exception
335 // is if the common subexpression is in the sole predecessor block.
336 const MachineBasicBlock *MBB = MI->getParent();
337 const MachineBasicBlock *CSMBB = CSMI->getParent();
339 bool CrossMBB = false;
341 if (MBB->pred_size() != 1 || *MBB->pred_begin() != CSMBB)
344 for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
345 if (MRI->isAllocatable(PhysDefs[i].second) ||
346 MRI->isReserved(PhysDefs[i].second))
347 // Avoid extending live range of physical registers if they are
348 //allocatable or reserved.
353 MachineBasicBlock::const_iterator I = CSMI; I = std::next(I);
354 MachineBasicBlock::const_iterator E = MI;
355 MachineBasicBlock::const_iterator EE = CSMBB->end();
356 unsigned LookAheadLeft = LookAheadLimit;
357 while (LookAheadLeft) {
358 // Skip over dbg_value's.
359 while (I != E && I != EE && I->isDebugInstr())
363 assert(CrossMBB && "Reaching end-of-MBB without finding MI?");
375 for (const MachineOperand &MO : I->operands()) {
376 // RegMasks go on instructions like calls that clobber lots of physregs.
377 // Don't attempt to CSE across such an instruction.
380 if (!MO.isReg() || !MO.isDef())
382 Register MOReg = MO.getReg();
383 if (Register::isVirtualRegister(MOReg))
385 if (PhysRefs.count(MOReg))
396 bool MachineCSE::isCSECandidate(MachineInstr *MI) {
397 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() || MI->isKill() ||
398 MI->isInlineAsm() || MI->isDebugInstr())
402 if (MI->isCopyLike())
405 // Ignore stuff that we obviously can't move.
406 if (MI->mayStore() || MI->isCall() || MI->isTerminator() ||
407 MI->mayRaiseFPException() || MI->hasUnmodeledSideEffects())
411 // Okay, this instruction does a load. As a refinement, we allow the target
412 // to decide whether the loaded value is actually a constant. If so, we can
413 // actually use it as a load.
414 if (!MI->isDereferenceableInvariantLoad(AA))
415 // FIXME: we should be able to hoist loads with no other side effects if
416 // there are no other instructions which can change memory in this loop.
417 // This is a trivial form of alias analysis.
421 // Ignore stack guard loads, otherwise the register that holds CSEed value may
422 // be spilled and get loaded back with corrupted data.
423 if (MI->getOpcode() == TargetOpcode::LOAD_STACK_GUARD)
429 /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
430 /// common expression that defines Reg. CSBB is basic block where CSReg is
432 bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
433 MachineBasicBlock *CSBB, MachineInstr *MI) {
434 // FIXME: Heuristics that works around the lack the live range splitting.
436 // If CSReg is used at all uses of Reg, CSE should not increase register
437 // pressure of CSReg.
438 bool MayIncreasePressure = true;
439 if (Register::isVirtualRegister(CSReg) && Register::isVirtualRegister(Reg)) {
440 MayIncreasePressure = false;
441 SmallPtrSet<MachineInstr*, 8> CSUses;
442 for (MachineInstr &MI : MRI->use_nodbg_instructions(CSReg)) {
445 for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
446 if (!CSUses.count(&MI)) {
447 MayIncreasePressure = true;
452 if (!MayIncreasePressure) return true;
454 // Heuristics #1: Don't CSE "cheap" computation if the def is not local or in
455 // an immediate predecessor. We don't want to increase register pressure and
456 // end up causing other computation to be spilled.
457 if (TII->isAsCheapAsAMove(*MI)) {
458 MachineBasicBlock *BB = MI->getParent();
459 if (CSBB != BB && !CSBB->isSuccessor(BB))
463 // Heuristics #2: If the expression doesn't not use a vr and the only use
464 // of the redundant computation are copies, do not cse.
465 bool HasVRegUse = false;
466 for (const MachineOperand &MO : MI->operands()) {
467 if (MO.isReg() && MO.isUse() && Register::isVirtualRegister(MO.getReg())) {
473 bool HasNonCopyUse = false;
474 for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
476 if (!MI.isCopyLike()) {
477 HasNonCopyUse = true;
485 // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
486 // it unless the defined value is already used in the BB of the new use.
488 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(CSReg)) {
489 HasPHI |= UseMI.isPHI();
490 if (UseMI.getParent() == MI->getParent())
497 void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
498 LLVM_DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
499 ScopeType *Scope = new ScopeType(VNT);
500 ScopeMap[MBB] = Scope;
503 void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
504 LLVM_DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
505 DenseMap<MachineBasicBlock*, ScopeType*>::iterator SI = ScopeMap.find(MBB);
506 assert(SI != ScopeMap.end());
511 bool MachineCSE::ProcessBlockCSE(MachineBasicBlock *MBB) {
512 bool Changed = false;
514 SmallVector<std::pair<unsigned, unsigned>, 8> CSEPairs;
515 SmallVector<unsigned, 2> ImplicitDefsToUpdate;
516 SmallVector<unsigned, 2> ImplicitDefs;
517 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
518 MachineInstr *MI = &*I;
521 if (!isCSECandidate(MI))
524 bool FoundCSE = VNT.count(MI);
526 // Using trivial copy propagation to find more CSE opportunities.
527 if (PerformTrivialCopyPropagation(MI, MBB)) {
530 // After coalescing MI itself may become a copy.
531 if (MI->isCopyLike())
534 // Try again to see if CSE is possible.
535 FoundCSE = VNT.count(MI);
539 // Commute commutable instructions.
540 bool Commuted = false;
541 if (!FoundCSE && MI->isCommutable()) {
542 if (MachineInstr *NewMI = TII->commuteInstruction(*MI)) {
544 FoundCSE = VNT.count(NewMI);
546 // New instruction. It doesn't need to be kept.
547 NewMI->eraseFromParent();
549 } else if (!FoundCSE)
550 // MI was changed but it didn't help, commute it back!
551 (void)TII->commuteInstruction(*MI);
555 // If the instruction defines physical registers and the values *may* be
556 // used, then it's not safe to replace it with a common subexpression.
557 // It's also not safe if the instruction uses physical registers.
558 bool CrossMBBPhysDef = false;
559 SmallSet<unsigned, 8> PhysRefs;
560 PhysDefVector PhysDefs;
561 bool PhysUseDef = false;
562 if (FoundCSE && hasLivePhysRegDefUses(MI, MBB, PhysRefs,
563 PhysDefs, PhysUseDef)) {
566 // ... Unless the CS is local or is in the sole predecessor block
567 // and it also defines the physical register which is not clobbered
568 // in between and the physical register uses were not clobbered.
569 // This can never be the case if the instruction both uses and
570 // defines the same physical register, which was detected above.
572 unsigned CSVN = VNT.lookup(MI);
573 MachineInstr *CSMI = Exps[CSVN];
574 if (PhysRegDefsReach(CSMI, MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
580 VNT.insert(MI, CurrVN++);
585 // Found a common subexpression, eliminate it.
586 unsigned CSVN = VNT.lookup(MI);
587 MachineInstr *CSMI = Exps[CSVN];
588 LLVM_DEBUG(dbgs() << "Examining: " << *MI);
589 LLVM_DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
591 // Check if it's profitable to perform this CSE.
593 unsigned NumDefs = MI->getNumDefs();
595 for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
596 MachineOperand &MO = MI->getOperand(i);
597 if (!MO.isReg() || !MO.isDef())
599 Register OldReg = MO.getReg();
600 Register NewReg = CSMI->getOperand(i).getReg();
602 // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
603 // we should make sure it is not dead at CSMI.
604 if (MO.isImplicit() && !MO.isDead() && CSMI->getOperand(i).isDead())
605 ImplicitDefsToUpdate.push_back(i);
607 // Keep track of implicit defs of CSMI and MI, to clear possibly
608 // made-redundant kill flags.
609 if (MO.isImplicit() && !MO.isDead() && OldReg == NewReg)
610 ImplicitDefs.push_back(OldReg);
612 if (OldReg == NewReg) {
617 assert(Register::isVirtualRegister(OldReg) &&
618 Register::isVirtualRegister(NewReg) &&
619 "Do not CSE physical register defs!");
621 if (!isProfitableToCSE(NewReg, OldReg, CSMI->getParent(), MI)) {
622 LLVM_DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
627 // Don't perform CSE if the result of the new instruction cannot exist
628 // within the constraints (register class, bank, or low-level type) of
629 // the old instruction.
630 if (!MRI->constrainRegAttrs(NewReg, OldReg)) {
632 dbgs() << "*** Not the same register constraints, avoid CSE!\n");
637 CSEPairs.push_back(std::make_pair(OldReg, NewReg));
641 // Actually perform the elimination.
643 for (std::pair<unsigned, unsigned> &CSEPair : CSEPairs) {
644 unsigned OldReg = CSEPair.first;
645 unsigned NewReg = CSEPair.second;
646 // OldReg may have been unused but is used now, clear the Dead flag
647 MachineInstr *Def = MRI->getUniqueVRegDef(NewReg);
648 assert(Def != nullptr && "CSEd register has no unique definition?");
649 Def->clearRegisterDeads(NewReg);
650 // Replace with NewReg and clear kill flags which may be wrong now.
651 MRI->replaceRegWith(OldReg, NewReg);
652 MRI->clearKillFlags(NewReg);
655 // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
656 // we should make sure it is not dead at CSMI.
657 for (unsigned ImplicitDefToUpdate : ImplicitDefsToUpdate)
658 CSMI->getOperand(ImplicitDefToUpdate).setIsDead(false);
659 for (auto PhysDef : PhysDefs)
660 if (!MI->getOperand(PhysDef.first).isDead())
661 CSMI->getOperand(PhysDef.first).setIsDead(false);
663 // Go through implicit defs of CSMI and MI, and clear the kill flags on
664 // their uses in all the instructions between CSMI and MI.
665 // We might have made some of the kill flags redundant, consider:
666 // subs ... implicit-def %nzcv <- CSMI
667 // csinc ... implicit killed %nzcv <- this kill flag isn't valid anymore
668 // subs ... implicit-def %nzcv <- MI, to be eliminated
669 // csinc ... implicit killed %nzcv
670 // Since we eliminated MI, and reused a register imp-def'd by CSMI
671 // (here %nzcv), that register, if it was killed before MI, should have
672 // that kill flag removed, because it's lifetime was extended.
673 if (CSMI->getParent() == MI->getParent()) {
674 for (MachineBasicBlock::iterator II = CSMI, IE = MI; II != IE; ++II)
675 for (auto ImplicitDef : ImplicitDefs)
676 if (MachineOperand *MO = II->findRegisterUseOperand(
677 ImplicitDef, /*isKill=*/true, TRI))
678 MO->setIsKill(false);
680 // If the instructions aren't in the same BB, bail out and clear the
681 // kill flag on all uses of the imp-def'd register.
682 for (auto ImplicitDef : ImplicitDefs)
683 MRI->clearKillFlags(ImplicitDef);
686 if (CrossMBBPhysDef) {
687 // Add physical register defs now coming in from a predecessor to MBB
689 while (!PhysDefs.empty()) {
690 auto LiveIn = PhysDefs.pop_back_val();
691 if (!MBB->isLiveIn(LiveIn.second))
692 MBB->addLiveIn(LiveIn.second);
697 MI->eraseFromParent();
699 if (!PhysRefs.empty())
705 VNT.insert(MI, CurrVN++);
709 ImplicitDefsToUpdate.clear();
710 ImplicitDefs.clear();
716 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
717 /// dominator tree node if its a leaf or all of its children are done. Walk
718 /// up the dominator tree to destroy ancestors which are now done.
720 MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
721 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren) {
722 if (OpenChildren[Node])
726 ExitScope(Node->getBlock());
728 // Now traverse upwards to pop ancestors whose offsprings are all done.
729 while (MachineDomTreeNode *Parent = Node->getIDom()) {
730 unsigned Left = --OpenChildren[Parent];
733 ExitScope(Parent->getBlock());
738 bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
739 SmallVector<MachineDomTreeNode*, 32> Scopes;
740 SmallVector<MachineDomTreeNode*, 8> WorkList;
741 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
745 // Perform a DFS walk to determine the order of visit.
746 WorkList.push_back(Node);
748 Node = WorkList.pop_back_val();
749 Scopes.push_back(Node);
750 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
751 OpenChildren[Node] = Children.size();
752 for (MachineDomTreeNode *Child : Children)
753 WorkList.push_back(Child);
754 } while (!WorkList.empty());
757 bool Changed = false;
758 for (MachineDomTreeNode *Node : Scopes) {
759 MachineBasicBlock *MBB = Node->getBlock();
761 Changed |= ProcessBlockCSE(MBB);
762 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
763 ExitScopeIfDone(Node, OpenChildren);
769 // We use stronger checks for PRE candidate rather than for CSE ones to embrace
770 // checks inside ProcessBlockCSE(), not only inside isCSECandidate(). This helps
771 // to exclude instrs created by PRE that won't be CSEed later.
772 bool MachineCSE::isPRECandidate(MachineInstr *MI) {
773 if (!isCSECandidate(MI) ||
774 MI->isNotDuplicable() ||
776 MI->isAsCheapAsAMove() ||
777 MI->getNumDefs() != 1 ||
778 MI->getNumExplicitDefs() != 1)
781 for (auto def : MI->defs())
782 if (!Register::isVirtualRegister(def.getReg()))
785 for (auto use : MI->uses())
786 if (use.isReg() && !Register::isVirtualRegister(use.getReg()))
792 bool MachineCSE::ProcessBlockPRE(MachineDominatorTree *DT,
793 MachineBasicBlock *MBB) {
794 bool Changed = false;
795 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;) {
796 MachineInstr *MI = &*I;
799 if (!isPRECandidate(MI))
802 if (!PREMap.count(MI)) {
807 auto MBB1 = PREMap[MI];
809 !DT->properlyDominates(MBB, MBB1) &&
810 "MBB cannot properly dominate MBB1 while DFS through dominators tree!");
811 auto CMBB = DT->findNearestCommonDominator(MBB, MBB1);
812 if (!CMBB->isLegalToHoistInto())
815 if (!isProfitableToHoistInto(CMBB, MBB, MBB1))
818 // Two instrs are partial redundant if their basic blocks are reachable
819 // from one to another but one doesn't dominate another.
821 auto BB = MBB->getBasicBlock(), BB1 = MBB1->getBasicBlock();
822 if (BB != nullptr && BB1 != nullptr &&
823 (isPotentiallyReachable(BB1, BB) ||
824 isPotentiallyReachable(BB, BB1))) {
826 assert(MI->getOperand(0).isDef() &&
827 "First operand of instr with one explicit def must be this def");
828 Register VReg = MI->getOperand(0).getReg();
829 Register NewReg = MRI->cloneVirtualRegister(VReg);
830 if (!isProfitableToCSE(NewReg, VReg, CMBB, MI))
832 MachineInstr &NewMI =
833 TII->duplicate(*CMBB, CMBB->getFirstTerminator(), *MI);
834 NewMI.getOperand(0).setReg(NewReg);
845 // This simple PRE (partial redundancy elimination) pass doesn't actually
846 // eliminate partial redundancy but transforms it to full redundancy,
847 // anticipating that the next CSE step will eliminate this created redundancy.
848 // If CSE doesn't eliminate this, than created instruction will remain dead
849 // and eliminated later by Remove Dead Machine Instructions pass.
850 bool MachineCSE::PerformSimplePRE(MachineDominatorTree *DT) {
851 SmallVector<MachineDomTreeNode *, 32> BBs;
854 bool Changed = false;
855 BBs.push_back(DT->getRootNode());
857 auto Node = BBs.pop_back_val();
858 const std::vector<MachineDomTreeNode *> &Children = Node->getChildren();
859 for (MachineDomTreeNode *Child : Children)
860 BBs.push_back(Child);
862 MachineBasicBlock *MBB = Node->getBlock();
863 Changed |= ProcessBlockPRE(DT, MBB);
865 } while (!BBs.empty());
870 bool MachineCSE::isProfitableToHoistInto(MachineBasicBlock *CandidateBB,
871 MachineBasicBlock *MBB,
872 MachineBasicBlock *MBB1) {
873 if (CandidateBB->getParent()->getFunction().hasMinSize())
875 assert(DT->dominates(CandidateBB, MBB) && "CandidateBB should dominate MBB");
876 assert(DT->dominates(CandidateBB, MBB1) &&
877 "CandidateBB should dominate MBB1");
878 return MBFI->getBlockFreq(CandidateBB) <=
879 MBFI->getBlockFreq(MBB) + MBFI->getBlockFreq(MBB1);
882 bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
883 if (skipFunction(MF.getFunction()))
886 TII = MF.getSubtarget().getInstrInfo();
887 TRI = MF.getSubtarget().getRegisterInfo();
888 MRI = &MF.getRegInfo();
889 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
890 DT = &getAnalysis<MachineDominatorTree>();
891 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
892 LookAheadLimit = TII->getMachineCSELookAheadLimit();
893 bool ChangedPRE, ChangedCSE;
894 ChangedPRE = PerformSimplePRE(DT);
895 ChangedCSE = PerformCSE(DT->getRootNode());
896 return ChangedPRE || ChangedCSE;