LLVM  10.0.0
ReachingDefAnalysis.cpp
Go to the documentation of this file.
1 //===---- ReachingDefAnalysis.cpp - 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 
13 #include "llvm/Support/Debug.h"
14 
15 using namespace llvm;
16 
17 #define DEBUG_TYPE "reaching-deps-analysis"
18 
20 INITIALIZE_PASS(ReachingDefAnalysis, DEBUG_TYPE, "ReachingDefAnalysis", false,
21  true)
22 
23 void ReachingDefAnalysis::enterBasicBlock(
24  const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
25 
26  MachineBasicBlock *MBB = TraversedMBB.MBB;
27  unsigned MBBNumber = MBB->getNumber();
28  assert(MBBNumber < MBBReachingDefs.size() &&
29  "Unexpected basic block number.");
30  MBBReachingDefs[MBBNumber].resize(NumRegUnits);
31 
32  // Reset instruction counter in each basic block.
33  CurInstr = 0;
34 
35  // Set up LiveRegs to represent registers entering MBB.
36  // Default values are 'nothing happened a long time ago'.
37  if (LiveRegs.empty())
38  LiveRegs.assign(NumRegUnits, ReachingDefDefaultVal);
39 
40  // This is the entry block.
41  if (MBB->pred_empty()) {
42  for (const auto &LI : MBB->liveins()) {
43  for (MCRegUnitIterator Unit(LI.PhysReg, TRI); Unit.isValid(); ++Unit) {
44  // Treat function live-ins as if they were defined just before the first
45  // instruction. Usually, function arguments are set up immediately
46  // before the call.
47  LiveRegs[*Unit] = -1;
48  MBBReachingDefs[MBBNumber][*Unit].push_back(LiveRegs[*Unit]);
49  }
50  }
51  LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": entry\n");
52  return;
53  }
54 
55  // Try to coalesce live-out registers from predecessors.
56  for (MachineBasicBlock *pred : MBB->predecessors()) {
57  assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
58  "Should have pre-allocated MBBInfos for all MBBs");
59  const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
60  // Incoming is null if this is a backedge from a BB
61  // we haven't processed yet
62  if (Incoming.empty())
63  continue;
64 
65  for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
66  // Use the most recent predecessor def for each register.
67  LiveRegs[Unit] = std::max(LiveRegs[Unit], Incoming[Unit]);
68  if ((LiveRegs[Unit] != ReachingDefDefaultVal))
69  MBBReachingDefs[MBBNumber][Unit].push_back(LiveRegs[Unit]);
70  }
71  }
72 
74  << (!TraversedMBB.IsDone ? ": incomplete\n"
75  : ": all preds known\n"));
76 }
77 
78 void ReachingDefAnalysis::leaveBasicBlock(
79  const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
80  assert(!LiveRegs.empty() && "Must enter basic block first.");
81  unsigned MBBNumber = TraversedMBB.MBB->getNumber();
82  assert(MBBNumber < MBBOutRegsInfos.size() &&
83  "Unexpected basic block number.");
84  // Save register clearances at end of MBB - used by enterBasicBlock().
85  MBBOutRegsInfos[MBBNumber] = LiveRegs;
86 
87  // While processing the basic block, we kept `Def` relative to the start
88  // of the basic block for convenience. However, future use of this information
89  // only cares about the clearance from the end of the block, so adjust
90  // everything to be relative to the end of the basic block.
91  for (int &OutLiveReg : MBBOutRegsInfos[MBBNumber])
92  OutLiveReg -= CurInstr;
93  LiveRegs.clear();
94 }
95 
96 void ReachingDefAnalysis::processDefs(MachineInstr *MI) {
97  assert(!MI->isDebugInstr() && "Won't process debug instructions");
98 
99  unsigned MBBNumber = MI->getParent()->getNumber();
100  assert(MBBNumber < MBBReachingDefs.size() &&
101  "Unexpected basic block number.");
102  const MCInstrDesc &MCID = MI->getDesc();
103  for (unsigned i = 0,
104  e = MI->isVariadic() ? MI->getNumOperands() : MCID.getNumDefs();
105  i != e; ++i) {
106  MachineOperand &MO = MI->getOperand(i);
107  if (!MO.isReg() || !MO.getReg())
108  continue;
109  if (MO.isUse())
110  continue;
111  for (MCRegUnitIterator Unit(MO.getReg(), TRI); Unit.isValid(); ++Unit) {
112  // This instruction explicitly defines the current reg unit.
113  LLVM_DEBUG(dbgs() << printReg(MO.getReg(), TRI) << ":\t" << CurInstr
114  << '\t' << *MI);
115 
116  // How many instructions since this reg unit was last written?
117  LiveRegs[*Unit] = CurInstr;
118  MBBReachingDefs[MBBNumber][*Unit].push_back(CurInstr);
119  }
120  }
121  InstIds[MI] = CurInstr;
122  ++CurInstr;
123 }
124 
125 void ReachingDefAnalysis::processBasicBlock(
126  const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
127  enterBasicBlock(TraversedMBB);
128  for (MachineInstr &MI : *TraversedMBB.MBB) {
129  if (!MI.isDebugInstr())
130  processDefs(&MI);
131  }
132  leaveBasicBlock(TraversedMBB);
133 }
134 
136  MF = &mf;
137  TRI = MF->getSubtarget().getRegisterInfo();
138 
139  LiveRegs.clear();
140  NumRegUnits = TRI->getNumRegUnits();
141 
142  MBBReachingDefs.resize(mf.getNumBlockIDs());
143 
144  LLVM_DEBUG(dbgs() << "********** REACHING DEFINITION ANALYSIS **********\n");
145 
146  // Initialize the MBBOutRegsInfos
147  MBBOutRegsInfos.resize(mf.getNumBlockIDs());
148 
149  // Traverse the basic blocks.
150  LoopTraversal Traversal;
151  LoopTraversal::TraversalOrder TraversedMBBOrder = Traversal.traverse(mf);
152  for (LoopTraversal::TraversedMBBInfo TraversedMBB : TraversedMBBOrder) {
153  processBasicBlock(TraversedMBB);
154  }
155 
156  // Sorting all reaching defs found for a ceartin reg unit in a given BB.
157  for (MBBDefsInfo &MBBDefs : MBBReachingDefs) {
158  for (MBBRegUnitDefs &RegUnitDefs : MBBDefs)
159  llvm::sort(RegUnitDefs);
160  }
161 
162  return false;
163 }
164 
166  // Clear the internal vectors.
167  MBBOutRegsInfos.clear();
168  MBBReachingDefs.clear();
169  InstIds.clear();
170 }
171 
173  assert(InstIds.count(MI) && "Unexpected machine instuction.");
174  int InstId = InstIds[MI];
175  int DefRes = ReachingDefDefaultVal;
176  unsigned MBBNumber = MI->getParent()->getNumber();
177  assert(MBBNumber < MBBReachingDefs.size() &&
178  "Unexpected basic block number.");
179  int LatestDef = ReachingDefDefaultVal;
180  for (MCRegUnitIterator Unit(PhysReg, TRI); Unit.isValid(); ++Unit) {
181  for (int Def : MBBReachingDefs[MBBNumber][*Unit]) {
182  if (Def >= InstId)
183  break;
184  DefRes = Def;
185  }
186  LatestDef = std::max(LatestDef, DefRes);
187  }
188  return LatestDef;
189 }
190 
192  return getInstFromId(MI->getParent(), getReachingDef(MI, PhysReg));
193 }
194 
196  int PhysReg) {
197  MachineBasicBlock *ParentA = A->getParent();
198  MachineBasicBlock *ParentB = B->getParent();
199  if (ParentA != ParentB)
200  return false;
201 
202  return getReachingDef(A, PhysReg) == getReachingDef(B, PhysReg);
203 }
204 
206  int InstId) {
207  assert(static_cast<size_t>(MBB->getNumber()) < MBBReachingDefs.size() &&
208  "Unexpected basic block number.");
209  assert(InstId < static_cast<int>(MBB->size()) &&
210  "Unexpected instruction id.");
211 
212  if (InstId < 0)
213  return nullptr;
214 
215  for (auto &MI : *MBB) {
216  if (InstIds.count(&MI) && InstIds[&MI] == InstId)
217  return &MI;
218  }
219  return nullptr;
220 }
221 
223  assert(InstIds.count(MI) && "Unexpected machine instuction.");
224  return InstIds[MI] - getReachingDef(MI, PhysReg);
225 }
226 
229  MachineBasicBlock *MBB = Def->getParent();
231  while (++MI != MBB->end()) {
232  // If/when we find a new reaching def, we know that there's no more uses
233  // of 'Def'.
234  if (getReachingMIDef(&*MI, PhysReg) != Def)
235  return;
236 
237  for (auto &MO : MI->operands()) {
238  if (!MO.isReg() || !MO.isUse() || MO.getReg() != PhysReg)
239  continue;
240 
241  Uses.push_back(&*MI);
242  if (MO.isKill())
243  return;
244  }
245  }
246 }
247 
250  getReachingLocalUses(Def, PhysReg, Uses);
251  return Uses.size();
252 }
253 
255  MachineBasicBlock *MBB = MI->getParent();
256  LivePhysRegs LiveRegs(*TRI);
257  LiveRegs.addLiveOuts(*MBB);
258 
259  // Yes if the register is live out of the basic block.
260  if (LiveRegs.contains(PhysReg))
261  return true;
262 
263  // Walk backwards through the block to see if the register is live at some
264  // point.
265  for (auto Last = MBB->rbegin(), End = MBB->rend(); Last != End; ++Last) {
266  LiveRegs.stepBackward(*Last);
267  if (LiveRegs.contains(PhysReg))
268  return InstIds[&*Last] > InstIds[MI];
269  }
270  return false;
271 }
272 
274  MachineBasicBlock *MBB = MI->getParent();
275  LivePhysRegs LiveRegs(*TRI);
276  LiveRegs.addLiveOuts(*MBB);
277  if (!LiveRegs.contains(PhysReg))
278  return false;
279 
280  MachineInstr *Last = &MBB->back();
281  int Def = getReachingDef(MI, PhysReg);
282  if (getReachingDef(Last, PhysReg) != Def)
283  return false;
284 
285  // Finally check that the last instruction doesn't redefine the register.
286  for (auto &MO : Last->operands())
287  if (MO.isReg() && MO.isDef() && MO.getReg() == PhysReg)
288  return false;
289 
290  return true;
291 }
292 
294  int PhysReg) {
295  LivePhysRegs LiveRegs(*TRI);
296  LiveRegs.addLiveOuts(*MBB);
297  if (!LiveRegs.contains(PhysReg))
298  return nullptr;
299 
300  MachineInstr *Last = &MBB->back();
301  int Def = getReachingDef(Last, PhysReg);
302  for (auto &MO : Last->operands())
303  if (MO.isReg() && MO.isDef() && MO.getReg() == PhysReg)
304  return Last;
305 
306  return Def < 0 ? nullptr : getInstFromId(MBB, Def);
307 }
308 
310  int PhysReg) {
312  auto E = MI->getParent()->rend();
313  I++;
314 
315  for ( ; I != E; I++)
316  for (auto &MO : I->operands())
317  if (MO.isReg() && MO.isUse() && MO.getReg() == PhysReg)
318  return &*I;
319 
320  return nullptr;
321 }
322 
324  int PhysReg, SmallVectorImpl<MachineInstr*> &Uses) {
325  MachineInstr *Use = nullptr;
326  MachineInstr *Pos = MI;
327 
328  while ((Use = getInstWithUseBefore(Pos, PhysReg))) {
329  Uses.push_back(Use);
330  Pos = Use;
331  }
332 }
bool hasSameReachingDef(MachineInstr *A, MachineInstr *B, int PhysReg)
Return whether A and B use the same def of PhysReg.
void getAllInstWithUseBefore(MachineInstr *MI, int PhysReg, SmallVectorImpl< MachineInstr *> &Uses)
Provides all instructions before MI that uses PhysReg.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID&#39;s allocated.
void push_back(const T &Elt)
Definition: SmallVector.h:211
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:188
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
unsigned const TargetRegisterInfo * TRI
bool contains(MCPhysReg Reg) const
Returns true if register Reg is contained in the set.
Definition: LivePhysRegs.h:106
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:492
unsigned getNumRegUnits() const
Return the number of (native) register units in the target.
INITIALIZE_PASS(ReachingDefAnalysis, DEBUG_TYPE, "ReachingDefAnalysis", false, true) void ReachingDefAnalysis
This class provides the reaching def analysis.
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:429
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:423
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they&#39;re not in a MachineFuncti...
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
reverse_iterator rend()
unsigned getNumUses(MachineInstr *MI, int PhysReg)
Provide the number of uses, in the same block as MI, of the register that MI defines.
reverse_iterator rbegin()
MachineInstrBundleIterator< MachineInstr > iterator
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineInstr * getInstFromId(MachineBasicBlock *MBB, int InstId)
Provides the MI, from the given block, corresponding to the Id or a nullptr if the id does not refer ...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
void addLiveOuts(const MachineBasicBlock &MBB)
Adds all live-out registers of basic block MBB.
void stepBackward(const MachineInstr &MI)
Simulates liveness when stepping backwards over an instruction(bundle).
MachineInstr * getReachingMIDef(MachineInstr *MI, int PhysReg)
Provides the instruction of the closest reaching def instruction of PhysReg that reaches MI...
constexpr double e
Definition: MathExtras.h:57
iterator_range< pred_iterator > predecessors()
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
size_t size() const
Definition: SmallVector.h:52
bool isDebugInstr() const
void getReachingLocalUses(MachineInstr *MI, int PhysReg, SmallVectorImpl< MachineInstr *> &Uses)
Provides the uses, in the same block as MI, of register that MI defines.
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1114
hexagon gen pred
bool isReachingDefLiveOut(MachineInstr *MI, int PhysReg)
Return whether the reaching def for MI also is live out of its parent block.
bool isRegUsedAfter(MachineInstr *MI, int PhysReg)
Return whether the given register is used after MI, whether it&#39;s a local use or a live out...
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:390
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
MachineInstr * getInstWithUseBefore(MachineInstr *MI, int PhysReg)
Provides the first instruction before MI that uses PhysReg.
bool isVariadic(QueryType Type=IgnoreBundle) const
Return true if this instruction can have a variable number of operands.
Definition: MachineInstr.h:656
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:271
Representation of each machine instruction.
Definition: MachineInstr.h:63
A set of physical registers with utility functions to track liveness when walking backward/forward th...
Definition: LivePhysRegs.h:48
int getClearance(MachineInstr *MI, MCPhysReg PhysReg)
Provides the clearance - the number of instructions since the closest reaching def instuction of Phys...
#define I(x, y, z)
Definition: MD5.cpp:58
TraversalOrder traverse(MachineFunction &MF)
This class provides the basic blocks traversal order used by passes like ReachingDefAnalysis and Exec...
Definition: LoopTraversal.h:65
iterator_range< livein_iterator > liveins() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
int getReachingDef(MachineInstr *MI, int PhysReg)
Provides the instruction id of the closest reaching def instruction of PhysReg that reaches MI...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
MachineBasicBlock * MBB
The basic block.
Definition: LoopTraversal.h:89
aarch64 promote const
MachineInstr * getLocalLiveOutMIDef(MachineBasicBlock *MBB, int PhysReg)
Return the local MI that produces the live out value for PhysReg, or nullptr for a non-live out or no...
IRTranslator LLVM IR MI
Register getReg() const
getReg - Returns the register number.
#define DEBUG_TYPE
#define LLVM_DEBUG(X)
Definition: Debug.h:122
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:431
void resize(size_type N)
Definition: SmallVector.h:344