xref: /llvm-project/llvm/lib/CodeGen/ReachingDefAnalysis.cpp (revision cb27006a9461b78b3f7e9128af22ba6311665c70)
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 
9 #include "llvm/ADT/SmallSet.h"
10 #include "llvm/CodeGen/LivePhysRegs.h"
11 #include "llvm/CodeGen/ReachingDefAnalysis.h"
12 #include "llvm/CodeGen/TargetRegisterInfo.h"
13 #include "llvm/CodeGen/TargetSubtargetInfo.h"
14 #include "llvm/Support/Debug.h"
15 
16 using namespace llvm;
17 
18 #define DEBUG_TYPE "reaching-deps-analysis"
19 
20 char ReachingDefAnalysis::ID = 0;
21 INITIALIZE_PASS(ReachingDefAnalysis, DEBUG_TYPE, "ReachingDefAnalysis", false,
22                 true)
23 
24 static bool isValidReg(const MachineOperand &MO) {
25   return MO.isReg() && MO.getReg();
26 }
27 
28 static bool isValidRegUse(const MachineOperand &MO) {
29   return isValidReg(MO) && MO.isUse();
30 }
31 
32 static bool isValidRegUseOf(const MachineOperand &MO, int PhysReg) {
33   return isValidRegUse(MO) && MO.getReg() == PhysReg;
34 }
35 
36 static bool isValidRegDef(const MachineOperand &MO) {
37   return isValidReg(MO) && MO.isDef();
38 }
39 
40 static bool isValidRegDefOf(const MachineOperand &MO, int PhysReg) {
41   return isValidRegDef(MO) && MO.getReg() == PhysReg;
42 }
43 
44 void ReachingDefAnalysis::enterBasicBlock(MachineBasicBlock *MBB) {
45   unsigned MBBNumber = MBB->getNumber();
46   assert(MBBNumber < MBBReachingDefs.size() &&
47          "Unexpected basic block number.");
48   MBBReachingDefs[MBBNumber].resize(NumRegUnits);
49 
50   // Reset instruction counter in each basic block.
51   CurInstr = 0;
52 
53   // Set up LiveRegs to represent registers entering MBB.
54   // Default values are 'nothing happened a long time ago'.
55   if (LiveRegs.empty())
56     LiveRegs.assign(NumRegUnits, ReachingDefDefaultVal);
57 
58   // This is the entry block.
59   if (MBB->pred_empty()) {
60     for (const auto &LI : MBB->liveins()) {
61       for (MCRegUnitIterator Unit(LI.PhysReg, TRI); Unit.isValid(); ++Unit) {
62         // Treat function live-ins as if they were defined just before the first
63         // instruction.  Usually, function arguments are set up immediately
64         // before the call.
65         if (LiveRegs[*Unit] != -1) {
66           LiveRegs[*Unit] = -1;
67           MBBReachingDefs[MBBNumber][*Unit].push_back(-1);
68         }
69       }
70     }
71     LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": entry\n");
72     return;
73   }
74 
75   // Try to coalesce live-out registers from predecessors.
76   for (MachineBasicBlock *pred : MBB->predecessors()) {
77     assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
78            "Should have pre-allocated MBBInfos for all MBBs");
79     const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
80     // Incoming is null if this is a backedge from a BB
81     // we haven't processed yet
82     if (Incoming.empty())
83       continue;
84 
85     // Find the most recent reaching definition from a predecessor.
86     for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
87       LiveRegs[Unit] = std::max(LiveRegs[Unit], Incoming[Unit]);
88   }
89 
90   // Insert the most recent reaching definition we found.
91   for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
92     if (LiveRegs[Unit] != ReachingDefDefaultVal)
93       MBBReachingDefs[MBBNumber][Unit].push_back(LiveRegs[Unit]);
94 }
95 
96 void ReachingDefAnalysis::leaveBasicBlock(MachineBasicBlock *MBB) {
97   assert(!LiveRegs.empty() && "Must enter basic block first.");
98   unsigned MBBNumber = MBB->getNumber();
99   assert(MBBNumber < MBBOutRegsInfos.size() &&
100          "Unexpected basic block number.");
101   // Save register clearances at end of MBB - used by enterBasicBlock().
102   MBBOutRegsInfos[MBBNumber] = LiveRegs;
103 
104   // While processing the basic block, we kept `Def` relative to the start
105   // of the basic block for convenience. However, future use of this information
106   // only cares about the clearance from the end of the block, so adjust
107   // everything to be relative to the end of the basic block.
108   for (int &OutLiveReg : MBBOutRegsInfos[MBBNumber])
109     if (OutLiveReg != ReachingDefDefaultVal)
110       OutLiveReg -= CurInstr;
111   LiveRegs.clear();
112 }
113 
114 void ReachingDefAnalysis::processDefs(MachineInstr *MI) {
115   assert(!MI->isDebugInstr() && "Won't process debug instructions");
116 
117   unsigned MBBNumber = MI->getParent()->getNumber();
118   assert(MBBNumber < MBBReachingDefs.size() &&
119          "Unexpected basic block number.");
120 
121   for (auto &MO : MI->operands()) {
122     if (!isValidRegDef(MO))
123       continue;
124     for (MCRegUnitIterator Unit(MO.getReg(), TRI); Unit.isValid(); ++Unit) {
125       // This instruction explicitly defines the current reg unit.
126       LLVM_DEBUG(dbgs() << printReg(*Unit, TRI) << ":\t" << CurInstr
127                         << '\t' << *MI);
128 
129       // How many instructions since this reg unit was last written?
130       if (LiveRegs[*Unit] != CurInstr) {
131         LiveRegs[*Unit] = CurInstr;
132         MBBReachingDefs[MBBNumber][*Unit].push_back(CurInstr);
133       }
134     }
135   }
136   InstIds[MI] = CurInstr;
137   ++CurInstr;
138 }
139 
140 void ReachingDefAnalysis::reprocessBasicBlock(MachineBasicBlock *MBB) {
141   unsigned MBBNumber = MBB->getNumber();
142   assert(MBBNumber < MBBReachingDefs.size() &&
143          "Unexpected basic block number.");
144 
145   // Count number of non-debug instructions for end of block adjustment.
146   auto NonDbgInsts =
147     instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end());
148   int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
149 
150   // When reprocessing a block, the only thing we need to do is check whether
151   // there is now a more recent incoming reaching definition from a predecessor.
152   for (MachineBasicBlock *pred : MBB->predecessors()) {
153     assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
154            "Should have pre-allocated MBBInfos for all MBBs");
155     const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
156     // Incoming may be empty for dead predecessors.
157     if (Incoming.empty())
158       continue;
159 
160     for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
161       int Def = Incoming[Unit];
162       if (Def == ReachingDefDefaultVal)
163         continue;
164 
165       auto Start = MBBReachingDefs[MBBNumber][Unit].begin();
166       if (Start != MBBReachingDefs[MBBNumber][Unit].end() && *Start < 0) {
167         if (*Start >= Def)
168           continue;
169 
170         // Update existing reaching def from predecessor to a more recent one.
171         *Start = Def;
172       } else {
173         // Insert new reaching def from predecessor.
174         MBBReachingDefs[MBBNumber][Unit].insert(Start, Def);
175       }
176 
177       // Update reaching def at end of of BB. Keep in mind that these are
178       // adjusted relative to the end of the basic block.
179       if (MBBOutRegsInfos[MBBNumber][Unit] < Def - NumInsts)
180         MBBOutRegsInfos[MBBNumber][Unit] = Def - NumInsts;
181     }
182   }
183 }
184 
185 void ReachingDefAnalysis::processBasicBlock(
186     const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
187   MachineBasicBlock *MBB = TraversedMBB.MBB;
188   LLVM_DEBUG(dbgs() << printMBBReference(*MBB)
189                     << (!TraversedMBB.IsDone ? ": incomplete\n"
190                                              : ": all preds known\n"));
191 
192   if (!TraversedMBB.PrimaryPass) {
193     // Reprocess MBB that is part of a loop.
194     reprocessBasicBlock(MBB);
195     return;
196   }
197 
198   enterBasicBlock(MBB);
199   for (MachineInstr &MI :
200        instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end()))
201     processDefs(&MI);
202   leaveBasicBlock(MBB);
203 }
204 
205 bool ReachingDefAnalysis::runOnMachineFunction(MachineFunction &mf) {
206   MF = &mf;
207   TRI = MF->getSubtarget().getRegisterInfo();
208   LLVM_DEBUG(dbgs() << "********** REACHING DEFINITION ANALYSIS **********\n");
209   init();
210   traverse();
211   return false;
212 }
213 
214 void ReachingDefAnalysis::releaseMemory() {
215   // Clear the internal vectors.
216   MBBOutRegsInfos.clear();
217   MBBReachingDefs.clear();
218   InstIds.clear();
219   LiveRegs.clear();
220 }
221 
222 void ReachingDefAnalysis::reset() {
223   releaseMemory();
224   init();
225   traverse();
226 }
227 
228 void ReachingDefAnalysis::init() {
229   NumRegUnits = TRI->getNumRegUnits();
230   MBBReachingDefs.resize(MF->getNumBlockIDs());
231   // Initialize the MBBOutRegsInfos
232   MBBOutRegsInfos.resize(MF->getNumBlockIDs());
233   LoopTraversal Traversal;
234   TraversedMBBOrder = Traversal.traverse(*MF);
235 }
236 
237 void ReachingDefAnalysis::traverse() {
238   // Traverse the basic blocks.
239   for (LoopTraversal::TraversedMBBInfo TraversedMBB : TraversedMBBOrder)
240     processBasicBlock(TraversedMBB);
241 #ifndef NDEBUG
242   // Make sure reaching defs are sorted and unique.
243   for (MBBDefsInfo &MBBDefs : MBBReachingDefs) {
244     for (MBBRegUnitDefs &RegUnitDefs : MBBDefs) {
245       int LastDef = ReachingDefDefaultVal;
246       for (int Def : RegUnitDefs) {
247         assert(Def > LastDef && "Defs must be sorted and unique");
248         LastDef = Def;
249       }
250     }
251   }
252 #endif
253 }
254 
255 int ReachingDefAnalysis::getReachingDef(MachineInstr *MI, int PhysReg) const {
256   assert(InstIds.count(MI) && "Unexpected machine instuction.");
257   int InstId = InstIds.lookup(MI);
258   int DefRes = ReachingDefDefaultVal;
259   unsigned MBBNumber = MI->getParent()->getNumber();
260   assert(MBBNumber < MBBReachingDefs.size() &&
261          "Unexpected basic block number.");
262   int LatestDef = ReachingDefDefaultVal;
263   for (MCRegUnitIterator Unit(PhysReg, TRI); Unit.isValid(); ++Unit) {
264     for (int Def : MBBReachingDefs[MBBNumber][*Unit]) {
265       if (Def >= InstId)
266         break;
267       DefRes = Def;
268     }
269     LatestDef = std::max(LatestDef, DefRes);
270   }
271   return LatestDef;
272 }
273 
274 MachineInstr* ReachingDefAnalysis::getReachingLocalMIDef(MachineInstr *MI,
275                                                          int PhysReg) const {
276   return hasLocalDefBefore(MI, PhysReg)
277     ? getInstFromId(MI->getParent(), getReachingDef(MI, PhysReg))
278     : nullptr;
279 }
280 
281 bool ReachingDefAnalysis::hasSameReachingDef(MachineInstr *A, MachineInstr *B,
282                                              int PhysReg) const {
283   MachineBasicBlock *ParentA = A->getParent();
284   MachineBasicBlock *ParentB = B->getParent();
285   if (ParentA != ParentB)
286     return false;
287 
288   return getReachingDef(A, PhysReg) == getReachingDef(B, PhysReg);
289 }
290 
291 MachineInstr *ReachingDefAnalysis::getInstFromId(MachineBasicBlock *MBB,
292                                                  int InstId) const {
293   assert(static_cast<size_t>(MBB->getNumber()) < MBBReachingDefs.size() &&
294          "Unexpected basic block number.");
295   assert(InstId < static_cast<int>(MBB->size()) &&
296          "Unexpected instruction id.");
297 
298   if (InstId < 0)
299     return nullptr;
300 
301   for (auto &MI : *MBB) {
302     auto F = InstIds.find(&MI);
303     if (F != InstIds.end() && F->second == InstId)
304       return &MI;
305   }
306 
307   return nullptr;
308 }
309 
310 int
311 ReachingDefAnalysis::getClearance(MachineInstr *MI, MCPhysReg PhysReg) const {
312   assert(InstIds.count(MI) && "Unexpected machine instuction.");
313   return InstIds.lookup(MI) - getReachingDef(MI, PhysReg);
314 }
315 
316 bool
317 ReachingDefAnalysis::hasLocalDefBefore(MachineInstr *MI, int PhysReg) const {
318   return getReachingDef(MI, PhysReg) >= 0;
319 }
320 
321 void ReachingDefAnalysis::getReachingLocalUses(MachineInstr *Def, int PhysReg,
322                                                InstSet &Uses) const {
323   MachineBasicBlock *MBB = Def->getParent();
324   MachineBasicBlock::iterator MI = MachineBasicBlock::iterator(Def);
325   while (++MI != MBB->end()) {
326     if (MI->isDebugInstr())
327       continue;
328 
329     // If/when we find a new reaching def, we know that there's no more uses
330     // of 'Def'.
331     if (getReachingLocalMIDef(&*MI, PhysReg) != Def)
332       return;
333 
334     for (auto &MO : MI->operands()) {
335       if (!isValidRegUseOf(MO, PhysReg))
336         continue;
337 
338       Uses.insert(&*MI);
339       if (MO.isKill())
340         return;
341     }
342   }
343 }
344 
345 bool
346 ReachingDefAnalysis::getLiveInUses(MachineBasicBlock *MBB, int PhysReg,
347                                    InstSet &Uses) const {
348   for (MachineInstr &MI :
349        instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end())) {
350     for (auto &MO : MI.operands()) {
351       if (!isValidRegUseOf(MO, PhysReg))
352         continue;
353       if (getReachingDef(&MI, PhysReg) >= 0)
354         return false;
355       Uses.insert(&MI);
356     }
357   }
358   auto Last = MBB->getLastNonDebugInstr();
359   if (Last == MBB->end())
360     return true;
361   return isReachingDefLiveOut(&*Last, PhysReg);
362 }
363 
364 void
365 ReachingDefAnalysis::getGlobalUses(MachineInstr *MI, int PhysReg,
366                                    InstSet &Uses) const {
367   MachineBasicBlock *MBB = MI->getParent();
368 
369   // Collect the uses that each def touches within the block.
370   getReachingLocalUses(MI, PhysReg, Uses);
371 
372   // Handle live-out values.
373   if (auto *LiveOut = getLocalLiveOutMIDef(MI->getParent(), PhysReg)) {
374     if (LiveOut != MI)
375       return;
376 
377     SmallVector<MachineBasicBlock*, 4> ToVisit;
378     ToVisit.insert(ToVisit.begin(), MBB->successors().begin(),
379                    MBB->successors().end());
380     SmallPtrSet<MachineBasicBlock*, 4>Visited;
381     while (!ToVisit.empty()) {
382       MachineBasicBlock *MBB = ToVisit.back();
383       ToVisit.pop_back();
384       if (Visited.count(MBB) || !MBB->isLiveIn(PhysReg))
385         continue;
386       if (getLiveInUses(MBB, PhysReg, Uses))
387         ToVisit.insert(ToVisit.end(), MBB->successors().begin(),
388                        MBB->successors().end());
389       Visited.insert(MBB);
390     }
391   }
392 }
393 
394 void
395 ReachingDefAnalysis::getGlobalReachingDefs(MachineInstr *MI, int PhysReg,
396                                            InstSet &Defs) const {
397   if (auto *Def = getUniqueReachingMIDef(MI, PhysReg)) {
398     Defs.insert(Def);
399     return;
400   }
401 
402   for (auto *MBB : MI->getParent()->predecessors())
403     getLiveOuts(MBB, PhysReg, Defs);
404 }
405 
406 void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock *MBB, int PhysReg,
407                                       InstSet &Defs) const {
408   SmallPtrSet<MachineBasicBlock*, 2> VisitedBBs;
409   getLiveOuts(MBB, PhysReg, Defs, VisitedBBs);
410 }
411 
412 void
413 ReachingDefAnalysis::getLiveOuts(MachineBasicBlock *MBB, int PhysReg,
414                                  InstSet &Defs, BlockSet &VisitedBBs) const {
415   if (VisitedBBs.count(MBB))
416     return;
417 
418   VisitedBBs.insert(MBB);
419   LivePhysRegs LiveRegs(*TRI);
420   LiveRegs.addLiveOuts(*MBB);
421   if (!LiveRegs.contains(PhysReg))
422     return;
423 
424   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
425     Defs.insert(Def);
426   else
427     for (auto *Pred : MBB->predecessors())
428       getLiveOuts(Pred, PhysReg, Defs, VisitedBBs);
429 }
430 
431 MachineInstr *ReachingDefAnalysis::getUniqueReachingMIDef(MachineInstr *MI,
432                                                           int PhysReg) const {
433   // If there's a local def before MI, return it.
434   MachineInstr *LocalDef = getReachingLocalMIDef(MI, PhysReg);
435   if (LocalDef && InstIds.lookup(LocalDef) < InstIds.lookup(MI))
436     return LocalDef;
437 
438   SmallPtrSet<MachineInstr*, 2> Incoming;
439   MachineBasicBlock *Parent = MI->getParent();
440   for (auto *Pred : Parent->predecessors())
441     getLiveOuts(Pred, PhysReg, Incoming);
442 
443   // Check that we have a single incoming value and that it does not
444   // come from the same block as MI - since it would mean that the def
445   // is executed after MI.
446   if (Incoming.size() == 1 && (*Incoming.begin())->getParent() != Parent)
447     return *Incoming.begin();
448   return nullptr;
449 }
450 
451 MachineInstr *ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
452                                                 unsigned Idx) const {
453   assert(MI->getOperand(Idx).isReg() && "Expected register operand");
454   return getUniqueReachingMIDef(MI, MI->getOperand(Idx).getReg());
455 }
456 
457 MachineInstr *ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
458                                                 MachineOperand &MO) const {
459   assert(MO.isReg() && "Expected register operand");
460   return getUniqueReachingMIDef(MI, MO.getReg());
461 }
462 
463 bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI, int PhysReg) const {
464   MachineBasicBlock *MBB = MI->getParent();
465   LivePhysRegs LiveRegs(*TRI);
466   LiveRegs.addLiveOuts(*MBB);
467 
468   // Yes if the register is live out of the basic block.
469   if (LiveRegs.contains(PhysReg))
470     return true;
471 
472   // Walk backwards through the block to see if the register is live at some
473   // point.
474   for (MachineInstr &Last :
475        instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
476     LiveRegs.stepBackward(Last);
477     if (LiveRegs.contains(PhysReg))
478       return InstIds.lookup(&Last) > InstIds.lookup(MI);
479   }
480   return false;
481 }
482 
483 bool ReachingDefAnalysis::isRegDefinedAfter(MachineInstr *MI,
484                                             int PhysReg) const {
485   MachineBasicBlock *MBB = MI->getParent();
486   auto Last = MBB->getLastNonDebugInstr();
487   if (Last != MBB->end() &&
488       getReachingDef(MI, PhysReg) != getReachingDef(&*Last, PhysReg))
489     return true;
490 
491   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
492     return Def == getReachingLocalMIDef(MI, PhysReg);
493 
494   return false;
495 }
496 
497 bool
498 ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr *MI, int PhysReg) const {
499   MachineBasicBlock *MBB = MI->getParent();
500   LivePhysRegs LiveRegs(*TRI);
501   LiveRegs.addLiveOuts(*MBB);
502   if (!LiveRegs.contains(PhysReg))
503     return false;
504 
505   auto Last = MBB->getLastNonDebugInstr();
506   int Def = getReachingDef(MI, PhysReg);
507   if (Last != MBB->end() && getReachingDef(&*Last, PhysReg) != Def)
508     return false;
509 
510   // Finally check that the last instruction doesn't redefine the register.
511   for (auto &MO : Last->operands())
512     if (isValidRegDefOf(MO, PhysReg))
513       return false;
514 
515   return true;
516 }
517 
518 MachineInstr* ReachingDefAnalysis::getLocalLiveOutMIDef(MachineBasicBlock *MBB,
519                                                         int PhysReg) const {
520   LivePhysRegs LiveRegs(*TRI);
521   LiveRegs.addLiveOuts(*MBB);
522   if (!LiveRegs.contains(PhysReg))
523     return nullptr;
524 
525   auto Last = MBB->getLastNonDebugInstr();
526   if (Last == MBB->end())
527     return nullptr;
528 
529   int Def = getReachingDef(&*Last, PhysReg);
530   for (auto &MO : Last->operands())
531     if (isValidRegDefOf(MO, PhysReg))
532       return &*Last;
533 
534   return Def < 0 ? nullptr : getInstFromId(MBB, Def);
535 }
536 
537 static bool mayHaveSideEffects(MachineInstr &MI) {
538   return MI.mayLoadOrStore() || MI.mayRaiseFPException() ||
539          MI.hasUnmodeledSideEffects() || MI.isTerminator() ||
540          MI.isCall() || MI.isBarrier() || MI.isBranch() || MI.isReturn();
541 }
542 
543 // Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
544 // not define a register that is used by any instructions, after and including,
545 // 'To'. These instructions also must not redefine any of Froms operands.
546 template<typename Iterator>
547 bool ReachingDefAnalysis::isSafeToMove(MachineInstr *From,
548                                        MachineInstr *To) const {
549   if (From->getParent() != To->getParent() || From == To)
550     return false;
551 
552   SmallSet<int, 2> Defs;
553   // First check that From would compute the same value if moved.
554   for (auto &MO : From->operands()) {
555     if (!isValidReg(MO))
556       continue;
557     if (MO.isDef())
558       Defs.insert(MO.getReg());
559     else if (!hasSameReachingDef(From, To, MO.getReg()))
560       return false;
561   }
562 
563   // Now walk checking that the rest of the instructions will compute the same
564   // value and that we're not overwriting anything. Don't move the instruction
565   // past any memory, control-flow or other ambiguous instructions.
566   for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
567     if (mayHaveSideEffects(*I))
568       return false;
569     for (auto &MO : I->operands())
570       if (MO.isReg() && MO.getReg() && Defs.count(MO.getReg()))
571         return false;
572   }
573   return true;
574 }
575 
576 bool ReachingDefAnalysis::isSafeToMoveForwards(MachineInstr *From,
577                                                MachineInstr *To) const {
578   using Iterator = MachineBasicBlock::iterator;
579   // Walk forwards until we find the instruction.
580   for (auto I = Iterator(From), E = From->getParent()->end(); I != E; ++I)
581     if (&*I == To)
582       return isSafeToMove<Iterator>(From, To);
583   return false;
584 }
585 
586 bool ReachingDefAnalysis::isSafeToMoveBackwards(MachineInstr *From,
587                                                 MachineInstr *To) const {
588   using Iterator = MachineBasicBlock::reverse_iterator;
589   // Walk backwards until we find the instruction.
590   for (auto I = Iterator(From), E = From->getParent()->rend(); I != E; ++I)
591     if (&*I == To)
592       return isSafeToMove<Iterator>(From, To);
593   return false;
594 }
595 
596 bool ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI,
597                                          InstSet &ToRemove) const {
598   SmallPtrSet<MachineInstr*, 1> Ignore;
599   SmallPtrSet<MachineInstr*, 2> Visited;
600   return isSafeToRemove(MI, Visited, ToRemove, Ignore);
601 }
602 
603 bool
604 ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI, InstSet &ToRemove,
605                                     InstSet &Ignore) const {
606   SmallPtrSet<MachineInstr*, 2> Visited;
607   return isSafeToRemove(MI, Visited, ToRemove, Ignore);
608 }
609 
610 bool
611 ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI, InstSet &Visited,
612                                     InstSet &ToRemove, InstSet &Ignore) const {
613   if (Visited.count(MI) || Ignore.count(MI))
614     return true;
615   else if (mayHaveSideEffects(*MI)) {
616     // Unless told to ignore the instruction, don't remove anything which has
617     // side effects.
618     return false;
619   }
620 
621   Visited.insert(MI);
622   for (auto &MO : MI->operands()) {
623     if (!isValidRegDef(MO))
624       continue;
625 
626     SmallPtrSet<MachineInstr*, 4> Uses;
627     getGlobalUses(MI, MO.getReg(), Uses);
628 
629     for (auto I : Uses) {
630       if (Ignore.count(I) || ToRemove.count(I))
631         continue;
632       if (!isSafeToRemove(I, Visited, ToRemove, Ignore))
633         return false;
634     }
635   }
636   ToRemove.insert(MI);
637   return true;
638 }
639 
640 void ReachingDefAnalysis::collectKilledOperands(MachineInstr *MI,
641                                                 InstSet &Dead) const {
642   Dead.insert(MI);
643   auto IsDead = [this, &Dead](MachineInstr *Def, int PhysReg) {
644     if (mayHaveSideEffects(*Def))
645       return false;
646 
647     unsigned LiveDefs = 0;
648     for (auto &MO : Def->operands()) {
649       if (!isValidRegDef(MO))
650         continue;
651       if (!MO.isDead())
652         ++LiveDefs;
653     }
654 
655     if (LiveDefs > 1)
656       return false;
657 
658     SmallPtrSet<MachineInstr*, 4> Uses;
659     getGlobalUses(Def, PhysReg, Uses);
660     for (auto *Use : Uses)
661       if (!Dead.count(Use))
662         return false;
663     return true;
664   };
665 
666   for (auto &MO : MI->operands()) {
667     if (!isValidRegUse(MO))
668       continue;
669     if (MachineInstr *Def = getMIOperand(MI, MO))
670       if (IsDead(Def, MO.getReg()))
671         collectKilledOperands(Def, Dead);
672   }
673 }
674 
675 bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI,
676                                            int PhysReg) const {
677   SmallPtrSet<MachineInstr*, 1> Ignore;
678   return isSafeToDefRegAt(MI, PhysReg, Ignore);
679 }
680 
681 bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI, int PhysReg,
682                                            InstSet &Ignore) const {
683   // Check for any uses of the register after MI.
684   if (isRegUsedAfter(MI, PhysReg)) {
685     if (auto *Def = getReachingLocalMIDef(MI, PhysReg)) {
686       SmallPtrSet<MachineInstr*, 2> Uses;
687       getGlobalUses(Def, PhysReg, Uses);
688       for (auto *Use : Uses)
689         if (!Ignore.count(Use))
690           return false;
691     } else
692       return false;
693   }
694 
695   MachineBasicBlock *MBB = MI->getParent();
696   // Check for any defs after MI.
697   if (isRegDefinedAfter(MI, PhysReg)) {
698     auto I = MachineBasicBlock::iterator(MI);
699     for (auto E = MBB->end(); I != E; ++I) {
700       if (Ignore.count(&*I))
701         continue;
702       for (auto &MO : I->operands())
703         if (isValidRegDefOf(MO, PhysReg))
704           return false;
705     }
706   }
707   return true;
708 }
709