LLVM 21.0.0git
ReachingDefAnalysis.cpp
Go to the documentation of this file.
1//===---- ReachingDefAnalysis.cpp - Reaching Def Analysis ---*- C++ -*-----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
11#include "llvm/ADT/SmallSet.h"
17#include "llvm/Support/Debug.h"
18
19using namespace llvm;
20
21#define DEBUG_TYPE "reaching-defs-analysis"
22
23static cl::opt<bool> PrintAllReachingDefs("print-all-reaching-defs", cl::Hidden,
24 cl::desc("Used for test purpuses"),
26
28INITIALIZE_PASS(ReachingDefAnalysis, DEBUG_TYPE, "ReachingDefAnalysis", false,
29 true)
30
31static bool isValidReg(const MachineOperand &MO) {
32 return MO.isReg() && MO.getReg();
33}
34
35static bool isValidRegUse(const MachineOperand &MO) {
36 return isValidReg(MO) && MO.isUse();
37}
38
39static bool isValidRegUseOf(const MachineOperand &MO, Register Reg,
40 const TargetRegisterInfo *TRI) {
41 if (!isValidRegUse(MO))
42 return false;
43 return TRI->regsOverlap(MO.getReg(), Reg);
44}
45
46static bool isValidRegDef(const MachineOperand &MO) {
47 return isValidReg(MO) && MO.isDef();
48}
49
50static bool isValidRegDefOf(const MachineOperand &MO, Register Reg,
51 const TargetRegisterInfo *TRI) {
52 if (!isValidRegDef(MO))
53 return false;
54 return TRI->regsOverlap(MO.getReg(), Reg);
55}
56
57static bool isFIDef(const MachineInstr &MI, int FrameIndex,
58 const TargetInstrInfo *TII) {
59 int DefFrameIndex = 0;
60 int SrcFrameIndex = 0;
61 if (TII->isStoreToStackSlot(MI, DefFrameIndex) ||
62 TII->isStackSlotCopy(MI, DefFrameIndex, SrcFrameIndex))
63 return DefFrameIndex == FrameIndex;
64 return false;
65}
66
67void ReachingDefAnalysis::enterBasicBlock(MachineBasicBlock *MBB) {
68 unsigned MBBNumber = MBB->getNumber();
69 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
70 "Unexpected basic block number.");
71 MBBReachingDefs.startBasicBlock(MBBNumber, NumRegUnits);
72
73 // Reset instruction counter in each basic block.
74 CurInstr = 0;
75
76 // Set up LiveRegs to represent registers entering MBB.
77 // Default values are 'nothing happened a long time ago'.
78 if (LiveRegs.empty())
79 LiveRegs.assign(NumRegUnits, ReachingDefDefaultVal);
80
81 // This is the entry block.
82 if (MBB->pred_empty()) {
83 for (const auto &LI : MBB->liveins()) {
84 for (MCRegUnit Unit : TRI->regunits(LI.PhysReg)) {
85 // Treat function live-ins as if they were defined just before the first
86 // instruction. Usually, function arguments are set up immediately
87 // before the call.
88 if (LiveRegs[Unit] != -1) {
89 LiveRegs[Unit] = -1;
90 MBBReachingDefs.append(MBBNumber, Unit, -1);
91 }
92 }
93 }
94 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": entry\n");
95 return;
96 }
97
98 // Try to coalesce live-out registers from predecessors.
100 assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
101 "Should have pre-allocated MBBInfos for all MBBs");
102 const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
103 // Incoming is null if this is a backedge from a BB
104 // we haven't processed yet
105 if (Incoming.empty())
106 continue;
107
108 // Find the most recent reaching definition from a predecessor.
109 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
110 LiveRegs[Unit] = std::max(LiveRegs[Unit], Incoming[Unit]);
111 }
112
113 // Insert the most recent reaching definition we found.
114 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
115 if (LiveRegs[Unit] != ReachingDefDefaultVal)
116 MBBReachingDefs.append(MBBNumber, Unit, LiveRegs[Unit]);
117}
118
119void ReachingDefAnalysis::leaveBasicBlock(MachineBasicBlock *MBB) {
120 assert(!LiveRegs.empty() && "Must enter basic block first.");
121 unsigned MBBNumber = MBB->getNumber();
122 assert(MBBNumber < MBBOutRegsInfos.size() &&
123 "Unexpected basic block number.");
124 // Save register clearances at end of MBB - used by enterBasicBlock().
125 MBBOutRegsInfos[MBBNumber] = LiveRegs;
126
127 // While processing the basic block, we kept `Def` relative to the start
128 // of the basic block for convenience. However, future use of this information
129 // only cares about the clearance from the end of the block, so adjust
130 // everything to be relative to the end of the basic block.
131 for (int &OutLiveReg : MBBOutRegsInfos[MBBNumber])
132 if (OutLiveReg != ReachingDefDefaultVal)
133 OutLiveReg -= CurInstr;
134 LiveRegs.clear();
135}
136
137void ReachingDefAnalysis::processDefs(MachineInstr *MI) {
138 assert(!MI->isDebugInstr() && "Won't process debug instructions");
139
140 unsigned MBBNumber = MI->getParent()->getNumber();
141 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
142 "Unexpected basic block number.");
143
144 for (auto &MO : MI->operands()) {
145 if (MO.isFI()) {
146 int FrameIndex = MO.getIndex();
147 assert(FrameIndex >= 0 && "Can't handle negative frame indicies yet!");
148 if (!isFIDef(*MI, FrameIndex, TII))
149 continue;
150 if (MBBFrameObjsReachingDefs.contains(MBBNumber)) {
151 auto Frame2InstrIdx = MBBFrameObjsReachingDefs[MBBNumber];
152 if (Frame2InstrIdx.count(FrameIndex - ObjectIndexBegin) > 0)
153 Frame2InstrIdx[FrameIndex - ObjectIndexBegin].push_back(CurInstr);
154 else
155 Frame2InstrIdx[FrameIndex - ObjectIndexBegin] = {CurInstr};
156 } else {
157 MBBFrameObjsReachingDefs[MBBNumber] = {
158 {FrameIndex - ObjectIndexBegin, {CurInstr}}};
159 }
160 }
161 if (!isValidRegDef(MO))
162 continue;
163 for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
164 // This instruction explicitly defines the current reg unit.
165 LLVM_DEBUG(dbgs() << printRegUnit(Unit, TRI) << ":\t" << CurInstr << '\t'
166 << *MI);
167
168 // How many instructions since this reg unit was last written?
169 if (LiveRegs[Unit] != CurInstr) {
170 LiveRegs[Unit] = CurInstr;
171 MBBReachingDefs.append(MBBNumber, Unit, CurInstr);
172 }
173 }
174 }
175 InstIds[MI] = CurInstr;
176 ++CurInstr;
177}
178
179void ReachingDefAnalysis::reprocessBasicBlock(MachineBasicBlock *MBB) {
180 unsigned MBBNumber = MBB->getNumber();
181 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
182 "Unexpected basic block number.");
183
184 // Count number of non-debug instructions for end of block adjustment.
185 auto NonDbgInsts =
187 int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
188
189 // When reprocessing a block, the only thing we need to do is check whether
190 // there is now a more recent incoming reaching definition from a predecessor.
192 assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
193 "Should have pre-allocated MBBInfos for all MBBs");
194 const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
195 // Incoming may be empty for dead predecessors.
196 if (Incoming.empty())
197 continue;
198
199 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
200 int Def = Incoming[Unit];
201 if (Def == ReachingDefDefaultVal)
202 continue;
203
204 auto Defs = MBBReachingDefs.defs(MBBNumber, Unit);
205 if (!Defs.empty() && Defs.front() < 0) {
206 if (Defs.front() >= Def)
207 continue;
208
209 // Update existing reaching def from predecessor to a more recent one.
210 MBBReachingDefs.replaceFront(MBBNumber, Unit, Def);
211 } else {
212 // Insert new reaching def from predecessor.
213 MBBReachingDefs.prepend(MBBNumber, Unit, Def);
214 }
215
216 // Update reaching def at end of BB. Keep in mind that these are
217 // adjusted relative to the end of the basic block.
218 if (MBBOutRegsInfos[MBBNumber][Unit] < Def - NumInsts)
219 MBBOutRegsInfos[MBBNumber][Unit] = Def - NumInsts;
220 }
221 }
222}
223
224void ReachingDefAnalysis::processBasicBlock(
225 const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
226 MachineBasicBlock *MBB = TraversedMBB.MBB;
228 << (!TraversedMBB.IsDone ? ": incomplete\n"
229 : ": all preds known\n"));
230
231 if (!TraversedMBB.PrimaryPass) {
232 // Reprocess MBB that is part of a loop.
233 reprocessBasicBlock(MBB);
234 return;
235 }
236
237 enterBasicBlock(MBB);
238 for (MachineInstr &MI :
240 processDefs(&MI);
241 leaveBasicBlock(MBB);
242}
243
245 dbgs() << "RDA results for " << MF.getName() << "\n";
246 int Num = 0;
249 for (MachineBasicBlock &MBB : MF) {
250 for (MachineInstr &MI : MBB) {
251 for (MachineOperand &MO : MI.operands()) {
252 Register Reg;
253 if (MO.isFI()) {
254 int FrameIndex = MO.getIndex();
255 assert(FrameIndex >= 0 &&
256 "Can't handle negative frame indicies yet!");
257 Reg = Register::index2StackSlot(FrameIndex);
258 } else if (MO.isReg()) {
259 if (MO.isDef())
260 continue;
261 Reg = MO.getReg();
262 if (!Reg.isValid())
263 continue;
264 } else
265 continue;
266 Defs.clear();
267 getGlobalReachingDefs(&MI, Reg, Defs);
268 MO.print(dbgs(), TRI);
270 for (MachineInstr *Def : Defs)
271 Nums.push_back(InstToNumMap[Def]);
272 llvm::sort(Nums);
273 dbgs() << ":{ ";
274 for (int Num : Nums)
275 dbgs() << Num << " ";
276 dbgs() << "}\n";
277 }
278 dbgs() << Num << ": " << MI << "\n";
279 InstToNumMap[&MI] = Num;
280 ++Num;
281 }
282 }
283}
284
286 MF = &mf;
287 TRI = MF->getSubtarget().getRegisterInfo();
288 const TargetSubtargetInfo &STI = MF->getSubtarget();
289 TRI = STI.getRegisterInfo();
290 TII = STI.getInstrInfo();
291 LLVM_DEBUG(dbgs() << "********** REACHING DEFINITION ANALYSIS **********\n");
292 init();
293 traverse();
296 return false;
297}
298
300 // Clear the internal vectors.
301 MBBOutRegsInfos.clear();
302 MBBReachingDefs.clear();
303 MBBFrameObjsReachingDefs.clear();
304 InstIds.clear();
305 LiveRegs.clear();
306}
307
310 init();
311 traverse();
312}
313
315 NumRegUnits = TRI->getNumRegUnits();
316 NumStackObjects = MF->getFrameInfo().getNumObjects();
317 ObjectIndexBegin = MF->getFrameInfo().getObjectIndexBegin();
318 MBBReachingDefs.init(MF->getNumBlockIDs());
319 // Initialize the MBBOutRegsInfos
320 MBBOutRegsInfos.resize(MF->getNumBlockIDs());
321 LoopTraversal Traversal;
322 TraversedMBBOrder = Traversal.traverse(*MF);
323}
324
326 // Traverse the basic blocks.
327 for (LoopTraversal::TraversedMBBInfo TraversedMBB : TraversedMBBOrder)
328 processBasicBlock(TraversedMBB);
329#ifndef NDEBUG
330 // Make sure reaching defs are sorted and unique.
331 for (unsigned MBBNumber = 0, NumBlockIDs = MF->getNumBlockIDs();
332 MBBNumber != NumBlockIDs; ++MBBNumber) {
333 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
334 int LastDef = ReachingDefDefaultVal;
335 for (int Def : MBBReachingDefs.defs(MBBNumber, Unit)) {
336 assert(Def > LastDef && "Defs must be sorted and unique");
337 LastDef = Def;
338 }
339 }
340 }
341#endif
342}
343
345 assert(InstIds.count(MI) && "Unexpected machine instuction.");
346 int InstId = InstIds.lookup(MI);
347 int DefRes = ReachingDefDefaultVal;
348 unsigned MBBNumber = MI->getParent()->getNumber();
349 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
350 "Unexpected basic block number.");
351 int LatestDef = ReachingDefDefaultVal;
352
353 if (Reg.isStack()) {
354 int FrameIndex = Reg.stackSlotIndex();
355 for (int Def : MBBFrameObjsReachingDefs.lookup(MBBNumber).lookup(
356 FrameIndex - ObjectIndexBegin)) {
357 if (Def >= InstId)
358 break;
359 DefRes = Def;
360 }
361 LatestDef = std::max(LatestDef, DefRes);
362 return LatestDef;
363 }
364
365 for (MCRegUnit Unit : TRI->regunits(Reg)) {
366 for (int Def : MBBReachingDefs.defs(MBBNumber, Unit)) {
367 if (Def >= InstId)
368 break;
369 DefRes = Def;
370 }
371 LatestDef = std::max(LatestDef, DefRes);
372 }
373 return LatestDef;
374}
375
376MachineInstr *ReachingDefAnalysis::getReachingLocalMIDef(MachineInstr *MI,
377 Register Reg) const {
378 return hasLocalDefBefore(MI, Reg)
379 ? getInstFromId(MI->getParent(), getReachingDef(MI, Reg))
380 : nullptr;
381}
382
384 Register Reg) const {
385 MachineBasicBlock *ParentA = A->getParent();
386 MachineBasicBlock *ParentB = B->getParent();
387 if (ParentA != ParentB)
388 return false;
389
390 return getReachingDef(A, Reg) == getReachingDef(B, Reg);
391}
392
393MachineInstr *ReachingDefAnalysis::getInstFromId(MachineBasicBlock *MBB,
394 int InstId) const {
395 assert(static_cast<size_t>(MBB->getNumber()) <
396 MBBReachingDefs.numBlockIDs() &&
397 "Unexpected basic block number.");
398 assert(InstId < static_cast<int>(MBB->size()) &&
399 "Unexpected instruction id.");
400
401 if (InstId < 0)
402 return nullptr;
403
404 for (auto &MI : *MBB) {
405 auto F = InstIds.find(&MI);
406 if (F != InstIds.end() && F->second == InstId)
407 return &MI;
408 }
409
410 return nullptr;
411}
412
414 assert(InstIds.count(MI) && "Unexpected machine instuction.");
415 return InstIds.lookup(MI) - getReachingDef(MI, Reg);
416}
417
419 Register Reg) const {
420 return getReachingDef(MI, Reg) >= 0;
421}
422
424 InstSet &Uses) const {
425 MachineBasicBlock *MBB = Def->getParent();
427 while (++MI != MBB->end()) {
428 if (MI->isDebugInstr())
429 continue;
430
431 // If/when we find a new reaching def, we know that there's no more uses
432 // of 'Def'.
433 if (getReachingLocalMIDef(&*MI, Reg) != Def)
434 return;
435
436 for (auto &MO : MI->operands()) {
437 if (!isValidRegUseOf(MO, Reg, TRI))
438 continue;
439
440 Uses.insert(&*MI);
441 if (MO.isKill())
442 return;
443 }
444 }
445}
446
448 InstSet &Uses) const {
449 for (MachineInstr &MI :
451 for (auto &MO : MI.operands()) {
452 if (!isValidRegUseOf(MO, Reg, TRI))
453 continue;
454 if (getReachingDef(&MI, Reg) >= 0)
455 return false;
456 Uses.insert(&MI);
457 }
458 }
459 auto Last = MBB->getLastNonDebugInstr();
460 if (Last == MBB->end())
461 return true;
462 return isReachingDefLiveOut(&*Last, Reg);
463}
464
466 InstSet &Uses) const {
467 MachineBasicBlock *MBB = MI->getParent();
468
469 // Collect the uses that each def touches within the block.
471
472 // Handle live-out values.
473 if (auto *LiveOut = getLocalLiveOutMIDef(MI->getParent(), Reg)) {
474 if (LiveOut != MI)
475 return;
476
479 while (!ToVisit.empty()) {
481 if (Visited.count(MBB) || !MBB->isLiveIn(Reg))
482 continue;
483 if (getLiveInUses(MBB, Reg, Uses))
484 llvm::append_range(ToVisit, MBB->successors());
485 Visited.insert(MBB);
486 }
487 }
488}
489
491 InstSet &Defs) const {
492 if (auto *Def = getUniqueReachingMIDef(MI, Reg)) {
493 Defs.insert(Def);
494 return;
495 }
496
497 for (auto *MBB : MI->getParent()->predecessors())
498 getLiveOuts(MBB, Reg, Defs);
499}
500
502 InstSet &Defs) const {
504 getLiveOuts(MBB, Reg, Defs, VisitedBBs);
505}
506
508 InstSet &Defs,
509 BlockSet &VisitedBBs) const {
510 if (VisitedBBs.count(MBB))
511 return;
512
513 VisitedBBs.insert(MBB);
514 LiveRegUnits LiveRegs(*TRI);
515 LiveRegs.addLiveOuts(*MBB);
516 if (Reg.isPhysical() && LiveRegs.available(Reg))
517 return;
518
519 if (auto *Def = getLocalLiveOutMIDef(MBB, Reg))
520 Defs.insert(Def);
521 else
522 for (auto *Pred : MBB->predecessors())
523 getLiveOuts(Pred, Reg, Defs, VisitedBBs);
524}
525
527 Register Reg) const {
528 // If there's a local def before MI, return it.
529 MachineInstr *LocalDef = getReachingLocalMIDef(MI, Reg);
530 if (LocalDef && InstIds.lookup(LocalDef) < InstIds.lookup(MI))
531 return LocalDef;
532
534 MachineBasicBlock *Parent = MI->getParent();
535 for (auto *Pred : Parent->predecessors())
536 getLiveOuts(Pred, Reg, Incoming);
537
538 // Check that we have a single incoming value and that it does not
539 // come from the same block as MI - since it would mean that the def
540 // is executed after MI.
541 if (Incoming.size() == 1 && (*Incoming.begin())->getParent() != Parent)
542 return *Incoming.begin();
543 return nullptr;
544}
545
547 unsigned Idx) const {
548 assert(MI->getOperand(Idx).isReg() && "Expected register operand");
549 return getUniqueReachingMIDef(MI, MI->getOperand(Idx).getReg());
550}
551
553 MachineOperand &MO) const {
554 assert(MO.isReg() && "Expected register operand");
555 return getUniqueReachingMIDef(MI, MO.getReg());
556}
557
559 MachineBasicBlock *MBB = MI->getParent();
560 LiveRegUnits LiveRegs(*TRI);
561 LiveRegs.addLiveOuts(*MBB);
562
563 // Yes if the register is live out of the basic block.
564 if (!LiveRegs.available(Reg))
565 return true;
566
567 // Walk backwards through the block to see if the register is live at some
568 // point.
569 for (MachineInstr &Last :
571 LiveRegs.stepBackward(Last);
572 if (!LiveRegs.available(Reg))
573 return InstIds.lookup(&Last) > InstIds.lookup(MI);
574 }
575 return false;
576}
577
579 Register Reg) const {
580 MachineBasicBlock *MBB = MI->getParent();
581 auto Last = MBB->getLastNonDebugInstr();
582 if (Last != MBB->end() &&
583 getReachingDef(MI, Reg) != getReachingDef(&*Last, Reg))
584 return true;
585
586 if (auto *Def = getLocalLiveOutMIDef(MBB, Reg))
587 return Def == getReachingLocalMIDef(MI, Reg);
588
589 return false;
590}
591
593 Register Reg) const {
594 MachineBasicBlock *MBB = MI->getParent();
595 LiveRegUnits LiveRegs(*TRI);
596 LiveRegs.addLiveOuts(*MBB);
597 if (Reg.isPhysical() && LiveRegs.available(Reg))
598 return false;
599
600 auto Last = MBB->getLastNonDebugInstr();
601 int Def = getReachingDef(MI, Reg);
602 if (Last != MBB->end() && getReachingDef(&*Last, Reg) != Def)
603 return false;
604
605 // Finally check that the last instruction doesn't redefine the register.
606 for (auto &MO : Last->operands())
607 if (isValidRegDefOf(MO, Reg, TRI))
608 return false;
609
610 return true;
611}
612
614 Register Reg) const {
615 LiveRegUnits LiveRegs(*TRI);
616 LiveRegs.addLiveOuts(*MBB);
617 if (Reg.isPhysical() && LiveRegs.available(Reg))
618 return nullptr;
619
620 auto Last = MBB->getLastNonDebugInstr();
621 if (Last == MBB->end())
622 return nullptr;
623
624 if (Reg.isStack()) {
625 int FrameIndex = Reg.stackSlotIndex();
626 if (isFIDef(*Last, FrameIndex, TII))
627 return &*Last;
628 }
629
630 int Def = getReachingDef(&*Last, Reg);
631
632 for (auto &MO : Last->operands())
633 if (isValidRegDefOf(MO, Reg, TRI))
634 return &*Last;
635
636 return Def < 0 ? nullptr : getInstFromId(MBB, Def);
637}
638
640 return MI.mayLoadOrStore() || MI.mayRaiseFPException() ||
641 MI.hasUnmodeledSideEffects() || MI.isTerminator() ||
642 MI.isCall() || MI.isBarrier() || MI.isBranch() || MI.isReturn();
643}
644
645// Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
646// not define a register that is used by any instructions, after and including,
647// 'To'. These instructions also must not redefine any of Froms operands.
648template<typename Iterator>
649bool ReachingDefAnalysis::isSafeToMove(MachineInstr *From,
650 MachineInstr *To) const {
651 if (From->getParent() != To->getParent() || From == To)
652 return false;
653
654 SmallSet<int, 2> Defs;
655 // First check that From would compute the same value if moved.
656 for (auto &MO : From->operands()) {
657 if (!isValidReg(MO))
658 continue;
659 if (MO.isDef())
660 Defs.insert(MO.getReg());
661 else if (!hasSameReachingDef(From, To, MO.getReg()))
662 return false;
663 }
664
665 // Now walk checking that the rest of the instructions will compute the same
666 // value and that we're not overwriting anything. Don't move the instruction
667 // past any memory, control-flow or other ambiguous instructions.
668 for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
669 if (mayHaveSideEffects(*I))
670 return false;
671 for (auto &MO : I->operands())
672 if (MO.isReg() && MO.getReg() && Defs.count(MO.getReg()))
673 return false;
674 }
675 return true;
676}
677
679 MachineInstr *To) const {
680 using Iterator = MachineBasicBlock::iterator;
681 // Walk forwards until we find the instruction.
682 for (auto I = Iterator(From), E = From->getParent()->end(); I != E; ++I)
683 if (&*I == To)
684 return isSafeToMove<Iterator>(From, To);
685 return false;
686}
687
689 MachineInstr *To) const {
691 // Walk backwards until we find the instruction.
692 for (auto I = Iterator(From), E = From->getParent()->rend(); I != E; ++I)
693 if (&*I == To)
694 return isSafeToMove<Iterator>(From, To);
695 return false;
696}
697
699 InstSet &ToRemove) const {
702 return isSafeToRemove(MI, Visited, ToRemove, Ignore);
703}
704
705bool
707 InstSet &Ignore) const {
709 return isSafeToRemove(MI, Visited, ToRemove, Ignore);
710}
711
712bool
714 InstSet &ToRemove, InstSet &Ignore) const {
715 if (Visited.count(MI) || Ignore.count(MI))
716 return true;
717 else if (mayHaveSideEffects(*MI)) {
718 // Unless told to ignore the instruction, don't remove anything which has
719 // side effects.
720 return false;
721 }
722
723 Visited.insert(MI);
724 for (auto &MO : MI->operands()) {
725 if (!isValidRegDef(MO))
726 continue;
727
729 getGlobalUses(MI, MO.getReg(), Uses);
730
731 for (auto *I : Uses) {
732 if (Ignore.count(I) || ToRemove.count(I))
733 continue;
734 if (!isSafeToRemove(I, Visited, ToRemove, Ignore))
735 return false;
736 }
737 }
738 ToRemove.insert(MI);
739 return true;
740}
741
743 InstSet &Dead) const {
744 Dead.insert(MI);
745 auto IsDead = [this, &Dead](MachineInstr *Def, Register Reg) {
746 if (mayHaveSideEffects(*Def))
747 return false;
748
749 unsigned LiveDefs = 0;
750 for (auto &MO : Def->operands()) {
751 if (!isValidRegDef(MO))
752 continue;
753 if (!MO.isDead())
754 ++LiveDefs;
755 }
756
757 if (LiveDefs > 1)
758 return false;
759
761 getGlobalUses(Def, Reg, Uses);
762 return llvm::set_is_subset(Uses, Dead);
763 };
764
765 for (auto &MO : MI->operands()) {
766 if (!isValidRegUse(MO))
767 continue;
768 if (MachineInstr *Def = getMIOperand(MI, MO))
769 if (IsDead(Def, MO.getReg()))
770 collectKilledOperands(Def, Dead);
771 }
772}
773
775 Register Reg) const {
777 return isSafeToDefRegAt(MI, Reg, Ignore);
778}
779
781 InstSet &Ignore) const {
782 // Check for any uses of the register after MI.
783 if (isRegUsedAfter(MI, Reg)) {
784 if (auto *Def = getReachingLocalMIDef(MI, Reg)) {
786 getGlobalUses(Def, Reg, Uses);
788 return false;
789 } else
790 return false;
791 }
792
793 MachineBasicBlock *MBB = MI->getParent();
794 // Check for any defs after MI.
795 if (isRegDefinedAfter(MI, Reg)) {
797 for (auto E = MBB->end(); I != E; ++I) {
798 if (Ignore.count(&*I))
799 continue;
800 for (auto &MO : I->operands())
801 if (isValidRegDefOf(MO, Reg, TRI))
802 return false;
803 }
804 }
805 return true;
806}
aarch64 promote const
ReachingDefAnalysis InstSet & ToRemove
ReachingDefAnalysis InstSet InstSet & Ignore
MachineBasicBlock & MBB
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(...)
Definition: Debug.h:106
const HexagonInstrInfo * TII
hexagon gen pred
IRTranslator LLVM IR MI
A set of register units.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
static bool isValidRegUseOf(const MachineOperand &MO, Register Reg, const TargetRegisterInfo *TRI)
static bool mayHaveSideEffects(MachineInstr &MI)
static bool isFIDef(const MachineInstr &MI, int FrameIndex, const TargetInstrInfo *TII)
static bool isValidRegDef(const MachineOperand &MO)
static cl::opt< bool > PrintAllReachingDefs("print-all-reaching-defs", cl::Hidden, cl::desc("Used for test purpuses"), cl::Hidden)
static bool isValidRegDefOf(const MachineOperand &MO, Register Reg, const TargetRegisterInfo *TRI)
static bool isValidRegUse(const MachineOperand &MO)
#define DEBUG_TYPE
Remove Loads Into Fake Uses
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool IsDead
This file defines generic set operations that may be used on set's of different types,...
This file defines the SmallSet class.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:194
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:147
Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const override
If the specified machine instruction is a direct store to a stack slot, return the virtual or physica...
A set of register units used to track register liveness.
Definition: LiveRegUnits.h:30
bool available(MCPhysReg Reg) const
Returns true if no part of physical register Reg is live.
Definition: LiveRegUnits.h:116
void stepBackward(const MachineInstr &MI)
Updates liveness when stepping backwards over the instruction MI.
void addLiveOuts(const MachineBasicBlock &MBB)
Adds registers living out of block MBB.
This class provides the basic blocks traversal order used by passes like ReachingDefAnalysis and Exec...
Definition: LoopTraversal.h:65
TraversalOrder traverse(MachineFunction &MF)
void append(unsigned MBBNumber, unsigned Unit, int Def)
ArrayRef< ReachingDef > defs(unsigned MBBNumber, unsigned Unit) const
void replaceFront(unsigned MBBNumber, unsigned Unit, int Def)
void init(unsigned NumBlockIDs)
void prepend(unsigned MBBNumber, unsigned Unit, int Def)
void startBasicBlock(unsigned MBBNumber, unsigned NumRegUnits)
unsigned getNumRegUnits() const
Return the number of (native) register units in the target.
iterator_range< MCRegUnitIterator > regunits(MCRegister Reg) const
Returns an iterator range over all regunits for Reg.
instr_iterator instr_begin()
iterator_range< livein_iterator > liveins() const
reverse_instr_iterator instr_rbegin()
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
reverse_instr_iterator instr_rend()
iterator getLastNonDebugInstr(bool SkipPseudoOp=true)
Returns an iterator to the last non-debug instruction in the basic block, or end().
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
instr_iterator instr_end()
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
unsigned getNumObjects() const
Return the number of objects.
int getObjectIndexBegin() const
Return the minimum frame object index.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
Representation of each machine instruction.
Definition: MachineInstr.h:71
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:349
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
This class provides the reaching def analysis.
MachineInstr * getLocalLiveOutMIDef(MachineBasicBlock *MBB, Register Reg) const
Return the local MI that produces the live out value for Reg, or nullptr for a non-live out or non-lo...
void traverse()
Traverse the machine function, mapping definitions.
bool isSafeToMoveForwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved forwards to just before To.
bool isRegUsedAfter(MachineInstr *MI, Register Reg) const
Return whether the given register is used after MI, whether it's a local use or a live out.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
bool isSafeToRemove(MachineInstr *MI, InstSet &ToRemove) const
Return whether removing this instruction will have no effect on the program, returning the redundant ...
MachineInstr * getMIOperand(MachineInstr *MI, unsigned Idx) const
If a single MachineInstr creates the reaching definition, for MIs operand at Idx, then return it.
void printAllReachingDefs(MachineFunction &MF)
void reset()
Re-run the analysis.
int getReachingDef(MachineInstr *MI, Register Reg) const
Provides the instruction id of the closest reaching def instruction of Reg that reaches MI,...
void init()
Initialize data structures.
void getGlobalUses(MachineInstr *MI, Register Reg, InstSet &Uses) const
Collect the users of the value stored in Reg, which is defined by MI.
void collectKilledOperands(MachineInstr *MI, InstSet &Dead) const
Assuming MI is dead, recursively search the incoming operands which are killed by MI and collect thos...
bool isSafeToMoveBackwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved backwards to just after To.
void getLiveOuts(MachineBasicBlock *MBB, Register Reg, InstSet &Defs, BlockSet &VisitedBBs) const
Search MBB for a definition of Reg and insert it into Defs.
int getClearance(MachineInstr *MI, Register Reg) const
Provides the clearance - the number of instructions since the closest reaching def instuction of Reg ...
bool hasLocalDefBefore(MachineInstr *MI, Register Reg) const
Provide whether the register has been defined in the same basic block as, and before,...
bool isReachingDefLiveOut(MachineInstr *MI, Register Reg) const
Return whether the reaching def for MI also is live out of its parent block.
bool getLiveInUses(MachineBasicBlock *MBB, Register Reg, InstSet &Uses) const
For the given block, collect the instructions that use the live-in value of the provided register.
bool isSafeToDefRegAt(MachineInstr *MI, Register Reg) const
Return whether a MachineInstr could be inserted at MI and safely define the given register without af...
bool hasSameReachingDef(MachineInstr *A, MachineInstr *B, Register Reg) const
Return whether A and B use the same def of Reg.
void getReachingLocalUses(MachineInstr *MI, Register Reg, InstSet &Uses) const
Provides the uses, in the same block as MI, of register that MI defines.
bool isRegDefinedAfter(MachineInstr *MI, Register Reg) const
Return whether the given register is defined after MI.
MachineInstr * getUniqueReachingMIDef(MachineInstr *MI, Register Reg) const
If a single MachineInstr creates the reaching definition, then return it.
void getGlobalReachingDefs(MachineInstr *MI, Register Reg, InstSet &Defs) const
Collect all possible definitions of the value stored in Reg, which is used by MI.
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static Register index2StackSlot(int FI)
Convert a non-negative frame index to a stack slot register value.
Definition: Register.h:58
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:363
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:452
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:384
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:132
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:175
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:181
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
void resize(size_type N)
Definition: SmallVector.h:638
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
@ FrameIndex
Definition: ISDOpcodes.h:80
NodeAddr< DefNode * > Def
Definition: RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Printable printRegUnit(unsigned Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2115
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1664
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
MachineBasicBlock * MBB
The basic block.
Definition: LoopTraversal.h:89
bool IsDone
True if the block that is ready for its final round of processing.
Definition: LoopTraversal.h:95
bool PrimaryPass
True if this is the first time we process the basic block.
Definition: LoopTraversal.h:92