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 "CodeGenOptions.h"
17#include "PHIEliminationUtils.h"
18#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/Statistic.h"
45#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
56namespace {
57
58class PHIEliminationImpl {
59 const CodeGenOptions *Opts = nullptr;
60 MachineRegisterInfo *MRI = nullptr; // Machine register information
61 SlotIndexes *SI = nullptr;
62 LiveIntervals *LIS = nullptr;
63 MachineLoopInfo *MLI = nullptr;
64 MachineDominatorTree *MDT = nullptr;
65 MachinePostDominatorTree *PDT = nullptr;
66 const MachineBranchProbabilityInfo *MBPI = nullptr;
67 MachineBlockFrequencyInfo *MBFI = nullptr;
68
69 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
70 /// in predecessor basic blocks.
71 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
72
73 void LowerPHINode(MachineBasicBlock &MBB,
75 bool AllEdgesCritical);
76
77 /// analyzePHINodes - Gather information about the PHI nodes in
78 /// here. In particular, we want to map the number of uses of a virtual
79 /// register which is used in a PHI node. We map that to the BB the
80 /// vreg is coming from. This is used later to determine when the vreg
81 /// is killed in the BB.
82 void analyzePHINodes(const MachineFunction &MF);
83
84 /// Split critical edges where necessary for good coalescer performance.
85 bool SplitPHIEdges(MachineFunction &MF, MachineBasicBlock &MBB,
87
88 void computeLiveOutSets(const MachineFunction &MF);
89
90 bool isLiveOutPastPHIs(Register Reg, const MachineBasicBlock *MBB);
91
92 using BBVRegPair = std::pair<unsigned, Register>;
93 using VRegPHIUse = DenseMap<BBVRegPair, unsigned>;
94
95 // Count the number of non-undef PHI uses of each register in each BB.
96 VRegPHIUse VRegPHIUseCount;
97
98 struct PHISrcLaneKill {
99 LaneBitmask Lanes;
100 SlotIndex Index;
101 };
102
103 using PHISrcLaneKillMap =
105
106 // Copies are not always inserted in index order, so keep the kills sorted
107 // to find the latest read of a lane by searching from the back.
108 static void addPHISrcLaneKill(SmallVectorImpl<PHISrcLaneKill> &Kills,
109 LaneBitmask Lanes, SlotIndex Index) {
110 auto It = Kills.end();
111 if (!Kills.empty() && Index < Kills.back().Index) {
112 It = upper_bound(Kills, Index,
113 [](SlotIndex Idx, const PHISrcLaneKill &Kill) {
114 return Idx < Kill.Index;
115 });
116 }
117
118 Kills.insert(It, {Lanes, Index});
119 }
120
121 // Index of each PHI source copy inserted in a BB, and the lanes of the
122 // source register it reads.
123 PHISrcLaneKillMap PHISrcLaneKills;
124
125 // Defs of PHI sources which are implicit_def.
127
128 // Map reusable lowered PHI node -> incoming join register.
129 using LoweredPHIMap =
131 LoweredPHIMap LoweredPHIs;
132
133 // A set of live-out regs for each MBB which is used to update LIS
134 // efficiently also with large functions.
135 std::vector<SparseBitVector<>> LiveOutSets;
136
137public:
138 PHIEliminationImpl(MachineFunctionPass *P) {
139 auto *SIWrapper = P->getAnalysisIfAvailable<SlotIndexesWrapperPass>();
140 auto *LISWrapper = P->getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
141 auto *MLIWrapper = P->getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
142 auto *MDTWrapper =
143 P->getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
144 auto *PDTWrapper =
145 P->getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
146 auto *MBPIWrapper =
147 P->getAnalysisIfAvailable<MachineBranchProbabilityInfoWrapperPass>();
148 auto *MBFIWrapper =
149 P->getAnalysisIfAvailable<MachineBlockFrequencyInfoWrapperPass>();
150
151 SI = SIWrapper ? &SIWrapper->getSI() : nullptr;
152 LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
153 MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
154 MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
155 PDT = PDTWrapper ? &PDTWrapper->getPostDomTree() : nullptr;
156 MBPI = MBPIWrapper ? &MBPIWrapper->getMBPI() : nullptr;
157 MBFI = MBFIWrapper ? &MBFIWrapper->getMBFI() : nullptr;
158 }
159
160 PHIEliminationImpl(MachineFunction &MF, MachineFunctionAnalysisManager &AM)
168
169 bool run(MachineFunction &MF);
170};
171
172class PHIElimination : public MachineFunctionPass {
173public:
174 static char ID; // Pass identification, replacement for typeid
175
176 PHIElimination() : MachineFunctionPass(ID) {}
177
178 bool runOnMachineFunction(MachineFunction &MF) override {
179 PHIEliminationImpl Impl(this);
180 return Impl.run(MF);
181 }
182
183 MachineFunctionProperties getSetProperties() const override {
184 return MachineFunctionProperties().setNoPHIs();
185 }
186
187 void getAnalysisUsage(AnalysisUsage &AU) const override;
188};
189
190} // end anonymous namespace
191
195 PHIEliminationImpl Impl(MF, MFAM);
196 bool Changed = Impl.run(MF);
197 if (!Changed)
198 return PreservedAnalyses::all();
200 PA.preserve<LiveIntervalsAnalysis>();
201 PA.preserve<SlotIndexesAnalysis>();
202 PA.preserve<MachineDominatorTreeAnalysis>();
204 PA.preserve<MachineLoopAnalysis>();
205 PA.preserve<MachineBlockFrequencyAnalysis>();
206 return PA;
207}
208
209STATISTIC(NumLowered, "Number of phis lowered");
210STATISTIC(NumCriticalEdgesSplit, "Number of critical edges split");
211STATISTIC(NumReused, "Number of reused lowered phis");
212
213char PHIElimination::ID = 0;
214
215char &llvm::PHIEliminationID = PHIElimination::ID;
216
218 "Eliminate PHI nodes for register allocation", false,
219 false)
225 "Eliminate PHI nodes for register allocation", false, false)
226
227void PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
228 AU.addUsedIfAvailable<SlotIndexesWrapperPass>();
229 AU.addUsedIfAvailable<LiveIntervalsWrapperPass>();
230 AU.addUsedIfAvailable<MachineLoopInfoWrapperPass>();
231 AU.addPreserved<SlotIndexesWrapperPass>();
232 AU.addPreserved<LiveIntervalsWrapperPass>();
233 AU.addPreserved<MachineDominatorTreeWrapperPass>();
234 AU.addPreserved<MachinePostDominatorTreeWrapperPass>();
235 AU.addPreserved<MachineLoopInfoWrapperPass>();
236 AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
237 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
239}
240
241bool PHIEliminationImpl::run(MachineFunction &MF) {
242 Opts = &getCodeGenOptions(MF);
243 MRI = &MF.getRegInfo();
244
245 MachineDomTreeUpdater MDTU(MDT, PDT,
246 MachineDomTreeUpdater::UpdateStrategy::Lazy);
247
248 bool Changed = false;
249
250 // Split critical edges to help the coalescer.
251 if (Opts->phi_elim_edge_splitting && LIS) {
252 for (auto &MBB : MF)
253 Changed |= SplitPHIEdges(MF, MBB, MLI, MDTU);
254 }
255
256 // This pass takes the function out of SSA form.
257 MRI->leaveSSA();
258
259 // Populate VRegPHIUseCount
260 if (LIS)
261 analyzePHINodes(MF);
262
263 // Eliminate PHI instructions by inserting copies into predecessor blocks.
264 for (auto &MBB : MF)
265 Changed |= EliminatePHINodes(MF, MBB);
266
267 // Remove dead IMPLICIT_DEF instructions.
268 for (MachineInstr *DefMI : ImpDefs) {
269 Register DefReg = DefMI->getOperand(0).getReg();
270 if (MRI->use_nodbg_empty(DefReg)) {
271 if (SI)
272 SI->removeMachineInstrFromMaps(*DefMI);
274 }
275 }
276
277 // Clean up the lowered PHI instructions.
278 for (auto &I : LoweredPHIs) {
279 if (SI)
280 SI->removeMachineInstrFromMaps(*I.first);
281 MF.deleteMachineInstr(I.first);
282 }
283
284 LoweredPHIs.clear();
285 ImpDefs.clear();
286 VRegPHIUseCount.clear();
287 PHISrcLaneKills.clear();
288
289 MF.getProperties().setNoPHIs();
290
291 return Changed;
292}
293
294/// Move debug instructions preceding \p Position to immediately after it.
297 MachineBasicBlock::iterator InsertPt = std::next(Position);
298 for (auto I = MBB.begin(); I != Position;) {
299 if (!I->isDebugInstr()) {
300 ++I;
301 continue;
302 }
303
304 auto DebugBegin = I;
305 I = skipDebugInstructionsForward(I, Position,
306 /*SkipPseudoOp=*/false);
307 MBB.splice(InsertPt, &MBB, DebugBegin, I);
308 }
309}
310
311/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
312/// predecessor basic blocks.
313bool PHIEliminationImpl::EliminatePHINodes(MachineFunction &MF,
315 if (MBB.empty() || !MBB.front().isPHI())
316 return false; // Quick exit for basic blocks without PHIs.
317
318 // Ignore debug instructions when choosing the destination-copy position.
319 // Move any skipped debug instructions after that position so they remain
320 // after the destination copies. Do not change pseudo-probe placement.
323 /*SkipPseudoOp=*/false),
324 MBB.begin(), /*SkipPseudoOp=*/false);
326
327 // If all incoming edges are critical, we try to deduplicate identical PHIs so
328 // that we generate fewer copies. If at any edge is non-critical, we either
329 // have less than two predecessors (=> no PHIs) or a predecessor has only us
330 // as a successor (=> identical PHI node can't occur in different block).
331 bool AllEdgesCritical = MBB.pred_size() >= 2;
333 if (Pred->succ_size() < 2) {
334 AllEdgesCritical = false;
335 break;
336 }
337 }
338
339 while (MBB.front().isPHI())
340 LowerPHINode(MBB, LastPHIIt, AllEdgesCritical);
341
342 return true;
343}
344
345/// Return true if all defs of VirtReg are implicit-defs.
346/// This includes registers with no defs.
347static bool isImplicitlyDefined(Register VirtReg,
348 const MachineRegisterInfo &MRI) {
349 for (MachineInstr &DI : MRI.def_instructions(VirtReg))
350 if (!DI.isImplicitDef())
351 return false;
352 return true;
353}
354
355/// Return true if all sources of the phi node are implicit_def's, or undef's.
356static bool allPhiOperandsUndefined(const MachineInstr &MPhi,
357 const MachineRegisterInfo &MRI) {
358 for (unsigned I = 1, E = MPhi.getNumOperands(); I != E; I += 2) {
359 const MachineOperand &MO = MPhi.getOperand(I);
360 if (!isImplicitlyDefined(MO.getReg(), MRI) && !MO.isUndef())
361 return false;
362 }
363 return true;
364}
365/// LowerPHINode - Lower the PHI node at the top of the specified block.
366void PHIEliminationImpl::LowerPHINode(MachineBasicBlock &MBB,
368 bool AllEdgesCritical) {
369 ++NumLowered;
370
371 MachineBasicBlock::iterator AfterPHIsIt = std::next(LastPHIIt);
372
373 // Unlink the PHI node from the basic block, but don't delete the PHI yet.
374 MachineInstr *MPhi = MBB.remove(&*MBB.begin());
375
376 unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
377 Register DestReg = MPhi->getOperand(0).getReg();
378 assert(MPhi->getOperand(0).getSubReg() == 0 && "Can't handle sub-reg PHIs");
379
380 // Create a new register for the incoming PHI arguments.
382 Register IncomingReg;
383 bool EliminateNow = true; // delay elimination of nodes in LoweredPHIs
384 bool reusedIncoming = false; // Is IncomingReg reused from an earlier PHI?
385
386 // Insert a register to register copy at the top of the current block (but
387 // after any remaining phi nodes) which copies the new incoming register
388 // into the phi node destination.
389 MachineInstr *PHICopy = nullptr;
392 if (allPhiOperandsUndefined(*MPhi, *MRI))
393 // If all sources of a PHI node are implicit_def or undef uses, just emit an
394 // implicit_def instead of a copy.
395 PHICopy = BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
396 TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
397 else {
398 // Can we reuse an earlier PHI node? This only happens for critical edges,
399 // typically those created by tail duplication. Typically, an identical PHI
400 // node can't occur, so avoid hashing/storing such PHIs, which is somewhat
401 // expensive.
402 Register *Entry = nullptr;
403 if (AllEdgesCritical)
404 Entry = &LoweredPHIs[MPhi];
405 if (Entry && *Entry) {
406 // An identical PHI node was already lowered. Reuse the incoming register.
407 IncomingReg = *Entry;
408 reusedIncoming = true;
409 ++NumReused;
410 LLVM_DEBUG(dbgs() << "Reusing " << printReg(IncomingReg) << " for "
411 << *MPhi);
412 } else {
413 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
414 IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
415 if (Entry) {
416 EliminateNow = false;
417 *Entry = IncomingReg;
418 }
419 }
420
421 // Give the target possiblity to handle special cases fallthrough otherwise
422 PHICopy = TII->createPHIDestinationCopy(
423 MBB, AfterPHIsIt, MPhi->getDebugLoc(), IncomingReg, DestReg);
424 }
425
426 if (MPhi->peekDebugInstrNum() && IncomingReg) {
427 // If referred to by debug-info, store where this PHI was.
429 unsigned ID = MPhi->peekDebugInstrNum();
430 auto P = MachineFunction::DebugPHIRegallocPos(&MBB, IncomingReg, 0);
431 auto Res = MF->DebugPHIPositions.insert({ID, P});
432 assert(Res.second);
433 (void)Res;
434 }
435
436 // Update LiveIntervals for the new copy or implicit def.
437 SlotIndex DestCopyIndex;
438 if (SI)
439 DestCopyIndex = SI->insertMachineInstrInMaps(*PHICopy);
440
441 if (LIS) {
442 assert(DestCopyIndex.isValid() &&
443 "Expected a valid SlotIndex if LIS is available.");
444 SlotIndex MBBStartIndex = LIS->getMBBStartIdx(&MBB);
445 if (IncomingReg) {
446 // Add the region from the beginning of MBB to the copy instruction to
447 // IncomingReg's live interval.
448 LiveInterval &IncomingLI = LIS->getOrCreateEmptyInterval(IncomingReg);
449 VNInfo *IncomingVNI = IncomingLI.getVNInfoAt(MBBStartIndex);
450 if (!IncomingVNI)
451 IncomingVNI =
452 IncomingLI.getNextValue(MBBStartIndex, LIS->getVNInfoAllocator());
454 MBBStartIndex, DestCopyIndex.getRegSlot(), IncomingVNI));
455 }
456
457 LiveInterval &DestLI = LIS->getInterval(DestReg);
458 assert(!DestLI.empty() && "PHIs should have non-empty LiveIntervals.");
459
460 // Make sure the instruction's dead flag matches the dead range created
461 // below.
462 if (DestLI.endIndex().isDead())
463 PHICopy->getOperand(0).setIsDead();
464
465 SlotIndex NewStart = DestCopyIndex.getRegSlot();
466
467 SmallVector<LiveRange *> ToUpdate({&DestLI});
468 for (auto &SR : DestLI.subranges())
469 ToUpdate.push_back(&SR);
470
471 for (auto LR : ToUpdate) {
472 auto DestSegment = LR->find(MBBStartIndex);
473 assert(DestSegment != LR->end() &&
474 "PHI destination must be live in block");
475
476 if (LR->endIndex().isDead()) {
477 // A dead PHI's live range begins and ends at the start of the MBB, but
478 // the lowered copy, which will still be dead, needs to begin and end at
479 // the copy instruction.
480 VNInfo *OrigDestVNI = LR->getVNInfoAt(DestSegment->start);
481 assert(OrigDestVNI && "PHI destination should be live at block entry.");
482 LR->removeSegment(DestSegment->start, DestSegment->start.getDeadSlot());
483 LR->createDeadDef(NewStart, LIS->getVNInfoAllocator());
484 LR->removeValNo(OrigDestVNI);
485 continue;
486 }
487
488 // Destination copies are not inserted in the same order as the PHI nodes
489 // they replace. Hence the start of the live range may need to be adjusted
490 // to match the actual slot index of the copy.
491 if (DestSegment->start > NewStart) {
492 VNInfo *VNI = LR->getVNInfoAt(DestSegment->start);
493 assert(VNI && "value should be defined for known segment");
494 LR->addSegment(
495 LiveInterval::Segment(NewStart, DestSegment->start, VNI));
496 } else if (DestSegment->start < NewStart) {
497 assert(DestSegment->start >= MBBStartIndex);
498 assert(DestSegment->end >= DestCopyIndex.getRegSlot());
499 LR->removeSegment(DestSegment->start, NewStart);
500 }
501 VNInfo *DestVNI = LR->getVNInfoAt(NewStart);
502 assert(DestVNI && "PHI destination should be live at its definition.");
503 DestVNI->def = NewStart;
504 }
505
506 // Adjust the VRegPHIUseCount map to account for the removal of this PHI
507 // node.
508 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
509 if (!MPhi->getOperand(i).isUndef()) {
510 --VRegPHIUseCount[BBVRegPair(
511 MPhi->getOperand(i + 1).getMBB()->getNumber(),
512 MPhi->getOperand(i).getReg())];
513 }
514 }
515 }
516
517 // Now loop over all of the incoming arguments, changing them to copy into the
518 // IncomingReg register in the corresponding predecessor basic block.
520 for (int i = NumSrcs - 1; i >= 0; --i) {
521 Register SrcReg = MPhi->getOperand(i * 2 + 1).getReg();
522 unsigned SrcSubReg = MPhi->getOperand(i * 2 + 1).getSubReg();
523 bool SrcUndef = MPhi->getOperand(i * 2 + 1).isUndef() ||
524 isImplicitlyDefined(SrcReg, *MRI);
525 assert(SrcReg.isVirtual() &&
526 "Machine PHI Operands must all be virtual registers!");
527
528 // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
529 // path the PHI.
530 MachineBasicBlock &opBlock = *MPhi->getOperand(i * 2 + 2).getMBB();
531
532 // Check to make sure we haven't already emitted the copy for this block.
533 // This can happen because PHI nodes may have multiple entries for the same
534 // basic block.
535 if (!MBBsInsertedInto.insert(&opBlock).second)
536 continue; // If the copy has already been emitted, we're done.
537
538 MachineInstr *SrcRegDef = MRI->getVRegDef(SrcReg);
539 if (SrcRegDef && TII->isUnspillableTerminator(SrcRegDef)) {
540 assert(SrcRegDef->getOperand(0).isReg() &&
541 SrcRegDef->getOperand(0).isDef() &&
542 "Expected operand 0 to be a reg def!");
543 // Now that the PHI's use has been removed (as the instruction was
544 // removed) there should be no other uses of the SrcReg.
545 assert(MRI->use_empty(SrcReg) &&
546 "Expected a single use from UnspillableTerminator");
547 SrcRegDef->getOperand(0).setReg(IncomingReg);
548
549 if (LIS) {
550 LiveInterval &SrcLI = LIS->getInterval(SrcReg);
551 SlotIndex DefIdx = LIS->getInstructionIndex(*SrcRegDef).getRegSlot();
552 LiveInterval &IncomingLI = LIS->getOrCreateEmptyInterval(IncomingReg);
553 VNInfo *VNI =
554 IncomingLI.getNextValue(DefIdx, LIS->getVNInfoAllocator());
555 for (const LiveInterval::Segment &S : SrcLI)
556 IncomingLI.addSegment(LiveInterval::Segment(S.start, S.end, VNI));
557 LIS->removeInterval(SrcReg);
558 }
559
560 continue;
561 }
562
563 // Find a safe location to insert the copy, this may be the first terminator
564 // in the block (or end()).
566 findPHICopyInsertPoint(&opBlock, &MBB, SrcReg);
567
568 // Insert the copy.
569 MachineInstr *NewSrcInstr = nullptr;
570 if (!reusedIncoming && IncomingReg) {
571 if (SrcUndef) {
572 // The source register is undefined, so there is no need for a real
573 // COPY, but we still need to ensure joint dominance by defs.
574 // Insert an IMPLICIT_DEF instruction.
575 NewSrcInstr =
576 BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(),
577 TII->get(TargetOpcode::IMPLICIT_DEF), IncomingReg);
578
579 // Clean up the old implicit-def, if there even was one.
580 if (MachineInstr *DefMI = MRI->getVRegDef(SrcReg))
581 if (DefMI->isImplicitDef())
582 ImpDefs.insert(DefMI);
583 } else {
584 // Delete the debug location, since the copy is inserted into a
585 // different basic block.
586 NewSrcInstr = TII->createPHISourceCopy(opBlock, InsertPos, nullptr,
587 SrcReg, SrcSubReg, IncomingReg);
588 }
589 }
590
591 BBVRegPair SrcKey(opBlock.getNumber(), SrcReg);
592 bool IsLastPHIUse = !VRegPHIUseCount.lookup(SrcKey);
593
594 if (SI && NewSrcInstr)
595 SI->insertMachineInstrInMaps(*NewSrcInstr);
596
597 if (LIS) {
598 if (NewSrcInstr) {
599 assert(
600 SI &&
601 "Expected SI to be available to insert new MI if LIS is available");
602 LIS->addSegmentToEndOfBlock(IncomingReg, *NewSrcInstr);
603
604 if (!SrcUndef && LIS->getInterval(SrcReg).hasSubRanges()) {
605 addPHISrcLaneKill(
606 PHISrcLaneKills[SrcKey], TRI.getSubRegIndexLaneMask(SrcSubReg),
607 LIS->getInstructionIndex(*NewSrcInstr).getRegSlot());
608 }
609 }
610
611 if (!SrcUndef && IsLastPHIUse) {
612 LiveInterval &SrcLI = LIS->getInterval(SrcReg);
613
614 bool isLiveOut = false;
615 for (MachineBasicBlock *Succ : opBlock.successors()) {
616 SlotIndex startIdx = LIS->getMBBStartIdx(Succ);
617 VNInfo *VNI = SrcLI.getVNInfoAt(startIdx);
618
619 // Definitions by other PHIs are not truly live-in for our purposes.
620 if (VNI && VNI->def != startIdx) {
621 isLiveOut = true;
622 break;
623 }
624 }
625
626 PHISrcLaneKillMap::iterator KillsIt = PHISrcLaneKills.end();
627 if (SrcLI.hasSubRanges())
628 KillsIt = PHISrcLaneKills.find(SrcKey);
629
630 if (!isLiveOut) {
631 auto RecordLaneKill = [&](MachineInstr &MI) {
632 addPHISrcLaneKill(
633 KillsIt->second,
634 AnalyzeVirtRegLanesInBundle(MI, SrcReg, *MRI, TRI).first,
635 LIS->getInstructionIndex(MI).getRegSlot());
636 };
637
638 // Each lane dies at its own last read, which can be earlier than the
639 // last read of the whole register, so record a kill for every read
640 // after the first inserted copy, not just for the last one. A copy
641 // for a landing pad goes before the call, so this can include
642 // ordinary instructions and the copies themselves.
643 MachineBasicBlock::iterator ScanStart = InsertPos;
644 if (KillsIt != PHISrcLaneKills.end()) {
645 SlotIndex FirstCopyIndex = KillsIt->second.front().Index;
646 if (InsertPos == opBlock.end() ||
647 FirstCopyIndex <= SI->getIndexBefore(*InsertPos).getRegSlot()) {
648 ScanStart = std::next(MachineBasicBlock::iterator(
649 LIS->getInstructionFromIndex(FirstCopyIndex)));
650 }
651 }
652
653 MachineBasicBlock::iterator KillInst = opBlock.end();
654 for (MachineBasicBlock::iterator MI = ScanStart; MI != opBlock.end();
655 ++MI) {
656 if (MI->isDebugInstr() ||
657 !MI->readsRegister(SrcReg, /*TRI=*/nullptr))
658 continue;
659 KillInst = MI;
660 if (KillsIt != PHISrcLaneKills.end())
661 RecordLaneKill(*MI);
662 }
663
664 if (KillInst == opBlock.end()) {
665 // No terminator uses the register.
666
667 if (reusedIncoming || !IncomingReg) {
668 // We may have to rewind a bit if we didn't just insert a copy.
669 KillInst = InsertPos;
670 while (KillInst != opBlock.begin()) {
671 --KillInst;
672 if (KillInst->isDebugInstr())
673 continue;
674 if (KillInst->readsRegister(SrcReg, /*TRI=*/nullptr))
675 break;
676 }
677 if (KillsIt != PHISrcLaneKills.end())
678 RecordLaneKill(*KillInst);
679 } else {
680 // We just inserted this copy, and its lanes are already recorded.
681 KillInst = std::prev(InsertPos);
682 }
683 }
684 assert(KillInst->readsRegister(SrcReg, /*TRI=*/nullptr) &&
685 "Cannot find kill instruction");
686
687 SlotIndex LastUseIndex = LIS->getInstructionIndex(*KillInst);
688 SlotIndex BlockEndIndex = LIS->getMBBEndIdx(&opBlock);
689 SrcLI.removeSegment(LastUseIndex.getRegSlot(), BlockEndIndex);
690 if (KillsIt != PHISrcLaneKills.end()) {
691 for (LiveInterval::SubRange &SR : SrcLI.subranges()) {
692 LiveQueryResult LRQ = SR.Query(LastUseIndex);
693 if (!LRQ.valueOut())
694 continue;
695
696 // The segment can continue past this block when another
697 // predecessor reads the lane; only trim the part in opBlock.
698 SlotIndex EndIndex = std::min(LRQ.endPoint(), BlockEndIndex);
699 for (const PHISrcLaneKill &Kill : reverse(KillsIt->second)) {
700 if ((Kill.Lanes & SR.LaneMask).any()) {
701 if (Kill.Index < EndIndex)
702 SR.removeSegment(Kill.Index, EndIndex);
703 break;
704 }
705 }
706 }
707 }
708 }
709
710 if (KillsIt != PHISrcLaneKills.end())
711 PHISrcLaneKills.erase(KillsIt);
712 }
713 }
714 }
715
716 // Really delete the PHI instruction now, if it is not in the LoweredPHIs map.
717 if (EliminateNow) {
718 if (SI)
719 SI->removeMachineInstrFromMaps(*MPhi);
720 MF.deleteMachineInstr(MPhi);
721 }
722}
723
724/// analyzePHINodes - Gather information about the PHI nodes in here. In
725/// particular, we want to map the number of uses of a virtual register which is
726/// used in a PHI node. We map that to the BB the vreg is coming from. This is
727/// used later to determine when the vreg is killed in the BB.
728void PHIEliminationImpl::analyzePHINodes(const MachineFunction &MF) {
729 for (const auto &MBB : MF) {
730 for (const auto &BBI : MBB) {
731 if (!BBI.isPHI())
732 break;
733 for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) {
734 if (!BBI.getOperand(i).isUndef()) {
735 ++VRegPHIUseCount[BBVRegPair(
736 BBI.getOperand(i + 1).getMBB()->getNumber(),
737 BBI.getOperand(i).getReg())];
738 }
739 }
740 }
741 }
742}
743
744bool PHIEliminationImpl::SplitPHIEdges(MachineFunction &MF,
746 MachineLoopInfo *MLI,
747 MachineDomTreeUpdater &MDTU) {
748 if (MBB.empty() || !MBB.front().isPHI() || MBB.isEHPad())
749 return false; // Quick exit for basic blocks without PHIs.
750
751 const MachineLoop *CurLoop = MLI ? MLI->getLoopFor(&MBB) : nullptr;
752 bool IsLoopHeader = CurLoop && &MBB == CurLoop->getHeader();
753
754 bool Changed = false;
755 for (MachineBasicBlock::iterator BBI = MBB.begin(), BBE = MBB.end();
756 BBI != BBE && BBI->isPHI(); ++BBI) {
757 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
758 Register Reg = BBI->getOperand(i).getReg();
759 MachineBasicBlock *PreMBB = BBI->getOperand(i + 1).getMBB();
760 // Is there a critical edge from PreMBB to MBB?
761 if (PreMBB->succ_size() == 1)
762 continue;
763
764 // Avoid splitting backedges of loops. It would introduce small
765 // out-of-line blocks into the loop which is very bad for code placement.
766 if (PreMBB == &MBB && !Opts->phi_elim_split_all_critical_edges)
767 continue;
768 const MachineLoop *PreLoop = MLI ? MLI->getLoopFor(PreMBB) : nullptr;
769 if (IsLoopHeader && PreLoop == CurLoop &&
770 !Opts->phi_elim_split_all_critical_edges)
771 continue;
772
773 // isLiveOutPastPHIs only returns true when the source register is
774 // live-out for some other reason than a phi use. That means the copy we
775 // will insert in PreMBB won't be a kill, and there is a risk it may not
776 // be coalesced away.
777 //
778 // If the copy would be a kill, there is no need to split the edge.
779 bool ShouldSplit = isLiveOutPastPHIs(Reg, PreMBB);
780 if (!ShouldSplit && Opts->phi_elim_live_out_early_exit)
781 continue;
782 if (ShouldSplit) {
783 LLVM_DEBUG(dbgs() << printReg(Reg) << " live-out before critical edge "
784 << printMBBReference(*PreMBB) << " -> "
785 << printMBBReference(MBB) << ": " << *BBI);
786 }
787
788 // If Reg is not live-in to MBB, it means it must be live-in to some
789 // other PreMBB successor, and we can avoid the interference by splitting
790 // the edge.
791 //
792 // If Reg *is* live-in to MBB, the interference is inevitable and a copy
793 // is likely to be left after coalescing. If we are looking at a loop
794 // exiting edge, split it so we won't insert code in the loop, otherwise
795 // don't bother.
796 ShouldSplit =
797 ShouldSplit && !LIS->isLiveInToMBB(LIS->getInterval(Reg), &MBB);
798
799 // Check for a loop exiting edge.
800 if (!ShouldSplit && CurLoop != PreLoop) {
801 LLVM_DEBUG({
802 dbgs() << "Split wouldn't help, maybe avoid loop copies?\n";
803 if (PreLoop)
804 dbgs() << "PreLoop: " << *PreLoop;
805 if (CurLoop)
806 dbgs() << "CurLoop: " << *CurLoop;
807 });
808 // This edge could be entering a loop, exiting a loop, or it could be
809 // both: Jumping directly form one loop to the header of a sibling
810 // loop.
811 // Split unless this edge is entering CurLoop from an outer loop.
812 ShouldSplit = PreLoop && !PreLoop->contains(CurLoop);
813 }
814 if (!ShouldSplit && !Opts->phi_elim_split_all_critical_edges)
815 continue;
816 if (LiveOutSets.empty())
817 computeLiveOutSets(MF);
818 MachineBasicBlock *NewBB =
819 PreMBB->SplitCriticalEdge(&MBB, {LIS, SI, MLI, &LiveOutSets}, &MDTU);
820 if (!NewBB) {
821 LLVM_DEBUG(dbgs() << "Failed to split critical edge.\n");
822 continue;
823 }
824
825 // Patch up MBFI after split if it is available.
826 if (MBFI) {
827 assert(MBPI);
828 MBFI->onEdgeSplit(*PreMBB, *NewBB, *MBPI);
829 }
830
831 Changed = true;
832 ++NumCriticalEdgesSplit;
833 }
834 }
835 return Changed;
836}
837
838void PHIEliminationImpl::computeLiveOutSets(const MachineFunction &MF) {
839 LiveOutSets.resize(MF.getNumBlockIDs());
840 for (unsigned Idx = 0, NumVRegs = MRI->getNumVirtRegs(); Idx != NumVRegs;
841 ++Idx) {
843 if (!LIS->hasInterval(Reg))
844 continue;
845 for (const LiveRange::Segment &S : LIS->getInterval(Reg)) {
846 for (const MachineBasicBlock *MBB = LIS->getMBBFromIndex(S.start);
847 MBB && LIS->getMBBEndIdx(MBB) <= S.end; MBB = MBB->getNextNode())
848 LiveOutSets[MBB->getNumber()].set(Idx);
849 }
850 }
851}
852
853bool PHIEliminationImpl::isLiveOutPastPHIs(Register Reg,
854 const MachineBasicBlock *MBB) {
855 // LiveIntervals considers uses in PHIs to be on the edge rather than in the
856 // predecessor basic block, so that a register used only in a PHI is live out
857 // of the block.
858 const LiveInterval &LI = LIS->getInterval(Reg);
859 for (const MachineBasicBlock *SI : MBB->successors())
860 if (LIS->isLiveInToMBB(LI, SI))
861 return true;
862 return false;
863}
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
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
#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 bool isImplicitlyDefined(Register VirtReg, const MachineRegisterInfo &MRI)
Return true if all defs of VirtReg are implicit-defs.
static void moveDebugInstructionsAfter(MachineBasicBlock &MBB, MachineBasicBlock::iterator Position)
Move debug instructions preceding Position to immediately after it.
#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 '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
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
const HexagonRegisterInfo & getRegisterInfo() const
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()
Result of a LiveRange query.
VNInfo * valueOut() const
Return the value leaving the instruction, if any.
SlotIndex endPoint() const
Return the end point of the last live range segment to interact with the instruction,...
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...
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.
Properties which a MachineFunction may have at a given point in time.
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.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator insert(iterator I, T &&Elt)
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...
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
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.
@ Kill
The last use of a register.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2081
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.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
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 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.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
LLVM_ABI std::pair< LaneBitmask, LaneBitmask > AnalyzeVirtRegLanesInBundle(const MachineInstr &MI, Register Reg, const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI)
Return a pair of lane masks (reads, writes) indicating which lanes this instruction uses with Reg.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This represents a simple continuous liveness interval for a value.