10bf841acSMarina Yatsina //===---- ReachingDefAnalysis.cpp - Reaching Def Analysis ---*- C++ -*-----===//
20bf841acSMarina Yatsina //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60bf841acSMarina Yatsina //
70bf841acSMarina Yatsina //===----------------------------------------------------------------------===//
80bf841acSMarina Yatsina 
9ac30ea2fSSam Parker #include "llvm/ADT/SmallSet.h"
10cced971fSSam Parker #include "llvm/CodeGen/LivePhysRegs.h"
110bf841acSMarina Yatsina #include "llvm/CodeGen/ReachingDefAnalysis.h"
120bf841acSMarina Yatsina #include "llvm/CodeGen/TargetRegisterInfo.h"
130bf841acSMarina Yatsina #include "llvm/CodeGen/TargetSubtargetInfo.h"
141d7b4136SReid Kleckner #include "llvm/Support/Debug.h"
150bf841acSMarina Yatsina 
160bf841acSMarina Yatsina using namespace llvm;
170bf841acSMarina Yatsina 
180bf841acSMarina Yatsina #define DEBUG_TYPE "reaching-deps-analysis"
190bf841acSMarina Yatsina 
200bf841acSMarina Yatsina char ReachingDefAnalysis::ID = 0;
210bf841acSMarina Yatsina INITIALIZE_PASS(ReachingDefAnalysis, DEBUG_TYPE, "ReachingDefAnalysis", false,
220bf841acSMarina Yatsina                 true)
230bf841acSMarina Yatsina 
240bf841acSMarina Yatsina void ReachingDefAnalysis::enterBasicBlock(
250bf841acSMarina Yatsina     const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
260bf841acSMarina Yatsina 
270bf841acSMarina Yatsina   MachineBasicBlock *MBB = TraversedMBB.MBB;
28e4d63a49SMarina Yatsina   unsigned MBBNumber = MBB->getNumber();
290bf841acSMarina Yatsina   assert(MBBNumber < MBBReachingDefs.size() &&
300bf841acSMarina Yatsina          "Unexpected basic block number.");
310bf841acSMarina Yatsina   MBBReachingDefs[MBBNumber].resize(NumRegUnits);
320bf841acSMarina Yatsina 
330bf841acSMarina Yatsina   // Reset instruction counter in each basic block.
340bf841acSMarina Yatsina   CurInstr = 0;
350bf841acSMarina Yatsina 
360bf841acSMarina Yatsina   // Set up LiveRegs to represent registers entering MBB.
370bf841acSMarina Yatsina   // Default values are 'nothing happened a long time ago'.
380bf841acSMarina Yatsina   if (LiveRegs.empty())
390f110a88SCraig Topper     LiveRegs.assign(NumRegUnits, ReachingDefDefaultVal);
400bf841acSMarina Yatsina 
410bf841acSMarina Yatsina   // This is the entry block.
420bf841acSMarina Yatsina   if (MBB->pred_empty()) {
430bf841acSMarina Yatsina     for (const auto &LI : MBB->liveins()) {
440bf841acSMarina Yatsina       for (MCRegUnitIterator Unit(LI.PhysReg, TRI); Unit.isValid(); ++Unit) {
450bf841acSMarina Yatsina         // Treat function live-ins as if they were defined just before the first
460bf841acSMarina Yatsina         // instruction.  Usually, function arguments are set up immediately
470bf841acSMarina Yatsina         // before the call.
480bf841acSMarina Yatsina         LiveRegs[*Unit] = -1;
490bf841acSMarina Yatsina         MBBReachingDefs[MBBNumber][*Unit].push_back(LiveRegs[*Unit]);
500bf841acSMarina Yatsina       }
510bf841acSMarina Yatsina     }
52d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": entry\n");
530bf841acSMarina Yatsina     return;
540bf841acSMarina Yatsina   }
550bf841acSMarina Yatsina 
560bf841acSMarina Yatsina   // Try to coalesce live-out registers from predecessors.
570bf841acSMarina Yatsina   for (MachineBasicBlock *pred : MBB->predecessors()) {
58e4d63a49SMarina Yatsina     assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
590bf841acSMarina Yatsina            "Should have pre-allocated MBBInfos for all MBBs");
600bf841acSMarina Yatsina     const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
610bf841acSMarina Yatsina     // Incoming is null if this is a backedge from a BB
620bf841acSMarina Yatsina     // we haven't processed yet
630bf841acSMarina Yatsina     if (Incoming.empty())
640bf841acSMarina Yatsina       continue;
650bf841acSMarina Yatsina 
660bf841acSMarina Yatsina     for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
670bf841acSMarina Yatsina       // Use the most recent predecessor def for each register.
680bf841acSMarina Yatsina       LiveRegs[Unit] = std::max(LiveRegs[Unit], Incoming[Unit]);
690f110a88SCraig Topper       if ((LiveRegs[Unit] != ReachingDefDefaultVal))
700bf841acSMarina Yatsina         MBBReachingDefs[MBBNumber][Unit].push_back(LiveRegs[Unit]);
710bf841acSMarina Yatsina     }
720bf841acSMarina Yatsina   }
730bf841acSMarina Yatsina 
74d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << printMBBReference(*MBB)
750bf841acSMarina Yatsina                     << (!TraversedMBB.IsDone ? ": incomplete\n"
760bf841acSMarina Yatsina                                              : ": all preds known\n"));
770bf841acSMarina Yatsina }
780bf841acSMarina Yatsina 
790bf841acSMarina Yatsina void ReachingDefAnalysis::leaveBasicBlock(
800bf841acSMarina Yatsina     const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
810bf841acSMarina Yatsina   assert(!LiveRegs.empty() && "Must enter basic block first.");
82e4d63a49SMarina Yatsina   unsigned MBBNumber = TraversedMBB.MBB->getNumber();
830bf841acSMarina Yatsina   assert(MBBNumber < MBBOutRegsInfos.size() &&
840bf841acSMarina Yatsina          "Unexpected basic block number.");
850bf841acSMarina Yatsina   // Save register clearances at end of MBB - used by enterBasicBlock().
860bf841acSMarina Yatsina   MBBOutRegsInfos[MBBNumber] = LiveRegs;
870bf841acSMarina Yatsina 
880bf841acSMarina Yatsina   // While processing the basic block, we kept `Def` relative to the start
890bf841acSMarina Yatsina   // of the basic block for convenience. However, future use of this information
900bf841acSMarina Yatsina   // only cares about the clearance from the end of the block, so adjust
910bf841acSMarina Yatsina   // everything to be relative to the end of the basic block.
920bf841acSMarina Yatsina   for (int &OutLiveReg : MBBOutRegsInfos[MBBNumber])
930bf841acSMarina Yatsina     OutLiveReg -= CurInstr;
940bf841acSMarina Yatsina   LiveRegs.clear();
950bf841acSMarina Yatsina }
960bf841acSMarina Yatsina 
970bf841acSMarina Yatsina void ReachingDefAnalysis::processDefs(MachineInstr *MI) {
98801bf7ebSShiva Chen   assert(!MI->isDebugInstr() && "Won't process debug instructions");
990bf841acSMarina Yatsina 
100e4d63a49SMarina Yatsina   unsigned MBBNumber = MI->getParent()->getNumber();
1010bf841acSMarina Yatsina   assert(MBBNumber < MBBReachingDefs.size() &&
1020bf841acSMarina Yatsina          "Unexpected basic block number.");
1030bf841acSMarina Yatsina   const MCInstrDesc &MCID = MI->getDesc();
1040bf841acSMarina Yatsina   for (unsigned i = 0,
1050bf841acSMarina Yatsina                 e = MI->isVariadic() ? MI->getNumOperands() : MCID.getNumDefs();
1060bf841acSMarina Yatsina        i != e; ++i) {
1070bf841acSMarina Yatsina     MachineOperand &MO = MI->getOperand(i);
1080bf841acSMarina Yatsina     if (!MO.isReg() || !MO.getReg())
1090bf841acSMarina Yatsina       continue;
1100bf841acSMarina Yatsina     if (MO.isUse())
1110bf841acSMarina Yatsina       continue;
1120bf841acSMarina Yatsina     for (MCRegUnitIterator Unit(MO.getReg(), TRI); Unit.isValid(); ++Unit) {
1130bf841acSMarina Yatsina       // This instruction explicitly defines the current reg unit.
114d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << printReg(MO.getReg(), TRI) << ":\t" << CurInstr
115d34e60caSNicola Zaghen                         << '\t' << *MI);
1160bf841acSMarina Yatsina 
1170bf841acSMarina Yatsina       // How many instructions since this reg unit was last written?
1180bf841acSMarina Yatsina       LiveRegs[*Unit] = CurInstr;
1190bf841acSMarina Yatsina       MBBReachingDefs[MBBNumber][*Unit].push_back(CurInstr);
1200bf841acSMarina Yatsina     }
1210bf841acSMarina Yatsina   }
1220bf841acSMarina Yatsina   InstIds[MI] = CurInstr;
1230bf841acSMarina Yatsina   ++CurInstr;
1240bf841acSMarina Yatsina }
1250bf841acSMarina Yatsina 
1260bf841acSMarina Yatsina void ReachingDefAnalysis::processBasicBlock(
1270bf841acSMarina Yatsina     const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
1280bf841acSMarina Yatsina   enterBasicBlock(TraversedMBB);
1290bf841acSMarina Yatsina   for (MachineInstr &MI : *TraversedMBB.MBB) {
130801bf7ebSShiva Chen     if (!MI.isDebugInstr())
1310bf841acSMarina Yatsina       processDefs(&MI);
1320bf841acSMarina Yatsina   }
1330bf841acSMarina Yatsina   leaveBasicBlock(TraversedMBB);
1340bf841acSMarina Yatsina }
1350bf841acSMarina Yatsina 
1360bf841acSMarina Yatsina bool ReachingDefAnalysis::runOnMachineFunction(MachineFunction &mf) {
1370bf841acSMarina Yatsina   MF = &mf;
1380bf841acSMarina Yatsina   TRI = MF->getSubtarget().getRegisterInfo();
139d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** REACHING DEFINITION ANALYSIS **********\n");
140659500c0SSam Parker   init();
141659500c0SSam Parker   traverse();
1420bf841acSMarina Yatsina   return false;
1430bf841acSMarina Yatsina }
1440bf841acSMarina Yatsina 
1450bf841acSMarina Yatsina void ReachingDefAnalysis::releaseMemory() {
1460bf841acSMarina Yatsina   // Clear the internal vectors.
1470bf841acSMarina Yatsina   MBBOutRegsInfos.clear();
1480bf841acSMarina Yatsina   MBBReachingDefs.clear();
1490bf841acSMarina Yatsina   InstIds.clear();
150659500c0SSam Parker   LiveRegs.clear();
151659500c0SSam Parker }
152659500c0SSam Parker 
153659500c0SSam Parker void ReachingDefAnalysis::reset() {
154659500c0SSam Parker   releaseMemory();
155659500c0SSam Parker   init();
156659500c0SSam Parker   traverse();
157659500c0SSam Parker }
158659500c0SSam Parker 
159659500c0SSam Parker void ReachingDefAnalysis::init() {
160659500c0SSam Parker   NumRegUnits = TRI->getNumRegUnits();
161659500c0SSam Parker   MBBReachingDefs.resize(MF->getNumBlockIDs());
162659500c0SSam Parker   // Initialize the MBBOutRegsInfos
163659500c0SSam Parker   MBBOutRegsInfos.resize(MF->getNumBlockIDs());
164659500c0SSam Parker   LoopTraversal Traversal;
165659500c0SSam Parker   TraversedMBBOrder = Traversal.traverse(*MF);
166659500c0SSam Parker }
167659500c0SSam Parker 
168659500c0SSam Parker void ReachingDefAnalysis::traverse() {
169659500c0SSam Parker   // Traverse the basic blocks.
170659500c0SSam Parker   for (LoopTraversal::TraversedMBBInfo TraversedMBB : TraversedMBBOrder)
171659500c0SSam Parker     processBasicBlock(TraversedMBB);
172659500c0SSam Parker   // Sorting all reaching defs found for a ceartin reg unit in a given BB.
173659500c0SSam Parker   for (MBBDefsInfo &MBBDefs : MBBReachingDefs) {
174659500c0SSam Parker     for (MBBRegUnitDefs &RegUnitDefs : MBBDefs)
175659500c0SSam Parker       llvm::sort(RegUnitDefs);
176659500c0SSam Parker   }
1770bf841acSMarina Yatsina }
1780bf841acSMarina Yatsina 
1790d1468dbSSam Parker int ReachingDefAnalysis::getReachingDef(MachineInstr *MI, int PhysReg) const {
1800bf841acSMarina Yatsina   assert(InstIds.count(MI) && "Unexpected machine instuction.");
1810d1468dbSSam Parker   int InstId = InstIds.lookup(MI);
1820f110a88SCraig Topper   int DefRes = ReachingDefDefaultVal;
183e4d63a49SMarina Yatsina   unsigned MBBNumber = MI->getParent()->getNumber();
1840bf841acSMarina Yatsina   assert(MBBNumber < MBBReachingDefs.size() &&
1850bf841acSMarina Yatsina          "Unexpected basic block number.");
1860f110a88SCraig Topper   int LatestDef = ReachingDefDefaultVal;
1870bf841acSMarina Yatsina   for (MCRegUnitIterator Unit(PhysReg, TRI); Unit.isValid(); ++Unit) {
1880bf841acSMarina Yatsina     for (int Def : MBBReachingDefs[MBBNumber][*Unit]) {
1890bf841acSMarina Yatsina       if (Def >= InstId)
1900bf841acSMarina Yatsina         break;
1910bf841acSMarina Yatsina       DefRes = Def;
1920bf841acSMarina Yatsina     }
1930bf841acSMarina Yatsina     LatestDef = std::max(LatestDef, DefRes);
1940bf841acSMarina Yatsina   }
1950bf841acSMarina Yatsina   return LatestDef;
1960bf841acSMarina Yatsina }
1970bf841acSMarina Yatsina 
1980d1468dbSSam Parker MachineInstr* ReachingDefAnalysis::getReachingMIDef(MachineInstr *MI,
1990d1468dbSSam Parker                                                     int PhysReg) const {
200cced971fSSam Parker   return getInstFromId(MI->getParent(), getReachingDef(MI, PhysReg));
201cced971fSSam Parker }
202cced971fSSam Parker 
20328166816SSam Parker bool ReachingDefAnalysis::hasSameReachingDef(MachineInstr *A, MachineInstr *B,
2040d1468dbSSam Parker                                              int PhysReg) const {
20528166816SSam Parker   MachineBasicBlock *ParentA = A->getParent();
20628166816SSam Parker   MachineBasicBlock *ParentB = B->getParent();
20728166816SSam Parker   if (ParentA != ParentB)
20828166816SSam Parker     return false;
20928166816SSam Parker 
21028166816SSam Parker   return getReachingDef(A, PhysReg) == getReachingDef(B, PhysReg);
21128166816SSam Parker }
21228166816SSam Parker 
213cced971fSSam Parker MachineInstr *ReachingDefAnalysis::getInstFromId(MachineBasicBlock *MBB,
2140d1468dbSSam Parker                                                  int InstId) const {
21528166816SSam Parker   assert(static_cast<size_t>(MBB->getNumber()) < MBBReachingDefs.size() &&
216cced971fSSam Parker          "Unexpected basic block number.");
217cced971fSSam Parker   assert(InstId < static_cast<int>(MBB->size()) &&
218cced971fSSam Parker          "Unexpected instruction id.");
219cced971fSSam Parker 
220cced971fSSam Parker   if (InstId < 0)
221cced971fSSam Parker     return nullptr;
222cced971fSSam Parker 
223cced971fSSam Parker   for (auto &MI : *MBB) {
22493b0536fSSjoerd Meijer     auto F = InstIds.find(&MI);
22593b0536fSSjoerd Meijer     if (F != InstIds.end() && F->second == InstId)
226cced971fSSam Parker       return &MI;
227cced971fSSam Parker   }
22893b0536fSSjoerd Meijer 
229cced971fSSam Parker   return nullptr;
230cced971fSSam Parker }
231cced971fSSam Parker 
2320d1468dbSSam Parker int
2330d1468dbSSam Parker ReachingDefAnalysis::getClearance(MachineInstr *MI, MCPhysReg PhysReg) const {
2340bf841acSMarina Yatsina   assert(InstIds.count(MI) && "Unexpected machine instuction.");
2350d1468dbSSam Parker   return InstIds.lookup(MI) - getReachingDef(MI, PhysReg);
2360bf841acSMarina Yatsina }
237cced971fSSam Parker 
238ac30ea2fSSam Parker bool
239ac30ea2fSSam Parker ReachingDefAnalysis::hasLocalDefBefore(MachineInstr *MI, int PhysReg) const {
240ac30ea2fSSam Parker   return getReachingDef(MI, PhysReg) >= 0;
241ac30ea2fSSam Parker }
242ac30ea2fSSam Parker 
24328166816SSam Parker void ReachingDefAnalysis::getReachingLocalUses(MachineInstr *Def, int PhysReg,
2447ad879caSSam Parker                                                InstSet &Uses) const {
24528166816SSam Parker   MachineBasicBlock *MBB = Def->getParent();
24628166816SSam Parker   MachineBasicBlock::iterator MI = MachineBasicBlock::iterator(Def);
24728166816SSam Parker   while (++MI != MBB->end()) {
24805532575SSam Parker     if (MI->isDebugInstr())
24905532575SSam Parker       continue;
25005532575SSam Parker 
25128166816SSam Parker     // If/when we find a new reaching def, we know that there's no more uses
25228166816SSam Parker     // of 'Def'.
25328166816SSam Parker     if (getReachingMIDef(&*MI, PhysReg) != Def)
25428166816SSam Parker       return;
25528166816SSam Parker 
256acbc9aedSSam Parker     for (auto &MO : MI->operands()) {
257acbc9aedSSam Parker       if (!MO.isReg() || !MO.isUse() || MO.getReg() != PhysReg)
258acbc9aedSSam Parker         continue;
259acbc9aedSSam Parker 
26042350cd8SSam Parker       Uses.insert(&*MI);
26128166816SSam Parker       if (MO.isKill())
26228166816SSam Parker         return;
26328166816SSam Parker     }
26428166816SSam Parker   }
26528166816SSam Parker }
26628166816SSam Parker 
2670d1468dbSSam Parker bool
2680d1468dbSSam Parker ReachingDefAnalysis::getLiveInUses(MachineBasicBlock *MBB, int PhysReg,
2697ad879caSSam Parker                                    InstSet &Uses) const {
27042350cd8SSam Parker   for (auto &MI : *MBB) {
27105532575SSam Parker     if (MI.isDebugInstr())
27205532575SSam Parker       continue;
27342350cd8SSam Parker     for (auto &MO : MI.operands()) {
27442350cd8SSam Parker       if (!MO.isReg() || !MO.isUse() || MO.getReg() != PhysReg)
27542350cd8SSam Parker         continue;
27642350cd8SSam Parker       if (getReachingDef(&MI, PhysReg) >= 0)
27742350cd8SSam Parker         return false;
27842350cd8SSam Parker       Uses.insert(&MI);
27942350cd8SSam Parker     }
28042350cd8SSam Parker   }
28142350cd8SSam Parker   return isReachingDefLiveOut(&MBB->back(), PhysReg);
28242350cd8SSam Parker }
28342350cd8SSam Parker 
2840d1468dbSSam Parker void
2850d1468dbSSam Parker ReachingDefAnalysis::getGlobalUses(MachineInstr *MI, int PhysReg,
2867ad879caSSam Parker                                    InstSet &Uses) const {
28742350cd8SSam Parker   MachineBasicBlock *MBB = MI->getParent();
28842350cd8SSam Parker 
28942350cd8SSam Parker   // Collect the uses that each def touches within the block.
29042350cd8SSam Parker   getReachingLocalUses(MI, PhysReg, Uses);
29142350cd8SSam Parker 
29242350cd8SSam Parker   // Handle live-out values.
29342350cd8SSam Parker   if (auto *LiveOut = getLocalLiveOutMIDef(MI->getParent(), PhysReg)) {
29442350cd8SSam Parker     if (LiveOut != MI)
29542350cd8SSam Parker       return;
29642350cd8SSam Parker 
29742350cd8SSam Parker     SmallVector<MachineBasicBlock*, 4> ToVisit;
29842350cd8SSam Parker     ToVisit.insert(ToVisit.begin(), MBB->successors().begin(),
29942350cd8SSam Parker                    MBB->successors().end());
30042350cd8SSam Parker     SmallPtrSet<MachineBasicBlock*, 4>Visited;
30142350cd8SSam Parker     while (!ToVisit.empty()) {
30242350cd8SSam Parker       MachineBasicBlock *MBB = ToVisit.back();
30342350cd8SSam Parker       ToVisit.pop_back();
30442350cd8SSam Parker       if (Visited.count(MBB) || !MBB->isLiveIn(PhysReg))
30542350cd8SSam Parker         continue;
30642350cd8SSam Parker       if (getLiveInUses(MBB, PhysReg, Uses))
30742350cd8SSam Parker         ToVisit.insert(ToVisit.end(), MBB->successors().begin(),
30842350cd8SSam Parker                        MBB->successors().end());
30942350cd8SSam Parker       Visited.insert(MBB);
31042350cd8SSam Parker     }
31142350cd8SSam Parker   }
312cced971fSSam Parker }
313cced971fSSam Parker 
3140d1468dbSSam Parker bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI, int PhysReg) const {
315cced971fSSam Parker   MachineBasicBlock *MBB = MI->getParent();
316cced971fSSam Parker   LivePhysRegs LiveRegs(*TRI);
317cced971fSSam Parker   LiveRegs.addLiveOuts(*MBB);
318cced971fSSam Parker 
319cced971fSSam Parker   // Yes if the register is live out of the basic block.
320cced971fSSam Parker   if (LiveRegs.contains(PhysReg))
321cced971fSSam Parker     return true;
322cced971fSSam Parker 
323cced971fSSam Parker   // Walk backwards through the block to see if the register is live at some
324cced971fSSam Parker   // point.
325cced971fSSam Parker   for (auto Last = MBB->rbegin(), End = MBB->rend(); Last != End; ++Last) {
326cced971fSSam Parker     LiveRegs.stepBackward(*Last);
327cced971fSSam Parker     if (LiveRegs.contains(PhysReg))
3280d1468dbSSam Parker       return InstIds.lookup(&*Last) > InstIds.lookup(MI);
329cced971fSSam Parker   }
330cced971fSSam Parker   return false;
331cced971fSSam Parker }
332cced971fSSam Parker 
333ac30ea2fSSam Parker bool ReachingDefAnalysis::isRegDefinedAfter(MachineInstr *MI,
334ac30ea2fSSam Parker                                             int PhysReg) const {
335ac30ea2fSSam Parker   MachineBasicBlock *MBB = MI->getParent();
336ac30ea2fSSam Parker   if (getReachingDef(MI, PhysReg) != getReachingDef(&MBB->back(), PhysReg))
337ac30ea2fSSam Parker     return true;
338ac30ea2fSSam Parker 
339ac30ea2fSSam Parker   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
340ac30ea2fSSam Parker     return Def == getReachingMIDef(MI, PhysReg);
341ac30ea2fSSam Parker 
342ac30ea2fSSam Parker   return false;
343ac30ea2fSSam Parker }
344ac30ea2fSSam Parker 
3450d1468dbSSam Parker bool
3460d1468dbSSam Parker ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr *MI, int PhysReg) const {
347acbc9aedSSam Parker   MachineBasicBlock *MBB = MI->getParent();
348acbc9aedSSam Parker   LivePhysRegs LiveRegs(*TRI);
349acbc9aedSSam Parker   LiveRegs.addLiveOuts(*MBB);
350acbc9aedSSam Parker   if (!LiveRegs.contains(PhysReg))
351acbc9aedSSam Parker     return false;
352acbc9aedSSam Parker 
353acbc9aedSSam Parker   MachineInstr *Last = &MBB->back();
354acbc9aedSSam Parker   int Def = getReachingDef(MI, PhysReg);
355acbc9aedSSam Parker   if (getReachingDef(Last, PhysReg) != Def)
356acbc9aedSSam Parker     return false;
357acbc9aedSSam Parker 
358acbc9aedSSam Parker   // Finally check that the last instruction doesn't redefine the register.
359acbc9aedSSam Parker   for (auto &MO : Last->operands())
360acbc9aedSSam Parker     if (MO.isReg() && MO.isDef() && MO.getReg() == PhysReg)
361acbc9aedSSam Parker       return false;
362acbc9aedSSam Parker 
363acbc9aedSSam Parker   return true;
364acbc9aedSSam Parker }
365acbc9aedSSam Parker 
366acbc9aedSSam Parker MachineInstr* ReachingDefAnalysis::getLocalLiveOutMIDef(MachineBasicBlock *MBB,
3670d1468dbSSam Parker                                                         int PhysReg) const {
368acbc9aedSSam Parker   LivePhysRegs LiveRegs(*TRI);
369acbc9aedSSam Parker   LiveRegs.addLiveOuts(*MBB);
370acbc9aedSSam Parker   if (!LiveRegs.contains(PhysReg))
371acbc9aedSSam Parker     return nullptr;
372acbc9aedSSam Parker 
373acbc9aedSSam Parker   MachineInstr *Last = &MBB->back();
374acbc9aedSSam Parker   int Def = getReachingDef(Last, PhysReg);
375acbc9aedSSam Parker   for (auto &MO : Last->operands())
376acbc9aedSSam Parker     if (MO.isReg() && MO.isDef() && MO.getReg() == PhysReg)
377acbc9aedSSam Parker       return Last;
378acbc9aedSSam Parker 
379acbc9aedSSam Parker   return Def < 0 ? nullptr : getInstFromId(MBB, Def);
380acbc9aedSSam Parker }
381ac30ea2fSSam Parker 
3820a8cae10SSam Parker static bool mayHaveSideEffects(MachineInstr &MI) {
3830a8cae10SSam Parker   return MI.mayLoadOrStore() || MI.mayRaiseFPException() ||
3840a8cae10SSam Parker          MI.hasUnmodeledSideEffects() || MI.isTerminator() ||
3850a8cae10SSam Parker          MI.isCall() || MI.isBarrier() || MI.isBranch() || MI.isReturn();
3860a8cae10SSam Parker }
3870a8cae10SSam Parker 
388ac30ea2fSSam Parker // Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
389ac30ea2fSSam Parker // not define a register that is used by any instructions, after and including,
390ac30ea2fSSam Parker // 'To'. These instructions also must not redefine any of Froms operands.
391ac30ea2fSSam Parker template<typename Iterator>
392ac30ea2fSSam Parker bool ReachingDefAnalysis::isSafeToMove(MachineInstr *From,
393ac30ea2fSSam Parker                                        MachineInstr *To) const {
394ac30ea2fSSam Parker   if (From->getParent() != To->getParent())
395ac30ea2fSSam Parker     return false;
396ac30ea2fSSam Parker 
397ac30ea2fSSam Parker   SmallSet<int, 2> Defs;
398ac30ea2fSSam Parker   // First check that From would compute the same value if moved.
399ac30ea2fSSam Parker   for (auto &MO : From->operands()) {
400ac30ea2fSSam Parker     if (!MO.isReg() || MO.isUndef() || !MO.getReg())
401ac30ea2fSSam Parker       continue;
402ac30ea2fSSam Parker     if (MO.isDef())
403ac30ea2fSSam Parker       Defs.insert(MO.getReg());
404ac30ea2fSSam Parker     else if (!hasSameReachingDef(From, To, MO.getReg()))
405ac30ea2fSSam Parker       return false;
406ac30ea2fSSam Parker   }
407ac30ea2fSSam Parker 
408ac30ea2fSSam Parker   // Now walk checking that the rest of the instructions will compute the same
4090a8cae10SSam Parker   // value and that we're not overwriting anything. Don't move the instruction
4100a8cae10SSam Parker   // past any memory, control-flow or other ambigious instructions.
411ac30ea2fSSam Parker   for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
4120a8cae10SSam Parker     if (mayHaveSideEffects(*I))
4130a8cae10SSam Parker       return false;
414ac30ea2fSSam Parker     for (auto &MO : I->operands())
4150a8cae10SSam Parker       if (MO.isReg() && MO.getReg() && Defs.count(MO.getReg()))
416ac30ea2fSSam Parker         return false;
417ac30ea2fSSam Parker   }
418ac30ea2fSSam Parker   return true;
419ac30ea2fSSam Parker }
420ac30ea2fSSam Parker 
421ac30ea2fSSam Parker bool ReachingDefAnalysis::isSafeToMoveForwards(MachineInstr *From,
422ac30ea2fSSam Parker                                                MachineInstr *To) const {
423ac30ea2fSSam Parker   return isSafeToMove<MachineBasicBlock::reverse_iterator>(From, To);
424ac30ea2fSSam Parker }
425ac30ea2fSSam Parker 
426ac30ea2fSSam Parker bool ReachingDefAnalysis::isSafeToMoveBackwards(MachineInstr *From,
427ac30ea2fSSam Parker                                                 MachineInstr *To) const {
428ac30ea2fSSam Parker   return isSafeToMove<MachineBasicBlock::iterator>(From, To);
429ac30ea2fSSam Parker }
430ac30ea2fSSam Parker 
431ac30ea2fSSam Parker bool ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI,
432ac30ea2fSSam Parker                                          InstSet &ToRemove) const {
433ac30ea2fSSam Parker   SmallPtrSet<MachineInstr*, 1> Ignore;
434ac30ea2fSSam Parker   SmallPtrSet<MachineInstr*, 2> Visited;
435ac30ea2fSSam Parker   return isSafeToRemove(MI, Visited, ToRemove, Ignore);
436ac30ea2fSSam Parker }
437ac30ea2fSSam Parker 
438ac30ea2fSSam Parker bool
439ac30ea2fSSam Parker ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI, InstSet &ToRemove,
440ac30ea2fSSam Parker                                     InstSet &Ignore) const {
441ac30ea2fSSam Parker   SmallPtrSet<MachineInstr*, 2> Visited;
442ac30ea2fSSam Parker   return isSafeToRemove(MI, Visited, ToRemove, Ignore);
443ac30ea2fSSam Parker }
444ac30ea2fSSam Parker 
445ac30ea2fSSam Parker bool
446ac30ea2fSSam Parker ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI, InstSet &Visited,
447ac30ea2fSSam Parker                                     InstSet &ToRemove, InstSet &Ignore) const {
448ac30ea2fSSam Parker   if (Visited.count(MI) || Ignore.count(MI))
449ac30ea2fSSam Parker     return true;
4500a8cae10SSam Parker   else if (mayHaveSideEffects(*MI)) {
451ac30ea2fSSam Parker     // Unless told to ignore the instruction, don't remove anything which has
452ac30ea2fSSam Parker     // side effects.
453ac30ea2fSSam Parker     return false;
454ac30ea2fSSam Parker   }
455ac30ea2fSSam Parker 
456ac30ea2fSSam Parker   Visited.insert(MI);
457ac30ea2fSSam Parker   for (auto &MO : MI->operands()) {
458ac30ea2fSSam Parker     if (!MO.isReg() || MO.isUse() || MO.getReg() == 0)
459ac30ea2fSSam Parker       continue;
460ac30ea2fSSam Parker 
461ac30ea2fSSam Parker     SmallPtrSet<MachineInstr*, 4> Uses;
462ac30ea2fSSam Parker     getGlobalUses(MI, MO.getReg(), Uses);
463ac30ea2fSSam Parker 
464ac30ea2fSSam Parker     for (auto I : Uses) {
465ac30ea2fSSam Parker       if (Ignore.count(I) || ToRemove.count(I))
466ac30ea2fSSam Parker         continue;
467ac30ea2fSSam Parker       if (!isSafeToRemove(I, Visited, ToRemove, Ignore))
468ac30ea2fSSam Parker         return false;
469ac30ea2fSSam Parker     }
470ac30ea2fSSam Parker   }
471ac30ea2fSSam Parker   ToRemove.insert(MI);
472ac30ea2fSSam Parker   return true;
473ac30ea2fSSam Parker }
474ac30ea2fSSam Parker 
475*a67eb221SSam Parker void ReachingDefAnalysis::collectLocalKilledOperands(MachineInstr *MI,
476*a67eb221SSam Parker                                                      InstSet &Dead) const {
477*a67eb221SSam Parker   Dead.insert(MI);
478*a67eb221SSam Parker   auto IsDead = [this](MachineInstr *Def, int PhysReg) {
479*a67eb221SSam Parker     unsigned LiveDefs = 0;
480*a67eb221SSam Parker     for (auto &MO : Def->defs())
481*a67eb221SSam Parker       if (!MO.isDead())
482*a67eb221SSam Parker         ++LiveDefs;
483*a67eb221SSam Parker 
484*a67eb221SSam Parker     if (LiveDefs > 1)
485*a67eb221SSam Parker       return false;
486*a67eb221SSam Parker 
487*a67eb221SSam Parker     SmallPtrSet<MachineInstr*, 4> Uses;
488*a67eb221SSam Parker     getGlobalUses(Def, PhysReg, Uses);
489*a67eb221SSam Parker     return Uses.size() == 1;
490*a67eb221SSam Parker   };
491*a67eb221SSam Parker 
492*a67eb221SSam Parker   for (auto &MO : MI->uses()) {
493*a67eb221SSam Parker     if (!MO.isReg() || MO.getReg() == 0 || !MO.isKill())
494*a67eb221SSam Parker       continue;
495*a67eb221SSam Parker     if (MachineInstr *Def = getReachingMIDef(MI, MO.getReg()))
496*a67eb221SSam Parker       if (IsDead(Def, MO.getReg()))
497*a67eb221SSam Parker         collectLocalKilledOperands(Def, Dead);
498*a67eb221SSam Parker   }
499*a67eb221SSam Parker }
500*a67eb221SSam Parker 
501ac30ea2fSSam Parker bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI,
502ac30ea2fSSam Parker                                            int PhysReg) const {
503ac30ea2fSSam Parker   SmallPtrSet<MachineInstr*, 1> Ignore;
504ac30ea2fSSam Parker   return isSafeToDefRegAt(MI, PhysReg, Ignore);
505ac30ea2fSSam Parker }
506ac30ea2fSSam Parker 
507ac30ea2fSSam Parker bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI, int PhysReg,
508ac30ea2fSSam Parker                                            InstSet &Ignore) const {
509ac30ea2fSSam Parker   // Check for any uses of the register after MI.
510ac30ea2fSSam Parker   if (isRegUsedAfter(MI, PhysReg)) {
511ac30ea2fSSam Parker     if (auto *Def = getReachingMIDef(MI, PhysReg)) {
512ac30ea2fSSam Parker       SmallPtrSet<MachineInstr*, 2> Uses;
513ac30ea2fSSam Parker       getReachingLocalUses(Def, PhysReg, Uses);
514ac30ea2fSSam Parker       for (auto *Use : Uses)
515ac30ea2fSSam Parker         if (!Ignore.count(Use))
516ac30ea2fSSam Parker           return false;
517ac30ea2fSSam Parker     } else
518ac30ea2fSSam Parker       return false;
519ac30ea2fSSam Parker   }
520ac30ea2fSSam Parker 
521ac30ea2fSSam Parker   MachineBasicBlock *MBB = MI->getParent();
522ac30ea2fSSam Parker   // Check for any defs after MI.
523ac30ea2fSSam Parker   if (isRegDefinedAfter(MI, PhysReg)) {
524ac30ea2fSSam Parker     auto I = MachineBasicBlock::iterator(MI);
525ac30ea2fSSam Parker     for (auto E = MBB->end(); I != E; ++I) {
526ac30ea2fSSam Parker       if (Ignore.count(&*I))
527ac30ea2fSSam Parker         continue;
528ac30ea2fSSam Parker       for (auto &MO : I->operands())
529ac30ea2fSSam Parker         if (MO.isReg() && MO.isDef() && MO.getReg() == PhysReg)
530ac30ea2fSSam Parker           return false;
531ac30ea2fSSam Parker     }
532ac30ea2fSSam Parker   }
533ac30ea2fSSam Parker   return true;
534ac30ea2fSSam Parker }
535