LLVM 23.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[static_cast<unsigned>(Unit)] != FunctionLiveInMarker) {
138 LiveRegs[static_cast<unsigned>(Unit)] = FunctionLiveInMarker;
139 MBBReachingDefs.append(MBBNumber, Unit, FunctionLiveInMarker);
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, static_cast<MCRegUnit>(Unit),
166 LiveRegs[Unit]);
167}
168
169void ReachingDefInfo::leaveBasicBlock(MachineBasicBlock *MBB) {
170 assert(!LiveRegs.empty() && "Must enter basic block first.");
171 unsigned MBBNumber = MBB->getNumber();
172 assert(MBBNumber < MBBOutRegsInfos.size() &&
173 "Unexpected basic block number.");
174 // Save register clearances at end of MBB - used by enterBasicBlock().
175 MBBOutRegsInfos[MBBNumber] = LiveRegs;
176
177 // While processing the basic block, we kept `Def` relative to the start
178 // of the basic block for convenience. However, future use of this information
179 // only cares about the clearance from the end of the block, so adjust
180 // everything to be relative to the end of the basic block.
181 for (int &OutLiveReg : MBBOutRegsInfos[MBBNumber])
182 if (OutLiveReg != ReachingDefDefaultVal)
183 OutLiveReg -= CurInstr;
184 LiveRegs.clear();
185}
186
187void ReachingDefInfo::processDefs(MachineInstr *MI) {
188 assert(!MI->isDebugInstr() && "Won't process debug instructions");
189
190 unsigned MBBNumber = MI->getParent()->getNumber();
191 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
192 "Unexpected basic block number.");
193
194 for (auto &MO : MI->operands()) {
195 if (MO.isFI()) {
196 int FrameIndex = MO.getIndex();
197 if (!isFIDef(*MI, FrameIndex, TII))
198 continue;
199 MBBFrameObjsReachingDefs[{MBBNumber, FrameIndex}].push_back(CurInstr);
200 }
201 if (!isValidRegDef(MO))
202 continue;
203 for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
204 // This instruction explicitly defines the current reg unit.
205 LLVM_DEBUG(dbgs() << printRegUnit(Unit, TRI) << ":\t" << CurInstr << '\t'
206 << *MI);
207
208 // How many instructions since this reg unit was last written?
209 if (LiveRegs[static_cast<unsigned>(Unit)] != CurInstr) {
210 LiveRegs[static_cast<unsigned>(Unit)] = CurInstr;
211 MBBReachingDefs.append(MBBNumber, Unit, CurInstr);
212 }
213 }
214 }
215 InstIds[MI] = CurInstr;
216 ++CurInstr;
217}
218
219void ReachingDefInfo::reprocessBasicBlock(MachineBasicBlock *MBB) {
220 unsigned MBBNumber = MBB->getNumber();
221 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
222 "Unexpected basic block number.");
223
224 // Count number of non-debug instructions for end of block adjustment.
225 auto NonDbgInsts =
227 int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
228
229 // When reprocessing a block, the only thing we need to do is check whether
230 // there is now a more recent incoming reaching definition from a predecessor.
231 for (MachineBasicBlock *pred : MBB->predecessors()) {
232 assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
233 "Should have pre-allocated MBBInfos for all MBBs");
234 const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
235 // Incoming may be empty for dead predecessors.
236 if (Incoming.empty())
237 continue;
238
239 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
240 int Def = Incoming[Unit];
241 if (Def == ReachingDefDefaultVal)
242 continue;
243
244 auto Defs = MBBReachingDefs.defs(MBBNumber, static_cast<MCRegUnit>(Unit));
245 if (!Defs.empty() && Defs.front() < 0) {
246 if (Defs.front() >= Def)
247 continue;
248
249 // Update existing reaching def from predecessor to a more recent one.
250 MBBReachingDefs.replaceFront(MBBNumber, static_cast<MCRegUnit>(Unit),
251 Def);
252 } else {
253 // Insert new reaching def from predecessor.
254 MBBReachingDefs.prepend(MBBNumber, static_cast<MCRegUnit>(Unit), Def);
255 }
256
257 // Update reaching def at end of BB. Keep in mind that these are
258 // adjusted relative to the end of the basic block.
259 if (MBBOutRegsInfos[MBBNumber][Unit] < Def - NumInsts)
260 MBBOutRegsInfos[MBBNumber][Unit] = Def - NumInsts;
261 }
262 }
263}
264
265void ReachingDefInfo::processBasicBlock(
266 const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
267 MachineBasicBlock *MBB = TraversedMBB.MBB;
269 << (!TraversedMBB.IsDone ? ": incomplete\n"
270 : ": all preds known\n"));
271
272 if (!TraversedMBB.PrimaryPass) {
273 // Reprocess MBB that is part of a loop.
274 reprocessBasicBlock(MBB);
275 return;
276 }
277
278 enterBasicBlock(MBB);
279 for (MachineInstr &MI :
281 processDefs(&MI);
282 leaveBasicBlock(MBB);
283}
284
286 MF = &mf;
287 const TargetSubtargetInfo &STI = MF->getSubtarget();
288 TRI = STI.getRegisterInfo();
289 TII = STI.getInstrInfo();
290 LLVM_DEBUG(dbgs() << "********** REACHING DEFINITION ANALYSIS **********\n");
291 init();
292 traverse();
293}
294
296 // Create a map from instruction to numerical ids.
297 // Since a reaching def can come after instruction,
298 // this map needs to be populated first.
299 int Num = 0;
301 for (MachineBasicBlock &MBB : *MF) {
302 for (MachineInstr &MI : MBB) {
303 InstToNumMap[&MI] = Num;
304 ++Num;
305 }
306 }
307
309 for (MachineBasicBlock &MBB : *MF) {
310 OS << printMBBReference(MBB) << ":\n";
311 for (MachineInstr &MI : MBB) {
312 for (MachineOperand &MO : MI.operands()) {
313 Register Reg;
314 if (MO.isFI()) {
315 int FrameIndex = MO.getIndex();
316 Reg = Register::index2StackSlot(FrameIndex);
317 } else if (MO.isReg()) {
318 if (MO.isDef())
319 continue;
320 Reg = MO.getReg();
321 if (!Reg.isValid())
322 continue;
323 } else
324 continue;
325 Defs.clear();
326 getGlobalReachingDefs(&MI, Reg, Defs);
327 MO.print(OS, TRI);
329 for (MachineInstr *Def : Defs)
330 Nums.push_back(InstToNumMap[Def]);
331 llvm::sort(Nums);
332 OS << ":{ ";
333 for (int Num : Nums)
334 OS << Num << " ";
335 OS << "}\n";
336 }
337 OS << InstToNumMap[&MI] << ": " << MI << "\n";
338 }
339 }
340}
341
343 RDI.run(mf);
344 return false;
345}
346
348 // Clear the internal vectors.
349 MBBOutRegsInfos.clear();
350 MBBReachingDefs.clear();
351 MBBFrameObjsReachingDefs.clear();
352 InstIds.clear();
353 LiveRegs.clear();
354}
355
358 init();
359 traverse();
360}
361
363 NumRegUnits = TRI->getNumRegUnits();
364 NumStackObjects = MF->getFrameInfo().getNumObjects();
365 ObjectIndexBegin = MF->getFrameInfo().getObjectIndexBegin();
366 MBBReachingDefs.init(MF->getNumBlockIDs());
367 // Initialize the MBBOutRegsInfos
368 MBBOutRegsInfos.resize(MF->getNumBlockIDs());
369 LoopTraversal Traversal;
370 TraversedMBBOrder = Traversal.traverse(*MF);
371}
372
374 // Traverse the basic blocks.
375 for (LoopTraversal::TraversedMBBInfo TraversedMBB : TraversedMBBOrder)
376 processBasicBlock(TraversedMBB);
377#ifndef NDEBUG
378 // Make sure reaching defs are sorted and unique.
379 for (unsigned MBBNumber = 0, NumBlockIDs = MF->getNumBlockIDs();
380 MBBNumber != NumBlockIDs; ++MBBNumber) {
381 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
382 int LastDef = ReachingDefDefaultVal;
383 for (int Def :
384 MBBReachingDefs.defs(MBBNumber, static_cast<MCRegUnit>(Unit))) {
385 assert(Def > LastDef && "Defs must be sorted and unique");
386 LastDef = Def;
387 }
388 }
389 }
390#endif
391}
392
394 assert(InstIds.count(MI) && "Unexpected machine instuction.");
395 int InstId = InstIds.lookup(MI);
396 int DefRes = ReachingDefDefaultVal;
397 unsigned MBBNumber = MI->getParent()->getNumber();
398 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
399 "Unexpected basic block number.");
400 int LatestDef = ReachingDefDefaultVal;
401
402 if (Reg.isStack()) {
403 // Check that there was a reaching def.
404 int FrameIndex = Reg.stackSlotIndex();
405 auto Lookup = MBBFrameObjsReachingDefs.find({MBBNumber, FrameIndex});
406 if (Lookup == MBBFrameObjsReachingDefs.end())
407 return LatestDef;
408 auto &Defs = Lookup->second;
409 for (int Def : Defs) {
410 if (Def >= InstId)
411 break;
412 DefRes = Def;
413 }
414 LatestDef = std::max(LatestDef, DefRes);
415 return LatestDef;
416 }
417
418 for (MCRegUnit Unit : TRI->regunits(Reg)) {
419 for (int Def : MBBReachingDefs.defs(MBBNumber, Unit)) {
420 if (Def >= InstId)
421 break;
422 DefRes = Def;
423 }
424 LatestDef = std::max(LatestDef, DefRes);
425 }
426 return LatestDef;
427}
428
429MachineInstr *ReachingDefInfo::getReachingLocalMIDef(MachineInstr *MI,
430 Register Reg) const {
431 return hasLocalDefBefore(MI, Reg)
432 ? getInstFromId(MI->getParent(), getReachingDef(MI, Reg))
433 : nullptr;
434}
435
437 Register Reg) const {
438 MachineBasicBlock *ParentA = A->getParent();
439 MachineBasicBlock *ParentB = B->getParent();
440 if (ParentA != ParentB)
441 return false;
442
443 return getReachingDef(A, Reg) == getReachingDef(B, Reg);
444}
445
446MachineInstr *ReachingDefInfo::getInstFromId(MachineBasicBlock *MBB,
447 int InstId) const {
448 assert(static_cast<size_t>(MBB->getNumber()) <
449 MBBReachingDefs.numBlockIDs() &&
450 "Unexpected basic block number.");
451 assert(InstId < static_cast<int>(MBB->size()) &&
452 "Unexpected instruction id.");
453
454 if (InstId < 0)
455 return nullptr;
456
457 for (auto &MI : *MBB) {
458 auto F = InstIds.find(&MI);
459 if (F != InstIds.end() && F->second == InstId)
460 return &MI;
461 }
462
463 return nullptr;
464}
465
467 assert(InstIds.count(MI) && "Unexpected machine instuction.");
468 return InstIds.lookup(MI) - getReachingDef(MI, Reg);
469}
470
472 return getReachingDef(MI, Reg) >= 0;
473}
474
476 InstSet &Uses) const {
477 MachineBasicBlock *MBB = Def->getParent();
479 while (++MI != MBB->end()) {
480 if (MI->isDebugInstr())
481 continue;
482
483 // If/when we find a new reaching def, we know that there's no more uses
484 // of 'Def'.
485 if (getReachingLocalMIDef(&*MI, Reg) != Def)
486 return;
487
488 for (auto &MO : MI->operands()) {
489 if (!isValidRegUseOf(MO, Reg, TRI))
490 continue;
491
492 Uses.insert(&*MI);
493 if (MO.isKill())
494 return;
495 }
496 }
497}
498
500 InstSet &Uses) const {
501 for (MachineInstr &MI :
502 instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end())) {
503 for (auto &MO : MI.operands()) {
504 if (!isValidRegUseOf(MO, Reg, TRI))
505 continue;
506 if (getReachingDef(&MI, Reg) >= 0)
507 return false;
508 Uses.insert(&MI);
509 }
510 }
511 auto Last = MBB->getLastNonDebugInstr();
512 if (Last == MBB->end())
513 return true;
514 return isReachingDefLiveOut(&*Last, Reg);
515}
516
518 InstSet &Uses) const {
519 MachineBasicBlock *MBB = MI->getParent();
520
521 // Collect the uses that each def touches within the block.
523
524 // Handle live-out values.
525 if (auto *LiveOut = getLocalLiveOutMIDef(MI->getParent(), Reg)) {
526 if (LiveOut != MI)
527 return;
528
529 SmallVector<MachineBasicBlock *, 4> ToVisit(MBB->successors());
531 while (!ToVisit.empty()) {
533 if (Visited.count(MBB) || !MBB->isLiveIn(Reg))
534 continue;
535 if (getLiveInUses(MBB, Reg, Uses))
536 llvm::append_range(ToVisit, MBB->successors());
537 Visited.insert(MBB);
538 }
539 }
540}
541
543 InstSet &Defs) const {
544 if (auto *Def = getUniqueReachingMIDef(MI, Reg)) {
545 Defs.insert(Def);
546 return;
547 }
548
549 for (auto *MBB : MI->getParent()->predecessors())
550 getLiveOuts(MBB, Reg, Defs);
551}
552
554 InstSet &Defs) const {
556 getLiveOuts(MBB, Reg, Defs, VisitedBBs);
557}
558
560 InstSet &Defs, BlockSet &VisitedBBs) const {
561 if (VisitedBBs.count(MBB))
562 return;
563
564 VisitedBBs.insert(MBB);
565 LiveRegUnits LiveRegs(*TRI);
566 LiveRegs.addLiveOuts(*MBB);
567 if (Reg.isPhysical() && LiveRegs.available(Reg))
568 return;
569
570 if (auto *Def = getLocalLiveOutMIDef(MBB, Reg))
571 Defs.insert(Def);
572 else
573 for (auto *Pred : MBB->predecessors())
574 getLiveOuts(Pred, Reg, Defs, VisitedBBs);
575}
576
578 Register Reg) const {
579 // If there's a local def before MI, return it.
580 MachineInstr *LocalDef = getReachingLocalMIDef(MI, Reg);
581 if (LocalDef && InstIds.lookup(LocalDef) < InstIds.lookup(MI))
582 return LocalDef;
583
585 MachineBasicBlock *Parent = MI->getParent();
586 for (auto *Pred : Parent->predecessors())
587 getLiveOuts(Pred, Reg, Incoming);
588
589 // Check that we have a single incoming value and that it does not
590 // come from the same block as MI - since it would mean that the def
591 // is executed after MI.
592 if (Incoming.size() == 1 && (*Incoming.begin())->getParent() != Parent)
593 return *Incoming.begin();
594 return nullptr;
595}
596
598 unsigned Idx) const {
599 assert(MI->getOperand(Idx).isReg() && "Expected register operand");
600 return getUniqueReachingMIDef(MI, MI->getOperand(Idx).getReg());
601}
602
604 MachineOperand &MO) const {
605 assert(MO.isReg() && "Expected register operand");
606 return getUniqueReachingMIDef(MI, MO.getReg());
607}
608
610 MachineBasicBlock *MBB = MI->getParent();
611 LiveRegUnits LiveRegs(*TRI);
612 LiveRegs.addLiveOuts(*MBB);
613
614 // Yes if the register is live out of the basic block.
615 if (!LiveRegs.available(Reg))
616 return true;
617
618 // Walk backwards through the block to see if the register is live at some
619 // point.
620 for (MachineInstr &Last :
621 instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
622 LiveRegs.stepBackward(Last);
623 if (!LiveRegs.available(Reg))
624 return InstIds.lookup(&Last) > InstIds.lookup(MI);
625 }
626 return false;
627}
628
630 MachineBasicBlock *MBB = MI->getParent();
631 auto Last = MBB->getLastNonDebugInstr();
632 if (Last != MBB->end() &&
633 getReachingDef(MI, Reg) != getReachingDef(&*Last, Reg))
634 return true;
635
636 if (auto *Def = getLocalLiveOutMIDef(MBB, Reg))
637 return Def == getReachingLocalMIDef(MI, Reg);
638
639 return false;
640}
641
643 Register Reg) const {
644 MachineBasicBlock *MBB = MI->getParent();
645 LiveRegUnits LiveRegs(*TRI);
646 LiveRegs.addLiveOuts(*MBB);
647 if (Reg.isPhysical() && LiveRegs.available(Reg))
648 return false;
649
650 auto Last = MBB->getLastNonDebugInstr();
651 int Def = getReachingDef(MI, Reg);
652 if (Last != MBB->end() && getReachingDef(&*Last, Reg) != Def)
653 return false;
654
655 // Finally check that the last instruction doesn't redefine the register.
656 for (auto &MO : Last->operands())
657 if (isValidRegDefOf(MO, Reg, TRI))
658 return false;
659
660 return true;
661}
662
664 Register Reg) const {
665 LiveRegUnits LiveRegs(*TRI);
666 LiveRegs.addLiveOuts(*MBB);
667 if (Reg.isPhysical() && LiveRegs.available(Reg))
668 return nullptr;
669
670 auto Last = MBB->getLastNonDebugInstr();
671 if (Last == MBB->end())
672 return nullptr;
673
674 // Check if Last is the definition
675 if (Reg.isStack()) {
676 int FrameIndex = Reg.stackSlotIndex();
677 if (isFIDef(*Last, FrameIndex, TII))
678 return &*Last;
679 } else {
680 for (auto &MO : Last->operands())
681 if (isValidRegDefOf(MO, Reg, TRI))
682 return &*Last;
683 }
684
685 int Def = getReachingDef(&*Last, Reg);
686 return Def < 0 ? nullptr : getInstFromId(MBB, Def);
687}
688
690 return MI.mayLoadOrStore() || MI.mayRaiseFPException() ||
691 MI.hasUnmodeledSideEffects() || MI.isTerminator() ||
692 MI.isCall() || MI.isBarrier() || MI.isBranch() || MI.isReturn();
693}
694
695// Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
696// not define a register that is used by any instructions, after and including,
697// 'To'. These instructions also must not redefine any of Froms operands.
698template <typename Iterator>
699bool ReachingDefInfo::isSafeToMove(MachineInstr *From, MachineInstr *To) const {
700 if (From->getParent() != To->getParent() || From == To)
701 return false;
702
703 SmallSet<Register, 2> Defs;
704 // First check that From would compute the same value if moved.
705 for (auto &MO : From->operands()) {
706 if (!isValidReg(MO))
707 continue;
708 if (MO.isDef())
709 Defs.insert(MO.getReg());
710 else if (!hasSameReachingDef(From, To, MO.getReg()))
711 return false;
712 }
713
714 // Now walk checking that the rest of the instructions will compute the same
715 // value and that we're not overwriting anything. Don't move the instruction
716 // past any memory, control-flow or other ambiguous instructions.
717 for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
718 if (mayHaveSideEffects(*I))
719 return false;
720 for (auto &MO : I->operands())
721 if (MO.isReg() && MO.getReg() && Defs.count(MO.getReg()))
722 return false;
723 }
724 return true;
725}
726
728 MachineInstr *To) const {
729 using Iterator = MachineBasicBlock::iterator;
730 // Walk forwards until we find the instruction.
731 for (auto I = Iterator(From), E = From->getParent()->end(); I != E; ++I)
732 if (&*I == To)
733 return isSafeToMove<Iterator>(From, To);
734 return false;
735}
736
738 MachineInstr *To) const {
740 // Walk backwards until we find the instruction.
741 for (auto I = Iterator(From), E = From->getParent()->rend(); I != E; ++I)
742 if (&*I == To)
743 return isSafeToMove<Iterator>(From, To);
744 return false;
745}
746
753
755 InstSet &Ignore) const {
757 return isSafeToRemove(MI, Visited, ToRemove, Ignore);
758}
759
760bool ReachingDefInfo::isSafeToRemove(MachineInstr *MI, InstSet &Visited,
761 InstSet &ToRemove, InstSet &Ignore) const {
762 if (Visited.count(MI) || Ignore.count(MI))
763 return true;
764 else if (mayHaveSideEffects(*MI)) {
765 // Unless told to ignore the instruction, don't remove anything which has
766 // side effects.
767 return false;
768 }
769
770 Visited.insert(MI);
771 for (auto &MO : MI->operands()) {
772 if (!isValidRegDef(MO))
773 continue;
774
776 getGlobalUses(MI, MO.getReg(), Uses);
777
778 for (auto *I : Uses) {
779 if (Ignore.count(I) || ToRemove.count(I))
780 continue;
781 if (!isSafeToRemove(I, Visited, ToRemove, Ignore))
782 return false;
783 }
784 }
785 ToRemove.insert(MI);
786 return true;
787}
788
790 InstSet &Dead) const {
791 Dead.insert(MI);
792 auto IsDead = [this, &Dead](MachineInstr *Def, Register Reg) {
793 if (mayHaveSideEffects(*Def))
794 return false;
795
796 unsigned LiveDefs = 0;
797 for (auto &MO : Def->operands()) {
798 if (!isValidRegDef(MO))
799 continue;
800 if (!MO.isDead())
801 ++LiveDefs;
802 }
803
804 if (LiveDefs > 1)
805 return false;
806
808 getGlobalUses(Def, Reg, Uses);
809 return llvm::set_is_subset(Uses, Dead);
810 };
811
812 for (auto &MO : MI->operands()) {
813 if (!isValidRegUse(MO))
814 continue;
815 if (MachineInstr *Def = getMIOperand(MI, MO))
816 if (IsDead(Def, MO.getReg()))
817 collectKilledOperands(Def, Dead);
818 }
819}
820
825
827 InstSet &Ignore) const {
828 // Check for any uses of the register after MI.
829 if (isRegUsedAfter(MI, Reg)) {
830 if (auto *Def = getReachingLocalMIDef(MI, Reg)) {
832 getGlobalUses(Def, Reg, Uses);
834 return false;
835 } else
836 return false;
837 }
838
839 MachineBasicBlock *MBB = MI->getParent();
840 // Check for any defs after MI.
841 if (isRegDefinedAfter(MI, Reg)) {
843 for (auto E = MBB->end(); I != E; ++I) {
844 if (Ignore.count(&*I))
845 continue;
846 for (auto &MO : I->operands())
847 if (isValidRegDefOf(MO, Reg, TRI))
848 return false;
849 }
850 }
851 return true;
852}
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: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.
Definition Types.h:26
LLVM_ABI void initializeReachingDefInfoWrapperPassPass(PassRegistry &)
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:2198
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:1634
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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.