LLVM 22.0.0git
MachineLateInstrsCleanup.cpp
Go to the documentation of this file.
1//==--- MachineLateInstrsCleanup.cpp - Late Instructions Cleanup Pass -----===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This simple pass removes any identical and redundant immediate or address
10// loads to the same register. The immediate loads removed can originally be
11// the result of rematerialization, while the addresses are redundant frame
12// addressing anchor points created during Frame Indices elimination.
13//
14//===----------------------------------------------------------------------===//
15
17#include "llvm/ADT/BitVector.h"
19#include "llvm/ADT/Statistic.h"
29#include "llvm/Pass.h"
30#include "llvm/Support/Debug.h"
31
32using namespace llvm;
33
34#define DEBUG_TYPE "machine-latecleanup"
35
36STATISTIC(NumRemoved, "Number of redundant instructions removed.");
37
38namespace {
39
40class MachineLateInstrsCleanup {
41 const TargetRegisterInfo *TRI = nullptr;
42 const TargetInstrInfo *TII = nullptr;
43
44 // Data structures to map regs to their definitions and kills per MBB.
45 struct Reg2MIMap : public SmallDenseMap<Register, MachineInstr *> {
46 bool hasIdentical(Register Reg, MachineInstr *ArgMI) {
47 MachineInstr *MI = lookup(Reg);
48 return MI && MI->isIdenticalTo(*ArgMI);
49 }
50 };
52 std::vector<Reg2MIMap> RegDefs;
53 std::vector<Reg2MIVecMap> RegKills;
54
55 // Walk through the instructions in MBB and remove any redundant
56 // instructions.
57 bool processBlock(MachineBasicBlock *MBB);
58
59 void removeRedundantDef(MachineInstr *MI);
60 void clearKillsForDef(Register Reg, MachineBasicBlock *MBB,
61 BitVector &VisitedPreds, MachineInstr *ToRemoveMI);
62
63public:
64 bool run(MachineFunction &MF);
65};
66
67class MachineLateInstrsCleanupLegacy : public MachineFunctionPass {
68public:
69 static char ID; // Pass identification, replacement for typeid
70
71 MachineLateInstrsCleanupLegacy() : MachineFunctionPass(ID) {
74 }
75
76 void getAnalysisUsage(AnalysisUsage &AU) const override {
77 AU.setPreservesCFG();
79 }
80
81 bool runOnMachineFunction(MachineFunction &MF) override;
82
84 return MachineFunctionProperties().setNoVRegs();
85 }
86};
87
88} // end anonymous namespace
89
90char MachineLateInstrsCleanupLegacy::ID = 0;
91
92char &llvm::MachineLateInstrsCleanupID = MachineLateInstrsCleanupLegacy::ID;
93
94INITIALIZE_PASS(MachineLateInstrsCleanupLegacy, DEBUG_TYPE,
95 "Machine Late Instructions Cleanup Pass", false, false)
96
97bool MachineLateInstrsCleanupLegacy::runOnMachineFunction(MachineFunction &MF) {
98 if (skipFunction(MF.getFunction()))
99 return false;
100
101 return MachineLateInstrsCleanup().run(MF);
102}
103
107 MFPropsModifier _(*this, MF);
108 if (!MachineLateInstrsCleanup().run(MF))
109 return PreservedAnalyses::all();
111 PA.preserveSet<CFGAnalyses>();
112 return PA;
113}
114
115bool MachineLateInstrsCleanup::run(MachineFunction &MF) {
118
119 RegDefs.clear();
120 RegDefs.resize(MF.getNumBlockIDs());
121 RegKills.clear();
122 RegKills.resize(MF.getNumBlockIDs());
123
124 // Visit all MBBs in an order that maximises the reuse from predecessors.
125 bool Changed = false;
127 for (MachineBasicBlock *MBB : RPOT)
128 Changed |= processBlock(MBB);
129
130 return Changed;
131}
132
133// Clear any preceding kill flag on Reg after removing a redundant
134// definition.
135void MachineLateInstrsCleanup::clearKillsForDef(Register Reg,
137 BitVector &VisitedPreds,
138 MachineInstr *ToRemoveMI) {
139 VisitedPreds.set(MBB->getNumber());
140
141 // Clear kill flag(s) in MBB, that have been seen after the preceding
142 // definition. If Reg or one of its subregs was killed, it would actually
143 // be ok to stop after removing that (and any other) kill-flag, but it
144 // doesn't seem noticeably faster while it would be a bit more complicated.
145 Reg2MIVecMap &MBBKills = RegKills[MBB->getNumber()];
146 if (auto Kills = MBBKills.find(Reg); Kills != MBBKills.end())
147 for (auto *KillMI : Kills->second)
148 KillMI->clearRegisterKills(Reg, TRI);
149
150 // Definition in current MBB: done.
151 Reg2MIMap &MBBDefs = RegDefs[MBB->getNumber()];
152 MachineInstr *DefMI = MBBDefs[Reg];
153 assert(DefMI->isIdenticalTo(*ToRemoveMI) && "Previous def not identical?");
154 if (DefMI->getParent() == MBB)
155 return;
156
157 // If an earlier def is not in MBB, continue in predecessors.
158 if (!MBB->isLiveIn(Reg))
159 MBB->addLiveIn(Reg);
160 assert(!MBB->pred_empty() && "Predecessor def not found!");
161 for (MachineBasicBlock *Pred : MBB->predecessors())
162 if (!VisitedPreds.test(Pred->getNumber()))
163 clearKillsForDef(Reg, Pred, VisitedPreds, ToRemoveMI);
164}
165
166void MachineLateInstrsCleanup::removeRedundantDef(MachineInstr *MI) {
167 Register Reg = MI->getOperand(0).getReg();
168 BitVector VisitedPreds(MI->getMF()->getNumBlockIDs());
169 clearKillsForDef(Reg, MI->getParent(), VisitedPreds, MI);
170 MI->eraseFromParent();
171 ++NumRemoved;
172}
173
174// Return true if MI is a potential candidate for reuse/removal and if so
175// also the register it defines in DefedReg. A candidate is a simple
176// instruction that does not touch memory, has only one register definition
177// and the only reg it may use is FrameReg. Typically this is an immediate
178// load or a load-address instruction.
179static bool isCandidate(const MachineInstr *MI, Register &DefedReg,
180 Register FrameReg) {
181 DefedReg = MCRegister::NoRegister;
182 bool SawStore = true;
183 if (!MI->isSafeToMove(SawStore) || MI->isImplicitDef() || MI->isInlineAsm())
184 return false;
185 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
186 const MachineOperand &MO = MI->getOperand(i);
187 if (MO.isReg()) {
188 if (MO.isDef()) {
189 if (i == 0 && !MO.isImplicit() && !MO.isDead())
190 DefedReg = MO.getReg();
191 else
192 return false;
193 } else if (MO.getReg() && MO.getReg() != FrameReg)
194 return false;
195 } else if (!(MO.isImm() || MO.isCImm() || MO.isFPImm() || MO.isCPI() ||
196 MO.isGlobal() || MO.isSymbol()))
197 return false;
198 }
199 return DefedReg.isValid();
200}
201
202bool MachineLateInstrsCleanup::processBlock(MachineBasicBlock *MBB) {
203 bool Changed = false;
204 Reg2MIMap &MBBDefs = RegDefs[MBB->getNumber()];
205 Reg2MIVecMap &MBBKills = RegKills[MBB->getNumber()];
206
207 // Find reusable definitions in the predecessor(s).
208 if (!MBB->pred_empty() && !MBB->isEHPad() &&
210 MachineBasicBlock *FirstPred = *MBB->pred_begin();
211 for (auto [Reg, DefMI] : RegDefs[FirstPred->getNumber()])
212 if (llvm::all_of(
214 [&, &Reg = Reg, &DefMI = DefMI](const MachineBasicBlock *Pred) {
215 return RegDefs[Pred->getNumber()].hasIdentical(Reg, DefMI);
216 })) {
217 MBBDefs[Reg] = DefMI;
218 LLVM_DEBUG(dbgs() << "Reusable instruction from pred(s): in "
219 << printMBBReference(*MBB) << ": " << *DefMI);
220 }
221 }
222
223 // Process MBB.
226 Register FrameReg = TRI->getFrameRegister(*MF);
228 // If FrameReg is modified, no previous load-address instructions (using
229 // it) are valid.
230 if (MI.modifiesRegister(FrameReg, TRI)) {
231 MBBDefs.clear();
232 MBBKills.clear();
233 continue;
234 }
235
236 Register DefedReg;
237 bool IsCandidate = isCandidate(&MI, DefedReg, FrameReg);
238
239 // Check for an earlier identical and reusable instruction.
240 if (IsCandidate && MBBDefs.hasIdentical(DefedReg, &MI)) {
241 LLVM_DEBUG(dbgs() << "Removing redundant instruction in "
242 << printMBBReference(*MBB) << ": " << MI);
243 removeRedundantDef(&MI);
244 Changed = true;
245 continue;
246 }
247
248 // Clear any entries in map that MI clobbers.
249 for (auto DefI : llvm::make_early_inc_range(MBBDefs)) {
250 Register Reg = DefI.first;
251 if (MI.modifiesRegister(Reg, TRI)) {
252 MBBDefs.erase(Reg);
253 MBBKills.erase(Reg);
254 } else if (MI.findRegisterUseOperandIdx(Reg, TRI, true /*isKill*/) != -1)
255 // Keep track of all instructions that fully or partially kills Reg.
256 MBBKills[Reg].push_back(&MI);
257 }
258
259 // Record this MI for potential later reuse.
260 if (IsCandidate) {
261 LLVM_DEBUG(dbgs() << "Found interesting instruction in "
262 << printMBBReference(*MBB) << ": " << MI);
263 MBBDefs[DefedReg] = &MI;
264 assert(!MBBKills.count(DefedReg) && "Should already have been removed.");
265 }
266 }
267
268 return Changed;
269}
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
This file implements the BitVector class.
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
static bool lookup(const GsymReader &GR, DataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
Definition: InlineInfo.cpp:108
static bool isCandidate(const MachineInstr *MI, Register &DefedReg, Register FrameReg)
#define DEBUG_TYPE
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:56
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
#define LLVM_DEBUG(...)
Definition: Debug.h:119
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
Represent the analysis usage information of a pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:270
bool test(unsigned Idx) const
Definition: BitVector.h:461
BitVector & set()
Definition: BitVector.h:351
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:73
static constexpr unsigned NoRegister
Definition: MCRegister.h:52
An RAII based helper class to modify MachineFunctionProperties when running pass.
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
bool isEHPad() const
Returns true if the block is a landing pad.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< pred_iterator > predecessors()
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
virtual MachineFunctionProperties getRequiredProperties() const
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
Representation of each machine instruction.
Definition: MachineInstr.h:72
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:359
LLVM_ABI bool isIdenticalTo(const MachineInstr &Other, MICheckType Check=CheckDefs) const
Return true if this instruction is identical to Other.
PreservedAnalyses run(MachineFunction &MachineFunction, MachineFunctionAnalysisManager &MachineFunctionAM)
MachineOperand class - Representation of each machine instruction operand.
bool isCImm() const
isCImm - Test if this is a MO_CImmediate operand.
bool isImplicit() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isCPI() const
isCPI - Tests if this is a MO_ConstantPoolIndex operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
Register getReg() const
getReg - Returns the register number.
bool isFPImm() const
isFPImm - Tests if this is a MO_FPImmediate operand.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
constexpr bool isValid() const
Definition: Register.h:107
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
Reg
All possible values of the reg field in the ModR/M byte.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:338
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1744
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:663
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI char & MachineLateInstrsCleanupID
MachineLateInstrsCleanup - This pass removes redundant identical instructions after register allocati...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
LLVM_ABI void initializeMachineLateInstrsCleanupLegacyPass(PassRegistry &)
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.