LLVM 20.0.0git
ReachingDefAnalysis.h
Go to the documentation of this file.
1//==--- llvm/CodeGen/ReachingDefAnalysis.h - Reaching Def Analysis -*- C++ -*---==//
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/// \file Reaching Defs Analysis pass.
10///
11/// This pass tracks for each instruction what is the "closest" reaching def of
12/// a given register. It is used by BreakFalseDeps (for clearance calculation)
13/// and ExecutionDomainFix (for arbitrating conflicting domains).
14///
15/// Note that this is different from the usual definition notion of liveness.
16/// The CPU doesn't care whether or not we consider a register killed.
17///
18//
19//===----------------------------------------------------------------------===//
20
21#ifndef LLVM_CODEGEN_REACHINGDEFANALYSIS_H
22#define LLVM_CODEGEN_REACHINGDEFANALYSIS_H
23
24#include "llvm/ADT/DenseMap.h"
30
31namespace llvm {
32
33class MachineBasicBlock;
34class MachineInstr;
35
36/// Thin wrapper around "int" used to store reaching definitions,
37/// using an encoding that makes it compatible with TinyPtrVector.
38/// The 0th LSB is forced zero (and will be used for pointer union tagging),
39/// The 1st LSB is forced one (to make sure the value is non-zero).
41 uintptr_t Encoded;
43 explicit ReachingDef(uintptr_t Encoded) : Encoded(Encoded) {}
44
45public:
46 ReachingDef(std::nullptr_t) : Encoded(0) {}
47 ReachingDef(int Instr) : Encoded(((uintptr_t) Instr << 2) | 2) {}
48 operator int() const { return ((int) Encoded) >> 2; }
49};
50
51template<>
53 static constexpr int NumLowBitsAvailable = 1;
54
55 static inline void *getAsVoidPointer(const ReachingDef &RD) {
56 return reinterpret_cast<void *>(RD.Encoded);
57 }
58
59 static inline ReachingDef getFromVoidPointer(void *P) {
60 return ReachingDef(reinterpret_cast<uintptr_t>(P));
61 }
62
63 static inline ReachingDef getFromVoidPointer(const void *P) {
64 return ReachingDef(reinterpret_cast<uintptr_t>(P));
65 }
66};
67
68// The storage for all reaching definitions.
70public:
71 void init(unsigned NumBlockIDs) { AllReachingDefs.resize(NumBlockIDs); }
72
73 unsigned numBlockIDs() const { return AllReachingDefs.size(); }
74
75 void startBasicBlock(unsigned MBBNumber, unsigned NumRegUnits) {
76 AllReachingDefs[MBBNumber].resize(NumRegUnits);
77 }
78
79 void append(unsigned MBBNumber, unsigned Unit, int Def) {
80 AllReachingDefs[MBBNumber][Unit].push_back(Def);
81 }
82
83 void prepend(unsigned MBBNumber, unsigned Unit, int Def) {
84 auto &Defs = AllReachingDefs[MBBNumber][Unit];
85 Defs.insert(Defs.begin(), Def);
86 }
87
88 void replaceFront(unsigned MBBNumber, unsigned Unit, int Def) {
89 assert(!AllReachingDefs[MBBNumber][Unit].empty());
90 *AllReachingDefs[MBBNumber][Unit].begin() = Def;
91 }
92
93 void clear() { AllReachingDefs.clear(); }
94
95 ArrayRef<ReachingDef> defs(unsigned MBBNumber, unsigned Unit) const {
96 if (AllReachingDefs[MBBNumber].empty())
97 // Block IDs are not necessarily dense.
98 return ArrayRef<ReachingDef>();
99 return AllReachingDefs[MBBNumber][Unit];
100 }
101
102private:
103 /// All reaching defs of a given RegUnit for a given MBB.
104 using MBBRegUnitDefs = TinyPtrVector<ReachingDef>;
105 /// All reaching defs of all reg units for a given MBB
106 using MBBDefsInfo = std::vector<MBBRegUnitDefs>;
107
108 /// All reaching defs of all reg units for all MBBs
109 SmallVector<MBBDefsInfo, 4> AllReachingDefs;
110};
111
112/// This class provides the reaching def analysis.
114private:
115 MachineFunction *MF = nullptr;
116 const TargetRegisterInfo *TRI = nullptr;
117 LoopTraversal::TraversalOrder TraversedMBBOrder;
118 unsigned NumRegUnits = 0;
119 /// Instruction that defined each register, relative to the beginning of the
120 /// current basic block. When a LiveRegsDefInfo is used to represent a
121 /// live-out register, this value is relative to the end of the basic block,
122 /// so it will be a negative number.
123 using LiveRegsDefInfo = std::vector<int>;
124 LiveRegsDefInfo LiveRegs;
125
126 /// Keeps clearance information for all registers. Note that this
127 /// is different from the usual definition notion of liveness. The CPU
128 /// doesn't care whether or not we consider a register killed.
130 OutRegsInfoMap MBBOutRegsInfos;
131
132 /// Current instruction number.
133 /// The first instruction in each basic block is 0.
134 int CurInstr = -1;
135
136 /// Maps instructions to their instruction Ids, relative to the beginning of
137 /// their basic blocks.
139
140 MBBReachingDefsInfo MBBReachingDefs;
141
142 /// Default values are 'nothing happened a long time ago'.
143 const int ReachingDefDefaultVal = -(1 << 21);
144
147
148public:
149 static char ID; // Pass identification, replacement for typeid
150
153 }
154 void releaseMemory() override;
155
156 void getAnalysisUsage(AnalysisUsage &AU) const override {
157 AU.setPreservesAll();
159 }
160
161 bool runOnMachineFunction(MachineFunction &MF) override;
162
167 }
168
169 /// Re-run the analysis.
170 void reset();
171
172 /// Initialize data structures.
173 void init();
174
175 /// Traverse the machine function, mapping definitions.
176 void traverse();
177
178 /// Provides the instruction id of the closest reaching def instruction of
179 /// PhysReg that reaches MI, relative to the begining of MI's basic block.
180 int getReachingDef(MachineInstr *MI, MCRegister PhysReg) const;
181
182 /// Return whether A and B use the same def of PhysReg.
184 MCRegister PhysReg) const;
185
186 /// Return whether the reaching def for MI also is live out of its parent
187 /// block.
188 bool isReachingDefLiveOut(MachineInstr *MI, MCRegister PhysReg) const;
189
190 /// Return the local MI that produces the live out value for PhysReg, or
191 /// nullptr for a non-live out or non-local def.
193 MCRegister PhysReg) const;
194
195 /// If a single MachineInstr creates the reaching definition, then return it.
196 /// Otherwise return null.
198 MCRegister PhysReg) const;
199
200 /// If a single MachineInstr creates the reaching definition, for MIs operand
201 /// at Idx, then return it. Otherwise return null.
202 MachineInstr *getMIOperand(MachineInstr *MI, unsigned Idx) const;
203
204 /// If a single MachineInstr creates the reaching definition, for MIs MO,
205 /// then return it. Otherwise return null.
207
208 /// Provide whether the register has been defined in the same basic block as,
209 /// and before, MI.
210 bool hasLocalDefBefore(MachineInstr *MI, MCRegister PhysReg) const;
211
212 /// Return whether the given register is used after MI, whether it's a local
213 /// use or a live out.
214 bool isRegUsedAfter(MachineInstr *MI, MCRegister PhysReg) const;
215
216 /// Return whether the given register is defined after MI.
217 bool isRegDefinedAfter(MachineInstr *MI, MCRegister PhysReg) const;
218
219 /// Provides the clearance - the number of instructions since the closest
220 /// reaching def instuction of PhysReg that reaches MI.
221 int getClearance(MachineInstr *MI, MCRegister PhysReg) const;
222
223 /// Provides the uses, in the same block as MI, of register that MI defines.
224 /// This does not consider live-outs.
226 InstSet &Uses) const;
227
228 /// Search MBB for a definition of PhysReg and insert it into Defs. If no
229 /// definition is found, recursively search the predecessor blocks for them.
230 void getLiveOuts(MachineBasicBlock *MBB, MCRegister PhysReg, InstSet &Defs,
231 BlockSet &VisitedBBs) const;
233 InstSet &Defs) const;
234
235 /// For the given block, collect the instructions that use the live-in
236 /// value of the provided register. Return whether the value is still
237 /// live on exit.
239 InstSet &Uses) const;
240
241 /// Collect the users of the value stored in PhysReg, which is defined
242 /// by MI.
243 void getGlobalUses(MachineInstr *MI, MCRegister PhysReg, InstSet &Uses) const;
244
245 /// Collect all possible definitions of the value stored in PhysReg, which is
246 /// used by MI.
248 InstSet &Defs) const;
249
250 /// Return whether From can be moved forwards to just before To.
252
253 /// Return whether From can be moved backwards to just after To.
255
256 /// Assuming MI is dead, recursively search the incoming operands which are
257 /// killed by MI and collect those that would become dead.
258 void collectKilledOperands(MachineInstr *MI, InstSet &Dead) const;
259
260 /// Return whether removing this instruction will have no effect on the
261 /// program, returning the redundant use-def chain.
262 bool isSafeToRemove(MachineInstr *MI, InstSet &ToRemove) const;
263
264 /// Return whether removing this instruction will have no effect on the
265 /// program, ignoring the possible effects on some instructions, returning
266 /// the redundant use-def chain.
267 bool isSafeToRemove(MachineInstr *MI, InstSet &ToRemove,
268 InstSet &Ignore) const;
269
270 /// Return whether a MachineInstr could be inserted at MI and safely define
271 /// the given register without affecting the program.
272 bool isSafeToDefRegAt(MachineInstr *MI, MCRegister PhysReg) const;
273
274 /// Return whether a MachineInstr could be inserted at MI and safely define
275 /// the given register without affecting the program, ignoring any effects
276 /// on the provided instructions.
278 InstSet &Ignore) const;
279
280private:
281 /// Set up LiveRegs by merging predecessor live-out values.
282 void enterBasicBlock(MachineBasicBlock *MBB);
283
284 /// Update live-out values.
285 void leaveBasicBlock(MachineBasicBlock *MBB);
286
287 /// Process he given basic block.
288 void processBasicBlock(const LoopTraversal::TraversedMBBInfo &TraversedMBB);
289
290 /// Process block that is part of a loop again.
291 void reprocessBasicBlock(MachineBasicBlock *MBB);
292
293 /// Update def-ages for registers defined by MI.
294 /// Also break dependencies on partial defs and undef uses.
295 void processDefs(MachineInstr *);
296
297 /// Utility function for isSafeToMoveForwards/Backwards.
298 template<typename Iterator>
299 bool isSafeToMove(MachineInstr *From, MachineInstr *To) const;
300
301 /// Return whether removing this instruction will have no effect on the
302 /// program, ignoring the possible effects on some instructions, returning
303 /// the redundant use-def chain.
304 bool isSafeToRemove(MachineInstr *MI, InstSet &Visited,
305 InstSet &ToRemove, InstSet &Ignore) const;
306
307 /// Provides the MI, from the given block, corresponding to the Id or a
308 /// nullptr if the id does not refer to the block.
309 MachineInstr *getInstFromId(MachineBasicBlock *MBB, int InstId) const;
310
311 /// Provides the instruction of the closest reaching def instruction of
312 /// PhysReg that reaches MI, relative to the begining of MI's basic block.
313 MachineInstr *getReachingLocalMIDef(MachineInstr *MI,
314 MCRegister PhysReg) const;
315};
316
317} // namespace llvm
318
319#endif // LLVM_CODEGEN_REACHINGDEFANALYSIS_H
ReachingDefAnalysis InstSet & ToRemove
ReachingDefAnalysis InstSet InstSet & Ignore
MachineBasicBlock & MBB
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the DenseMap class.
IRTranslator LLVM IR MI
#define P(N)
Remove Loads Into Fake Uses
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
void append(unsigned MBBNumber, unsigned Unit, int Def)
ArrayRef< ReachingDef > defs(unsigned MBBNumber, unsigned Unit) const
void replaceFront(unsigned MBBNumber, unsigned Unit, int Def)
void init(unsigned NumBlockIDs)
void prepend(unsigned MBBNumber, unsigned Unit, int Def)
void startBasicBlock(unsigned MBBNumber, unsigned NumRegUnits)
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
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.
Properties which a MachineFunction may have at a given point in time.
MachineFunctionProperties & set(Property P)
Representation of each machine instruction.
Definition: MachineInstr.h:69
MachineOperand class - Representation of each machine instruction operand.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class provides the reaching def analysis.
void traverse()
Traverse the machine function, mapping definitions.
bool isSafeToMoveForwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved forwards to just before To.
bool isSafeToDefRegAt(MachineInstr *MI, MCRegister PhysReg) const
Return whether a MachineInstr could be inserted at MI and safely define the given register without af...
bool getLiveInUses(MachineBasicBlock *MBB, MCRegister PhysReg, InstSet &Uses) const
For the given block, collect the instructions that use the live-in value of the provided register.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
bool isSafeToRemove(MachineInstr *MI, InstSet &ToRemove) const
Return whether removing this instruction will have no effect on the program, returning the redundant ...
MachineInstr * getLocalLiveOutMIDef(MachineBasicBlock *MBB, MCRegister PhysReg) const
Return the local MI that produces the live out value for PhysReg, or nullptr for a non-live out or no...
MachineInstr * getMIOperand(MachineInstr *MI, unsigned Idx) const
If a single MachineInstr creates the reaching definition, for MIs operand at Idx, then return it.
void getReachingLocalUses(MachineInstr *MI, MCRegister PhysReg, InstSet &Uses) const
Provides the uses, in the same block as MI, of register that MI defines.
void reset()
Re-run the analysis.
bool isRegUsedAfter(MachineInstr *MI, MCRegister PhysReg) const
Return whether the given register is used after MI, whether it's a local use or a live out.
bool hasLocalDefBefore(MachineInstr *MI, MCRegister PhysReg) const
Provide whether the register has been defined in the same basic block as, and before,...
void init()
Initialize data structures.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
void getLiveOuts(MachineBasicBlock *MBB, MCRegister PhysReg, InstSet &Defs, BlockSet &VisitedBBs) const
Search MBB for a definition of PhysReg and insert it into Defs.
bool hasSameReachingDef(MachineInstr *A, MachineInstr *B, MCRegister PhysReg) const
Return whether A and B use the same def of PhysReg.
void getGlobalUses(MachineInstr *MI, MCRegister PhysReg, InstSet &Uses) const
Collect the users of the value stored in PhysReg, which is defined by MI.
void collectKilledOperands(MachineInstr *MI, InstSet &Dead) const
Assuming MI is dead, recursively search the incoming operands which are killed by MI and collect thos...
bool isRegDefinedAfter(MachineInstr *MI, MCRegister PhysReg) const
Return whether the given register is defined after MI.
int getReachingDef(MachineInstr *MI, MCRegister PhysReg) const
Provides the instruction id of the closest reaching def instruction of PhysReg that reaches MI,...
bool isSafeToMoveBackwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved backwards to just after To.
void getGlobalReachingDefs(MachineInstr *MI, MCRegister PhysReg, InstSet &Defs) const
Collect all possible definitions of the value stored in PhysReg, which is used by MI.
MachineInstr * getUniqueReachingMIDef(MachineInstr *MI, MCRegister PhysReg) const
If a single MachineInstr creates the reaching definition, then return it.
bool isReachingDefLiveOut(MachineInstr *MI, MCRegister PhysReg) const
Return whether the reaching def for MI also is live out of its parent block.
MachineFunctionProperties getRequiredProperties() const override
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
int getClearance(MachineInstr *MI, MCRegister PhysReg) const
Provides the clearance - the number of instructions since the closest reaching def instuction of Phys...
Thin wrapper around "int" used to store reaching definitions, using an encoding that makes it compati...
ReachingDef(std::nullptr_t)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:363
size_t size() const
Definition: SmallVector.h:78
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:805
void resize(size_type N)
Definition: SmallVector.h:638
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Definition: TinyPtrVector.h:29
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void initializeReachingDefAnalysisPass(PassRegistry &)
static ReachingDef getFromVoidPointer(const void *P)
static ReachingDef getFromVoidPointer(void *P)
static void * getAsVoidPointer(const ReachingDef &RD)
A traits type that is used to handle pointer types and things that are just wrappers for pointers as ...