LLVM 24.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"
16#include "llvm/Support/Debug.h"
17
18using namespace llvm;
19
20#define DEBUG_TYPE "reaching-defs-analysis"
21
22AnalysisKey ReachingDefAnalysis::Key;
23
31
35 MFPropsModifier _(*this, MF);
36
37 auto &RDI = MFAM.getResult<ReachingDefAnalysis>(MF);
38 OS << "Reaching definitions for for machine function: " << MF.getName()
39 << '\n';
40 RDI.print(OS);
42}
43
45 "Reaching Definitions Analysis", false, true)
46
48
50 : MachineFunctionPass(ID) {}
51
55
58 MachineFunctionAnalysisManager::Invalidator &) {
59 // Check whether the analysis, all analyses on machine functions, or the
60 // machine function's CFG have been preserved.
61 auto PAC = PA.getChecker<ReachingDefAnalysis>();
62 return !PAC.preserved() &&
63 !PAC.preservedSet<AllAnalysesOn<MachineFunction>>() &&
64 !PAC.preservedSet<CFGAnalyses>();
65}
66
71
76
77static bool isValidReg(const MachineOperand &MO) {
78 return MO.isReg() && MO.getReg();
79}
80
81static bool isValidRegUse(const MachineOperand &MO) {
82 return isValidReg(MO) && MO.isUse();
83}
84
86 const TargetRegisterInfo *TRI) {
87 if (!isValidRegUse(MO))
88 return false;
89 return TRI->regsOverlap(MO.getReg(), Reg);
90}
91
92static bool isValidRegDef(const MachineOperand &MO) {
93 return isValidReg(MO) && MO.isDef();
94}
95
97 const TargetRegisterInfo *TRI) {
98 if (!isValidRegDef(MO))
99 return false;
100 return TRI->regsOverlap(MO.getReg(), Reg);
101}
102
103static bool isFIDef(const MachineInstr &MI, int FrameIndex,
104 const TargetInstrInfo *TII) {
105 int DefFrameIndex = 0;
106 int SrcFrameIndex = 0;
107 if (TII->isStoreToStackSlot(MI, DefFrameIndex) ||
108 TII->isStackSlotCopy(MI, DefFrameIndex, SrcFrameIndex))
109 return DefFrameIndex == FrameIndex;
110 return false;
111}
112
113void ReachingDefInfo::enterBasicBlock(MachineBasicBlock *MBB) {
114 unsigned MBBNumber = MBB->getNumber();
115 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
116 "Unexpected basic block number.");
117 assert(LiveRegs.empty() && "LiveRegs should be empty on BB entry");
118 MBBReachingDefs.startBasicBlock(MBBNumber, NumRegUnits);
119
120 // Reset instruction counter in each basic block.
121 CurInstr = 0;
122
123 // This is the entry block.
124 if (MBB == &MBB->getParent()->front()) {
125 LiveRegs.assign(NumRegUnits, ReachingDefDefaultVal);
126 for (const auto &LI : MBB->liveins()) {
127 for (MCRegUnit Unit : TRI->regunits(LI.PhysReg)) {
128 // Treat function live-ins as if they were defined just before the first
129 // instruction. Usually, function arguments are set up immediately
130 // before the call.
131 if (LiveRegs[static_cast<unsigned>(Unit)] != FunctionLiveInMarker) {
132 LiveRegs[static_cast<unsigned>(Unit)] = FunctionLiveInMarker;
133 MBBReachingDefs.append(MBBNumber, Unit, FunctionLiveInMarker);
134 }
135 }
136 }
137 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": entry\n");
138 return;
139 }
140
141 // Try to coalesce live-out registers from predecessors.
142 bool Initialized = false;
143 for (MachineBasicBlock *pred : MBB->predecessors()) {
144 assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
145 "Should have pre-allocated MBBInfos for all MBBs");
146 const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
147 // Incoming is null if this is a backedge from a BB
148 // we haven't processed yet
149 if (Incoming.empty())
150 continue;
151
152 // Directly copy over the reg infos for the first predecessor.
153 if (!Initialized) {
154 LiveRegs = Incoming;
155 Initialized = true;
156 continue;
157 }
158
159 // Find the most recent reaching definition from a predecessor.
160 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
161 LiveRegs[Unit] = std::max(LiveRegs[Unit], Incoming[Unit]);
162 }
163
164 if (!Initialized)
165 LiveRegs.assign(NumRegUnits, ReachingDefDefaultVal);
166
167 // Insert the most recent reaching definition we found.
168 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
169 if (LiveRegs[Unit] != ReachingDefDefaultVal)
170 MBBReachingDefs.append(MBBNumber, static_cast<MCRegUnit>(Unit),
171 LiveRegs[Unit]);
172}
173
174void ReachingDefInfo::leaveBasicBlock(MachineBasicBlock *MBB) {
175 assert(!LiveRegs.empty() && "Must enter basic block first.");
176 unsigned MBBNumber = MBB->getNumber();
177 assert(MBBNumber < MBBOutRegsInfos.size() &&
178 "Unexpected basic block number.");
179 // Save register clearances at end of MBB - used by enterBasicBlock().
180 MBBOutRegsInfos[MBBNumber] = LiveRegs;
181
182 // While processing the basic block, we kept `Def` relative to the start
183 // of the basic block for convenience. However, future use of this information
184 // only cares about the clearance from the end of the block, so adjust
185 // everything to be relative to the end of the basic block.
186 for (int &OutLiveReg : MBBOutRegsInfos[MBBNumber])
187 if (OutLiveReg != ReachingDefDefaultVal)
188 OutLiveReg -= CurInstr;
189 LiveRegs.clear();
190}
191
192void ReachingDefInfo::processDefs(MachineInstr *MI) {
193 assert(!MI->isDebugInstr() && "Won't process debug instructions");
194
195 unsigned MBBNumber = MI->getParent()->getNumber();
196 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
197 "Unexpected basic block number.");
198
199 for (auto &MO : MI->operands()) {
200 if (MO.isFI()) {
201 int FrameIndex = MO.getIndex();
202 if (!isFIDef(*MI, FrameIndex, TII))
203 continue;
204 MBBFrameObjsReachingDefs[{MBBNumber, FrameIndex}].push_back(CurInstr);
205 }
206 if (!isValidRegDef(MO))
207 continue;
208 for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
209 // This instruction explicitly defines the current reg unit.
210 LLVM_DEBUG(dbgs() << printRegUnit(Unit, TRI) << ":\t" << CurInstr << '\t'
211 << *MI);
212
213 // How many instructions since this reg unit was last written?
214 if (LiveRegs[static_cast<unsigned>(Unit)] != CurInstr) {
215 LiveRegs[static_cast<unsigned>(Unit)] = CurInstr;
216 MBBReachingDefs.append(MBBNumber, Unit, CurInstr);
217 }
218 }
219 }
220 InstIds[MI] = CurInstr;
221 ++CurInstr;
222}
223
224void ReachingDefInfo::reprocessBasicBlock(MachineBasicBlock *MBB) {
225 unsigned MBBNumber = MBB->getNumber();
226 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
227 "Unexpected basic block number.");
228
229 // Count number of non-debug instructions for end of block adjustment.
230 auto NonDbgInsts =
232 int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
233
234 // When reprocessing a block, the only thing we need to do is check whether
235 // there is now a more recent incoming reaching definition from a predecessor.
236 for (MachineBasicBlock *pred : MBB->predecessors()) {
237 assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
238 "Should have pre-allocated MBBInfos for all MBBs");
239 const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
240 // Incoming may be empty for dead predecessors.
241 if (Incoming.empty())
242 continue;
243
244 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
245 int Def = Incoming[Unit];
246 if (Def == ReachingDefDefaultVal)
247 continue;
248
249 auto Defs = MBBReachingDefs.defs(MBBNumber, static_cast<MCRegUnit>(Unit));
250 if (!Defs.empty() && Defs.front() < 0) {
251 if (Defs.front() >= Def)
252 continue;
253
254 // Update existing reaching def from predecessor to a more recent one.
255 MBBReachingDefs.replaceFront(MBBNumber, static_cast<MCRegUnit>(Unit),
256 Def);
257 } else {
258 // Insert new reaching def from predecessor.
259 MBBReachingDefs.prepend(MBBNumber, static_cast<MCRegUnit>(Unit), Def);
260 }
261
262 // Update reaching def at end of BB. Keep in mind that these are
263 // adjusted relative to the end of the basic block.
264 if (MBBOutRegsInfos[MBBNumber][Unit] < Def - NumInsts)
265 MBBOutRegsInfos[MBBNumber][Unit] = Def - NumInsts;
266 }
267 }
268}
269
270void ReachingDefInfo::processBasicBlock(
271 const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
272 MachineBasicBlock *MBB = TraversedMBB.MBB;
274 << (!TraversedMBB.IsDone ? ": incomplete\n"
275 : ": all preds known\n"));
276
277 if (!TraversedMBB.PrimaryPass) {
278 // Reprocess MBB that is part of a loop.
279 reprocessBasicBlock(MBB);
280 return;
281 }
282
283 enterBasicBlock(MBB);
284 for (MachineInstr &MI :
286 processDefs(&MI);
287 leaveBasicBlock(MBB);
288}
289
291 MF = &mf;
292 const TargetSubtargetInfo &STI = MF->getSubtarget();
293 TRI = STI.getRegisterInfo();
294 TII = STI.getInstrInfo();
295 LLVM_DEBUG(dbgs() << "********** REACHING DEFINITION ANALYSIS **********\n");
296 init();
297 traverse();
298}
299
301 // Create a map from instruction to numerical ids.
302 // Since a reaching def can come after instruction,
303 // this map needs to be populated first.
304 int Num = 0;
306 for (MachineBasicBlock &MBB : *MF) {
307 for (MachineInstr &MI : MBB) {
308 InstToNumMap[&MI] = Num;
309 ++Num;
310 }
311 }
312
314 for (MachineBasicBlock &MBB : *MF) {
315 OS << printMBBReference(MBB) << ":\n";
316 for (MachineInstr &MI : MBB) {
317 for (MachineOperand &MO : MI.operands()) {
318 Register Reg;
319 if (MO.isFI()) {
320 int FrameIndex = MO.getIndex();
321 Reg = Register::index2StackSlot(FrameIndex);
322 } else if (MO.isReg()) {
323 if (MO.isDef())
324 continue;
325 Reg = MO.getReg();
326 if (!Reg.isValid())
327 continue;
328 } else
329 continue;
330 Defs.clear();
331 getGlobalReachingDefs(&MI, Reg, Defs);
332 MO.print(OS, TRI);
334 for (MachineInstr *Def : Defs)
335 Nums.push_back(InstToNumMap[Def]);
336 llvm::sort(Nums);
337 OS << ":{ ";
338 for (int Num : Nums)
339 OS << Num << " ";
340 OS << "}\n";
341 }
342 OS << InstToNumMap[&MI] << ": " << MI << "\n";
343 }
344 }
345}
346
348 RDI.run(mf);
349 return false;
350}
351
353 // Clear the internal vectors.
354 MBBOutRegsInfos.clear();
355 MBBReachingDefs.clear();
356 MBBFrameObjsReachingDefs.clear();
357 InstIds.clear();
358 LiveRegs.clear();
359}
360
363 init();
364 traverse();
365}
366
368 NumRegUnits = TRI->getNumRegUnits();
369 MBBReachingDefs.init(MF->getNumBlockIDs());
370 // Initialize the MBBOutRegsInfos
371 MBBOutRegsInfos.resize(MF->getNumBlockIDs());
372 LoopTraversal Traversal;
373 TraversedMBBOrder = Traversal.traverse(*MF);
374}
375
377 // Traverse the basic blocks.
378 for (LoopTraversal::TraversedMBBInfo TraversedMBB : TraversedMBBOrder)
379 processBasicBlock(TraversedMBB);
380#ifndef NDEBUG
381 // Make sure reaching defs are sorted and unique.
382 for (unsigned MBBNumber = 0, NumBlockIDs = MF->getNumBlockIDs();
383 MBBNumber != NumBlockIDs; ++MBBNumber) {
384 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
385 int LastDef = ReachingDefDefaultVal;
386 for (int Def :
387 MBBReachingDefs.defs(MBBNumber, static_cast<MCRegUnit>(Unit))) {
388 assert(Def > LastDef && "Defs must be sorted and unique");
389 LastDef = Def;
390 }
391 }
392 }
393#endif
394}
395
397 assert(InstIds.count(MI) && "Unexpected machine instruction.");
398 int InstId = InstIds.lookup(MI);
399 int DefRes = ReachingDefDefaultVal;
400 unsigned MBBNumber = MI->getParent()->getNumber();
401 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
402 "Unexpected basic block number.");
403 int LatestDef = ReachingDefDefaultVal;
404
405 if (Reg.isStack()) {
406 // Check that there was a reaching def.
407 int FrameIndex = Reg.stackSlotIndex();
408 auto Lookup = MBBFrameObjsReachingDefs.find({MBBNumber, FrameIndex});
409 if (Lookup == MBBFrameObjsReachingDefs.end())
410 return LatestDef;
411 auto &Defs = Lookup->second;
412 for (int Def : Defs) {
413 if (Def >= InstId)
414 break;
415 DefRes = Def;
416 }
417 LatestDef = std::max(LatestDef, DefRes);
418 return LatestDef;
419 }
420
421 for (MCRegUnit Unit : TRI->regunits(Reg)) {
422 for (int Def : MBBReachingDefs.defs(MBBNumber, Unit)) {
423 if (Def >= InstId)
424 break;
425 DefRes = Def;
426 }
427 LatestDef = std::max(LatestDef, DefRes);
428 }
429 return LatestDef;
430}
431
432MachineInstr *ReachingDefInfo::getReachingLocalMIDef(MachineInstr *MI,
433 Register Reg) const {
434 return hasLocalDefBefore(MI, Reg)
435 ? getInstFromId(MI->getParent(), getReachingDef(MI, Reg))
436 : nullptr;
437}
438
440 Register Reg) const {
441 MachineBasicBlock *ParentA = A->getParent();
442 MachineBasicBlock *ParentB = B->getParent();
443 if (ParentA != ParentB)
444 return false;
445
446 return getReachingDef(A, Reg) == getReachingDef(B, Reg);
447}
448
449MachineInstr *ReachingDefInfo::getInstFromId(MachineBasicBlock *MBB,
450 int InstId) const {
451 assert(static_cast<size_t>(MBB->getNumber()) <
452 MBBReachingDefs.numBlockIDs() &&
453 "Unexpected basic block number.");
454 assert(InstId < static_cast<int>(MBB->size()) &&
455 "Unexpected instruction id.");
456
457 if (InstId < 0)
458 return nullptr;
459
460 for (auto &MI : *MBB) {
461 auto F = InstIds.find(&MI);
462 if (F != InstIds.end() && F->second == InstId)
463 return &MI;
464 }
465
466 return nullptr;
467}
468
470 assert(InstIds.count(MI) && "Unexpected machine instruction.");
471 return InstIds.lookup(MI) - getReachingDef(MI, Reg);
472}
473
475 return getReachingDef(MI, Reg) >= 0;
476}
477
479 InstSet &Uses) const {
480 MachineBasicBlock *MBB = Def->getParent();
482 while (++MI != MBB->end()) {
483 if (MI->isDebugInstr())
484 continue;
485
486 // If/when we find a new reaching def, we know that there's no more uses
487 // of 'Def'.
488 if (getReachingLocalMIDef(&*MI, Reg) != Def)
489 return;
490
491 for (auto &MO : MI->operands()) {
492 if (!isValidRegUseOf(MO, Reg, TRI))
493 continue;
494
495 Uses.insert(&*MI);
496 if (MO.isKill())
497 return;
498 }
499 }
500}
501
503 InstSet &Uses) const {
504 for (MachineInstr &MI :
505 instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end())) {
506 for (auto &MO : MI.operands()) {
507 if (!isValidRegUseOf(MO, Reg, TRI))
508 continue;
509 if (getReachingDef(&MI, Reg) >= 0)
510 return false;
511 Uses.insert(&MI);
512 }
513 }
514 auto Last = MBB->getLastNonDebugInstr();
515 if (Last == MBB->end())
516 return true;
517 return isReachingDefLiveOut(&*Last, Reg);
518}
519
521 InstSet &Uses) const {
522 MachineBasicBlock *MBB = MI->getParent();
523
524 // Collect the uses that each def touches within the block.
526
527 // Handle live-out values.
528 if (auto *LiveOut = getLocalLiveOutMIDef(MI->getParent(), Reg)) {
529 if (LiveOut != MI)
530 return;
531
532 SmallVector<MachineBasicBlock *, 4> ToVisit(MBB->successors());
534 while (!ToVisit.empty()) {
536 if (Visited.count(MBB) || !MBB->isLiveIn(Reg))
537 continue;
538 if (getLiveInUses(MBB, Reg, Uses))
539 llvm::append_range(ToVisit, MBB->successors());
540 Visited.insert(MBB);
541 }
542 }
543}
544
546 InstSet &Defs) const {
547 if (auto *Def = getUniqueReachingMIDef(MI, Reg)) {
548 Defs.insert(Def);
549 return;
550 }
551
552 for (auto *MBB : MI->getParent()->predecessors())
553 getLiveOuts(MBB, Reg, Defs);
554}
555
557 InstSet &Defs) const {
559 getLiveOuts(MBB, Reg, Defs, VisitedBBs);
560}
561
563 InstSet &Defs, BlockSet &VisitedBBs) const {
564 if (VisitedBBs.count(MBB))
565 return;
566
567 VisitedBBs.insert(MBB);
568 LiveRegUnits LiveRegs(*TRI);
569 LiveRegs.addLiveOuts(*MBB);
570 if (Reg.isPhysical() && LiveRegs.available(Reg))
571 return;
572
573 if (auto *Def = getLocalLiveOutMIDef(MBB, Reg))
574 Defs.insert(Def);
575 else
576 for (auto *Pred : MBB->predecessors())
577 getLiveOuts(Pred, Reg, Defs, VisitedBBs);
578}
579
581 Register Reg) const {
582 // If there's a local def before MI, return it.
583 MachineInstr *LocalDef = getReachingLocalMIDef(MI, Reg);
584 if (LocalDef && InstIds.lookup(LocalDef) < InstIds.lookup(MI))
585 return LocalDef;
586
588 MachineBasicBlock *Parent = MI->getParent();
589 for (auto *Pred : Parent->predecessors())
590 getLiveOuts(Pred, Reg, Incoming);
591
592 // Check that we have a single incoming value and that it does not
593 // come from the same block as MI - since it would mean that the def
594 // is executed after MI.
595 if (Incoming.size() == 1 && (*Incoming.begin())->getParent() != Parent)
596 return *Incoming.begin();
597 return nullptr;
598}
599
601 unsigned Idx) const {
602 assert(MI->getOperand(Idx).isReg() && "Expected register operand");
603 return getUniqueReachingMIDef(MI, MI->getOperand(Idx).getReg());
604}
605
607 MachineOperand &MO) const {
608 assert(MO.isReg() && "Expected register operand");
609 return getUniqueReachingMIDef(MI, MO.getReg());
610}
611
613 MachineBasicBlock *MBB = MI->getParent();
614 LiveRegUnits LiveRegs(*TRI);
615 LiveRegs.addLiveOuts(*MBB);
616
617 // Yes if the register is live out of the basic block.
618 if (!LiveRegs.available(Reg))
619 return true;
620
621 // Walk backwards through the block to see if the register is live at some
622 // point.
623 for (MachineInstr &Last :
624 instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
625 LiveRegs.stepBackward(Last);
626 if (!LiveRegs.available(Reg))
627 return InstIds.lookup(&Last) > InstIds.lookup(MI);
628 }
629 return false;
630}
631
633 MachineBasicBlock *MBB = MI->getParent();
634 auto Last = MBB->getLastNonDebugInstr();
635 if (Last != MBB->end() &&
636 getReachingDef(MI, Reg) != getReachingDef(&*Last, Reg))
637 return true;
638
639 if (auto *Def = getLocalLiveOutMIDef(MBB, Reg))
640 return Def == getReachingLocalMIDef(MI, Reg);
641
642 return false;
643}
644
646 Register Reg) const {
647 MachineBasicBlock *MBB = MI->getParent();
648 LiveRegUnits LiveRegs(*TRI);
649 LiveRegs.addLiveOuts(*MBB);
650 if (Reg.isPhysical() && LiveRegs.available(Reg))
651 return false;
652
653 auto Last = MBB->getLastNonDebugInstr();
654 int Def = getReachingDef(MI, Reg);
655 if (Last != MBB->end() && getReachingDef(&*Last, Reg) != Def)
656 return false;
657
658 // Finally check that the last instruction doesn't redefine the register.
659 for (auto &MO : Last->operands())
660 if (isValidRegDefOf(MO, Reg, TRI))
661 return false;
662
663 return true;
664}
665
667 Register Reg) const {
668 LiveRegUnits LiveRegs(*TRI);
669 LiveRegs.addLiveOuts(*MBB);
670 if (Reg.isPhysical() && LiveRegs.available(Reg))
671 return nullptr;
672
673 auto Last = MBB->getLastNonDebugInstr();
674 if (Last == MBB->end())
675 return nullptr;
676
677 // Check if Last is the definition
678 if (Reg.isStack()) {
679 int FrameIndex = Reg.stackSlotIndex();
680 if (isFIDef(*Last, FrameIndex, TII))
681 return &*Last;
682 } else {
683 for (auto &MO : Last->operands())
684 if (isValidRegDefOf(MO, Reg, TRI))
685 return &*Last;
686 }
687
688 int Def = getReachingDef(&*Last, Reg);
689 return Def < 0 ? nullptr : getInstFromId(MBB, Def);
690}
691
693 return MI.mayLoadOrStore() || MI.mayRaiseFPException() ||
694 MI.hasUnmodeledSideEffects() || MI.isTerminator() ||
695 MI.isCall() || MI.isBarrier() || MI.isBranch() || MI.isReturn();
696}
697
698// Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
699// not define a register that is used by any instructions, after and including,
700// 'To'. These instructions also must not redefine any of Froms operands.
701template <typename Iterator>
702bool ReachingDefInfo::isSafeToMove(MachineInstr *From, MachineInstr *To) const {
703 if (From->getParent() != To->getParent() || From == To)
704 return false;
705
706 SmallSet<Register, 2> Defs;
707 // First check that From would compute the same value if moved.
708 for (auto &MO : From->operands()) {
709 if (!isValidReg(MO))
710 continue;
711 if (MO.isDef())
712 Defs.insert(MO.getReg());
713 else if (!hasSameReachingDef(From, To, MO.getReg()))
714 return false;
715 }
716
717 // Now walk checking that the rest of the instructions will compute the same
718 // value and that we're not overwriting anything. Don't move the instruction
719 // past any memory, control-flow or other ambiguous instructions.
720 for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
721 if (mayHaveSideEffects(*I))
722 return false;
723 for (auto &MO : I->operands())
724 if (MO.isReg() && MO.getReg() && Defs.count(MO.getReg()))
725 return false;
726 }
727 return true;
728}
729
731 MachineInstr *To) const {
732 using Iterator = MachineBasicBlock::iterator;
733 // Walk forwards until we find the instruction.
734 for (auto I = Iterator(From), E = From->getParent()->end(); I != E; ++I)
735 if (&*I == To)
736 return isSafeToMove<Iterator>(From, To);
737 return false;
738}
739
741 MachineInstr *To) const {
743 // Walk backwards until we find the instruction.
744 for (auto I = Iterator(From), E = From->getParent()->rend(); I != E; ++I)
745 if (&*I == To)
746 return isSafeToMove<Iterator>(From, To);
747 return false;
748}
749
756
758 InstSet &Ignore) const {
760 return isSafeToRemove(MI, Visited, ToRemove, Ignore);
761}
762
763bool ReachingDefInfo::isSafeToRemove(MachineInstr *MI, InstSet &Visited,
764 InstSet &ToRemove, InstSet &Ignore) const {
765 if (Visited.count(MI) || Ignore.count(MI))
766 return true;
767 else if (mayHaveSideEffects(*MI)) {
768 // Unless told to ignore the instruction, don't remove anything which has
769 // side effects.
770 return false;
771 }
772
773 Visited.insert(MI);
774 for (auto &MO : MI->operands()) {
775 if (!isValidRegDef(MO))
776 continue;
777
779 getGlobalUses(MI, MO.getReg(), Uses);
780
781 for (auto *I : Uses) {
782 if (Ignore.count(I) || ToRemove.count(I))
783 continue;
784 if (!isSafeToRemove(I, Visited, ToRemove, Ignore))
785 return false;
786 }
787 }
788 ToRemove.insert(MI);
789 return true;
790}
791
793 InstSet &Dead) const {
794 Dead.insert(MI);
795 auto IsDead = [this, &Dead](MachineInstr *Def, Register Reg) {
796 if (mayHaveSideEffects(*Def))
797 return false;
798
799 unsigned LiveDefs = 0;
800 for (auto &MO : Def->operands()) {
801 if (!isValidRegDef(MO))
802 continue;
803 if (!MO.isDead())
804 ++LiveDefs;
805 }
806
807 if (LiveDefs > 1)
808 return false;
809
811 getGlobalUses(Def, Reg, Uses);
813 };
814
815 for (auto &MO : MI->operands()) {
816 if (!isValidRegUse(MO))
817 continue;
818 if (MachineInstr *Def = getMIOperand(MI, MO))
819 if (IsDead(Def, MO.getReg()))
821 }
822}
823
828
830 InstSet &Ignore) const {
831 // Check for any uses of the register after MI.
832 if (isRegUsedAfter(MI, Reg)) {
833 if (auto *Def = getReachingLocalMIDef(MI, Reg)) {
835 getGlobalUses(Def, Reg, Uses);
837 return false;
838 } else
839 return false;
840 }
841
842 MachineBasicBlock *MBB = MI->getParent();
843 // Check for any defs after MI.
844 if (isRegDefinedAfter(MI, Reg)) {
846 for (auto E = MBB->end(); I != E; ++I) {
847 if (Ignore.count(&*I))
848 continue;
849 for (auto &MO : I->operands())
850 if (isValidRegDefOf(MO, Reg, TRI))
851 return false;
852 }
853 }
854 return true;
855}
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:54
#define I(x, y, z)
Definition MD5.cpp:57
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:119
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...
LLVM_ABI 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
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
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.
const MachineBasicBlock & front() const
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.
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:276
LLVM_ABI 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.
LLVM_ABI MachineInstr * getUniqueReachingMIDef(MachineInstr *MI, Register Reg) const
If a single MachineInstr creates the reaching definition, then return it.
LLVM_ABI bool isReachingDefLiveOut(MachineInstr *MI, Register Reg) const
Return whether the reaching def for MI also is live out of its parent block.
LLVM_ABI bool isSafeToMoveForwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved forwards to just before To.
LLVM_ABI int getReachingDef(MachineInstr *MI, Register Reg) const
Provides the instruction id of the closest reaching def instruction of Reg that reaches MI,...
LLVM_ABI void run(MachineFunction &mf)
LLVM_ABI void getReachingLocalUses(MachineInstr *MI, Register Reg, InstSet &Uses) const
Provides the uses, in the same block as MI, of register that MI defines.
LLVM_ABI int getClearance(MachineInstr *MI, Register Reg) const
Provides the clearance - the number of instructions since the closest reaching def instruction of Reg...
LLVM_ABI bool isRegDefinedAfter(MachineInstr *MI, Register Reg) const
Return whether the given register is defined after MI.
LLVM_ABI void init()
Initialize data structures.
LLVM_ABI void print(raw_ostream &OS)
LLVM_ABI bool hasLocalDefBefore(MachineInstr *MI, Register Reg) const
Provide whether the register has been defined in the same basic block as, and before,...
LLVM_ABI void reset()
Re-run the analysis.
LLVM_ABI void getGlobalUses(MachineInstr *MI, Register Reg, InstSet &Uses) const
Collect the users of the value stored in Reg, which is defined by MI.
LLVM_ABI MachineInstr * getMIOperand(MachineInstr *MI, unsigned Idx) const
If a single MachineInstr creates the reaching definition, for MIs operand at Idx, then return it.
LLVM_ABI void getLiveOuts(MachineBasicBlock *MBB, Register Reg, InstSet &Defs, BlockSet &VisitedBBs) const
Search MBB for a definition of Reg and insert it into Defs.
LLVM_ABI void traverse()
Traverse the machine function, mapping definitions.
LLVM_ABI ReachingDefInfo()
LLVM_ABI bool isSafeToMoveBackwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved backwards to just after To.
LLVM_ABI void collectKilledOperands(MachineInstr *MI, InstSet &Dead) const
Assuming MI is dead, recursively search the incoming operands which are killed by MI and collect thos...
LLVM_ABI ~ReachingDefInfo()
LLVM_ABI bool hasSameReachingDef(MachineInstr *A, MachineInstr *B, Register Reg) const
Return whether A and B use the same def of Reg.
LLVM_ABI 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.
LLVM_ABI void getGlobalReachingDefs(MachineInstr *MI, Register Reg, InstSet &Defs) const
Collect all possible definitions of the value stored in Reg, which is used by MI.
LLVM_ABI bool isSafeToRemove(MachineInstr *MI, InstSet &ToRemove) const
Return whether removing this instruction will have no effect on the program, returning the redundant ...
LLVM_ABI 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...
LLVM_ABI bool invalidate(MachineFunction &F, const PreservedAnalyses &PA, MachineFunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
LLVM_ABI 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.
LLVM_ABI bool isSafeToDefRegAt(MachineInstr *MI, Register Reg) const
Return whether a MachineInstr could be inserted at MI and safely define the given register without af...
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2StackSlot(int FI)
Convert a frame index to a stack slot register value.
Definition Register.h:51
size_type size() const
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.
iterator begin() const
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:176
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:184
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
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
@ Dead
Unused definition.
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:2229
LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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
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.