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.releaseMemory();
349 PendingMF = &MF;
350 return false;
351}
352
354 if (PendingMF) {
355 RDI.run(*PendingMF);
356 PendingMF = nullptr;
357 }
358 return RDI;
359}
360
362 // Clear the internal vectors.
363 MBBOutRegsInfos.clear();
364 MBBReachingDefs.clear();
365 MBBFrameObjsReachingDefs.clear();
366 InstIds.clear();
367 LiveRegs.clear();
368 TraversedMBBOrder.clear();
369}
370
373 init();
374 traverse();
375}
376
378 NumRegUnits = TRI->getNumRegUnits();
379 MBBReachingDefs.init(MF->getNumBlockIDs());
380 // Initialize the MBBOutRegsInfos
381 MBBOutRegsInfos.resize(MF->getNumBlockIDs());
382 LoopTraversal Traversal;
383 TraversedMBBOrder = Traversal.traverse(*MF);
384}
385
387 // Traverse the basic blocks.
388 for (LoopTraversal::TraversedMBBInfo TraversedMBB : TraversedMBBOrder)
389 processBasicBlock(TraversedMBB);
390#ifndef NDEBUG
391 // Make sure reaching defs are sorted and unique.
392 for (unsigned MBBNumber = 0, NumBlockIDs = MF->getNumBlockIDs();
393 MBBNumber != NumBlockIDs; ++MBBNumber) {
394 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
395 int LastDef = ReachingDefDefaultVal;
396 for (int Def :
397 MBBReachingDefs.defs(MBBNumber, static_cast<MCRegUnit>(Unit))) {
398 assert(Def > LastDef && "Defs must be sorted and unique");
399 LastDef = Def;
400 }
401 }
402 }
403#endif
404}
405
407 assert(InstIds.count(MI) && "Unexpected machine instruction.");
408 int InstId = InstIds.lookup(MI);
409 int DefRes = ReachingDefDefaultVal;
410 unsigned MBBNumber = MI->getParent()->getNumber();
411 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
412 "Unexpected basic block number.");
413 int LatestDef = ReachingDefDefaultVal;
414
415 if (Reg.isStack()) {
416 // Check that there was a reaching def.
417 int FrameIndex = Reg.stackSlotIndex();
418 auto Lookup = MBBFrameObjsReachingDefs.find({MBBNumber, FrameIndex});
419 if (Lookup == MBBFrameObjsReachingDefs.end())
420 return LatestDef;
421 auto &Defs = Lookup->second;
422 for (int Def : Defs) {
423 if (Def >= InstId)
424 break;
425 DefRes = Def;
426 }
427 LatestDef = std::max(LatestDef, DefRes);
428 return LatestDef;
429 }
430
431 for (MCRegUnit Unit : TRI->regunits(Reg)) {
432 for (int Def : MBBReachingDefs.defs(MBBNumber, Unit)) {
433 if (Def >= InstId)
434 break;
435 DefRes = Def;
436 }
437 LatestDef = std::max(LatestDef, DefRes);
438 }
439 return LatestDef;
440}
441
442MachineInstr *ReachingDefInfo::getReachingLocalMIDef(MachineInstr *MI,
443 Register Reg) const {
444 return hasLocalDefBefore(MI, Reg)
445 ? getInstFromId(MI->getParent(), getReachingDef(MI, Reg))
446 : nullptr;
447}
448
450 Register Reg) const {
451 MachineBasicBlock *ParentA = A->getParent();
452 MachineBasicBlock *ParentB = B->getParent();
453 if (ParentA != ParentB)
454 return false;
455
456 return getReachingDef(A, Reg) == getReachingDef(B, Reg);
457}
458
459MachineInstr *ReachingDefInfo::getInstFromId(MachineBasicBlock *MBB,
460 int InstId) const {
461 assert(static_cast<size_t>(MBB->getNumber()) <
462 MBBReachingDefs.numBlockIDs() &&
463 "Unexpected basic block number.");
464 assert(InstId < static_cast<int>(MBB->size()) &&
465 "Unexpected instruction id.");
466
467 if (InstId < 0)
468 return nullptr;
469
470 for (auto &MI : *MBB) {
471 auto F = InstIds.find(&MI);
472 if (F != InstIds.end() && F->second == InstId)
473 return &MI;
474 }
475
476 return nullptr;
477}
478
480 assert(InstIds.count(MI) && "Unexpected machine instruction.");
481 return InstIds.lookup(MI) - getReachingDef(MI, Reg);
482}
483
485 return getReachingDef(MI, Reg) >= 0;
486}
487
489 InstSet &Uses) const {
490 MachineBasicBlock *MBB = Def->getParent();
492 while (++MI != MBB->end()) {
493 if (MI->isDebugInstr())
494 continue;
495
496 // If/when we find a new reaching def, we know that there's no more uses
497 // of 'Def'.
498 if (getReachingLocalMIDef(&*MI, Reg) != Def)
499 return;
500
501 for (auto &MO : MI->operands()) {
502 if (!isValidRegUseOf(MO, Reg, TRI))
503 continue;
504
505 Uses.insert(&*MI);
506 if (MO.isKill())
507 return;
508 }
509 }
510}
511
513 InstSet &Uses) const {
514 for (MachineInstr &MI :
515 instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end())) {
516 for (auto &MO : MI.operands()) {
517 if (!isValidRegUseOf(MO, Reg, TRI))
518 continue;
519 if (getReachingDef(&MI, Reg) >= 0)
520 return false;
521 Uses.insert(&MI);
522 }
523 }
524 auto Last = MBB->getLastNonDebugInstr();
525 if (Last == MBB->end())
526 return true;
527 return isReachingDefLiveOut(&*Last, Reg);
528}
529
531 InstSet &Uses) const {
532 MachineBasicBlock *MBB = MI->getParent();
533
534 // Collect the uses that each def touches within the block.
536
537 // Handle live-out values.
538 if (auto *LiveOut = getLocalLiveOutMIDef(MI->getParent(), Reg)) {
539 if (LiveOut != MI)
540 return;
541
542 SmallVector<MachineBasicBlock *, 4> ToVisit(MBB->successors());
544 while (!ToVisit.empty()) {
546 if (Visited.count(MBB) || !MBB->isLiveIn(Reg))
547 continue;
548 if (getLiveInUses(MBB, Reg, Uses))
549 llvm::append_range(ToVisit, MBB->successors());
550 Visited.insert(MBB);
551 }
552 }
553}
554
556 InstSet &Defs) const {
557 if (auto *Def = getUniqueReachingMIDef(MI, Reg)) {
558 Defs.insert(Def);
559 return;
560 }
561
562 for (auto *MBB : MI->getParent()->predecessors())
563 getLiveOuts(MBB, Reg, Defs);
564}
565
567 InstSet &Defs) const {
569 getLiveOuts(MBB, Reg, Defs, VisitedBBs);
570}
571
573 InstSet &Defs, BlockSet &VisitedBBs) const {
574 if (VisitedBBs.count(MBB))
575 return;
576
577 VisitedBBs.insert(MBB);
578 LiveRegUnits LiveRegs(*TRI);
579 LiveRegs.addLiveOuts(*MBB);
580 if (Reg.isPhysical() && LiveRegs.available(Reg))
581 return;
582
583 if (auto *Def = getLocalLiveOutMIDef(MBB, Reg))
584 Defs.insert(Def);
585 else
586 for (auto *Pred : MBB->predecessors())
587 getLiveOuts(Pred, Reg, Defs, VisitedBBs);
588}
589
591 Register Reg) const {
592 // If there's a local def before MI, return it.
593 MachineInstr *LocalDef = getReachingLocalMIDef(MI, Reg);
594 if (LocalDef && InstIds.lookup(LocalDef) < InstIds.lookup(MI))
595 return LocalDef;
596
598 MachineBasicBlock *Parent = MI->getParent();
599 for (auto *Pred : Parent->predecessors())
600 getLiveOuts(Pred, Reg, Incoming);
601
602 // Check that we have a single incoming value and that it does not
603 // come from the same block as MI - since it would mean that the def
604 // is executed after MI.
605 if (Incoming.size() == 1 && (*Incoming.begin())->getParent() != Parent)
606 return *Incoming.begin();
607 return nullptr;
608}
609
611 unsigned Idx) const {
612 assert(MI->getOperand(Idx).isReg() && "Expected register operand");
613 return getUniqueReachingMIDef(MI, MI->getOperand(Idx).getReg());
614}
615
617 MachineOperand &MO) const {
618 assert(MO.isReg() && "Expected register operand");
619 return getUniqueReachingMIDef(MI, MO.getReg());
620}
621
623 MachineBasicBlock *MBB = MI->getParent();
624 LiveRegUnits LiveRegs(*TRI);
625 LiveRegs.addLiveOuts(*MBB);
626
627 // Yes if the register is live out of the basic block.
628 if (!LiveRegs.available(Reg))
629 return true;
630
631 // Walk backwards through the block to see if the register is live at some
632 // point.
633 for (MachineInstr &Last :
634 instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
635 LiveRegs.stepBackward(Last);
636 if (!LiveRegs.available(Reg))
637 return InstIds.lookup(&Last) > InstIds.lookup(MI);
638 }
639 return false;
640}
641
643 MachineBasicBlock *MBB = MI->getParent();
644 auto Last = MBB->getLastNonDebugInstr();
645 if (Last != MBB->end() &&
646 getReachingDef(MI, Reg) != getReachingDef(&*Last, Reg))
647 return true;
648
649 if (auto *Def = getLocalLiveOutMIDef(MBB, Reg))
650 return Def == getReachingLocalMIDef(MI, Reg);
651
652 return false;
653}
654
656 Register Reg) const {
657 MachineBasicBlock *MBB = MI->getParent();
658 LiveRegUnits LiveRegs(*TRI);
659 LiveRegs.addLiveOuts(*MBB);
660 if (Reg.isPhysical() && LiveRegs.available(Reg))
661 return false;
662
663 auto Last = MBB->getLastNonDebugInstr();
664 int Def = getReachingDef(MI, Reg);
665 if (Last != MBB->end() && getReachingDef(&*Last, Reg) != Def)
666 return false;
667
668 // Finally check that the last instruction doesn't redefine the register.
669 for (auto &MO : Last->operands())
670 if (isValidRegDefOf(MO, Reg, TRI))
671 return false;
672
673 return true;
674}
675
677 Register Reg) const {
678 LiveRegUnits LiveRegs(*TRI);
679 LiveRegs.addLiveOuts(*MBB);
680 if (Reg.isPhysical() && LiveRegs.available(Reg))
681 return nullptr;
682
683 auto Last = MBB->getLastNonDebugInstr();
684 if (Last == MBB->end())
685 return nullptr;
686
687 // Check if Last is the definition
688 if (Reg.isStack()) {
689 int FrameIndex = Reg.stackSlotIndex();
690 if (isFIDef(*Last, FrameIndex, TII))
691 return &*Last;
692 } else {
693 for (auto &MO : Last->operands())
694 if (isValidRegDefOf(MO, Reg, TRI))
695 return &*Last;
696 }
697
698 int Def = getReachingDef(&*Last, Reg);
699 return Def < 0 ? nullptr : getInstFromId(MBB, Def);
700}
701
703 return MI.mayLoadOrStore() || MI.mayRaiseFPException() ||
704 MI.hasUnmodeledSideEffects() || MI.isTerminator() ||
705 MI.isCall() || MI.isBarrier() || MI.isBranch() || MI.isReturn();
706}
707
708// Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
709// not define a register that is used by any instructions, after and including,
710// 'To'. These instructions also must not redefine any of Froms operands.
711template <typename Iterator>
712bool ReachingDefInfo::isSafeToMove(MachineInstr *From, MachineInstr *To) const {
713 if (From->getParent() != To->getParent() || From == To)
714 return false;
715
716 SmallSet<Register, 2> Defs;
717 // First check that From would compute the same value if moved.
718 for (auto &MO : From->operands()) {
719 if (!isValidReg(MO))
720 continue;
721 if (MO.isDef())
722 Defs.insert(MO.getReg());
723 else if (!hasSameReachingDef(From, To, MO.getReg()))
724 return false;
725 }
726
727 // Now walk checking that the rest of the instructions will compute the same
728 // value and that we're not overwriting anything. Don't move the instruction
729 // past any memory, control-flow or other ambiguous instructions.
730 for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
731 if (mayHaveSideEffects(*I))
732 return false;
733 for (auto &MO : I->operands())
734 if (MO.isReg() && MO.getReg() && Defs.count(MO.getReg()))
735 return false;
736 }
737 return true;
738}
739
741 MachineInstr *To) const {
742 using Iterator = MachineBasicBlock::iterator;
743 // Walk forwards until we find the instruction.
744 for (auto I = Iterator(From), E = From->getParent()->end(); I != E; ++I)
745 if (&*I == To)
746 return isSafeToMove<Iterator>(From, To);
747 return false;
748}
749
751 MachineInstr *To) const {
753 // Walk backwards until we find the instruction.
754 for (auto I = Iterator(From), E = From->getParent()->rend(); I != E; ++I)
755 if (&*I == To)
756 return isSafeToMove<Iterator>(From, To);
757 return false;
758}
759
766
768 InstSet &Ignore) const {
770 return isSafeToRemove(MI, Visited, ToRemove, Ignore);
771}
772
773bool ReachingDefInfo::isSafeToRemove(MachineInstr *MI, InstSet &Visited,
774 InstSet &ToRemove, InstSet &Ignore) const {
775 if (Visited.count(MI) || Ignore.count(MI))
776 return true;
777 else if (mayHaveSideEffects(*MI)) {
778 // Unless told to ignore the instruction, don't remove anything which has
779 // side effects.
780 return false;
781 }
782
783 Visited.insert(MI);
784 for (auto &MO : MI->operands()) {
785 if (!isValidRegDef(MO))
786 continue;
787
789 getGlobalUses(MI, MO.getReg(), Uses);
790
791 for (auto *I : Uses) {
792 if (Ignore.count(I) || ToRemove.count(I))
793 continue;
794 if (!isSafeToRemove(I, Visited, ToRemove, Ignore))
795 return false;
796 }
797 }
798 ToRemove.insert(MI);
799 return true;
800}
801
803 InstSet &Dead) const {
804 Dead.insert(MI);
805 auto IsDead = [this, &Dead](MachineInstr *Def, Register Reg) {
806 if (mayHaveSideEffects(*Def))
807 return false;
808
809 unsigned LiveDefs = 0;
810 for (auto &MO : Def->operands()) {
811 if (!isValidRegDef(MO))
812 continue;
813 if (!MO.isDead())
814 ++LiveDefs;
815 }
816
817 if (LiveDefs > 1)
818 return false;
819
821 getGlobalUses(Def, Reg, Uses);
823 };
824
825 for (auto &MO : MI->operands()) {
826 if (!isValidRegUse(MO))
827 continue;
828 if (MachineInstr *Def = getMIOperand(MI, MO))
829 if (IsDead(Def, MO.getReg()))
831 }
832}
833
838
840 InstSet &Ignore) const {
841 // Check for any uses of the register after MI.
842 if (isRegUsedAfter(MI, Reg)) {
843 if (auto *Def = getReachingLocalMIDef(MI, Reg)) {
845 getGlobalUses(Def, Reg, Uses);
847 return false;
848 } else
849 return false;
850 }
851
852 MachineBasicBlock *MBB = MI->getParent();
853 // Check for any defs after MI.
854 if (isRegDefinedAfter(MI, Reg)) {
856 for (auto E = MBB->end(); I != E; ++I) {
857 if (Ignore.count(&*I))
858 continue;
859 for (auto &MO : I->operands())
860 if (isValidRegDefOf(MO, Reg, TRI))
861 return false;
862 }
863 }
864 return true;
865}
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:275
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.