LLVM 24.0.0git
PHIElimination.cpp
Go to the documentation of this file.
1//===- PhiElimination.cpp - Eliminate PHI nodes by inserting copies -------===//
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//
9// This pass eliminates machine instruction PHI nodes by inserting copy
10// instructions. This destroys SSA information, but is the desired input for
11// some register allocators.
12//
13//===----------------------------------------------------------------------===//
14
16#include "PHIEliminationUtils.h"
17#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/Statistic.h"
44#include "llvm/Pass.h"
46#include "llvm/Support/Debug.h"
48#include <cassert>
49#include <iterator>
50#include <utility>
51
52using namespace llvm;
53
54#define DEBUG_TYPE "phi-node-elimination"
55
56static cl::opt<bool>
57 DisableEdgeSplitting("disable-phi-elim-edge-splitting", cl::init(false),
59 cl::desc("Disable critical edge splitting "
60 "during PHI elimination"));
61
62static cl::opt<bool>
63 SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false),
65 cl::desc("Split all critical edges during "
66 "PHI elimination"));
67
69 "no-phi-elim-live-out-early-exit", cl::init(false), cl::Hidden,
70 cl::desc("Do not use an early exit if isLiveOutPastPHIs returns true."));
71
72namespace {
73
74class PHIEliminationImpl {
75 MachineRegisterInfo *MRI = nullptr; // Machine register information
76 SlotIndexes *SI = nullptr;
77 LiveIntervals *LIS = nullptr;
78 MachineLoopInfo *MLI = nullptr;
79 MachineDominatorTree *MDT = nullptr;
80 MachinePostDominatorTree *PDT = nullptr;
81 const MachineBranchProbabilityInfo *MBPI = nullptr;
82 MachineBlockFrequencyInfo *MBFI = nullptr;
83
84 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
85 /// in predecessor basic blocks.
86 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
87
88 void LowerPHINode(MachineBasicBlock &MBB,
90 bool AllEdgesCritical);
91
92 /// analyzePHINodes - Gather information about the PHI nodes in
93 /// here. In particular, we want to map the number of uses of a virtual
94 /// register which is used in a PHI node. We map that to the BB the
95 /// vreg is coming from. This is used later to determine when the vreg
96 /// is killed in the BB.
97 void analyzePHINodes(const MachineFunction &MF);
98
99 /// Split critical edges where necessary for good coalescer performance.
100 bool SplitPHIEdges(MachineFunction &MF, MachineBasicBlock &MBB,
102
103 void computeLiveOutSets(const MachineFunction &MF);
104
105 bool isLiveOutPastPHIs(Register Reg, const MachineBasicBlock *MBB);
106
107 using BBVRegPair = std::pair<unsigned, Register>;
108 using VRegPHIUse = DenseMap<BBVRegPair, unsigned>;
109
110 // Count the number of non-undef PHI uses of each register in each BB.
111 VRegPHIUse VRegPHIUseCount;
112
113 // PHI source registers whose subranges must be shrunk to their own uses once
114 // all PHIs are gone.
115 SmallSet<Register, 8> PHISrcRegsToShrink;
116
117 // Defs of PHI sources which are implicit_def.
119
120 // Map reusable lowered PHI node -> incoming join register.
121 using LoweredPHIMap =
123 LoweredPHIMap LoweredPHIs;
124
125 // A set of live-out regs for each MBB which is used to update LIS
126 // efficiently also with large functions.
127 std::vector<SparseBitVector<>> LiveOutSets;
128
129public:
130 PHIEliminationImpl(MachineFunctionPass *P) {
131 auto *SIWrapper = P->getAnalysisIfAvailable<SlotIndexesWrapperPass>();
132 auto *LISWrapper = P->getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
133 auto *MLIWrapper = P->getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
134 auto *MDTWrapper =
135 P->getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
136 auto *PDTWrapper =
137 P->getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
138 auto *MBPIWrapper =
139 P->getAnalysisIfAvailable<MachineBranchProbabilityInfoWrapperPass>();
140 auto *MBFIWrapper =
141 P->getAnalysisIfAvailable<MachineBlockFrequencyInfoWrapperPass>();
142
143 SI = SIWrapper ? &SIWrapper->getSI() : nullptr;
144 LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
145 MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
146 MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
147 PDT = PDTWrapper ? &PDTWrapper->getPostDomTree() : nullptr;
148 MBPI = MBPIWrapper ? &MBPIWrapper->getMBPI() : nullptr;
149 MBFI = MBFIWrapper ? &MBFIWrapper->getMBFI() : nullptr;
150 }
151
152 PHIEliminationImpl(MachineFunction &MF, MachineFunctionAnalysisManager &AM)
153 : SI(AM.getCachedResult<SlotIndexesAnalysis>(MF)),
154 LIS(AM.getCachedResult<LiveIntervalsAnalysis>(MF)),
155 MLI(AM.getCachedResult<MachineLoopAnalysis>(MF)),
156 MDT(AM.getCachedResult<MachineDominatorTreeAnalysis>(MF)),
157 PDT(AM.getCachedResult<MachinePostDominatorTreeAnalysis>(MF)),
158 MBPI(AM.getCachedResult<MachineBranchProbabilityAnalysis>(MF)),
159 MBFI(AM.getCachedResult<MachineBlockFrequencyAnalysis>(MF)) {}
160
161 bool run(MachineFunction &MF);
162};
163
164class PHIElimination : public MachineFunctionPass {
165public:
166 static char ID; // Pass identification, replacement for typeid
167
168 PHIElimination() : MachineFunctionPass(ID) {}
169
170 bool runOnMachineFunction(MachineFunction &MF) override {
171 PHIEliminationImpl Impl(this);
172 return Impl.run(MF);
173 }
174
175 MachineFunctionProperties getSetProperties() const override {
176 return MachineFunctionProperties().setNoPHIs();
177 }
178
179 void getAnalysisUsage(AnalysisUsage &AU) const override;
180};
181
182} // end anonymous namespace
183
187 PHIEliminationImpl Impl(MF, MFAM);
188 bool Changed = Impl.run(MF);
189 if (!Changed)
190 return PreservedAnalyses::all();
192 PA.preserve<LiveIntervalsAnalysis>();
193 PA.preserve<SlotIndexesAnalysis>();
194 PA.preserve<MachineDominatorTreeAnalysis>();
196 PA.preserve<MachineLoopAnalysis>();
197 PA.preserve<MachineBlockFrequencyAnalysis>();
198 return PA;
199}
200
201STATISTIC(NumLowered, "Number of phis lowered");
202STATISTIC(NumCriticalEdgesSplit, "Number of critical edges split");
203STATISTIC(NumReused, "Number of reused lowered phis");
204
205char PHIElimination::ID = 0;
206
207char &llvm::PHIEliminationID = PHIElimination::ID;
208
210 "Eliminate PHI nodes for register allocation", false,
211 false)
217 "Eliminate PHI nodes for register allocation", false, false)
218
219void PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
220 AU.addUsedIfAvailable<SlotIndexesWrapperPass>();
221 AU.addUsedIfAvailable<LiveIntervalsWrapperPass>();
222 AU.addUsedIfAvailable<MachineLoopInfoWrapperPass>();
223 AU.addPreserved<SlotIndexesWrapperPass>();
224 AU.addPreserved<LiveIntervalsWrapperPass>();
225 AU.addPreserved<MachineDominatorTreeWrapperPass>();
226 AU.addPreserved<MachinePostDominatorTreeWrapperPass>();
227 AU.addPreserved<MachineLoopInfoWrapperPass>();
228 AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
229 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
231}
232
233bool PHIEliminationImpl::run(MachineFunction &MF) {
234 MRI = &MF.getRegInfo();
235
236 MachineDomTreeUpdater MDTU(MDT, PDT,
237 MachineDomTreeUpdater::UpdateStrategy::Lazy);
238
239 bool Changed = false;
240
241 // Split critical edges to help the coalescer.
242 if (!DisableEdgeSplitting && LIS) {
243 for (auto &MBB : MF)
244 Changed |= SplitPHIEdges(MF, MBB, MLI, MDTU);
245 }
246
247 // This pass takes the function out of SSA form.
248 MRI->leaveSSA();
249
250 // Populate VRegPHIUseCount
251 if (LIS)
252 analyzePHINodes(MF);
253
254 // Eliminate PHI instructions by inserting copies into predecessor blocks.
255 for (auto &MBB : MF)
256 Changed |= EliminatePHINodes(MF, MBB);
257
258 // Remove dead IMPLICIT_DEF instructions.
259 for (MachineInstr *DefMI : ImpDefs) {
260 Register DefReg = DefMI->getOperand(0).getReg();
261 if (MRI->use_nodbg_empty(DefReg)) {
262 if (SI)
263 SI->removeMachineInstrFromMaps(*DefMI);
265 }
266 }
267
268 // Clean up the lowered PHI instructions.
269 for (auto &I : LoweredPHIs) {
270 if (SI)
271 SI->removeMachineInstrFromMaps(*I.first);
272 MF.deleteMachineInstr(I.first);
273 }
274
275 LoweredPHIs.clear();
276
277 // Different lanes may be used by different PHI source copies, or may already
278 // be dead in a predecessor. The main range's last use is therefore not a
279 // valid endpoint for every subrange. Wait until all PHIs have been removed
280 // before shrinking subranges to their remaining lane-specific uses.
281 for (Register Reg : PHISrcRegsToShrink) {
282 LiveInterval &LI = LIS->getInterval(Reg);
283 for (LiveInterval::SubRange &SR : LI.subranges())
284 LIS->shrinkToUses(SR, Reg);
285 }
286 PHISrcRegsToShrink.clear();
287
288 ImpDefs.clear();
289 VRegPHIUseCount.clear();
290
291 MF.getProperties().setNoPHIs();
292
293 return Changed;
294}
295
296/// Move debug instructions preceding \p Position to immediately after it.
299 MachineBasicBlock::iterator InsertPt = std::next(Position);
300 for (auto I = MBB.begin(); I != Position;) {
301 if (!I->isDebugInstr()) {
302 ++I;
303 continue;
304 }
305
306 auto DebugBegin = I;
307 I = skipDebugInstructionsForward(I, Position,
308 /*SkipPseudoOp=*/false);
309 MBB.splice(InsertPt, &MBB, DebugBegin, I);
310 }
311}
312
313/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
314/// predecessor basic blocks.
315bool PHIEliminationImpl::EliminatePHINodes(MachineFunction &MF,
317 if (MBB.empty() || !MBB.front().isPHI())
318 return false; // Quick exit for basic blocks without PHIs.
319
320 // Ignore debug instructions when choosing the destination-copy position.
321 // Move any skipped debug instructions after that position so they remain
322 // after the destination copies. Do not change pseudo-probe placement.
325 /*SkipPseudoOp=*/false),
326 MBB.begin(), /*SkipPseudoOp=*/false);
328
329 // If all incoming edges are critical, we try to deduplicate identical PHIs so
330 // that we generate fewer copies. If at any edge is non-critical, we either
331 // have less than two predecessors (=> no PHIs) or a predecessor has only us
332 // as a successor (=> identical PHI node can't occur in different block).
333 bool AllEdgesCritical = MBB.pred_size() >= 2;
335 if (Pred->succ_size() < 2) {
336 AllEdgesCritical = false;
337 break;
338 }
339 }
340
341 while (MBB.front().isPHI())
342 LowerPHINode(MBB, LastPHIIt, AllEdgesCritical);
343
344 return true;
345}
346
347/// Return true if all defs of VirtReg are implicit-defs.
348/// This includes registers with no defs.
349static bool isImplicitlyDefined(Register VirtReg,
350 const MachineRegisterInfo &MRI) {
351 for (MachineInstr &DI : MRI.def_instructions(VirtReg))
352 if (!DI.isImplicitDef())
353 return false;
354 return true;
355}
356
357/// Return true if all sources of the phi node are implicit_def's, or undef's.
358static bool allPhiOperandsUndefined(const MachineInstr &MPhi,
359 const MachineRegisterInfo &MRI) {
360 for (unsigned I = 1, E = MPhi.getNumOperands(); I != E; I += 2) {
361 const MachineOperand &MO = MPhi.getOperand(I);
362 if (!isImplicitlyDefined(MO.getReg(), MRI) && !MO.isUndef())
363 return false;
364 }
365 return true;
366}
367/// LowerPHINode - Lower the PHI node at the top of the specified block.
368void PHIEliminationImpl::LowerPHINode(MachineBasicBlock &MBB,
370 bool AllEdgesCritical) {
371 ++NumLowered;
372
373 MachineBasicBlock::iterator AfterPHIsIt = std::next(LastPHIIt);
374
375 // Unlink the PHI node from the basic block, but don't delete the PHI yet.
376 MachineInstr *MPhi = MBB.remove(&*MBB.begin());
377
378 unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
379 Register DestReg = MPhi->getOperand(0).getReg();
380 assert(MPhi->getOperand(0).getSubReg() == 0 && "Can't handle sub-reg PHIs");
381
382 // Create a new register for the incoming PHI arguments.
384 Register IncomingReg;
385 bool EliminateNow = true; // delay elimination of nodes in LoweredPHIs
386 bool reusedIncoming = false; // Is IncomingReg reused from an earlier PHI?
387
388 // Insert a register to register copy at the top of the current block (but
389 // after any remaining phi nodes) which copies the new incoming register
390 // into the phi node destination.
391 MachineInstr *PHICopy = nullptr;
393 if (allPhiOperandsUndefined(*MPhi, *MRI))
394 // If all sources of a PHI node are implicit_def or undef uses, just emit an
395 // implicit_def instead of a copy.
396 PHICopy = BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
397 TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
398 else {
399 // Can we reuse an earlier PHI node? This only happens for critical edges,
400 // typically those created by tail duplication. Typically, an identical PHI
401 // node can't occur, so avoid hashing/storing such PHIs, which is somewhat
402 // expensive.
403 Register *Entry = nullptr;
404 if (AllEdgesCritical)
405 Entry = &LoweredPHIs[MPhi];
406 if (Entry && *Entry) {
407 // An identical PHI node was already lowered. Reuse the incoming register.
408 IncomingReg = *Entry;
409 reusedIncoming = true;
410 ++NumReused;
411 LLVM_DEBUG(dbgs() << "Reusing " << printReg(IncomingReg) << " for "
412 << *MPhi);
413 } else {
414 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
415 IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
416 if (Entry) {
417 EliminateNow = false;
418 *Entry = IncomingReg;
419 }
420 }
421
422 // Give the target possiblity to handle special cases fallthrough otherwise
423 PHICopy = TII->createPHIDestinationCopy(
424 MBB, AfterPHIsIt, MPhi->getDebugLoc(), IncomingReg, DestReg);
425 }
426
427 if (MPhi->peekDebugInstrNum() && IncomingReg) {
428 // If referred to by debug-info, store where this PHI was.
430 unsigned ID = MPhi->peekDebugInstrNum();
431 auto P = MachineFunction::DebugPHIRegallocPos(&MBB, IncomingReg, 0);
432 auto Res = MF->DebugPHIPositions.insert({ID, P});
433 assert(Res.second);
434 (void)Res;
435 }
436
437 // Update LiveIntervals for the new copy or implicit def.
438 SlotIndex DestCopyIndex;
439 if (SI)
440 DestCopyIndex = SI->insertMachineInstrInMaps(*PHICopy);
441
442 if (LIS) {
443 assert(DestCopyIndex.isValid() &&
444 "Expected a valid SlotIndex if LIS is available.");
445 SlotIndex MBBStartIndex = LIS->getMBBStartIdx(&MBB);
446 if (IncomingReg) {
447 // Add the region from the beginning of MBB to the copy instruction to
448 // IncomingReg's live interval.
449 LiveInterval &IncomingLI = LIS->getOrCreateEmptyInterval(IncomingReg);
450 VNInfo *IncomingVNI = IncomingLI.getVNInfoAt(MBBStartIndex);
451 if (!IncomingVNI)
452 IncomingVNI =
453 IncomingLI.getNextValue(MBBStartIndex, LIS->getVNInfoAllocator());
455 MBBStartIndex, DestCopyIndex.getRegSlot(), IncomingVNI));
456 }
457
458 LiveInterval &DestLI = LIS->getInterval(DestReg);
459 assert(!DestLI.empty() && "PHIs should have non-empty LiveIntervals.");
460
461 // Make sure the instruction's dead flag matches the dead range created
462 // below.
463 if (DestLI.endIndex().isDead())
464 PHICopy->getOperand(0).setIsDead();
465
466 SlotIndex NewStart = DestCopyIndex.getRegSlot();
467
468 SmallVector<LiveRange *> ToUpdate({&DestLI});
469 for (auto &SR : DestLI.subranges())
470 ToUpdate.push_back(&SR);
471
472 for (auto LR : ToUpdate) {
473 auto DestSegment = LR->find(MBBStartIndex);
474 assert(DestSegment != LR->end() &&
475 "PHI destination must be live in block");
476
477 if (LR->endIndex().isDead()) {
478 // A dead PHI's live range begins and ends at the start of the MBB, but
479 // the lowered copy, which will still be dead, needs to begin and end at
480 // the copy instruction.
481 VNInfo *OrigDestVNI = LR->getVNInfoAt(DestSegment->start);
482 assert(OrigDestVNI && "PHI destination should be live at block entry.");
483 LR->removeSegment(DestSegment->start, DestSegment->start.getDeadSlot());
484 LR->createDeadDef(NewStart, LIS->getVNInfoAllocator());
485 LR->removeValNo(OrigDestVNI);
486 continue;
487 }
488
489 // Destination copies are not inserted in the same order as the PHI nodes
490 // they replace. Hence the start of the live range may need to be adjusted
491 // to match the actual slot index of the copy.
492 if (DestSegment->start > NewStart) {
493 VNInfo *VNI = LR->getVNInfoAt(DestSegment->start);
494 assert(VNI && "value should be defined for known segment");
495 LR->addSegment(
496 LiveInterval::Segment(NewStart, DestSegment->start, VNI));
497 } else if (DestSegment->start < NewStart) {
498 assert(DestSegment->start >= MBBStartIndex);
499 assert(DestSegment->end >= DestCopyIndex.getRegSlot());
500 LR->removeSegment(DestSegment->start, NewStart);
501 }
502 VNInfo *DestVNI = LR->getVNInfoAt(NewStart);
503 assert(DestVNI && "PHI destination should be live at its definition.");
504 DestVNI->def = NewStart;
505 }
506
507 // Adjust the VRegPHIUseCount map to account for the removal of this PHI
508 // node.
509 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
510 if (!MPhi->getOperand(i).isUndef()) {
511 --VRegPHIUseCount[BBVRegPair(
512 MPhi->getOperand(i + 1).getMBB()->getNumber(),
513 MPhi->getOperand(i).getReg())];
514 }
515 }
516 }
517
518 // Now loop over all of the incoming arguments, changing them to copy into the
519 // IncomingReg register in the corresponding predecessor basic block.
521 for (int i = NumSrcs - 1; i >= 0; --i) {
522 Register SrcReg = MPhi->getOperand(i * 2 + 1).getReg();
523 unsigned SrcSubReg = MPhi->getOperand(i * 2 + 1).getSubReg();
524 bool SrcUndef = MPhi->getOperand(i * 2 + 1).isUndef() ||
525 isImplicitlyDefined(SrcReg, *MRI);
526 assert(SrcReg.isVirtual() &&
527 "Machine PHI Operands must all be virtual registers!");
528
529 // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
530 // path the PHI.
531 MachineBasicBlock &opBlock = *MPhi->getOperand(i * 2 + 2).getMBB();
532
533 // Check to make sure we haven't already emitted the copy for this block.
534 // This can happen because PHI nodes may have multiple entries for the same
535 // basic block.
536 if (!MBBsInsertedInto.insert(&opBlock).second)
537 continue; // If the copy has already been emitted, we're done.
538
539 MachineInstr *SrcRegDef = MRI->getVRegDef(SrcReg);
540 if (SrcRegDef && TII->isUnspillableTerminator(SrcRegDef)) {
541 assert(SrcRegDef->getOperand(0).isReg() &&
542 SrcRegDef->getOperand(0).isDef() &&
543 "Expected operand 0 to be a reg def!");
544 // Now that the PHI's use has been removed (as the instruction was
545 // removed) there should be no other uses of the SrcReg.
546 assert(MRI->use_empty(SrcReg) &&
547 "Expected a single use from UnspillableTerminator");
548 SrcRegDef->getOperand(0).setReg(IncomingReg);
549
550 if (LIS) {
551 LiveInterval &SrcLI = LIS->getInterval(SrcReg);
552 SlotIndex DefIdx = LIS->getInstructionIndex(*SrcRegDef).getRegSlot();
553 LiveInterval &IncomingLI = LIS->getOrCreateEmptyInterval(IncomingReg);
554 VNInfo *VNI =
555 IncomingLI.getNextValue(DefIdx, LIS->getVNInfoAllocator());
556 for (const LiveInterval::Segment &S : SrcLI)
557 IncomingLI.addSegment(LiveInterval::Segment(S.start, S.end, VNI));
558 LIS->removeInterval(SrcReg);
559 }
560
561 continue;
562 }
563
564 // Find a safe location to insert the copy, this may be the first terminator
565 // in the block (or end()).
567 findPHICopyInsertPoint(&opBlock, &MBB, SrcReg);
568
569 // Insert the copy.
570 MachineInstr *NewSrcInstr = nullptr;
571 if (!reusedIncoming && IncomingReg) {
572 if (SrcUndef) {
573 // The source register is undefined, so there is no need for a real
574 // COPY, but we still need to ensure joint dominance by defs.
575 // Insert an IMPLICIT_DEF instruction.
576 NewSrcInstr =
577 BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(),
578 TII->get(TargetOpcode::IMPLICIT_DEF), IncomingReg);
579
580 // Clean up the old implicit-def, if there even was one.
581 if (MachineInstr *DefMI = MRI->getVRegDef(SrcReg))
582 if (DefMI->isImplicitDef())
583 ImpDefs.insert(DefMI);
584 } else {
585 // Delete the debug location, since the copy is inserted into a
586 // different basic block.
587 NewSrcInstr = TII->createPHISourceCopy(opBlock, InsertPos, nullptr,
588 SrcReg, SrcSubReg, IncomingReg);
589 }
590 }
591
592 if (SI && NewSrcInstr)
593 SI->insertMachineInstrInMaps(*NewSrcInstr);
594
595 if (LIS) {
596 if (NewSrcInstr) {
597 assert(
598 SI &&
599 "Expected SI to be available to insert new MI if LIS is available");
600 LIS->addSegmentToEndOfBlock(IncomingReg, *NewSrcInstr);
601 }
602
603 if (!SrcUndef &&
604 !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)]) {
605 LiveInterval &SrcLI = LIS->getInterval(SrcReg);
606 if (SrcLI.hasSubRanges())
607 PHISrcRegsToShrink.insert(SrcReg);
608
609 bool isLiveOut = false;
610 for (MachineBasicBlock *Succ : opBlock.successors()) {
611 SlotIndex startIdx = LIS->getMBBStartIdx(Succ);
612 VNInfo *VNI = SrcLI.getVNInfoAt(startIdx);
613
614 // Definitions by other PHIs are not truly live-in for our purposes.
615 if (VNI && VNI->def != startIdx) {
616 isLiveOut = true;
617 break;
618 }
619 }
620
621 if (!isLiveOut) {
622 MachineBasicBlock::iterator KillInst = opBlock.end();
623 for (MachineBasicBlock::iterator Term = InsertPos;
624 Term != opBlock.end(); ++Term) {
625 if (Term->readsRegister(SrcReg, /*TRI=*/nullptr))
626 KillInst = Term;
627 }
628
629 if (KillInst == opBlock.end()) {
630 // No terminator uses the register.
631
632 if (reusedIncoming || !IncomingReg) {
633 // We may have to rewind a bit if we didn't just insert a copy.
634 KillInst = InsertPos;
635 while (KillInst != opBlock.begin()) {
636 --KillInst;
637 if (KillInst->isDebugInstr())
638 continue;
639 if (KillInst->readsRegister(SrcReg, /*TRI=*/nullptr))
640 break;
641 }
642 } else {
643 // We just inserted this copy.
644 KillInst = std::prev(InsertPos);
645 }
646 }
647 assert(KillInst->readsRegister(SrcReg, /*TRI=*/nullptr) &&
648 "Cannot find kill instruction");
649
650 SlotIndex LastUseIndex = LIS->getInstructionIndex(*KillInst);
651 SrcLI.removeSegment(LastUseIndex.getRegSlot(),
652 LIS->getMBBEndIdx(&opBlock));
653 }
654 }
655 }
656 }
657
658 // Really delete the PHI instruction now, if it is not in the LoweredPHIs map.
659 if (EliminateNow) {
660 if (SI)
661 SI->removeMachineInstrFromMaps(*MPhi);
662 MF.deleteMachineInstr(MPhi);
663 }
664}
665
666/// analyzePHINodes - Gather information about the PHI nodes in here. In
667/// particular, we want to map the number of uses of a virtual register which is
668/// used in a PHI node. We map that to the BB the vreg is coming from. This is
669/// used later to determine when the vreg is killed in the BB.
670void PHIEliminationImpl::analyzePHINodes(const MachineFunction &MF) {
671 for (const auto &MBB : MF) {
672 for (const auto &BBI : MBB) {
673 if (!BBI.isPHI())
674 break;
675 for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) {
676 if (!BBI.getOperand(i).isUndef()) {
677 ++VRegPHIUseCount[BBVRegPair(
678 BBI.getOperand(i + 1).getMBB()->getNumber(),
679 BBI.getOperand(i).getReg())];
680 }
681 }
682 }
683 }
684}
685
686bool PHIEliminationImpl::SplitPHIEdges(MachineFunction &MF,
688 MachineLoopInfo *MLI,
689 MachineDomTreeUpdater &MDTU) {
690 if (MBB.empty() || !MBB.front().isPHI() || MBB.isEHPad())
691 return false; // Quick exit for basic blocks without PHIs.
692
693 const MachineLoop *CurLoop = MLI ? MLI->getLoopFor(&MBB) : nullptr;
694 bool IsLoopHeader = CurLoop && &MBB == CurLoop->getHeader();
695
696 bool Changed = false;
697 for (MachineBasicBlock::iterator BBI = MBB.begin(), BBE = MBB.end();
698 BBI != BBE && BBI->isPHI(); ++BBI) {
699 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
700 Register Reg = BBI->getOperand(i).getReg();
701 MachineBasicBlock *PreMBB = BBI->getOperand(i + 1).getMBB();
702 // Is there a critical edge from PreMBB to MBB?
703 if (PreMBB->succ_size() == 1)
704 continue;
705
706 // Avoid splitting backedges of loops. It would introduce small
707 // out-of-line blocks into the loop which is very bad for code placement.
708 if (PreMBB == &MBB && !SplitAllCriticalEdges)
709 continue;
710 const MachineLoop *PreLoop = MLI ? MLI->getLoopFor(PreMBB) : nullptr;
711 if (IsLoopHeader && PreLoop == CurLoop && !SplitAllCriticalEdges)
712 continue;
713
714 // isLiveOutPastPHIs only returns true when the source register is
715 // live-out for some other reason than a phi use. That means the copy we
716 // will insert in PreMBB won't be a kill, and there is a risk it may not
717 // be coalesced away.
718 //
719 // If the copy would be a kill, there is no need to split the edge.
720 bool ShouldSplit = isLiveOutPastPHIs(Reg, PreMBB);
721 if (!ShouldSplit && !NoPhiElimLiveOutEarlyExit)
722 continue;
723 if (ShouldSplit) {
724 LLVM_DEBUG(dbgs() << printReg(Reg) << " live-out before critical edge "
725 << printMBBReference(*PreMBB) << " -> "
726 << printMBBReference(MBB) << ": " << *BBI);
727 }
728
729 // If Reg is not live-in to MBB, it means it must be live-in to some
730 // other PreMBB successor, and we can avoid the interference by splitting
731 // the edge.
732 //
733 // If Reg *is* live-in to MBB, the interference is inevitable and a copy
734 // is likely to be left after coalescing. If we are looking at a loop
735 // exiting edge, split it so we won't insert code in the loop, otherwise
736 // don't bother.
737 ShouldSplit =
738 ShouldSplit && !LIS->isLiveInToMBB(LIS->getInterval(Reg), &MBB);
739
740 // Check for a loop exiting edge.
741 if (!ShouldSplit && CurLoop != PreLoop) {
742 LLVM_DEBUG({
743 dbgs() << "Split wouldn't help, maybe avoid loop copies?\n";
744 if (PreLoop)
745 dbgs() << "PreLoop: " << *PreLoop;
746 if (CurLoop)
747 dbgs() << "CurLoop: " << *CurLoop;
748 });
749 // This edge could be entering a loop, exiting a loop, or it could be
750 // both: Jumping directly form one loop to the header of a sibling
751 // loop.
752 // Split unless this edge is entering CurLoop from an outer loop.
753 ShouldSplit = PreLoop && !PreLoop->contains(CurLoop);
754 }
755 if (!ShouldSplit && !SplitAllCriticalEdges)
756 continue;
757 if (LiveOutSets.empty())
758 computeLiveOutSets(MF);
759 MachineBasicBlock *NewBB =
760 PreMBB->SplitCriticalEdge(&MBB, {LIS, SI, MLI, &LiveOutSets}, &MDTU);
761 if (!NewBB) {
762 LLVM_DEBUG(dbgs() << "Failed to split critical edge.\n");
763 continue;
764 }
765
766 // Patch up MBFI after split if it is available.
767 if (MBFI) {
768 assert(MBPI);
769 MBFI->onEdgeSplit(*PreMBB, *NewBB, *MBPI);
770 }
771
772 Changed = true;
773 ++NumCriticalEdgesSplit;
774 }
775 }
776 return Changed;
777}
778
779void PHIEliminationImpl::computeLiveOutSets(const MachineFunction &MF) {
780 LiveOutSets.resize(MF.getNumBlockIDs());
781 for (unsigned Idx = 0, NumVRegs = MRI->getNumVirtRegs(); Idx != NumVRegs;
782 ++Idx) {
784 if (!LIS->hasInterval(Reg))
785 continue;
786 for (const LiveRange::Segment &S : LIS->getInterval(Reg)) {
787 for (const MachineBasicBlock *MBB = LIS->getMBBFromIndex(S.start);
788 MBB && LIS->getMBBEndIdx(MBB) <= S.end; MBB = MBB->getNextNode())
789 LiveOutSets[MBB->getNumber()].set(Idx);
790 }
791 }
792}
793
794bool PHIEliminationImpl::isLiveOutPastPHIs(Register Reg,
795 const MachineBasicBlock *MBB) {
796 // LiveIntervals considers uses in PHIs to be on the edge rather than in the
797 // predecessor basic block, so that a register used only in a PHI is live out
798 // of the block.
799 const LiveInterval &LI = LIS->getInterval(Reg);
800 for (const MachineBasicBlock *SI : MBB->successors())
801 if (LIS->isLiveInToMBB(LI, SI))
802 return true;
803 return false;
804}
MachineInstrBuilder MachineInstrBuilder & DefMI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
#define P(N)
static bool allPhiOperandsUndefined(const MachineInstr &MPhi, const MachineRegisterInfo &MRI)
Return true if all sources of the phi node are implicit_def's, or undef's.
static cl::opt< bool > NoPhiElimLiveOutEarlyExit("no-phi-elim-live-out-early-exit", cl::init(false), cl::Hidden, cl::desc("Do not use an early exit if isLiveOutPastPHIs returns true."))
static bool isImplicitlyDefined(Register VirtReg, const MachineRegisterInfo &MRI)
Return true if all defs of VirtReg are implicit-defs.
static cl::opt< bool > DisableEdgeSplitting("disable-phi-elim-edge-splitting", cl::init(false), cl::Hidden, cl::desc("Disable critical edge splitting " "during PHI elimination"))
static void moveDebugInstructionsAfter(MachineBasicBlock &MBB, MachineBasicBlock::iterator Position)
Move debug instructions preceding Position to immediately after it.
static cl::opt< bool > SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false), cl::Hidden, cl::desc("Split all critical edges during " "PHI elimination"))
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineRegisterInfo & MRI
static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg)
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent the analysis usage information of a pass.
A live range for subregisters.
LiveInterval - This class represents the liveness of a register, or stack slot.
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
bool hasInterval(Register Reg) const
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
LiveInterval & getOrCreateEmptyInterval(Register Reg)
Return an existing interval for Reg.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
VNInfo::Allocator & getVNInfoAllocator()
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
void removeInterval(Register Reg)
Interval removal.
LLVM_ABI LiveInterval::Segment addSegmentToEndOfBlock(Register Reg, MachineInstr &startInst)
Given a register and an instruction, adds a live segment from that instruction to the end of its MBB.
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses.
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
bool isLiveInToMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
bool empty() const
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
VNInfo * getNextValue(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
LLVM_ABI void removeSegment(SlotIndex Start, SlotIndex End, bool RemoveDeadValNo=false)
Remove the specified interval from this live range.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getHeader() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
const MachineBlockFrequencyInfo & getMBFI() const
Definition MBFIWrapper.h:37
bool isEHPad() const
Returns true if the block is a landing pad.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator SkipPHIsLabelsAndDebug(iterator I, Register Reg=Register(), bool SkipPseudoOp=true)
Return the first instruction in MBB after I that is not a PHI, label or debug.
MachineInstr * remove(MachineInstr *I)
Remove the unbundled instruction from the instruction list without deleting it.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineBasicBlock * SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P, MachineDomTreeUpdater *MDTU=nullptr)
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI void onEdgeSplit(const MachineBasicBlock &NewPredecessor, const MachineBasicBlock &NewSuccessor, const MachineBranchProbabilityInfo &MBPI)
incrementally calculate block frequencies when we split edges, to avoid full CFG traversal.
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
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.
Location of a PHI instruction that is also a debug-info variable value, for the duration of register ...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
DenseMap< unsigned, DebugPHIRegallocPos > DebugPHIPositions
Map of debug instruction numbers to the position of their PHI instructions during register allocation...
Representation of each machine instruction.
bool isImplicitDef() const
unsigned getNumOperands() const
Retuns the total number of operands.
unsigned peekDebugInstrNum() const
Examine the instruction number of this MachineInstr.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
void setIsDead(bool Val=true)
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
bool use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
bool isValid() const
Returns true if this is a valid index.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
bool isDead() const
isDead - Returns true if this is a dead def kill slot.
SlotIndexes pass.
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.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
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.
virtual const TargetInstrInfo * getInstrInfo() const
VNInfo - Value Number Information.
SlotIndex def
The index of the defining instruction.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
@ Entry
Definition COFF.h:862
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
MachineBasicBlock::iterator findPHICopyInsertPoint(MachineBasicBlock *MBB, MachineBasicBlock *SuccMBB, Register SrcReg)
findPHICopyInsertPoint - Find a safe place in MBB to insert a copy from SrcReg when following the CFG...
LLVM_ABI unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
Loop over all of the edges in the CFG, breaking critical edges as they are found.
LLVM_ABI char & PHIEliminationID
PHIElimination - This pass eliminates machine instruction PHI nodes by inserting copy instructions.
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This represents a simple continuous liveness interval for a value.