xref: /src/contrib/llvm-project/llvm/lib/CodeGen/ReachingDefAnalysis.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583) !
1eb11fae6SDimitry Andric //===---- ReachingDefAnalysis.cpp - Reaching Def Analysis ---*- C++ -*-----===//
2eb11fae6SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6eb11fae6SDimitry Andric //
7eb11fae6SDimitry Andric //===----------------------------------------------------------------------===//
8eb11fae6SDimitry Andric 
9eb11fae6SDimitry Andric #include "llvm/CodeGen/ReachingDefAnalysis.h"
10ac9a064cSDimitry Andric #include "llvm/ADT/SetOperations.h"
11ac9a064cSDimitry Andric #include "llvm/ADT/SmallSet.h"
12ac9a064cSDimitry Andric #include "llvm/CodeGen/LiveRegUnits.h"
13eb11fae6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
14eb11fae6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
151d5ae102SDimitry Andric #include "llvm/Support/Debug.h"
16eb11fae6SDimitry Andric 
17eb11fae6SDimitry Andric using namespace llvm;
18eb11fae6SDimitry Andric 
19eb11fae6SDimitry Andric #define DEBUG_TYPE "reaching-deps-analysis"
20eb11fae6SDimitry Andric 
21eb11fae6SDimitry Andric char ReachingDefAnalysis::ID = 0;
22eb11fae6SDimitry Andric INITIALIZE_PASS(ReachingDefAnalysis, DEBUG_TYPE, "ReachingDefAnalysis", false,
23eb11fae6SDimitry Andric                 true)
24eb11fae6SDimitry Andric 
isValidReg(const MachineOperand & MO)25cfca06d7SDimitry Andric static bool isValidReg(const MachineOperand &MO) {
26cfca06d7SDimitry Andric   return MO.isReg() && MO.getReg();
27cfca06d7SDimitry Andric }
28eb11fae6SDimitry Andric 
isValidRegUse(const MachineOperand & MO)29cfca06d7SDimitry Andric static bool isValidRegUse(const MachineOperand &MO) {
30cfca06d7SDimitry Andric   return isValidReg(MO) && MO.isUse();
31cfca06d7SDimitry Andric }
32cfca06d7SDimitry Andric 
isValidRegUseOf(const MachineOperand & MO,MCRegister PhysReg,const TargetRegisterInfo * TRI)33c0981da4SDimitry Andric static bool isValidRegUseOf(const MachineOperand &MO, MCRegister PhysReg,
34c0981da4SDimitry Andric                             const TargetRegisterInfo *TRI) {
35c0981da4SDimitry Andric   if (!isValidRegUse(MO))
36c0981da4SDimitry Andric     return false;
37145449b1SDimitry Andric   return TRI->regsOverlap(MO.getReg(), PhysReg);
38cfca06d7SDimitry Andric }
39cfca06d7SDimitry Andric 
isValidRegDef(const MachineOperand & MO)40cfca06d7SDimitry Andric static bool isValidRegDef(const MachineOperand &MO) {
41cfca06d7SDimitry Andric   return isValidReg(MO) && MO.isDef();
42cfca06d7SDimitry Andric }
43cfca06d7SDimitry Andric 
isValidRegDefOf(const MachineOperand & MO,MCRegister PhysReg,const TargetRegisterInfo * TRI)44c0981da4SDimitry Andric static bool isValidRegDefOf(const MachineOperand &MO, MCRegister PhysReg,
45c0981da4SDimitry Andric                             const TargetRegisterInfo *TRI) {
46c0981da4SDimitry Andric   if (!isValidRegDef(MO))
47c0981da4SDimitry Andric     return false;
48145449b1SDimitry Andric   return TRI->regsOverlap(MO.getReg(), PhysReg);
49cfca06d7SDimitry Andric }
50cfca06d7SDimitry Andric 
enterBasicBlock(MachineBasicBlock * MBB)51cfca06d7SDimitry Andric void ReachingDefAnalysis::enterBasicBlock(MachineBasicBlock *MBB) {
52eb11fae6SDimitry Andric   unsigned MBBNumber = MBB->getNumber();
53eb11fae6SDimitry Andric   assert(MBBNumber < MBBReachingDefs.size() &&
54eb11fae6SDimitry Andric          "Unexpected basic block number.");
55eb11fae6SDimitry Andric   MBBReachingDefs[MBBNumber].resize(NumRegUnits);
56eb11fae6SDimitry Andric 
57eb11fae6SDimitry Andric   // Reset instruction counter in each basic block.
58eb11fae6SDimitry Andric   CurInstr = 0;
59eb11fae6SDimitry Andric 
60eb11fae6SDimitry Andric   // Set up LiveRegs to represent registers entering MBB.
61eb11fae6SDimitry Andric   // Default values are 'nothing happened a long time ago'.
62eb11fae6SDimitry Andric   if (LiveRegs.empty())
63eb11fae6SDimitry Andric     LiveRegs.assign(NumRegUnits, ReachingDefDefaultVal);
64eb11fae6SDimitry Andric 
65eb11fae6SDimitry Andric   // This is the entry block.
66eb11fae6SDimitry Andric   if (MBB->pred_empty()) {
67eb11fae6SDimitry Andric     for (const auto &LI : MBB->liveins()) {
687fa27ce4SDimitry Andric       for (MCRegUnit Unit : TRI->regunits(LI.PhysReg)) {
69eb11fae6SDimitry Andric         // Treat function live-ins as if they were defined just before the first
70eb11fae6SDimitry Andric         // instruction.  Usually, function arguments are set up immediately
71eb11fae6SDimitry Andric         // before the call.
727fa27ce4SDimitry Andric         if (LiveRegs[Unit] != -1) {
737fa27ce4SDimitry Andric           LiveRegs[Unit] = -1;
747fa27ce4SDimitry Andric           MBBReachingDefs[MBBNumber][Unit].push_back(-1);
75cfca06d7SDimitry Andric         }
76eb11fae6SDimitry Andric       }
77eb11fae6SDimitry Andric     }
78eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": entry\n");
79eb11fae6SDimitry Andric     return;
80eb11fae6SDimitry Andric   }
81eb11fae6SDimitry Andric 
82eb11fae6SDimitry Andric   // Try to coalesce live-out registers from predecessors.
83eb11fae6SDimitry Andric   for (MachineBasicBlock *pred : MBB->predecessors()) {
84eb11fae6SDimitry Andric     assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
85eb11fae6SDimitry Andric            "Should have pre-allocated MBBInfos for all MBBs");
86eb11fae6SDimitry Andric     const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
87eb11fae6SDimitry Andric     // Incoming is null if this is a backedge from a BB
88eb11fae6SDimitry Andric     // we haven't processed yet
89eb11fae6SDimitry Andric     if (Incoming.empty())
90eb11fae6SDimitry Andric       continue;
91eb11fae6SDimitry Andric 
92cfca06d7SDimitry Andric     // Find the most recent reaching definition from a predecessor.
93cfca06d7SDimitry Andric     for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
94eb11fae6SDimitry Andric       LiveRegs[Unit] = std::max(LiveRegs[Unit], Incoming[Unit]);
95cfca06d7SDimitry Andric   }
96cfca06d7SDimitry Andric 
97cfca06d7SDimitry Andric   // Insert the most recent reaching definition we found.
98cfca06d7SDimitry Andric   for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
99cfca06d7SDimitry Andric     if (LiveRegs[Unit] != ReachingDefDefaultVal)
100eb11fae6SDimitry Andric       MBBReachingDefs[MBBNumber][Unit].push_back(LiveRegs[Unit]);
101eb11fae6SDimitry Andric }
102eb11fae6SDimitry Andric 
leaveBasicBlock(MachineBasicBlock * MBB)103cfca06d7SDimitry Andric void ReachingDefAnalysis::leaveBasicBlock(MachineBasicBlock *MBB) {
104eb11fae6SDimitry Andric   assert(!LiveRegs.empty() && "Must enter basic block first.");
105cfca06d7SDimitry Andric   unsigned MBBNumber = MBB->getNumber();
106eb11fae6SDimitry Andric   assert(MBBNumber < MBBOutRegsInfos.size() &&
107eb11fae6SDimitry Andric          "Unexpected basic block number.");
108eb11fae6SDimitry Andric   // Save register clearances at end of MBB - used by enterBasicBlock().
109eb11fae6SDimitry Andric   MBBOutRegsInfos[MBBNumber] = LiveRegs;
110eb11fae6SDimitry Andric 
111eb11fae6SDimitry Andric   // While processing the basic block, we kept `Def` relative to the start
112eb11fae6SDimitry Andric   // of the basic block for convenience. However, future use of this information
113eb11fae6SDimitry Andric   // only cares about the clearance from the end of the block, so adjust
114eb11fae6SDimitry Andric   // everything to be relative to the end of the basic block.
115eb11fae6SDimitry Andric   for (int &OutLiveReg : MBBOutRegsInfos[MBBNumber])
116cfca06d7SDimitry Andric     if (OutLiveReg != ReachingDefDefaultVal)
117eb11fae6SDimitry Andric       OutLiveReg -= CurInstr;
118eb11fae6SDimitry Andric   LiveRegs.clear();
119eb11fae6SDimitry Andric }
120eb11fae6SDimitry Andric 
processDefs(MachineInstr * MI)121eb11fae6SDimitry Andric void ReachingDefAnalysis::processDefs(MachineInstr *MI) {
122eb11fae6SDimitry Andric   assert(!MI->isDebugInstr() && "Won't process debug instructions");
123eb11fae6SDimitry Andric 
124eb11fae6SDimitry Andric   unsigned MBBNumber = MI->getParent()->getNumber();
125eb11fae6SDimitry Andric   assert(MBBNumber < MBBReachingDefs.size() &&
126eb11fae6SDimitry Andric          "Unexpected basic block number.");
127cfca06d7SDimitry Andric 
128cfca06d7SDimitry Andric   for (auto &MO : MI->operands()) {
129cfca06d7SDimitry Andric     if (!isValidRegDef(MO))
130eb11fae6SDimitry Andric       continue;
1317fa27ce4SDimitry Andric     for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
132eb11fae6SDimitry Andric       // This instruction explicitly defines the current reg unit.
1337fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << printRegUnit(Unit, TRI) << ":\t" << CurInstr << '\t'
1347fa27ce4SDimitry Andric                         << *MI);
135eb11fae6SDimitry Andric 
136eb11fae6SDimitry Andric       // How many instructions since this reg unit was last written?
1377fa27ce4SDimitry Andric       if (LiveRegs[Unit] != CurInstr) {
1387fa27ce4SDimitry Andric         LiveRegs[Unit] = CurInstr;
1397fa27ce4SDimitry Andric         MBBReachingDefs[MBBNumber][Unit].push_back(CurInstr);
140eb11fae6SDimitry Andric       }
141eb11fae6SDimitry Andric     }
142cfca06d7SDimitry Andric   }
143eb11fae6SDimitry Andric   InstIds[MI] = CurInstr;
144eb11fae6SDimitry Andric   ++CurInstr;
145eb11fae6SDimitry Andric }
146eb11fae6SDimitry Andric 
reprocessBasicBlock(MachineBasicBlock * MBB)147cfca06d7SDimitry Andric void ReachingDefAnalysis::reprocessBasicBlock(MachineBasicBlock *MBB) {
148cfca06d7SDimitry Andric   unsigned MBBNumber = MBB->getNumber();
149cfca06d7SDimitry Andric   assert(MBBNumber < MBBReachingDefs.size() &&
150cfca06d7SDimitry Andric          "Unexpected basic block number.");
151cfca06d7SDimitry Andric 
152cfca06d7SDimitry Andric   // Count number of non-debug instructions for end of block adjustment.
153b60736ecSDimitry Andric   auto NonDbgInsts =
154b60736ecSDimitry Andric     instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end());
155b60736ecSDimitry Andric   int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
156cfca06d7SDimitry Andric 
157cfca06d7SDimitry Andric   // When reprocessing a block, the only thing we need to do is check whether
158cfca06d7SDimitry Andric   // there is now a more recent incoming reaching definition from a predecessor.
159cfca06d7SDimitry Andric   for (MachineBasicBlock *pred : MBB->predecessors()) {
160cfca06d7SDimitry Andric     assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
161cfca06d7SDimitry Andric            "Should have pre-allocated MBBInfos for all MBBs");
162cfca06d7SDimitry Andric     const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
163cfca06d7SDimitry Andric     // Incoming may be empty for dead predecessors.
164cfca06d7SDimitry Andric     if (Incoming.empty())
165cfca06d7SDimitry Andric       continue;
166cfca06d7SDimitry Andric 
167cfca06d7SDimitry Andric     for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
168cfca06d7SDimitry Andric       int Def = Incoming[Unit];
169cfca06d7SDimitry Andric       if (Def == ReachingDefDefaultVal)
170cfca06d7SDimitry Andric         continue;
171cfca06d7SDimitry Andric 
172cfca06d7SDimitry Andric       auto Start = MBBReachingDefs[MBBNumber][Unit].begin();
173cfca06d7SDimitry Andric       if (Start != MBBReachingDefs[MBBNumber][Unit].end() && *Start < 0) {
174cfca06d7SDimitry Andric         if (*Start >= Def)
175cfca06d7SDimitry Andric           continue;
176cfca06d7SDimitry Andric 
177cfca06d7SDimitry Andric         // Update existing reaching def from predecessor to a more recent one.
178cfca06d7SDimitry Andric         *Start = Def;
179cfca06d7SDimitry Andric       } else {
180cfca06d7SDimitry Andric         // Insert new reaching def from predecessor.
181cfca06d7SDimitry Andric         MBBReachingDefs[MBBNumber][Unit].insert(Start, Def);
182cfca06d7SDimitry Andric       }
183cfca06d7SDimitry Andric 
184b1c73532SDimitry Andric       // Update reaching def at end of BB. Keep in mind that these are
185cfca06d7SDimitry Andric       // adjusted relative to the end of the basic block.
186cfca06d7SDimitry Andric       if (MBBOutRegsInfos[MBBNumber][Unit] < Def - NumInsts)
187cfca06d7SDimitry Andric         MBBOutRegsInfos[MBBNumber][Unit] = Def - NumInsts;
188cfca06d7SDimitry Andric     }
189cfca06d7SDimitry Andric   }
190cfca06d7SDimitry Andric }
191cfca06d7SDimitry Andric 
processBasicBlock(const LoopTraversal::TraversedMBBInfo & TraversedMBB)192eb11fae6SDimitry Andric void ReachingDefAnalysis::processBasicBlock(
193eb11fae6SDimitry Andric     const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
194cfca06d7SDimitry Andric   MachineBasicBlock *MBB = TraversedMBB.MBB;
195cfca06d7SDimitry Andric   LLVM_DEBUG(dbgs() << printMBBReference(*MBB)
196cfca06d7SDimitry Andric                     << (!TraversedMBB.IsDone ? ": incomplete\n"
197cfca06d7SDimitry Andric                                              : ": all preds known\n"));
198cfca06d7SDimitry Andric 
199cfca06d7SDimitry Andric   if (!TraversedMBB.PrimaryPass) {
200cfca06d7SDimitry Andric     // Reprocess MBB that is part of a loop.
201cfca06d7SDimitry Andric     reprocessBasicBlock(MBB);
202cfca06d7SDimitry Andric     return;
203cfca06d7SDimitry Andric   }
204cfca06d7SDimitry Andric 
205cfca06d7SDimitry Andric   enterBasicBlock(MBB);
206b60736ecSDimitry Andric   for (MachineInstr &MI :
207b60736ecSDimitry Andric        instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end()))
208eb11fae6SDimitry Andric     processDefs(&MI);
209cfca06d7SDimitry Andric   leaveBasicBlock(MBB);
210eb11fae6SDimitry Andric }
211eb11fae6SDimitry Andric 
runOnMachineFunction(MachineFunction & mf)212eb11fae6SDimitry Andric bool ReachingDefAnalysis::runOnMachineFunction(MachineFunction &mf) {
213eb11fae6SDimitry Andric   MF = &mf;
214eb11fae6SDimitry Andric   TRI = MF->getSubtarget().getRegisterInfo();
215eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "********** REACHING DEFINITION ANALYSIS **********\n");
216cfca06d7SDimitry Andric   init();
217cfca06d7SDimitry Andric   traverse();
218eb11fae6SDimitry Andric   return false;
219eb11fae6SDimitry Andric }
220eb11fae6SDimitry Andric 
releaseMemory()221eb11fae6SDimitry Andric void ReachingDefAnalysis::releaseMemory() {
222eb11fae6SDimitry Andric   // Clear the internal vectors.
223eb11fae6SDimitry Andric   MBBOutRegsInfos.clear();
224eb11fae6SDimitry Andric   MBBReachingDefs.clear();
225eb11fae6SDimitry Andric   InstIds.clear();
226cfca06d7SDimitry Andric   LiveRegs.clear();
227eb11fae6SDimitry Andric }
228eb11fae6SDimitry Andric 
reset()229cfca06d7SDimitry Andric void ReachingDefAnalysis::reset() {
230cfca06d7SDimitry Andric   releaseMemory();
231cfca06d7SDimitry Andric   init();
232cfca06d7SDimitry Andric   traverse();
233cfca06d7SDimitry Andric }
234cfca06d7SDimitry Andric 
init()235cfca06d7SDimitry Andric void ReachingDefAnalysis::init() {
236cfca06d7SDimitry Andric   NumRegUnits = TRI->getNumRegUnits();
237cfca06d7SDimitry Andric   MBBReachingDefs.resize(MF->getNumBlockIDs());
238cfca06d7SDimitry Andric   // Initialize the MBBOutRegsInfos
239cfca06d7SDimitry Andric   MBBOutRegsInfos.resize(MF->getNumBlockIDs());
240cfca06d7SDimitry Andric   LoopTraversal Traversal;
241cfca06d7SDimitry Andric   TraversedMBBOrder = Traversal.traverse(*MF);
242cfca06d7SDimitry Andric }
243cfca06d7SDimitry Andric 
traverse()244cfca06d7SDimitry Andric void ReachingDefAnalysis::traverse() {
245cfca06d7SDimitry Andric   // Traverse the basic blocks.
246cfca06d7SDimitry Andric   for (LoopTraversal::TraversedMBBInfo TraversedMBB : TraversedMBBOrder)
247cfca06d7SDimitry Andric     processBasicBlock(TraversedMBB);
248cfca06d7SDimitry Andric #ifndef NDEBUG
249cfca06d7SDimitry Andric   // Make sure reaching defs are sorted and unique.
250cfca06d7SDimitry Andric   for (MBBDefsInfo &MBBDefs : MBBReachingDefs) {
251cfca06d7SDimitry Andric     for (MBBRegUnitDefs &RegUnitDefs : MBBDefs) {
252cfca06d7SDimitry Andric       int LastDef = ReachingDefDefaultVal;
253cfca06d7SDimitry Andric       for (int Def : RegUnitDefs) {
254cfca06d7SDimitry Andric         assert(Def > LastDef && "Defs must be sorted and unique");
255cfca06d7SDimitry Andric         LastDef = Def;
256cfca06d7SDimitry Andric       }
257cfca06d7SDimitry Andric     }
258cfca06d7SDimitry Andric   }
259cfca06d7SDimitry Andric #endif
260cfca06d7SDimitry Andric }
261cfca06d7SDimitry Andric 
getReachingDef(MachineInstr * MI,MCRegister PhysReg) const262b60736ecSDimitry Andric int ReachingDefAnalysis::getReachingDef(MachineInstr *MI,
263b60736ecSDimitry Andric                                         MCRegister PhysReg) const {
264eb11fae6SDimitry Andric   assert(InstIds.count(MI) && "Unexpected machine instuction.");
265cfca06d7SDimitry Andric   int InstId = InstIds.lookup(MI);
266eb11fae6SDimitry Andric   int DefRes = ReachingDefDefaultVal;
267eb11fae6SDimitry Andric   unsigned MBBNumber = MI->getParent()->getNumber();
268eb11fae6SDimitry Andric   assert(MBBNumber < MBBReachingDefs.size() &&
269eb11fae6SDimitry Andric          "Unexpected basic block number.");
270eb11fae6SDimitry Andric   int LatestDef = ReachingDefDefaultVal;
2717fa27ce4SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
2727fa27ce4SDimitry Andric     for (int Def : MBBReachingDefs[MBBNumber][Unit]) {
273eb11fae6SDimitry Andric       if (Def >= InstId)
274eb11fae6SDimitry Andric         break;
275eb11fae6SDimitry Andric       DefRes = Def;
276eb11fae6SDimitry Andric     }
277eb11fae6SDimitry Andric     LatestDef = std::max(LatestDef, DefRes);
278eb11fae6SDimitry Andric   }
279eb11fae6SDimitry Andric   return LatestDef;
280eb11fae6SDimitry Andric }
281eb11fae6SDimitry Andric 
282b60736ecSDimitry Andric MachineInstr *
getReachingLocalMIDef(MachineInstr * MI,MCRegister PhysReg) const283b60736ecSDimitry Andric ReachingDefAnalysis::getReachingLocalMIDef(MachineInstr *MI,
284b60736ecSDimitry Andric                                            MCRegister PhysReg) const {
285b60736ecSDimitry Andric   return hasLocalDefBefore(MI, PhysReg)
286b60736ecSDimitry Andric     ? getInstFromId(MI->getParent(), getReachingDef(MI, PhysReg))
287b60736ecSDimitry Andric     : nullptr;
288706b4fc4SDimitry Andric }
289706b4fc4SDimitry Andric 
hasSameReachingDef(MachineInstr * A,MachineInstr * B,MCRegister PhysReg) const290706b4fc4SDimitry Andric bool ReachingDefAnalysis::hasSameReachingDef(MachineInstr *A, MachineInstr *B,
291b60736ecSDimitry Andric                                              MCRegister PhysReg) const {
292706b4fc4SDimitry Andric   MachineBasicBlock *ParentA = A->getParent();
293706b4fc4SDimitry Andric   MachineBasicBlock *ParentB = B->getParent();
294706b4fc4SDimitry Andric   if (ParentA != ParentB)
295706b4fc4SDimitry Andric     return false;
296706b4fc4SDimitry Andric 
297706b4fc4SDimitry Andric   return getReachingDef(A, PhysReg) == getReachingDef(B, PhysReg);
298706b4fc4SDimitry Andric }
299706b4fc4SDimitry Andric 
getInstFromId(MachineBasicBlock * MBB,int InstId) const300706b4fc4SDimitry Andric MachineInstr *ReachingDefAnalysis::getInstFromId(MachineBasicBlock *MBB,
301cfca06d7SDimitry Andric                                                  int InstId) const {
302706b4fc4SDimitry Andric   assert(static_cast<size_t>(MBB->getNumber()) < MBBReachingDefs.size() &&
303706b4fc4SDimitry Andric          "Unexpected basic block number.");
304706b4fc4SDimitry Andric   assert(InstId < static_cast<int>(MBB->size()) &&
305706b4fc4SDimitry Andric          "Unexpected instruction id.");
306706b4fc4SDimitry Andric 
307706b4fc4SDimitry Andric   if (InstId < 0)
308706b4fc4SDimitry Andric     return nullptr;
309706b4fc4SDimitry Andric 
310706b4fc4SDimitry Andric   for (auto &MI : *MBB) {
311cfca06d7SDimitry Andric     auto F = InstIds.find(&MI);
312cfca06d7SDimitry Andric     if (F != InstIds.end() && F->second == InstId)
313706b4fc4SDimitry Andric       return &MI;
314706b4fc4SDimitry Andric   }
315cfca06d7SDimitry Andric 
316706b4fc4SDimitry Andric   return nullptr;
317706b4fc4SDimitry Andric }
318706b4fc4SDimitry Andric 
getClearance(MachineInstr * MI,MCRegister PhysReg) const319b60736ecSDimitry Andric int ReachingDefAnalysis::getClearance(MachineInstr *MI,
320b60736ecSDimitry Andric                                       MCRegister PhysReg) const {
321eb11fae6SDimitry Andric   assert(InstIds.count(MI) && "Unexpected machine instuction.");
322cfca06d7SDimitry Andric   return InstIds.lookup(MI) - getReachingDef(MI, PhysReg);
323cfca06d7SDimitry Andric }
324cfca06d7SDimitry Andric 
hasLocalDefBefore(MachineInstr * MI,MCRegister PhysReg) const325b60736ecSDimitry Andric bool ReachingDefAnalysis::hasLocalDefBefore(MachineInstr *MI,
326b60736ecSDimitry Andric                                             MCRegister PhysReg) const {
327cfca06d7SDimitry Andric   return getReachingDef(MI, PhysReg) >= 0;
328eb11fae6SDimitry Andric }
329706b4fc4SDimitry Andric 
getReachingLocalUses(MachineInstr * Def,MCRegister PhysReg,InstSet & Uses) const330b60736ecSDimitry Andric void ReachingDefAnalysis::getReachingLocalUses(MachineInstr *Def,
331b60736ecSDimitry Andric                                                MCRegister PhysReg,
332cfca06d7SDimitry Andric                                                InstSet &Uses) const {
333706b4fc4SDimitry Andric   MachineBasicBlock *MBB = Def->getParent();
334706b4fc4SDimitry Andric   MachineBasicBlock::iterator MI = MachineBasicBlock::iterator(Def);
335706b4fc4SDimitry Andric   while (++MI != MBB->end()) {
336cfca06d7SDimitry Andric     if (MI->isDebugInstr())
337cfca06d7SDimitry Andric       continue;
338cfca06d7SDimitry Andric 
339706b4fc4SDimitry Andric     // If/when we find a new reaching def, we know that there's no more uses
340706b4fc4SDimitry Andric     // of 'Def'.
341cfca06d7SDimitry Andric     if (getReachingLocalMIDef(&*MI, PhysReg) != Def)
342706b4fc4SDimitry Andric       return;
343706b4fc4SDimitry Andric 
344706b4fc4SDimitry Andric     for (auto &MO : MI->operands()) {
345c0981da4SDimitry Andric       if (!isValidRegUseOf(MO, PhysReg, TRI))
346706b4fc4SDimitry Andric         continue;
347706b4fc4SDimitry Andric 
348cfca06d7SDimitry Andric       Uses.insert(&*MI);
349706b4fc4SDimitry Andric       if (MO.isKill())
350706b4fc4SDimitry Andric         return;
351706b4fc4SDimitry Andric     }
352706b4fc4SDimitry Andric   }
353706b4fc4SDimitry Andric }
354706b4fc4SDimitry Andric 
getLiveInUses(MachineBasicBlock * MBB,MCRegister PhysReg,InstSet & Uses) const355b60736ecSDimitry Andric bool ReachingDefAnalysis::getLiveInUses(MachineBasicBlock *MBB,
356b60736ecSDimitry Andric                                         MCRegister PhysReg,
357cfca06d7SDimitry Andric                                         InstSet &Uses) const {
358b60736ecSDimitry Andric   for (MachineInstr &MI :
359b60736ecSDimitry Andric        instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end())) {
360cfca06d7SDimitry Andric     for (auto &MO : MI.operands()) {
361c0981da4SDimitry Andric       if (!isValidRegUseOf(MO, PhysReg, TRI))
362cfca06d7SDimitry Andric         continue;
363cfca06d7SDimitry Andric       if (getReachingDef(&MI, PhysReg) >= 0)
364cfca06d7SDimitry Andric         return false;
365cfca06d7SDimitry Andric       Uses.insert(&MI);
366cfca06d7SDimitry Andric     }
367cfca06d7SDimitry Andric   }
368b60736ecSDimitry Andric   auto Last = MBB->getLastNonDebugInstr();
369b60736ecSDimitry Andric   if (Last == MBB->end())
370b60736ecSDimitry Andric     return true;
371b60736ecSDimitry Andric   return isReachingDefLiveOut(&*Last, PhysReg);
372706b4fc4SDimitry Andric }
373706b4fc4SDimitry Andric 
getGlobalUses(MachineInstr * MI,MCRegister PhysReg,InstSet & Uses) const374b60736ecSDimitry Andric void ReachingDefAnalysis::getGlobalUses(MachineInstr *MI, MCRegister PhysReg,
375cfca06d7SDimitry Andric                                         InstSet &Uses) const {
376cfca06d7SDimitry Andric   MachineBasicBlock *MBB = MI->getParent();
377cfca06d7SDimitry Andric 
378cfca06d7SDimitry Andric   // Collect the uses that each def touches within the block.
379cfca06d7SDimitry Andric   getReachingLocalUses(MI, PhysReg, Uses);
380cfca06d7SDimitry Andric 
381cfca06d7SDimitry Andric   // Handle live-out values.
382cfca06d7SDimitry Andric   if (auto *LiveOut = getLocalLiveOutMIDef(MI->getParent(), PhysReg)) {
383cfca06d7SDimitry Andric     if (LiveOut != MI)
384cfca06d7SDimitry Andric       return;
385cfca06d7SDimitry Andric 
386b60736ecSDimitry Andric     SmallVector<MachineBasicBlock *, 4> ToVisit(MBB->successors());
387cfca06d7SDimitry Andric     SmallPtrSet<MachineBasicBlock*, 4>Visited;
388cfca06d7SDimitry Andric     while (!ToVisit.empty()) {
389c0981da4SDimitry Andric       MachineBasicBlock *MBB = ToVisit.pop_back_val();
390cfca06d7SDimitry Andric       if (Visited.count(MBB) || !MBB->isLiveIn(PhysReg))
391cfca06d7SDimitry Andric         continue;
392cfca06d7SDimitry Andric       if (getLiveInUses(MBB, PhysReg, Uses))
393b60736ecSDimitry Andric         llvm::append_range(ToVisit, MBB->successors());
394cfca06d7SDimitry Andric       Visited.insert(MBB);
395cfca06d7SDimitry Andric     }
396cfca06d7SDimitry Andric   }
397cfca06d7SDimitry Andric }
398cfca06d7SDimitry Andric 
getGlobalReachingDefs(MachineInstr * MI,MCRegister PhysReg,InstSet & Defs) const399b60736ecSDimitry Andric void ReachingDefAnalysis::getGlobalReachingDefs(MachineInstr *MI,
400b60736ecSDimitry Andric                                                 MCRegister PhysReg,
401cfca06d7SDimitry Andric                                                 InstSet &Defs) const {
402b60736ecSDimitry Andric   if (auto *Def = getUniqueReachingMIDef(MI, PhysReg)) {
403b60736ecSDimitry Andric     Defs.insert(Def);
404b60736ecSDimitry Andric     return;
405b60736ecSDimitry Andric   }
406b60736ecSDimitry Andric 
407b60736ecSDimitry Andric   for (auto *MBB : MI->getParent()->predecessors())
408b60736ecSDimitry Andric     getLiveOuts(MBB, PhysReg, Defs);
409b60736ecSDimitry Andric }
410b60736ecSDimitry Andric 
getLiveOuts(MachineBasicBlock * MBB,MCRegister PhysReg,InstSet & Defs) const411b60736ecSDimitry Andric void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock *MBB,
412b60736ecSDimitry Andric                                       MCRegister PhysReg, InstSet &Defs) const {
413cfca06d7SDimitry Andric   SmallPtrSet<MachineBasicBlock*, 2> VisitedBBs;
414cfca06d7SDimitry Andric   getLiveOuts(MBB, PhysReg, Defs, VisitedBBs);
415cfca06d7SDimitry Andric }
416cfca06d7SDimitry Andric 
getLiveOuts(MachineBasicBlock * MBB,MCRegister PhysReg,InstSet & Defs,BlockSet & VisitedBBs) const417b60736ecSDimitry Andric void ReachingDefAnalysis::getLiveOuts(MachineBasicBlock *MBB,
418b60736ecSDimitry Andric                                       MCRegister PhysReg, InstSet &Defs,
419b60736ecSDimitry Andric                                       BlockSet &VisitedBBs) const {
420cfca06d7SDimitry Andric   if (VisitedBBs.count(MBB))
421cfca06d7SDimitry Andric     return;
422cfca06d7SDimitry Andric 
423cfca06d7SDimitry Andric   VisitedBBs.insert(MBB);
424ac9a064cSDimitry Andric   LiveRegUnits LiveRegs(*TRI);
425cfca06d7SDimitry Andric   LiveRegs.addLiveOuts(*MBB);
426ac9a064cSDimitry Andric   if (LiveRegs.available(PhysReg))
427cfca06d7SDimitry Andric     return;
428cfca06d7SDimitry Andric 
429cfca06d7SDimitry Andric   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
430cfca06d7SDimitry Andric     Defs.insert(Def);
431cfca06d7SDimitry Andric   else
432cfca06d7SDimitry Andric     for (auto *Pred : MBB->predecessors())
433cfca06d7SDimitry Andric       getLiveOuts(Pred, PhysReg, Defs, VisitedBBs);
434cfca06d7SDimitry Andric }
435cfca06d7SDimitry Andric 
436b60736ecSDimitry Andric MachineInstr *
getUniqueReachingMIDef(MachineInstr * MI,MCRegister PhysReg) const437b60736ecSDimitry Andric ReachingDefAnalysis::getUniqueReachingMIDef(MachineInstr *MI,
438b60736ecSDimitry Andric                                             MCRegister PhysReg) const {
439cfca06d7SDimitry Andric   // If there's a local def before MI, return it.
440cfca06d7SDimitry Andric   MachineInstr *LocalDef = getReachingLocalMIDef(MI, PhysReg);
441cfca06d7SDimitry Andric   if (LocalDef && InstIds.lookup(LocalDef) < InstIds.lookup(MI))
442cfca06d7SDimitry Andric     return LocalDef;
443cfca06d7SDimitry Andric 
444cfca06d7SDimitry Andric   SmallPtrSet<MachineInstr*, 2> Incoming;
445b60736ecSDimitry Andric   MachineBasicBlock *Parent = MI->getParent();
446b60736ecSDimitry Andric   for (auto *Pred : Parent->predecessors())
447b60736ecSDimitry Andric     getLiveOuts(Pred, PhysReg, Incoming);
448cfca06d7SDimitry Andric 
449b60736ecSDimitry Andric   // Check that we have a single incoming value and that it does not
450b60736ecSDimitry Andric   // come from the same block as MI - since it would mean that the def
451b60736ecSDimitry Andric   // is executed after MI.
452b60736ecSDimitry Andric   if (Incoming.size() == 1 && (*Incoming.begin())->getParent() != Parent)
453cfca06d7SDimitry Andric     return *Incoming.begin();
454b60736ecSDimitry Andric   return nullptr;
455cfca06d7SDimitry Andric }
456cfca06d7SDimitry Andric 
getMIOperand(MachineInstr * MI,unsigned Idx) const457cfca06d7SDimitry Andric MachineInstr *ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
458cfca06d7SDimitry Andric                                                 unsigned Idx) const {
459cfca06d7SDimitry Andric   assert(MI->getOperand(Idx).isReg() && "Expected register operand");
460cfca06d7SDimitry Andric   return getUniqueReachingMIDef(MI, MI->getOperand(Idx).getReg());
461cfca06d7SDimitry Andric }
462cfca06d7SDimitry Andric 
getMIOperand(MachineInstr * MI,MachineOperand & MO) const463cfca06d7SDimitry Andric MachineInstr *ReachingDefAnalysis::getMIOperand(MachineInstr *MI,
464cfca06d7SDimitry Andric                                                 MachineOperand &MO) const {
465cfca06d7SDimitry Andric   assert(MO.isReg() && "Expected register operand");
466cfca06d7SDimitry Andric   return getUniqueReachingMIDef(MI, MO.getReg());
467cfca06d7SDimitry Andric }
468cfca06d7SDimitry Andric 
isRegUsedAfter(MachineInstr * MI,MCRegister PhysReg) const469b60736ecSDimitry Andric bool ReachingDefAnalysis::isRegUsedAfter(MachineInstr *MI,
470b60736ecSDimitry Andric                                          MCRegister PhysReg) const {
471706b4fc4SDimitry Andric   MachineBasicBlock *MBB = MI->getParent();
472ac9a064cSDimitry Andric   LiveRegUnits LiveRegs(*TRI);
473706b4fc4SDimitry Andric   LiveRegs.addLiveOuts(*MBB);
474706b4fc4SDimitry Andric 
475706b4fc4SDimitry Andric   // Yes if the register is live out of the basic block.
476ac9a064cSDimitry Andric   if (!LiveRegs.available(PhysReg))
477706b4fc4SDimitry Andric     return true;
478706b4fc4SDimitry Andric 
479706b4fc4SDimitry Andric   // Walk backwards through the block to see if the register is live at some
480706b4fc4SDimitry Andric   // point.
481b60736ecSDimitry Andric   for (MachineInstr &Last :
482b60736ecSDimitry Andric        instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
483b60736ecSDimitry Andric     LiveRegs.stepBackward(Last);
484ac9a064cSDimitry Andric     if (!LiveRegs.available(PhysReg))
485b60736ecSDimitry Andric       return InstIds.lookup(&Last) > InstIds.lookup(MI);
486706b4fc4SDimitry Andric   }
487706b4fc4SDimitry Andric   return false;
488706b4fc4SDimitry Andric }
489706b4fc4SDimitry Andric 
isRegDefinedAfter(MachineInstr * MI,MCRegister PhysReg) const490cfca06d7SDimitry Andric bool ReachingDefAnalysis::isRegDefinedAfter(MachineInstr *MI,
491b60736ecSDimitry Andric                                             MCRegister PhysReg) const {
492cfca06d7SDimitry Andric   MachineBasicBlock *MBB = MI->getParent();
493b60736ecSDimitry Andric   auto Last = MBB->getLastNonDebugInstr();
494b60736ecSDimitry Andric   if (Last != MBB->end() &&
495b60736ecSDimitry Andric       getReachingDef(MI, PhysReg) != getReachingDef(&*Last, PhysReg))
496cfca06d7SDimitry Andric     return true;
497cfca06d7SDimitry Andric 
498cfca06d7SDimitry Andric   if (auto *Def = getLocalLiveOutMIDef(MBB, PhysReg))
499cfca06d7SDimitry Andric     return Def == getReachingLocalMIDef(MI, PhysReg);
500cfca06d7SDimitry Andric 
501cfca06d7SDimitry Andric   return false;
502cfca06d7SDimitry Andric }
503cfca06d7SDimitry Andric 
isReachingDefLiveOut(MachineInstr * MI,MCRegister PhysReg) const504b60736ecSDimitry Andric bool ReachingDefAnalysis::isReachingDefLiveOut(MachineInstr *MI,
505b60736ecSDimitry Andric                                                MCRegister PhysReg) const {
506706b4fc4SDimitry Andric   MachineBasicBlock *MBB = MI->getParent();
507ac9a064cSDimitry Andric   LiveRegUnits LiveRegs(*TRI);
508706b4fc4SDimitry Andric   LiveRegs.addLiveOuts(*MBB);
509ac9a064cSDimitry Andric   if (LiveRegs.available(PhysReg))
510706b4fc4SDimitry Andric     return false;
511706b4fc4SDimitry Andric 
512b60736ecSDimitry Andric   auto Last = MBB->getLastNonDebugInstr();
513706b4fc4SDimitry Andric   int Def = getReachingDef(MI, PhysReg);
514b60736ecSDimitry Andric   if (Last != MBB->end() && getReachingDef(&*Last, PhysReg) != Def)
515706b4fc4SDimitry Andric     return false;
516706b4fc4SDimitry Andric 
517706b4fc4SDimitry Andric   // Finally check that the last instruction doesn't redefine the register.
518706b4fc4SDimitry Andric   for (auto &MO : Last->operands())
519c0981da4SDimitry Andric     if (isValidRegDefOf(MO, PhysReg, TRI))
520706b4fc4SDimitry Andric       return false;
521706b4fc4SDimitry Andric 
522706b4fc4SDimitry Andric   return true;
523706b4fc4SDimitry Andric }
524706b4fc4SDimitry Andric 
525b60736ecSDimitry Andric MachineInstr *
getLocalLiveOutMIDef(MachineBasicBlock * MBB,MCRegister PhysReg) const526b60736ecSDimitry Andric ReachingDefAnalysis::getLocalLiveOutMIDef(MachineBasicBlock *MBB,
527b60736ecSDimitry Andric                                           MCRegister PhysReg) const {
528ac9a064cSDimitry Andric   LiveRegUnits LiveRegs(*TRI);
529706b4fc4SDimitry Andric   LiveRegs.addLiveOuts(*MBB);
530ac9a064cSDimitry Andric   if (LiveRegs.available(PhysReg))
531706b4fc4SDimitry Andric     return nullptr;
532706b4fc4SDimitry Andric 
533b60736ecSDimitry Andric   auto Last = MBB->getLastNonDebugInstr();
534b60736ecSDimitry Andric   if (Last == MBB->end())
535b60736ecSDimitry Andric     return nullptr;
536b60736ecSDimitry Andric 
537b60736ecSDimitry Andric   int Def = getReachingDef(&*Last, PhysReg);
538706b4fc4SDimitry Andric   for (auto &MO : Last->operands())
539c0981da4SDimitry Andric     if (isValidRegDefOf(MO, PhysReg, TRI))
540b60736ecSDimitry Andric       return &*Last;
541706b4fc4SDimitry Andric 
542706b4fc4SDimitry Andric   return Def < 0 ? nullptr : getInstFromId(MBB, Def);
543706b4fc4SDimitry Andric }
544706b4fc4SDimitry Andric 
mayHaveSideEffects(MachineInstr & MI)545cfca06d7SDimitry Andric static bool mayHaveSideEffects(MachineInstr &MI) {
546cfca06d7SDimitry Andric   return MI.mayLoadOrStore() || MI.mayRaiseFPException() ||
547cfca06d7SDimitry Andric          MI.hasUnmodeledSideEffects() || MI.isTerminator() ||
548cfca06d7SDimitry Andric          MI.isCall() || MI.isBarrier() || MI.isBranch() || MI.isReturn();
549cfca06d7SDimitry Andric }
550706b4fc4SDimitry Andric 
551cfca06d7SDimitry Andric // Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
552cfca06d7SDimitry Andric // not define a register that is used by any instructions, after and including,
553cfca06d7SDimitry Andric // 'To'. These instructions also must not redefine any of Froms operands.
554cfca06d7SDimitry Andric template<typename Iterator>
isSafeToMove(MachineInstr * From,MachineInstr * To) const555cfca06d7SDimitry Andric bool ReachingDefAnalysis::isSafeToMove(MachineInstr *From,
556cfca06d7SDimitry Andric                                        MachineInstr *To) const {
557b60736ecSDimitry Andric   if (From->getParent() != To->getParent() || From == To)
558cfca06d7SDimitry Andric     return false;
559cfca06d7SDimitry Andric 
560cfca06d7SDimitry Andric   SmallSet<int, 2> Defs;
561cfca06d7SDimitry Andric   // First check that From would compute the same value if moved.
562cfca06d7SDimitry Andric   for (auto &MO : From->operands()) {
563cfca06d7SDimitry Andric     if (!isValidReg(MO))
564cfca06d7SDimitry Andric       continue;
565cfca06d7SDimitry Andric     if (MO.isDef())
566cfca06d7SDimitry Andric       Defs.insert(MO.getReg());
567cfca06d7SDimitry Andric     else if (!hasSameReachingDef(From, To, MO.getReg()))
568cfca06d7SDimitry Andric       return false;
569cfca06d7SDimitry Andric   }
570cfca06d7SDimitry Andric 
571cfca06d7SDimitry Andric   // Now walk checking that the rest of the instructions will compute the same
572cfca06d7SDimitry Andric   // value and that we're not overwriting anything. Don't move the instruction
573cfca06d7SDimitry Andric   // past any memory, control-flow or other ambiguous instructions.
574cfca06d7SDimitry Andric   for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
575cfca06d7SDimitry Andric     if (mayHaveSideEffects(*I))
576cfca06d7SDimitry Andric       return false;
577706b4fc4SDimitry Andric     for (auto &MO : I->operands())
578cfca06d7SDimitry Andric       if (MO.isReg() && MO.getReg() && Defs.count(MO.getReg()))
579cfca06d7SDimitry Andric         return false;
580cfca06d7SDimitry Andric   }
581cfca06d7SDimitry Andric   return true;
582706b4fc4SDimitry Andric }
583706b4fc4SDimitry Andric 
isSafeToMoveForwards(MachineInstr * From,MachineInstr * To) const584cfca06d7SDimitry Andric bool ReachingDefAnalysis::isSafeToMoveForwards(MachineInstr *From,
585cfca06d7SDimitry Andric                                                MachineInstr *To) const {
586b60736ecSDimitry Andric   using Iterator = MachineBasicBlock::iterator;
587b60736ecSDimitry Andric   // Walk forwards until we find the instruction.
588b60736ecSDimitry Andric   for (auto I = Iterator(From), E = From->getParent()->end(); I != E; ++I)
589b60736ecSDimitry Andric     if (&*I == To)
590b60736ecSDimitry Andric       return isSafeToMove<Iterator>(From, To);
591b60736ecSDimitry Andric   return false;
592706b4fc4SDimitry Andric }
593cfca06d7SDimitry Andric 
isSafeToMoveBackwards(MachineInstr * From,MachineInstr * To) const594cfca06d7SDimitry Andric bool ReachingDefAnalysis::isSafeToMoveBackwards(MachineInstr *From,
595cfca06d7SDimitry Andric                                                 MachineInstr *To) const {
596b60736ecSDimitry Andric   using Iterator = MachineBasicBlock::reverse_iterator;
597b60736ecSDimitry Andric   // Walk backwards until we find the instruction.
598b60736ecSDimitry Andric   for (auto I = Iterator(From), E = From->getParent()->rend(); I != E; ++I)
599b60736ecSDimitry Andric     if (&*I == To)
600b60736ecSDimitry Andric       return isSafeToMove<Iterator>(From, To);
601b60736ecSDimitry Andric   return false;
602cfca06d7SDimitry Andric }
603cfca06d7SDimitry Andric 
isSafeToRemove(MachineInstr * MI,InstSet & ToRemove) const604cfca06d7SDimitry Andric bool ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI,
605cfca06d7SDimitry Andric                                          InstSet &ToRemove) const {
606cfca06d7SDimitry Andric   SmallPtrSet<MachineInstr*, 1> Ignore;
607cfca06d7SDimitry Andric   SmallPtrSet<MachineInstr*, 2> Visited;
608cfca06d7SDimitry Andric   return isSafeToRemove(MI, Visited, ToRemove, Ignore);
609cfca06d7SDimitry Andric }
610cfca06d7SDimitry Andric 
611cfca06d7SDimitry Andric bool
isSafeToRemove(MachineInstr * MI,InstSet & ToRemove,InstSet & Ignore) const612cfca06d7SDimitry Andric ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI, InstSet &ToRemove,
613cfca06d7SDimitry Andric                                     InstSet &Ignore) const {
614cfca06d7SDimitry Andric   SmallPtrSet<MachineInstr*, 2> Visited;
615cfca06d7SDimitry Andric   return isSafeToRemove(MI, Visited, ToRemove, Ignore);
616cfca06d7SDimitry Andric }
617cfca06d7SDimitry Andric 
618cfca06d7SDimitry Andric bool
isSafeToRemove(MachineInstr * MI,InstSet & Visited,InstSet & ToRemove,InstSet & Ignore) const619cfca06d7SDimitry Andric ReachingDefAnalysis::isSafeToRemove(MachineInstr *MI, InstSet &Visited,
620cfca06d7SDimitry Andric                                     InstSet &ToRemove, InstSet &Ignore) const {
621cfca06d7SDimitry Andric   if (Visited.count(MI) || Ignore.count(MI))
622cfca06d7SDimitry Andric     return true;
623cfca06d7SDimitry Andric   else if (mayHaveSideEffects(*MI)) {
624cfca06d7SDimitry Andric     // Unless told to ignore the instruction, don't remove anything which has
625cfca06d7SDimitry Andric     // side effects.
626cfca06d7SDimitry Andric     return false;
627cfca06d7SDimitry Andric   }
628cfca06d7SDimitry Andric 
629cfca06d7SDimitry Andric   Visited.insert(MI);
630cfca06d7SDimitry Andric   for (auto &MO : MI->operands()) {
631cfca06d7SDimitry Andric     if (!isValidRegDef(MO))
632cfca06d7SDimitry Andric       continue;
633cfca06d7SDimitry Andric 
634cfca06d7SDimitry Andric     SmallPtrSet<MachineInstr*, 4> Uses;
635cfca06d7SDimitry Andric     getGlobalUses(MI, MO.getReg(), Uses);
636cfca06d7SDimitry Andric 
6374b4fe385SDimitry Andric     for (auto *I : Uses) {
638cfca06d7SDimitry Andric       if (Ignore.count(I) || ToRemove.count(I))
639cfca06d7SDimitry Andric         continue;
640cfca06d7SDimitry Andric       if (!isSafeToRemove(I, Visited, ToRemove, Ignore))
641cfca06d7SDimitry Andric         return false;
642cfca06d7SDimitry Andric     }
643cfca06d7SDimitry Andric   }
644cfca06d7SDimitry Andric   ToRemove.insert(MI);
645cfca06d7SDimitry Andric   return true;
646cfca06d7SDimitry Andric }
647cfca06d7SDimitry Andric 
collectKilledOperands(MachineInstr * MI,InstSet & Dead) const648cfca06d7SDimitry Andric void ReachingDefAnalysis::collectKilledOperands(MachineInstr *MI,
649cfca06d7SDimitry Andric                                                 InstSet &Dead) const {
650cfca06d7SDimitry Andric   Dead.insert(MI);
651b60736ecSDimitry Andric   auto IsDead = [this, &Dead](MachineInstr *Def, MCRegister PhysReg) {
652b60736ecSDimitry Andric     if (mayHaveSideEffects(*Def))
653b60736ecSDimitry Andric       return false;
654b60736ecSDimitry Andric 
655cfca06d7SDimitry Andric     unsigned LiveDefs = 0;
656cfca06d7SDimitry Andric     for (auto &MO : Def->operands()) {
657cfca06d7SDimitry Andric       if (!isValidRegDef(MO))
658cfca06d7SDimitry Andric         continue;
659cfca06d7SDimitry Andric       if (!MO.isDead())
660cfca06d7SDimitry Andric         ++LiveDefs;
661cfca06d7SDimitry Andric     }
662cfca06d7SDimitry Andric 
663cfca06d7SDimitry Andric     if (LiveDefs > 1)
664cfca06d7SDimitry Andric       return false;
665cfca06d7SDimitry Andric 
666cfca06d7SDimitry Andric     SmallPtrSet<MachineInstr*, 4> Uses;
667cfca06d7SDimitry Andric     getGlobalUses(Def, PhysReg, Uses);
668344a3780SDimitry Andric     return llvm::set_is_subset(Uses, Dead);
669cfca06d7SDimitry Andric   };
670cfca06d7SDimitry Andric 
671cfca06d7SDimitry Andric   for (auto &MO : MI->operands()) {
672cfca06d7SDimitry Andric     if (!isValidRegUse(MO))
673cfca06d7SDimitry Andric       continue;
674cfca06d7SDimitry Andric     if (MachineInstr *Def = getMIOperand(MI, MO))
675cfca06d7SDimitry Andric       if (IsDead(Def, MO.getReg()))
676cfca06d7SDimitry Andric         collectKilledOperands(Def, Dead);
677cfca06d7SDimitry Andric   }
678cfca06d7SDimitry Andric }
679cfca06d7SDimitry Andric 
isSafeToDefRegAt(MachineInstr * MI,MCRegister PhysReg) const680cfca06d7SDimitry Andric bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI,
681b60736ecSDimitry Andric                                            MCRegister PhysReg) const {
682cfca06d7SDimitry Andric   SmallPtrSet<MachineInstr*, 1> Ignore;
683cfca06d7SDimitry Andric   return isSafeToDefRegAt(MI, PhysReg, Ignore);
684cfca06d7SDimitry Andric }
685cfca06d7SDimitry Andric 
isSafeToDefRegAt(MachineInstr * MI,MCRegister PhysReg,InstSet & Ignore) const686b60736ecSDimitry Andric bool ReachingDefAnalysis::isSafeToDefRegAt(MachineInstr *MI, MCRegister PhysReg,
687cfca06d7SDimitry Andric                                            InstSet &Ignore) const {
688cfca06d7SDimitry Andric   // Check for any uses of the register after MI.
689cfca06d7SDimitry Andric   if (isRegUsedAfter(MI, PhysReg)) {
690cfca06d7SDimitry Andric     if (auto *Def = getReachingLocalMIDef(MI, PhysReg)) {
691cfca06d7SDimitry Andric       SmallPtrSet<MachineInstr*, 2> Uses;
692b60736ecSDimitry Andric       getGlobalUses(Def, PhysReg, Uses);
693344a3780SDimitry Andric       if (!llvm::set_is_subset(Uses, Ignore))
694cfca06d7SDimitry Andric         return false;
695cfca06d7SDimitry Andric     } else
696cfca06d7SDimitry Andric       return false;
697cfca06d7SDimitry Andric   }
698cfca06d7SDimitry Andric 
699cfca06d7SDimitry Andric   MachineBasicBlock *MBB = MI->getParent();
700cfca06d7SDimitry Andric   // Check for any defs after MI.
701cfca06d7SDimitry Andric   if (isRegDefinedAfter(MI, PhysReg)) {
702cfca06d7SDimitry Andric     auto I = MachineBasicBlock::iterator(MI);
703cfca06d7SDimitry Andric     for (auto E = MBB->end(); I != E; ++I) {
704cfca06d7SDimitry Andric       if (Ignore.count(&*I))
705cfca06d7SDimitry Andric         continue;
706cfca06d7SDimitry Andric       for (auto &MO : I->operands())
707c0981da4SDimitry Andric         if (isValidRegDefOf(MO, PhysReg, TRI))
708cfca06d7SDimitry Andric           return false;
709cfca06d7SDimitry Andric     }
710cfca06d7SDimitry Andric   }
711cfca06d7SDimitry Andric   return true;
712706b4fc4SDimitry Andric }
713