LLVM 22.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
23AnalysisKey ReachingDefAnalysis::Key;
24
32
36 MFPropsModifier _(*this, MF);
37
38 auto &RDI = MFAM.getResult<ReachingDefAnalysis>(MF);
39 OS << "Reaching definitions for for machine function: " << MF.getName()
40 << '\n';
41 RDI.print(OS);
43}
44
46 "Reaching Definitions Analysis", false, true)
47
49
53}
54
58
61 MachineFunctionAnalysisManager::Invalidator &) {
62 // Check whether the analysis, all analyses on machine functions, or the
63 // machine function's CFG have been preserved.
64 auto PAC = PA.getChecker<ReachingDefAnalysis>();
65 return !PAC.preserved() &&
66 !PAC.preservedSet<AllAnalysesOn<MachineFunction>>() &&
67 !PAC.preservedSet<CFGAnalyses>();
68}
69
74
79
80static bool isValidReg(const MachineOperand &MO) {
81 return MO.isReg() && MO.getReg();
82}
83
84static bool isValidRegUse(const MachineOperand &MO) {
85 return isValidReg(MO) && MO.isUse();
86}
87
89 const TargetRegisterInfo *TRI) {
90 if (!isValidRegUse(MO))
91 return false;
92 return TRI->regsOverlap(MO.getReg(), Reg);
93}
94
95static bool isValidRegDef(const MachineOperand &MO) {
96 return isValidReg(MO) && MO.isDef();
97}
98
100 const TargetRegisterInfo *TRI) {
101 if (!isValidRegDef(MO))
102 return false;
103 return TRI->regsOverlap(MO.getReg(), Reg);
104}
105
106static bool isFIDef(const MachineInstr &MI, int FrameIndex,
107 const TargetInstrInfo *TII) {
108 int DefFrameIndex = 0;
109 int SrcFrameIndex = 0;
110 if (TII->isStoreToStackSlot(MI, DefFrameIndex) ||
111 TII->isStackSlotCopy(MI, DefFrameIndex, SrcFrameIndex))
112 return DefFrameIndex == FrameIndex;
113 return false;
114}
115
116void ReachingDefInfo::enterBasicBlock(MachineBasicBlock *MBB) {
117 unsigned MBBNumber = MBB->getNumber();
118 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
119 "Unexpected basic block number.");
120 MBBReachingDefs.startBasicBlock(MBBNumber, NumRegUnits);
121
122 // Reset instruction counter in each basic block.
123 CurInstr = 0;
124
125 // Set up LiveRegs to represent registers entering MBB.
126 // Default values are 'nothing happened a long time ago'.
127 if (LiveRegs.empty())
128 LiveRegs.assign(NumRegUnits, ReachingDefDefaultVal);
129
130 // This is the entry block.
131 if (MBB->pred_empty()) {
132 for (const auto &LI : MBB->liveins()) {
133 for (MCRegUnit Unit : TRI->regunits(LI.PhysReg)) {
134 // Treat function live-ins as if they were defined just before the first
135 // instruction. Usually, function arguments are set up immediately
136 // before the call.
137 if (LiveRegs[Unit] != -1) {
138 LiveRegs[Unit] = -1;
139 MBBReachingDefs.append(MBBNumber, Unit, -1);
140 }
141 }
142 }
143 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": entry\n");
144 return;
145 }
146
147 // Try to coalesce live-out registers from predecessors.
148 for (MachineBasicBlock *pred : MBB->predecessors()) {
149 assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
150 "Should have pre-allocated MBBInfos for all MBBs");
151 const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
152 // Incoming is null if this is a backedge from a BB
153 // we haven't processed yet
154 if (Incoming.empty())
155 continue;
156
157 // Find the most recent reaching definition from a predecessor.
158 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
159 LiveRegs[Unit] = std::max(LiveRegs[Unit], Incoming[Unit]);
160 }
161
162 // Insert the most recent reaching definition we found.
163 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
164 if (LiveRegs[Unit] != ReachingDefDefaultVal)
165 MBBReachingDefs.append(MBBNumber, Unit, LiveRegs[Unit]);
166}
167
168void ReachingDefInfo::leaveBasicBlock(MachineBasicBlock *MBB) {
169 assert(!LiveRegs.empty() && "Must enter basic block first.");
170 unsigned MBBNumber = MBB->getNumber();
171 assert(MBBNumber < MBBOutRegsInfos.size() &&
172 "Unexpected basic block number.");
173 // Save register clearances at end of MBB - used by enterBasicBlock().
174 MBBOutRegsInfos[MBBNumber] = LiveRegs;
175
176 // While processing the basic block, we kept `Def` relative to the start
177 // of the basic block for convenience. However, future use of this information
178 // only cares about the clearance from the end of the block, so adjust
179 // everything to be relative to the end of the basic block.
180 for (int &OutLiveReg : MBBOutRegsInfos[MBBNumber])
181 if (OutLiveReg != ReachingDefDefaultVal)
182 OutLiveReg -= CurInstr;
183 LiveRegs.clear();
184}
185
186void ReachingDefInfo::processDefs(MachineInstr *MI) {
187 assert(!MI->isDebugInstr() && "Won't process debug instructions");
188
189 unsigned MBBNumber = MI->getParent()->getNumber();
190 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
191 "Unexpected basic block number.");
192
193 for (auto &MO : MI->operands()) {
194 if (MO.isFI()) {
195 int FrameIndex = MO.getIndex();
196 if (!isFIDef(*MI, FrameIndex, TII))
197 continue;
198 MBBFrameObjsReachingDefs[{MBBNumber, FrameIndex}].push_back(CurInstr);
199 }
200 if (!isValidRegDef(MO))
201 continue;
202 for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
203 // This instruction explicitly defines the current reg unit.
204 LLVM_DEBUG(dbgs() << printRegUnit(Unit, TRI) << ":\t" << CurInstr << '\t'
205 << *MI);
206
207 // How many instructions since this reg unit was last written?
208 if (LiveRegs[Unit] != CurInstr) {
209 LiveRegs[Unit] = CurInstr;
210 MBBReachingDefs.append(MBBNumber, Unit, CurInstr);
211 }
212 }
213 }
214 InstIds[MI] = CurInstr;
215 ++CurInstr;
216}
217
218void ReachingDefInfo::reprocessBasicBlock(MachineBasicBlock *MBB) {
219 unsigned MBBNumber = MBB->getNumber();
220 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
221 "Unexpected basic block number.");
222
223 // Count number of non-debug instructions for end of block adjustment.
224 auto NonDbgInsts =
226 int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
227
228 // When reprocessing a block, the only thing we need to do is check whether
229 // there is now a more recent incoming reaching definition from a predecessor.
230 for (MachineBasicBlock *pred : MBB->predecessors()) {
231 assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
232 "Should have pre-allocated MBBInfos for all MBBs");
233 const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
234 // Incoming may be empty for dead predecessors.
235 if (Incoming.empty())
236 continue;
237
238 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
239 int Def = Incoming[Unit];
240 if (Def == ReachingDefDefaultVal)
241 continue;
242
243 auto Defs = MBBReachingDefs.defs(MBBNumber, Unit);
244 if (!Defs.empty() && Defs.front() < 0) {
245 if (Defs.front() >= Def)
246 continue;
247
248 // Update existing reaching def from predecessor to a more recent one.
249 MBBReachingDefs.replaceFront(MBBNumber, Unit, Def);
250 } else {
251 // Insert new reaching def from predecessor.
252 MBBReachingDefs.prepend(MBBNumber, Unit, Def);
253 }
254
255 // Update reaching def at end of BB. Keep in mind that these are
256 // adjusted relative to the end of the basic block.
257 if (MBBOutRegsInfos[MBBNumber][Unit] < Def - NumInsts)
258 MBBOutRegsInfos[MBBNumber][Unit] = Def - NumInsts;
259 }
260 }
261}
262
263void ReachingDefInfo::processBasicBlock(
264 const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
265 MachineBasicBlock *MBB = TraversedMBB.MBB;
267 << (!TraversedMBB.IsDone ? ": incomplete\n"
268 : ": all preds known\n"));
269
270 if (!TraversedMBB.PrimaryPass) {
271 // Reprocess MBB that is part of a loop.
272 reprocessBasicBlock(MBB);
273 return;
274 }
275
276 enterBasicBlock(MBB);
277 for (MachineInstr &MI :
279 processDefs(&MI);
280 leaveBasicBlock(MBB);
281}
282
284 MF = &mf;
285 const TargetSubtargetInfo &STI = MF->getSubtarget();
286 TRI = STI.getRegisterInfo();
287 TII = STI.getInstrInfo();
288 LLVM_DEBUG(dbgs() << "********** REACHING DEFINITION ANALYSIS **********\n");
289 init();
290 traverse();
291}
292
294 OS << "RDA results for " << MF->getName() << "\n";
295 int Num = 0;
298 for (MachineBasicBlock &MBB : *MF) {
299 for (MachineInstr &MI : MBB) {
300 for (MachineOperand &MO : MI.operands()) {
301 Register Reg;
302 if (MO.isFI()) {
303 int FrameIndex = MO.getIndex();
304 Reg = Register::index2StackSlot(FrameIndex);
305 } else if (MO.isReg()) {
306 if (MO.isDef())
307 continue;
308 Reg = MO.getReg();
309 if (!Reg.isValid())
310 continue;
311 } else
312 continue;
313 Defs.clear();
314 getGlobalReachingDefs(&MI, Reg, Defs);
315 MO.print(OS, TRI);
317 for (MachineInstr *Def : Defs)
318 Nums.push_back(InstToNumMap[Def]);
319 llvm::sort(Nums);
320 OS << ":{ ";
321 for (int Num : Nums)
322 OS << Num << " ";
323 OS << "}\n";
324 }
325 OS << Num << ": " << MI << "\n";
326 InstToNumMap[&MI] = Num;
327 ++Num;
328 }
329 }
330}
331
333 RDI.run(mf);
334 return false;
335}
336
338 // Clear the internal vectors.
339 MBBOutRegsInfos.clear();
340 MBBReachingDefs.clear();
341 MBBFrameObjsReachingDefs.clear();
342 InstIds.clear();
343 LiveRegs.clear();
344}
345
348 init();
349 traverse();
350}
351
353 NumRegUnits = TRI->getNumRegUnits();
354 NumStackObjects = MF->getFrameInfo().getNumObjects();
355 ObjectIndexBegin = MF->getFrameInfo().getObjectIndexBegin();
356 MBBReachingDefs.init(MF->getNumBlockIDs());
357 // Initialize the MBBOutRegsInfos
358 MBBOutRegsInfos.resize(MF->getNumBlockIDs());
359 LoopTraversal Traversal;
360 TraversedMBBOrder = Traversal.traverse(*MF);
361}
362
364 // Traverse the basic blocks.
365 for (LoopTraversal::TraversedMBBInfo TraversedMBB : TraversedMBBOrder)
366 processBasicBlock(TraversedMBB);
367#ifndef NDEBUG
368 // Make sure reaching defs are sorted and unique.
369 for (unsigned MBBNumber = 0, NumBlockIDs = MF->getNumBlockIDs();
370 MBBNumber != NumBlockIDs; ++MBBNumber) {
371 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
372 int LastDef = ReachingDefDefaultVal;
373 for (int Def : MBBReachingDefs.defs(MBBNumber, Unit)) {
374 assert(Def > LastDef && "Defs must be sorted and unique");
375 LastDef = Def;
376 }
377 }
378 }
379#endif
380}
381
383 assert(InstIds.count(MI) && "Unexpected machine instuction.");
384 int InstId = InstIds.lookup(MI);
385 int DefRes = ReachingDefDefaultVal;
386 unsigned MBBNumber = MI->getParent()->getNumber();
387 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
388 "Unexpected basic block number.");
389 int LatestDef = ReachingDefDefaultVal;
390
391 if (Reg.isStack()) {
392 // Check that there was a reaching def.
393 int FrameIndex = Reg.stackSlotIndex();
394 auto Lookup = MBBFrameObjsReachingDefs.find({MBBNumber, FrameIndex});
395 if (Lookup == MBBFrameObjsReachingDefs.end())
396 return LatestDef;
397 auto &Defs = Lookup->second;
398 for (int Def : Defs) {
399 if (Def >= InstId)
400 break;
401 DefRes = Def;
402 }
403 LatestDef = std::max(LatestDef, DefRes);
404 return LatestDef;
405 }
406
407 for (MCRegUnit Unit : TRI->regunits(Reg)) {
408 for (int Def : MBBReachingDefs.defs(MBBNumber, Unit)) {
409 if (Def >= InstId)
410 break;
411 DefRes = Def;
412 }
413 LatestDef = std::max(LatestDef, DefRes);
414 }
415 return LatestDef;
416}
417
418MachineInstr *ReachingDefInfo::getReachingLocalMIDef(MachineInstr *MI,
419 Register Reg) const {
420 return hasLocalDefBefore(MI, Reg)
421 ? getInstFromId(MI->getParent(), getReachingDef(MI, Reg))
422 : nullptr;
423}
424
426 Register Reg) const {
427 MachineBasicBlock *ParentA = A->getParent();
428 MachineBasicBlock *ParentB = B->getParent();
429 if (ParentA != ParentB)
430 return false;
431
432 return getReachingDef(A, Reg) == getReachingDef(B, Reg);
433}
434
435MachineInstr *ReachingDefInfo::getInstFromId(MachineBasicBlock *MBB,
436 int InstId) const {
437 assert(static_cast<size_t>(MBB->getNumber()) <
438 MBBReachingDefs.numBlockIDs() &&
439 "Unexpected basic block number.");
440 assert(InstId < static_cast<int>(MBB->size()) &&
441 "Unexpected instruction id.");
442
443 if (InstId < 0)
444 return nullptr;
445
446 for (auto &MI : *MBB) {
447 auto F = InstIds.find(&MI);
448 if (F != InstIds.end() && F->second == InstId)
449 return &MI;
450 }
451
452 return nullptr;
453}
454
456 assert(InstIds.count(MI) && "Unexpected machine instuction.");
457 return InstIds.lookup(MI) - getReachingDef(MI, Reg);
458}
459
461 return getReachingDef(MI, Reg) >= 0;
462}
463
465 InstSet &Uses) const {
466 MachineBasicBlock *MBB = Def->getParent();
468 while (++MI != MBB->end()) {
469 if (MI->isDebugInstr())
470 continue;
471
472 // If/when we find a new reaching def, we know that there's no more uses
473 // of 'Def'.
474 if (getReachingLocalMIDef(&*MI, Reg) != Def)
475 return;
476
477 for (auto &MO : MI->operands()) {
478 if (!isValidRegUseOf(MO, Reg, TRI))
479 continue;
480
481 Uses.insert(&*MI);
482 if (MO.isKill())
483 return;
484 }
485 }
486}
487
489 InstSet &Uses) const {
490 for (MachineInstr &MI :
491 instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end())) {
492 for (auto &MO : MI.operands()) {
493 if (!isValidRegUseOf(MO, Reg, TRI))
494 continue;
495 if (getReachingDef(&MI, Reg) >= 0)
496 return false;
497 Uses.insert(&MI);
498 }
499 }
500 auto Last = MBB->getLastNonDebugInstr();
501 if (Last == MBB->end())
502 return true;
503 return isReachingDefLiveOut(&*Last, Reg);
504}
505
507 InstSet &Uses) const {
508 MachineBasicBlock *MBB = MI->getParent();
509
510 // Collect the uses that each def touches within the block.
512
513 // Handle live-out values.
514 if (auto *LiveOut = getLocalLiveOutMIDef(MI->getParent(), Reg)) {
515 if (LiveOut != MI)
516 return;
517
518 SmallVector<MachineBasicBlock *, 4> ToVisit(MBB->successors());
520 while (!ToVisit.empty()) {
522 if (Visited.count(MBB) || !MBB->isLiveIn(Reg))
523 continue;
524 if (getLiveInUses(MBB, Reg, Uses))
525 llvm::append_range(ToVisit, MBB->successors());
526 Visited.insert(MBB);
527 }
528 }
529}
530
532 InstSet &Defs) const {
533 if (auto *Def = getUniqueReachingMIDef(MI, Reg)) {
534 Defs.insert(Def);
535 return;
536 }
537
538 for (auto *MBB : MI->getParent()->predecessors())
539 getLiveOuts(MBB, Reg, Defs);
540}
541
543 InstSet &Defs) const {
545 getLiveOuts(MBB, Reg, Defs, VisitedBBs);
546}
547
549 InstSet &Defs, BlockSet &VisitedBBs) const {
550 if (VisitedBBs.count(MBB))
551 return;
552
553 VisitedBBs.insert(MBB);
554 LiveRegUnits LiveRegs(*TRI);
555 LiveRegs.addLiveOuts(*MBB);
556 if (Reg.isPhysical() && LiveRegs.available(Reg))
557 return;
558
559 if (auto *Def = getLocalLiveOutMIDef(MBB, Reg))
560 Defs.insert(Def);
561 else
562 for (auto *Pred : MBB->predecessors())
563 getLiveOuts(Pred, Reg, Defs, VisitedBBs);
564}
565
567 Register Reg) const {
568 // If there's a local def before MI, return it.
569 MachineInstr *LocalDef = getReachingLocalMIDef(MI, Reg);
570 if (LocalDef && InstIds.lookup(LocalDef) < InstIds.lookup(MI))
571 return LocalDef;
572
574 MachineBasicBlock *Parent = MI->getParent();
575 for (auto *Pred : Parent->predecessors())
576 getLiveOuts(Pred, Reg, Incoming);
577
578 // Check that we have a single incoming value and that it does not
579 // come from the same block as MI - since it would mean that the def
580 // is executed after MI.
581 if (Incoming.size() == 1 && (*Incoming.begin())->getParent() != Parent)
582 return *Incoming.begin();
583 return nullptr;
584}
585
587 unsigned Idx) const {
588 assert(MI->getOperand(Idx).isReg() && "Expected register operand");
589 return getUniqueReachingMIDef(MI, MI->getOperand(Idx).getReg());
590}
591
593 MachineOperand &MO) const {
594 assert(MO.isReg() && "Expected register operand");
595 return getUniqueReachingMIDef(MI, MO.getReg());
596}
597
599 MachineBasicBlock *MBB = MI->getParent();
600 LiveRegUnits LiveRegs(*TRI);
601 LiveRegs.addLiveOuts(*MBB);
602
603 // Yes if the register is live out of the basic block.
604 if (!LiveRegs.available(Reg))
605 return true;
606
607 // Walk backwards through the block to see if the register is live at some
608 // point.
609 for (MachineInstr &Last :
610 instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
611 LiveRegs.stepBackward(Last);
612 if (!LiveRegs.available(Reg))
613 return InstIds.lookup(&Last) > InstIds.lookup(MI);
614 }
615 return false;
616}
617
619 MachineBasicBlock *MBB = MI->getParent();
620 auto Last = MBB->getLastNonDebugInstr();
621 if (Last != MBB->end() &&
622 getReachingDef(MI, Reg) != getReachingDef(&*Last, Reg))
623 return true;
624
625 if (auto *Def = getLocalLiveOutMIDef(MBB, Reg))
626 return Def == getReachingLocalMIDef(MI, Reg);
627
628 return false;
629}
630
632 Register Reg) const {
633 MachineBasicBlock *MBB = MI->getParent();
634 LiveRegUnits LiveRegs(*TRI);
635 LiveRegs.addLiveOuts(*MBB);
636 if (Reg.isPhysical() && LiveRegs.available(Reg))
637 return false;
638
639 auto Last = MBB->getLastNonDebugInstr();
640 int Def = getReachingDef(MI, Reg);
641 if (Last != MBB->end() && getReachingDef(&*Last, Reg) != Def)
642 return false;
643
644 // Finally check that the last instruction doesn't redefine the register.
645 for (auto &MO : Last->operands())
646 if (isValidRegDefOf(MO, Reg, TRI))
647 return false;
648
649 return true;
650}
651
653 Register Reg) const {
654 LiveRegUnits LiveRegs(*TRI);
655 LiveRegs.addLiveOuts(*MBB);
656 if (Reg.isPhysical() && LiveRegs.available(Reg))
657 return nullptr;
658
659 auto Last = MBB->getLastNonDebugInstr();
660 if (Last == MBB->end())
661 return nullptr;
662
663 if (Reg.isStack()) {
664 int FrameIndex = Reg.stackSlotIndex();
665 if (isFIDef(*Last, FrameIndex, TII))
666 return &*Last;
667 }
668
669 int Def = getReachingDef(&*Last, Reg);
670
671 for (auto &MO : Last->operands())
672 if (isValidRegDefOf(MO, Reg, TRI))
673 return &*Last;
674
675 return Def < 0 ? nullptr : getInstFromId(MBB, Def);
676}
677
679 return MI.mayLoadOrStore() || MI.mayRaiseFPException() ||
680 MI.hasUnmodeledSideEffects() || MI.isTerminator() ||
681 MI.isCall() || MI.isBarrier() || MI.isBranch() || MI.isReturn();
682}
683
684// Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
685// not define a register that is used by any instructions, after and including,
686// 'To'. These instructions also must not redefine any of Froms operands.
687template <typename Iterator>
688bool ReachingDefInfo::isSafeToMove(MachineInstr *From, MachineInstr *To) const {
689 if (From->getParent() != To->getParent() || From == To)
690 return false;
691
692 SmallSet<Register, 2> Defs;
693 // First check that From would compute the same value if moved.
694 for (auto &MO : From->operands()) {
695 if (!isValidReg(MO))
696 continue;
697 if (MO.isDef())
698 Defs.insert(MO.getReg());
699 else if (!hasSameReachingDef(From, To, MO.getReg()))
700 return false;
701 }
702
703 // Now walk checking that the rest of the instructions will compute the same
704 // value and that we're not overwriting anything. Don't move the instruction
705 // past any memory, control-flow or other ambiguous instructions.
706 for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
707 if (mayHaveSideEffects(*I))
708 return false;
709 for (auto &MO : I->operands())
710 if (MO.isReg() && MO.getReg() && Defs.count(MO.getReg()))
711 return false;
712 }
713 return true;
714}
715
717 MachineInstr *To) const {
718 using Iterator = MachineBasicBlock::iterator;
719 // Walk forwards until we find the instruction.
720 for (auto I = Iterator(From), E = From->getParent()->end(); I != E; ++I)
721 if (&*I == To)
722 return isSafeToMove<Iterator>(From, To);
723 return false;
724}
725
727 MachineInstr *To) const {
729 // Walk backwards until we find the instruction.
730 for (auto I = Iterator(From), E = From->getParent()->rend(); I != E; ++I)
731 if (&*I == To)
732 return isSafeToMove<Iterator>(From, To);
733 return false;
734}
735
742
744 InstSet &Ignore) const {
746 return isSafeToRemove(MI, Visited, ToRemove, Ignore);
747}
748
749bool ReachingDefInfo::isSafeToRemove(MachineInstr *MI, InstSet &Visited,
750 InstSet &ToRemove, InstSet &Ignore) const {
751 if (Visited.count(MI) || Ignore.count(MI))
752 return true;
753 else if (mayHaveSideEffects(*MI)) {
754 // Unless told to ignore the instruction, don't remove anything which has
755 // side effects.
756 return false;
757 }
758
759 Visited.insert(MI);
760 for (auto &MO : MI->operands()) {
761 if (!isValidRegDef(MO))
762 continue;
763
765 getGlobalUses(MI, MO.getReg(), Uses);
766
767 for (auto *I : Uses) {
768 if (Ignore.count(I) || ToRemove.count(I))
769 continue;
770 if (!isSafeToRemove(I, Visited, ToRemove, Ignore))
771 return false;
772 }
773 }
774 ToRemove.insert(MI);
775 return true;
776}
777
779 InstSet &Dead) const {
780 Dead.insert(MI);
781 auto IsDead = [this, &Dead](MachineInstr *Def, Register Reg) {
782 if (mayHaveSideEffects(*Def))
783 return false;
784
785 unsigned LiveDefs = 0;
786 for (auto &MO : Def->operands()) {
787 if (!isValidRegDef(MO))
788 continue;
789 if (!MO.isDead())
790 ++LiveDefs;
791 }
792
793 if (LiveDefs > 1)
794 return false;
795
797 getGlobalUses(Def, Reg, Uses);
798 return llvm::set_is_subset(Uses, Dead);
799 };
800
801 for (auto &MO : MI->operands()) {
802 if (!isValidRegUse(MO))
803 continue;
804 if (MachineInstr *Def = getMIOperand(MI, MO))
805 if (IsDead(Def, MO.getReg()))
806 collectKilledOperands(Def, Dead);
807 }
808}
809
814
816 InstSet &Ignore) const {
817 // Check for any uses of the register after MI.
818 if (isRegUsedAfter(MI, Reg)) {
819 if (auto *Def = getReachingLocalMIDef(MI, Reg)) {
821 getGlobalUses(Def, Reg, Uses);
823 return false;
824 } else
825 return false;
826 }
827
828 MachineBasicBlock *MBB = MI->getParent();
829 // Check for any defs after MI.
830 if (isRegDefinedAfter(MI, Reg)) {
832 for (auto E = MBB->end(); I != E; ++I) {
833 if (Ignore.count(&*I))
834 continue;
835 for (auto &MO : I->operands())
836 if (isValidRegDefOf(MO, Reg, TRI))
837 return false;
838 }
839 }
840 return true;
841}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ReachingDefInfo & RDI
ReachingDefInfo InstSet InstSet & Ignore
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock & MBB
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
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
Register Reg
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool isValidRegUseOf(const MachineOperand &MO, Register Reg, const TargetRegisterInfo *TRI)
static bool mayHaveSideEffects(MachineInstr &MI)
static bool isValidReg(const MachineOperand &MO)
static bool isFIDef(const MachineInstr &MI, int FrameIndex, const TargetInstrInfo *TII)
static bool isValidRegDef(const MachineOperand &MO)
static bool isValidRegDefOf(const MachineOperand &MO, Register Reg, const TargetRegisterInfo *TRI)
static bool isValidRegUse(const MachineOperand &MO)
Remove Loads Into Fake Uses
bool IsDead
This file defines generic set operations that may be used on set's of different types,...
This file defines the SmallSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
A set of register units used to track register liveness.
This class provides the basic blocks traversal order used by passes like ReachingDefAnalysis and Exec...
TraversalOrder traverse(MachineFunction &MF)
An RAII based helper class to modify MachineFunctionProperties when running pass.
iterator_range< livein_iterator > liveins() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Properties which a MachineFunction may have at a given point in time.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
mop_range operands()
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.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
bool runOnMachineFunction(MachineFunction &F) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
MachineFunctionProperties getRequiredProperties() const override
This class provides the reaching def analysis.
MachineInstr * getUniqueReachingMIDef(MachineInstr *MI, Register Reg) const
If a single MachineInstr creates the reaching definition, then return it.
bool isReachingDefLiveOut(MachineInstr *MI, Register Reg) const
Return whether the reaching def for MI also is live out of its parent block.
bool isSafeToMoveForwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved forwards to just before To.
int getReachingDef(MachineInstr *MI, Register Reg) const
Provides the instruction id of the closest reaching def instruction of Reg that reaches MI,...
void run(MachineFunction &mf)
void getReachingLocalUses(MachineInstr *MI, Register Reg, InstSet &Uses) const
Provides the uses, in the same block as MI, of register that MI defines.
int getClearance(MachineInstr *MI, Register Reg) const
Provides the clearance - the number of instructions since the closest reaching def instuction of Reg ...
bool isRegDefinedAfter(MachineInstr *MI, Register Reg) const
Return whether the given register is defined after MI.
void init()
Initialize data structures.
void print(raw_ostream &OS)
bool hasLocalDefBefore(MachineInstr *MI, Register Reg) const
Provide whether the register has been defined in the same basic block as, and before,...
void reset()
Re-run the analysis.
void getGlobalUses(MachineInstr *MI, Register Reg, InstSet &Uses) const
Collect the users of the value stored in Reg, which is defined by MI.
MachineInstr * getMIOperand(MachineInstr *MI, unsigned Idx) const
If a single MachineInstr creates the reaching definition, for MIs operand at Idx, then return it.
void getLiveOuts(MachineBasicBlock *MBB, Register Reg, InstSet &Defs, BlockSet &VisitedBBs) const
Search MBB for a definition of Reg and insert it into Defs.
void traverse()
Traverse the machine function, mapping definitions.
bool isSafeToMoveBackwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved backwards to just after To.
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 hasSameReachingDef(MachineInstr *A, MachineInstr *B, Register Reg) const
Return whether A and B use the same def of Reg.
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 getGlobalReachingDefs(MachineInstr *MI, Register Reg, InstSet &Defs) const
Collect all possible definitions of the value stored in Reg, which is used by MI.
bool isSafeToRemove(MachineInstr *MI, InstSet &ToRemove) const
Return whether removing this instruction will have no effect on the program, returning the redundant ...
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...
bool invalidate(MachineFunction &F, const PreservedAnalyses &PA, MachineFunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
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...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2StackSlot(int FI)
Convert a non-negative frame index to a stack slot register value.
Definition Register.h:51
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
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:183
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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 TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void initializeReachingDefInfoWrapperPassPass(PassRegistry &)
LLVM_ABI 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:2136
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1622
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
unsigned MCRegUnit
Register units are used to compute register aliasing.
Definition MCRegister.h:30
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
MachineBasicBlock * MBB
The basic block.
bool IsDone
True if the block that is ready for its final round of processing.
bool PrimaryPass
True if this is the first time we process the basic block.