xref: /src/contrib/llvm-project/llvm/lib/CodeGen/MachineLateInstrsCleanup.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1e3b55780SDimitry Andric //==--- MachineLateInstrsCleanup.cpp - Late Instructions Cleanup Pass -----===//
2e3b55780SDimitry Andric //
3e3b55780SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e3b55780SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e3b55780SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e3b55780SDimitry Andric //
7e3b55780SDimitry Andric //===----------------------------------------------------------------------===//
8e3b55780SDimitry Andric //
9e3b55780SDimitry Andric // This simple pass removes any identical and redundant immediate or address
10e3b55780SDimitry Andric // loads to the same register. The immediate loads removed can originally be
11e3b55780SDimitry Andric // the result of rematerialization, while the addresses are redundant frame
12e3b55780SDimitry Andric // addressing anchor points created during Frame Indices elimination.
13e3b55780SDimitry Andric //
14e3b55780SDimitry Andric //===----------------------------------------------------------------------===//
15e3b55780SDimitry Andric 
16e3b55780SDimitry Andric #include "llvm/ADT/BitVector.h"
17e3b55780SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
18e3b55780SDimitry Andric #include "llvm/ADT/Statistic.h"
19e3b55780SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
20e3b55780SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
21e3b55780SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
22e3b55780SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
23e3b55780SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
24e3b55780SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
25e3b55780SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
26e3b55780SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
27e3b55780SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
28e3b55780SDimitry Andric #include "llvm/InitializePasses.h"
29e3b55780SDimitry Andric #include "llvm/Pass.h"
30e3b55780SDimitry Andric #include "llvm/Support/Debug.h"
31e3b55780SDimitry Andric 
32e3b55780SDimitry Andric using namespace llvm;
33e3b55780SDimitry Andric 
34e3b55780SDimitry Andric #define DEBUG_TYPE "machine-latecleanup"
35e3b55780SDimitry Andric 
36e3b55780SDimitry Andric STATISTIC(NumRemoved, "Number of redundant instructions removed.");
37e3b55780SDimitry Andric 
38e3b55780SDimitry Andric namespace {
39e3b55780SDimitry Andric 
40e3b55780SDimitry Andric class MachineLateInstrsCleanup : public MachineFunctionPass {
417fa27ce4SDimitry Andric   const TargetRegisterInfo *TRI = nullptr;
427fa27ce4SDimitry Andric   const TargetInstrInfo *TII = nullptr;
43e3b55780SDimitry Andric 
447fa27ce4SDimitry Andric   // Data structures to map regs to their definitions and kills per MBB.
457fa27ce4SDimitry Andric   struct Reg2MIMap : public SmallDenseMap<Register, MachineInstr *> {
hasIdentical__anon7496772f0111::MachineLateInstrsCleanup::Reg2MIMap467fa27ce4SDimitry Andric     bool hasIdentical(Register Reg, MachineInstr *ArgMI) {
477fa27ce4SDimitry Andric       MachineInstr *MI = lookup(Reg);
487fa27ce4SDimitry Andric       return MI && MI->isIdenticalTo(*ArgMI);
497fa27ce4SDimitry Andric     }
507fa27ce4SDimitry Andric   };
517fa27ce4SDimitry Andric 
527fa27ce4SDimitry Andric   std::vector<Reg2MIMap> RegDefs;
537fa27ce4SDimitry Andric   std::vector<Reg2MIMap> RegKills;
54e3b55780SDimitry Andric 
55e3b55780SDimitry Andric   // Walk through the instructions in MBB and remove any redundant
56e3b55780SDimitry Andric   // instructions.
57e3b55780SDimitry Andric   bool processBlock(MachineBasicBlock *MBB);
58e3b55780SDimitry Andric 
597fa27ce4SDimitry Andric   void removeRedundantDef(MachineInstr *MI);
607fa27ce4SDimitry Andric   void clearKillsForDef(Register Reg, MachineBasicBlock *MBB,
617fa27ce4SDimitry Andric                         MachineBasicBlock::iterator I,
627fa27ce4SDimitry Andric                         BitVector &VisitedPreds);
637fa27ce4SDimitry Andric 
64e3b55780SDimitry Andric public:
65e3b55780SDimitry Andric   static char ID; // Pass identification, replacement for typeid
66e3b55780SDimitry Andric 
MachineLateInstrsCleanup()67e3b55780SDimitry Andric   MachineLateInstrsCleanup() : MachineFunctionPass(ID) {
68e3b55780SDimitry Andric     initializeMachineLateInstrsCleanupPass(*PassRegistry::getPassRegistry());
69e3b55780SDimitry Andric   }
70e3b55780SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const71e3b55780SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
72e3b55780SDimitry Andric     AU.setPreservesCFG();
73e3b55780SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
74e3b55780SDimitry Andric   }
75e3b55780SDimitry Andric 
76e3b55780SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
77e3b55780SDimitry Andric 
getRequiredProperties() const78e3b55780SDimitry Andric   MachineFunctionProperties getRequiredProperties() const override {
79e3b55780SDimitry Andric     return MachineFunctionProperties().set(
80e3b55780SDimitry Andric         MachineFunctionProperties::Property::NoVRegs);
81e3b55780SDimitry Andric   }
82e3b55780SDimitry Andric };
83e3b55780SDimitry Andric 
84e3b55780SDimitry Andric } // end anonymous namespace
85e3b55780SDimitry Andric 
86e3b55780SDimitry Andric char MachineLateInstrsCleanup::ID = 0;
87e3b55780SDimitry Andric 
88e3b55780SDimitry Andric char &llvm::MachineLateInstrsCleanupID = MachineLateInstrsCleanup::ID;
89e3b55780SDimitry Andric 
90e3b55780SDimitry Andric INITIALIZE_PASS(MachineLateInstrsCleanup, DEBUG_TYPE,
91e3b55780SDimitry Andric                 "Machine Late Instructions Cleanup Pass", false, false)
92e3b55780SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)93e3b55780SDimitry Andric bool MachineLateInstrsCleanup::runOnMachineFunction(MachineFunction &MF) {
94e3b55780SDimitry Andric   if (skipFunction(MF.getFunction()))
95e3b55780SDimitry Andric     return false;
96e3b55780SDimitry Andric 
97e3b55780SDimitry Andric   TRI = MF.getSubtarget().getRegisterInfo();
98e3b55780SDimitry Andric   TII = MF.getSubtarget().getInstrInfo();
99e3b55780SDimitry Andric 
100e3b55780SDimitry Andric   RegDefs.clear();
101e3b55780SDimitry Andric   RegDefs.resize(MF.getNumBlockIDs());
1027fa27ce4SDimitry Andric   RegKills.clear();
1037fa27ce4SDimitry Andric   RegKills.resize(MF.getNumBlockIDs());
104e3b55780SDimitry Andric 
105e3b55780SDimitry Andric   // Visit all MBBs in an order that maximises the reuse from predecessors.
106e3b55780SDimitry Andric   bool Changed = false;
107e3b55780SDimitry Andric   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
108e3b55780SDimitry Andric   for (MachineBasicBlock *MBB : RPOT)
109e3b55780SDimitry Andric     Changed |= processBlock(MBB);
110e3b55780SDimitry Andric 
111e3b55780SDimitry Andric   return Changed;
112e3b55780SDimitry Andric }
113e3b55780SDimitry Andric 
114e3b55780SDimitry Andric // Clear any previous kill flag on Reg found before I in MBB. Walk backwards
115e3b55780SDimitry Andric // in MBB and if needed continue in predecessors until a use/def of Reg is
116e3b55780SDimitry Andric // encountered. This seems to be faster in practice than tracking kill flags
117e3b55780SDimitry Andric // in a map.
1187fa27ce4SDimitry Andric void MachineLateInstrsCleanup::
clearKillsForDef(Register Reg,MachineBasicBlock * MBB,MachineBasicBlock::iterator I,BitVector & VisitedPreds)1197fa27ce4SDimitry Andric clearKillsForDef(Register Reg, MachineBasicBlock *MBB,
120e3b55780SDimitry Andric                  MachineBasicBlock::iterator I,
1217fa27ce4SDimitry Andric                  BitVector &VisitedPreds) {
122e3b55780SDimitry Andric   VisitedPreds.set(MBB->getNumber());
1237fa27ce4SDimitry Andric 
1247fa27ce4SDimitry Andric   // Kill flag in MBB
1257fa27ce4SDimitry Andric   if (MachineInstr *KillMI = RegKills[MBB->getNumber()].lookup(Reg)) {
1267fa27ce4SDimitry Andric     KillMI->clearRegisterKills(Reg, TRI);
127e3b55780SDimitry Andric     return;
128e3b55780SDimitry Andric   }
129e3b55780SDimitry Andric 
1307fa27ce4SDimitry Andric   // Def in MBB (missing kill flag)
1317fa27ce4SDimitry Andric   if (MachineInstr *DefMI = RegDefs[MBB->getNumber()].lookup(Reg))
1327fa27ce4SDimitry Andric     if (DefMI->getParent() == MBB)
1337fa27ce4SDimitry Andric       return;
1347fa27ce4SDimitry Andric 
135e3b55780SDimitry Andric   // If an earlier def is not in MBB, continue in predecessors.
136e3b55780SDimitry Andric   if (!MBB->isLiveIn(Reg))
137e3b55780SDimitry Andric     MBB->addLiveIn(Reg);
138e3b55780SDimitry Andric   assert(!MBB->pred_empty() && "Predecessor def not found!");
139e3b55780SDimitry Andric   for (MachineBasicBlock *Pred : MBB->predecessors())
140e3b55780SDimitry Andric     if (!VisitedPreds.test(Pred->getNumber()))
1417fa27ce4SDimitry Andric       clearKillsForDef(Reg, Pred, Pred->end(), VisitedPreds);
142e3b55780SDimitry Andric }
143e3b55780SDimitry Andric 
removeRedundantDef(MachineInstr * MI)1447fa27ce4SDimitry Andric void MachineLateInstrsCleanup::removeRedundantDef(MachineInstr *MI) {
145e3b55780SDimitry Andric   Register Reg = MI->getOperand(0).getReg();
146e3b55780SDimitry Andric   BitVector VisitedPreds(MI->getMF()->getNumBlockIDs());
1477fa27ce4SDimitry Andric   clearKillsForDef(Reg, MI->getParent(), MI->getIterator(), VisitedPreds);
148e3b55780SDimitry Andric   MI->eraseFromParent();
149e3b55780SDimitry Andric   ++NumRemoved;
150e3b55780SDimitry Andric }
151e3b55780SDimitry Andric 
152e3b55780SDimitry Andric // Return true if MI is a potential candidate for reuse/removal and if so
153e3b55780SDimitry Andric // also the register it defines in DefedReg.  A candidate is a simple
154e3b55780SDimitry Andric // instruction that does not touch memory, has only one register definition
155e3b55780SDimitry Andric // and the only reg it may use is FrameReg. Typically this is an immediate
156e3b55780SDimitry Andric // load or a load-address instruction.
isCandidate(const MachineInstr * MI,Register & DefedReg,Register FrameReg)157e3b55780SDimitry Andric static bool isCandidate(const MachineInstr *MI, Register &DefedReg,
158e3b55780SDimitry Andric                         Register FrameReg) {
159e3b55780SDimitry Andric   DefedReg = MCRegister::NoRegister;
160e3b55780SDimitry Andric   bool SawStore = true;
161e3b55780SDimitry Andric   if (!MI->isSafeToMove(nullptr, SawStore) || MI->isImplicitDef() ||
162e3b55780SDimitry Andric       MI->isInlineAsm())
163e3b55780SDimitry Andric     return false;
164e3b55780SDimitry Andric   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
165e3b55780SDimitry Andric     const MachineOperand &MO = MI->getOperand(i);
166e3b55780SDimitry Andric     if (MO.isReg()) {
167e3b55780SDimitry Andric       if (MO.isDef()) {
168e3b55780SDimitry Andric         if (i == 0 && !MO.isImplicit() && !MO.isDead())
169e3b55780SDimitry Andric           DefedReg = MO.getReg();
170e3b55780SDimitry Andric         else
171e3b55780SDimitry Andric           return false;
172e3b55780SDimitry Andric       } else if (MO.getReg() && MO.getReg() != FrameReg)
173e3b55780SDimitry Andric         return false;
174e3b55780SDimitry Andric     } else if (!(MO.isImm() || MO.isCImm() || MO.isFPImm() || MO.isCPI() ||
175e3b55780SDimitry Andric                  MO.isGlobal() || MO.isSymbol()))
176e3b55780SDimitry Andric       return false;
177e3b55780SDimitry Andric   }
178e3b55780SDimitry Andric   return DefedReg.isValid();
179e3b55780SDimitry Andric }
180e3b55780SDimitry Andric 
processBlock(MachineBasicBlock * MBB)181e3b55780SDimitry Andric bool MachineLateInstrsCleanup::processBlock(MachineBasicBlock *MBB) {
182e3b55780SDimitry Andric   bool Changed = false;
1837fa27ce4SDimitry Andric   Reg2MIMap &MBBDefs = RegDefs[MBB->getNumber()];
1847fa27ce4SDimitry Andric   Reg2MIMap &MBBKills = RegKills[MBB->getNumber()];
185e3b55780SDimitry Andric 
186e3b55780SDimitry Andric   // Find reusable definitions in the predecessor(s).
1877fa27ce4SDimitry Andric   if (!MBB->pred_empty() && !MBB->isEHPad() &&
1887fa27ce4SDimitry Andric       !MBB->isInlineAsmBrIndirectTarget()) {
189e3b55780SDimitry Andric     MachineBasicBlock *FirstPred = *MBB->pred_begin();
190e3b55780SDimitry Andric     for (auto [Reg, DefMI] : RegDefs[FirstPred->getNumber()])
191e3b55780SDimitry Andric       if (llvm::all_of(
192e3b55780SDimitry Andric               drop_begin(MBB->predecessors()),
193e3b55780SDimitry Andric               [&, &Reg = Reg, &DefMI = DefMI](const MachineBasicBlock *Pred) {
1947fa27ce4SDimitry Andric                 return RegDefs[Pred->getNumber()].hasIdentical(Reg, DefMI);
195e3b55780SDimitry Andric               })) {
196e3b55780SDimitry Andric         MBBDefs[Reg] = DefMI;
197e3b55780SDimitry Andric         LLVM_DEBUG(dbgs() << "Reusable instruction from pred(s): in "
198e3b55780SDimitry Andric                           << printMBBReference(*MBB) << ":  " << *DefMI;);
199e3b55780SDimitry Andric       }
200e3b55780SDimitry Andric   }
201e3b55780SDimitry Andric 
202e3b55780SDimitry Andric   // Process MBB.
203e3b55780SDimitry Andric   MachineFunction *MF = MBB->getParent();
204e3b55780SDimitry Andric   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
205e3b55780SDimitry Andric   Register FrameReg = TRI->getFrameRegister(*MF);
206e3b55780SDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(*MBB)) {
207e3b55780SDimitry Andric     // If FrameReg is modified, no previous load-address instructions (using
208e3b55780SDimitry Andric     // it) are valid.
209e3b55780SDimitry Andric     if (MI.modifiesRegister(FrameReg, TRI)) {
210e3b55780SDimitry Andric       MBBDefs.clear();
2117fa27ce4SDimitry Andric       MBBKills.clear();
212e3b55780SDimitry Andric       continue;
213e3b55780SDimitry Andric     }
214e3b55780SDimitry Andric 
215e3b55780SDimitry Andric     Register DefedReg;
216e3b55780SDimitry Andric     bool IsCandidate = isCandidate(&MI, DefedReg, FrameReg);
217e3b55780SDimitry Andric 
218e3b55780SDimitry Andric     // Check for an earlier identical and reusable instruction.
2197fa27ce4SDimitry Andric     if (IsCandidate && MBBDefs.hasIdentical(DefedReg, &MI)) {
220e3b55780SDimitry Andric       LLVM_DEBUG(dbgs() << "Removing redundant instruction in "
221e3b55780SDimitry Andric                         << printMBBReference(*MBB) << ":  " << MI;);
2227fa27ce4SDimitry Andric       removeRedundantDef(&MI);
223e3b55780SDimitry Andric       Changed = true;
224e3b55780SDimitry Andric       continue;
225e3b55780SDimitry Andric     }
226e3b55780SDimitry Andric 
227e3b55780SDimitry Andric     // Clear any entries in map that MI clobbers.
2287fa27ce4SDimitry Andric     for (auto DefI : llvm::make_early_inc_range(MBBDefs)) {
2297fa27ce4SDimitry Andric       Register Reg = DefI.first;
2307fa27ce4SDimitry Andric       if (MI.modifiesRegister(Reg, TRI)) {
2317fa27ce4SDimitry Andric         MBBDefs.erase(Reg);
2327fa27ce4SDimitry Andric         MBBKills.erase(Reg);
233ac9a064cSDimitry Andric       } else if (MI.findRegisterUseOperandIdx(Reg, TRI, true /*isKill*/) != -1)
2347fa27ce4SDimitry Andric         // Keep track of register kills.
2357fa27ce4SDimitry Andric         MBBKills[Reg] = &MI;
236e3b55780SDimitry Andric     }
237e3b55780SDimitry Andric 
238e3b55780SDimitry Andric     // Record this MI for potential later reuse.
239e3b55780SDimitry Andric     if (IsCandidate) {
240e3b55780SDimitry Andric       LLVM_DEBUG(dbgs() << "Found interesting instruction in "
241e3b55780SDimitry Andric                         << printMBBReference(*MBB) << ":  " << MI;);
242e3b55780SDimitry Andric       MBBDefs[DefedReg] = &MI;
2437fa27ce4SDimitry Andric       assert(!MBBKills.count(DefedReg) && "Should already have been removed.");
244e3b55780SDimitry Andric     }
245e3b55780SDimitry Andric   }
246e3b55780SDimitry Andric 
247e3b55780SDimitry Andric   return Changed;
248e3b55780SDimitry Andric }
249