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
15#include "llvm/CodeGen/PHIElimination.h"
16#include "PHIEliminationUtils.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/LoopInfo.h"
21#include "llvm/CodeGen/LiveInterval.h"
22#include "llvm/CodeGen/LiveIntervals.h"
23#include "llvm/CodeGen/LiveVariables.h"
24#include "llvm/CodeGen/MachineBasicBlock.h"
25#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
26#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
27#include "llvm/CodeGen/MachineDomTreeUpdater.h"
28#include "llvm/CodeGen/MachineDominators.h"
29#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFunctionPass.h"
31#include "llvm/CodeGen/MachineInstr.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
33#include "llvm/CodeGen/MachineLoopInfo.h"
34#include "llvm/CodeGen/MachineOperand.h"
35#include "llvm/CodeGen/MachinePostDominators.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
37#include "llvm/CodeGen/RegisterClassInfo.h"
38#include "llvm/CodeGen/SlotIndexes.h"
39#include "llvm/CodeGen/TargetInstrInfo.h"
40#include "llvm/CodeGen/TargetOpcodes.h"
41#include "llvm/CodeGen/TargetRegisterInfo.h"
42#include "llvm/CodeGen/TargetSubtargetInfo.h"
43#include "llvm/InitializePasses.h"
44#include "llvm/Pass.h"
45#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/raw_ostream.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(Val: false),
58 cl::Hidden,
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(Val: false),
64 cl::Hidden,
65 cl::desc("Split all critical edges during "
66 "PHI elimination"));
67
68static cl::opt<bool> NoPhiElimLiveOutEarlyExit(
69 "no-phi-elim-live-out-early-exit", cl::init(Val: 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 LiveVariables *LV = nullptr;
77 SlotIndexes *SI = nullptr;
78 LiveIntervals *LIS = nullptr;
79 MachineLoopInfo *MLI = nullptr;
80 MachineDominatorTree *MDT = nullptr;
81 MachinePostDominatorTree *PDT = nullptr;
82 const MachineBranchProbabilityInfo *MBPI = nullptr;
83 MachineBlockFrequencyInfo *MBFI = nullptr;
84
85 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
86 /// in predecessor basic blocks.
87 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
88
89 void LowerPHINode(MachineBasicBlock &MBB,
90 MachineBasicBlock::iterator LastPHIIt,
91 bool AllEdgesCritical);
92
93 /// analyzePHINodes - Gather information about the PHI nodes in
94 /// here. In particular, we want to map the number of uses of a virtual
95 /// register which is used in a PHI node. We map that to the BB the
96 /// vreg is coming from. This is used later to determine when the vreg
97 /// is killed in the BB.
98 void analyzePHINodes(const MachineFunction &MF);
99
100 /// Split critical edges where necessary for good coalescer performance.
101 bool SplitPHIEdges(MachineFunction &MF, MachineBasicBlock &MBB,
102 MachineLoopInfo *MLI,
103 std::vector<SparseBitVector<>> *LiveInSets,
104 MachineDomTreeUpdater &MDTU);
105
106 // These functions are temporary abstractions around LiveVariables and
107 // LiveIntervals, so they can go away when LiveVariables does.
108 bool isLiveIn(Register Reg, const MachineBasicBlock *MBB);
109 bool isLiveOutPastPHIs(Register Reg, const MachineBasicBlock *MBB);
110
111 using BBVRegPair = std::pair<unsigned, Register>;
112 using VRegPHIUse = DenseMap<BBVRegPair, unsigned>;
113
114 // Count the number of non-undef PHI uses of each register in each BB.
115 VRegPHIUse VRegPHIUseCount;
116
117 // Defs of PHI sources which are implicit_def.
118 SmallPtrSet<MachineInstr *, 4> ImpDefs;
119
120 // Map reusable lowered PHI node -> incoming join register.
121 using LoweredPHIMap =
122 DenseMap<MachineInstr *, Register, MachineInstrExpressionTrait>;
123 LoweredPHIMap LoweredPHIs;
124
125 MachineFunctionPass *P = nullptr;
126 MachineFunctionAnalysisManager *MFAM = nullptr;
127
128public:
129 PHIEliminationImpl(MachineFunctionPass *P) : P(P) {
130 auto *LVWrapper = P->getAnalysisIfAvailable<LiveVariablesWrapperPass>();
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 LV = LVWrapper ? &LVWrapper->getLV() : nullptr;
144 SI = SIWrapper ? &SIWrapper->getSI() : nullptr;
145 LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
146 MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
147 MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
148 PDT = PDTWrapper ? &PDTWrapper->getPostDomTree() : nullptr;
149 MBPI = MBPIWrapper ? &MBPIWrapper->getMBPI() : nullptr;
150 MBFI = MBFIWrapper ? &MBFIWrapper->getMBFI() : nullptr;
151 }
152
153 PHIEliminationImpl(MachineFunction &MF, MachineFunctionAnalysisManager &AM)
154 : LV(AM.getCachedResult<LiveVariablesAnalysis>(IR&: MF)),
155 SI(AM.getCachedResult<SlotIndexesAnalysis>(IR&: MF)),
156 LIS(AM.getCachedResult<LiveIntervalsAnalysis>(IR&: MF)),
157 MLI(AM.getCachedResult<MachineLoopAnalysis>(IR&: MF)),
158 MDT(AM.getCachedResult<MachineDominatorTreeAnalysis>(IR&: MF)),
159 PDT(AM.getCachedResult<MachinePostDominatorTreeAnalysis>(IR&: MF)),
160 MBPI(AM.getCachedResult<MachineBranchProbabilityAnalysis>(IR&: MF)),
161 MBFI(AM.getCachedResult<MachineBlockFrequencyAnalysis>(IR&: MF)), MFAM(&AM) {
162 }
163
164 bool run(MachineFunction &MF);
165};
166
167class PHIElimination : public MachineFunctionPass {
168public:
169 static char ID; // Pass identification, replacement for typeid
170
171 PHIElimination() : MachineFunctionPass(ID) {}
172
173 bool runOnMachineFunction(MachineFunction &MF) override {
174 PHIEliminationImpl Impl(this);
175 return Impl.run(MF);
176 }
177
178 MachineFunctionProperties getSetProperties() const override {
179 return MachineFunctionProperties().setNoPHIs();
180 }
181
182 void getAnalysisUsage(AnalysisUsage &AU) const override;
183};
184
185} // end anonymous namespace
186
187PreservedAnalyses
188PHIEliminationPass::run(MachineFunction &MF,
189 MachineFunctionAnalysisManager &MFAM) {
190 PHIEliminationImpl Impl(MF, MFAM);
191 bool Changed = Impl.run(MF);
192 if (!Changed)
193 return PreservedAnalyses::all();
194 auto PA = getMachineFunctionPassPreservedAnalyses();
195 PA.preserve<LiveIntervalsAnalysis>();
196 PA.preserve<LiveVariablesAnalysis>();
197 PA.preserve<SlotIndexesAnalysis>();
198 PA.preserve<MachineDominatorTreeAnalysis>();
199 PA.preserve<MachinePostDominatorTreeAnalysis>();
200 PA.preserve<MachineLoopAnalysis>();
201 PA.preserve<MachineBlockFrequencyAnalysis>();
202 return PA;
203}
204
205STATISTIC(NumLowered, "Number of phis lowered");
206STATISTIC(NumCriticalEdgesSplit, "Number of critical edges split");
207STATISTIC(NumReused, "Number of reused lowered phis");
208
209char PHIElimination::ID = 0;
210
211char &llvm::PHIEliminationID = PHIElimination::ID;
212
213INITIALIZE_PASS_BEGIN(PHIElimination, DEBUG_TYPE,
214 "Eliminate PHI nodes for register allocation", false,
215 false)
216INITIALIZE_PASS_DEPENDENCY(LiveVariablesWrapperPass)
217INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass)
218INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfoWrapperPass)
219INITIALIZE_PASS_END(PHIElimination, DEBUG_TYPE,
220 "Eliminate PHI nodes for register allocation", false, false)
221
222void PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
223 AU.addUsedIfAvailable<LiveVariablesWrapperPass>();
224 AU.addUsedIfAvailable<MachineLoopInfoWrapperPass>();
225 AU.addPreserved<LiveVariablesWrapperPass>();
226 AU.addPreserved<SlotIndexesWrapperPass>();
227 AU.addPreserved<LiveIntervalsWrapperPass>();
228 AU.addPreserved<MachineDominatorTreeWrapperPass>();
229 AU.addPreserved<MachinePostDominatorTreeWrapperPass>();
230 AU.addPreserved<MachineLoopInfoWrapperPass>();
231 AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>();
232 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
233 MachineFunctionPass::getAnalysisUsage(AU);
234}
235
236bool PHIEliminationImpl::run(MachineFunction &MF) {
237 MRI = &MF.getRegInfo();
238
239 MachineDomTreeUpdater MDTU(MDT, PDT,
240 MachineDomTreeUpdater::UpdateStrategy::Lazy);
241
242 bool Changed = false;
243
244 // Split critical edges to help the coalescer.
245 if (!DisableEdgeSplitting && (LV || LIS)) {
246 // A set of live-in regs for each MBB which is used to update LV
247 // efficiently also with large functions.
248 std::vector<SparseBitVector<>> LiveInSets;
249 if (LV) {
250 LiveInSets.resize(new_size: MF.size());
251 for (unsigned Index = 0, e = MRI->getNumVirtRegs(); Index != e; ++Index) {
252 // Set the bit for this register for each MBB where it is
253 // live-through or live-in (killed).
254 Register VirtReg = Register::index2VirtReg(Index);
255 MachineInstr *DefMI = MRI->getVRegDef(Reg: VirtReg);
256 if (!DefMI)
257 continue;
258 LiveVariables::VarInfo &VI = LV->getVarInfo(Reg: VirtReg);
259 SparseBitVector<>::iterator AliveBlockItr = VI.AliveBlocks.begin();
260 SparseBitVector<>::iterator EndItr = VI.AliveBlocks.end();
261 while (AliveBlockItr != EndItr) {
262 unsigned BlockNum = *(AliveBlockItr++);
263 LiveInSets[BlockNum].set(Index);
264 }
265 // The register is live into an MBB in which it is killed but not
266 // defined. See comment for VarInfo in LiveVariables.h.
267 MachineBasicBlock *DefMBB = DefMI->getParent();
268 if (VI.Kills.size() > 1 ||
269 (!VI.Kills.empty() && VI.Kills.front()->getParent() != DefMBB))
270 for (auto *MI : VI.Kills)
271 LiveInSets[MI->getParent()->getNumber()].set(Index);
272 }
273 }
274
275 for (auto &MBB : MF)
276 Changed |=
277 SplitPHIEdges(MF, MBB, MLI, LiveInSets: (LV ? &LiveInSets : nullptr), MDTU);
278 }
279
280 // This pass takes the function out of SSA form.
281 MRI->leaveSSA();
282
283 // Populate VRegPHIUseCount
284 if (LV || LIS)
285 analyzePHINodes(MF);
286
287 // Eliminate PHI instructions by inserting copies into predecessor blocks.
288 for (auto &MBB : MF)
289 Changed |= EliminatePHINodes(MF, MBB);
290
291 // Remove dead IMPLICIT_DEF instructions.
292 for (MachineInstr *DefMI : ImpDefs) {
293 Register DefReg = DefMI->getOperand(i: 0).getReg();
294 if (MRI->use_nodbg_empty(RegNo: DefReg)) {
295 if (SI)
296 SI->removeMachineInstrFromMaps(MI&: *DefMI);
297 DefMI->eraseFromParent();
298 }
299 }
300
301 // Clean up the lowered PHI instructions.
302 for (auto &I : LoweredPHIs) {
303 if (SI)
304 SI->removeMachineInstrFromMaps(MI&: *I.first);
305 MF.deleteMachineInstr(MI: I.first);
306 }
307
308 LoweredPHIs.clear();
309 ImpDefs.clear();
310 VRegPHIUseCount.clear();
311
312 MF.getProperties().setNoPHIs();
313
314 return Changed;
315}
316
317/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
318/// predecessor basic blocks.
319bool PHIEliminationImpl::EliminatePHINodes(MachineFunction &MF,
320 MachineBasicBlock &MBB) {
321 if (MBB.empty() || !MBB.front().isPHI())
322 return false; // Quick exit for basic blocks without PHIs.
323
324 // Get an iterator to the last PHI node.
325 MachineBasicBlock::iterator LastPHIIt =
326 std::prev(x: MBB.SkipPHIsAndLabels(I: MBB.begin()));
327
328 // If all incoming edges are critical, we try to deduplicate identical PHIs so
329 // that we generate fewer copies. If at any edge is non-critical, we either
330 // have less than two predecessors (=> no PHIs) or a predecessor has only us
331 // as a successor (=> identical PHI node can't occur in different block).
332 bool AllEdgesCritical = MBB.pred_size() >= 2;
333 for (MachineBasicBlock *Pred : MBB.predecessors()) {
334 if (Pred->succ_size() < 2) {
335 AllEdgesCritical = false;
336 break;
337 }
338 }
339
340 while (MBB.front().isPHI())
341 LowerPHINode(MBB, LastPHIIt, AllEdgesCritical);
342
343 return true;
344}
345
346/// Return true if all defs of VirtReg are implicit-defs.
347/// This includes registers with no defs.
348static bool isImplicitlyDefined(Register VirtReg,
349 const MachineRegisterInfo &MRI) {
350 for (MachineInstr &DI : MRI.def_instructions(Reg: VirtReg))
351 if (!DI.isImplicitDef())
352 return false;
353 return true;
354}
355
356/// Return true if all sources of the phi node are implicit_def's, or undef's.
357static bool allPhiOperandsUndefined(const MachineInstr &MPhi,
358 const MachineRegisterInfo &MRI) {
359 for (unsigned I = 1, E = MPhi.getNumOperands(); I != E; I += 2) {
360 const MachineOperand &MO = MPhi.getOperand(i: I);
361 if (!isImplicitlyDefined(VirtReg: MO.getReg(), MRI) && !MO.isUndef())
362 return false;
363 }
364 return true;
365}
366/// LowerPHINode - Lower the PHI node at the top of the specified block.
367void PHIEliminationImpl::LowerPHINode(MachineBasicBlock &MBB,
368 MachineBasicBlock::iterator LastPHIIt,
369 bool AllEdgesCritical) {
370 ++NumLowered;
371
372 MachineBasicBlock::iterator AfterPHIsIt = std::next(x: LastPHIIt);
373
374 // Unlink the PHI node from the basic block, but don't delete the PHI yet.
375 MachineInstr *MPhi = MBB.remove(I: &*MBB.begin());
376
377 unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
378 Register DestReg = MPhi->getOperand(i: 0).getReg();
379 assert(MPhi->getOperand(0).getSubReg() == 0 && "Can't handle sub-reg PHIs");
380 bool isDead = MPhi->getOperand(i: 0).isDead();
381
382 // Create a new register for the incoming PHI arguments.
383 MachineFunction &MF = *MBB.getParent();
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;
392 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
393 if (allPhiOperandsUndefined(MPhi: *MPhi, MRI: *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(BB&: MBB, I: AfterPHIsIt, MIMD: MPhi->getDebugLoc(),
397 MCID: TII->get(Opcode: 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(Reg: DestReg);
415 IncomingReg = MF.getRegInfo().createVirtualRegister(RegClass: 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, InsPt: AfterPHIsIt, DL: MPhi->getDebugLoc(), Src: IncomingReg, Dst: DestReg);
425 }
426
427 if (MPhi->peekDebugInstrNum() && IncomingReg) {
428 // If referred to by debug-info, store where this PHI was.
429 MachineFunction *MF = MBB.getParent();
430 unsigned ID = MPhi->peekDebugInstrNum();
431 auto P = MachineFunction::DebugPHIRegallocPos(&MBB, IncomingReg, 0);
432 auto Res = MF->DebugPHIPositions.insert(KV: {ID, P});
433 assert(Res.second);
434 (void)Res;
435 }
436
437 // Update live variable information if there is any.
438 if (LV) {
439 if (IncomingReg) {
440 LiveVariables::VarInfo &VI = LV->getVarInfo(Reg: IncomingReg);
441
442 MachineInstr *OldKill = nullptr;
443 bool IsPHICopyAfterOldKill = false;
444
445 if (reusedIncoming && (OldKill = VI.findKill(MBB: &MBB))) {
446 // Calculate whether the PHICopy is after the OldKill.
447 // In general, the PHICopy is inserted as the first non-phi instruction
448 // by default, so it's before the OldKill. But some Target hooks for
449 // createPHIDestinationCopy() may modify the default insert position of
450 // PHICopy.
451 for (auto I = MBB.SkipPHIsAndLabels(I: MBB.begin()), E = MBB.end(); I != E;
452 ++I) {
453 if (I == PHICopy)
454 break;
455
456 if (I == OldKill) {
457 IsPHICopyAfterOldKill = true;
458 break;
459 }
460 }
461 }
462
463 // When we are reusing the incoming register and it has been marked killed
464 // by OldKill, if the PHICopy is after the OldKill, we should remove the
465 // killed flag from OldKill.
466 if (IsPHICopyAfterOldKill) {
467 LLVM_DEBUG(dbgs() << "Remove old kill from " << *OldKill);
468 LV->removeVirtualRegisterKilled(Reg: IncomingReg, MI&: *OldKill);
469 LLVM_DEBUG(MBB.dump());
470 }
471
472 // Add information to LiveVariables to know that the first used incoming
473 // value or the resued incoming value whose PHICopy is after the OldKIll
474 // is killed. Note that because the value is defined in several places
475 // (once each for each incoming block), the "def" block and instruction
476 // fields for the VarInfo is not filled in.
477 if (!OldKill || IsPHICopyAfterOldKill)
478 LV->addVirtualRegisterKilled(IncomingReg, MI&: *PHICopy);
479 }
480
481 // Since we are going to be deleting the PHI node, if it is the last use of
482 // any registers, or if the value itself is dead, we need to move this
483 // information over to the new copy we just inserted.
484 LV->removeVirtualRegistersKilled(MI&: *MPhi);
485
486 // If the result is dead, update LV.
487 if (isDead) {
488 LV->addVirtualRegisterDead(IncomingReg: DestReg, MI&: *PHICopy);
489 LV->removeVirtualRegisterDead(Reg: DestReg, MI&: *MPhi);
490 }
491 }
492
493 // Update LiveIntervals for the new copy or implicit def.
494 SlotIndex DestCopyIndex;
495 if (SI)
496 DestCopyIndex = SI->insertMachineInstrInMaps(MI&: *PHICopy);
497
498 if (LIS) {
499 assert(DestCopyIndex.isValid() &&
500 "Expected a valid SlotIndex if LIS is available.");
501 SlotIndex MBBStartIndex = LIS->getMBBStartIdx(mbb: &MBB);
502 if (IncomingReg) {
503 // Add the region from the beginning of MBB to the copy instruction to
504 // IncomingReg's live interval.
505 LiveInterval &IncomingLI = LIS->getOrCreateEmptyInterval(Reg: IncomingReg);
506 VNInfo *IncomingVNI = IncomingLI.getVNInfoAt(Idx: MBBStartIndex);
507 if (!IncomingVNI)
508 IncomingVNI =
509 IncomingLI.getNextValue(Def: MBBStartIndex, VNInfoAllocator&: LIS->getVNInfoAllocator());
510 IncomingLI.addSegment(S: LiveInterval::Segment(
511 MBBStartIndex, DestCopyIndex.getRegSlot(), IncomingVNI));
512 }
513
514 LiveInterval &DestLI = LIS->getInterval(Reg: DestReg);
515 assert(!DestLI.empty() && "PHIs should have non-empty LiveIntervals.");
516
517 SlotIndex NewStart = DestCopyIndex.getRegSlot();
518
519 SmallVector<LiveRange *> ToUpdate({&DestLI});
520 for (auto &SR : DestLI.subranges())
521 ToUpdate.push_back(Elt: &SR);
522
523 for (auto LR : ToUpdate) {
524 auto DestSegment = LR->find(Pos: MBBStartIndex);
525 assert(DestSegment != LR->end() &&
526 "PHI destination must be live in block");
527
528 if (LR->endIndex().isDead()) {
529 // A dead PHI's live range begins and ends at the start of the MBB, but
530 // the lowered copy, which will still be dead, needs to begin and end at
531 // the copy instruction.
532 VNInfo *OrigDestVNI = LR->getVNInfoAt(Idx: DestSegment->start);
533 assert(OrigDestVNI && "PHI destination should be live at block entry.");
534 LR->removeSegment(Start: DestSegment->start, End: DestSegment->start.getDeadSlot());
535 LR->createDeadDef(Def: NewStart, VNIAlloc&: LIS->getVNInfoAllocator());
536 LR->removeValNo(ValNo: OrigDestVNI);
537 continue;
538 }
539
540 // Destination copies are not inserted in the same order as the PHI nodes
541 // they replace. Hence the start of the live range may need to be adjusted
542 // to match the actual slot index of the copy.
543 if (DestSegment->start > NewStart) {
544 VNInfo *VNI = LR->getVNInfoAt(Idx: DestSegment->start);
545 assert(VNI && "value should be defined for known segment");
546 LR->addSegment(
547 S: LiveInterval::Segment(NewStart, DestSegment->start, VNI));
548 } else if (DestSegment->start < NewStart) {
549 assert(DestSegment->start >= MBBStartIndex);
550 assert(DestSegment->end >= DestCopyIndex.getRegSlot());
551 LR->removeSegment(Start: DestSegment->start, End: NewStart);
552 }
553 VNInfo *DestVNI = LR->getVNInfoAt(Idx: NewStart);
554 assert(DestVNI && "PHI destination should be live at its definition.");
555 DestVNI->def = NewStart;
556 }
557 }
558
559 // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
560 if (LV || LIS) {
561 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
562 if (!MPhi->getOperand(i).isUndef()) {
563 --VRegPHIUseCount[BBVRegPair(
564 MPhi->getOperand(i: i + 1).getMBB()->getNumber(),
565 MPhi->getOperand(i).getReg())];
566 }
567 }
568 }
569
570 // Now loop over all of the incoming arguments, changing them to copy into the
571 // IncomingReg register in the corresponding predecessor basic block.
572 SmallPtrSet<MachineBasicBlock *, 8> MBBsInsertedInto;
573 for (int i = NumSrcs - 1; i >= 0; --i) {
574 Register SrcReg = MPhi->getOperand(i: i * 2 + 1).getReg();
575 unsigned SrcSubReg = MPhi->getOperand(i: i * 2 + 1).getSubReg();
576 bool SrcUndef = MPhi->getOperand(i: i * 2 + 1).isUndef() ||
577 isImplicitlyDefined(VirtReg: SrcReg, MRI: *MRI);
578 assert(SrcReg.isVirtual() &&
579 "Machine PHI Operands must all be virtual registers!");
580
581 // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
582 // path the PHI.
583 MachineBasicBlock &opBlock = *MPhi->getOperand(i: i * 2 + 2).getMBB();
584
585 // Check to make sure we haven't already emitted the copy for this block.
586 // This can happen because PHI nodes may have multiple entries for the same
587 // basic block.
588 if (!MBBsInsertedInto.insert(Ptr: &opBlock).second)
589 continue; // If the copy has already been emitted, we're done.
590
591 MachineInstr *SrcRegDef = MRI->getVRegDef(Reg: SrcReg);
592 if (SrcRegDef && TII->isUnspillableTerminator(MI: SrcRegDef)) {
593 assert(SrcRegDef->getOperand(0).isReg() &&
594 SrcRegDef->getOperand(0).isDef() &&
595 "Expected operand 0 to be a reg def!");
596 // Now that the PHI's use has been removed (as the instruction was
597 // removed) there should be no other uses of the SrcReg.
598 assert(MRI->use_empty(SrcReg) &&
599 "Expected a single use from UnspillableTerminator");
600 SrcRegDef->getOperand(i: 0).setReg(IncomingReg);
601
602 // Update LiveVariables.
603 if (LV) {
604 LiveVariables::VarInfo &SrcVI = LV->getVarInfo(Reg: SrcReg);
605 LiveVariables::VarInfo &IncomingVI = LV->getVarInfo(Reg: IncomingReg);
606 IncomingVI.AliveBlocks = std::move(SrcVI.AliveBlocks);
607 SrcVI.AliveBlocks.clear();
608 }
609
610 continue;
611 }
612
613 // Find a safe location to insert the copy, this may be the first terminator
614 // in the block (or end()).
615 MachineBasicBlock::iterator InsertPos =
616 findPHICopyInsertPoint(MBB: &opBlock, SuccMBB: &MBB, SrcReg);
617
618 // Insert the copy.
619 MachineInstr *NewSrcInstr = nullptr;
620 if (!reusedIncoming && IncomingReg) {
621 if (SrcUndef) {
622 // The source register is undefined, so there is no need for a real
623 // COPY, but we still need to ensure joint dominance by defs.
624 // Insert an IMPLICIT_DEF instruction.
625 NewSrcInstr =
626 BuildMI(BB&: opBlock, I: InsertPos, MIMD: MPhi->getDebugLoc(),
627 MCID: TII->get(Opcode: TargetOpcode::IMPLICIT_DEF), DestReg: IncomingReg);
628
629 // Clean up the old implicit-def, if there even was one.
630 if (MachineInstr *DefMI = MRI->getVRegDef(Reg: SrcReg))
631 if (DefMI->isImplicitDef())
632 ImpDefs.insert(Ptr: DefMI);
633 } else {
634 // Delete the debug location, since the copy is inserted into a
635 // different basic block.
636 NewSrcInstr = TII->createPHISourceCopy(MBB&: opBlock, InsPt: InsertPos, DL: nullptr,
637 Src: SrcReg, SrcSubReg, Dst: IncomingReg);
638 }
639 }
640
641 // We only need to update the LiveVariables kill of SrcReg if this was the
642 // last PHI use of SrcReg to be lowered on this CFG edge and it is not live
643 // out of the predecessor. We can also ignore undef sources.
644 if (LV && !SrcUndef &&
645 !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)] &&
646 !LV->isLiveOut(Reg: SrcReg, MBB: opBlock)) {
647 // We want to be able to insert a kill of the register if this PHI (aka,
648 // the copy we just inserted) is the last use of the source value. Live
649 // variable analysis conservatively handles this by saying that the value
650 // is live until the end of the block the PHI entry lives in. If the value
651 // really is dead at the PHI copy, there will be no successor blocks which
652 // have the value live-in.
653
654 // Okay, if we now know that the value is not live out of the block, we
655 // can add a kill marker in this block saying that it kills the incoming
656 // value!
657
658 // In our final twist, we have to decide which instruction kills the
659 // register. In most cases this is the copy, however, terminator
660 // instructions at the end of the block may also use the value. In this
661 // case, we should mark the last such terminator as being the killing
662 // block, not the copy.
663 MachineBasicBlock::iterator KillInst = opBlock.end();
664 for (MachineBasicBlock::iterator Term = InsertPos; Term != opBlock.end();
665 ++Term) {
666 if (Term->readsRegister(Reg: SrcReg, /*TRI=*/nullptr))
667 KillInst = Term;
668 }
669
670 if (KillInst == opBlock.end()) {
671 // No terminator uses the register.
672
673 if (reusedIncoming || !IncomingReg) {
674 // We may have to rewind a bit if we didn't insert a copy this time.
675 KillInst = InsertPos;
676 while (KillInst != opBlock.begin()) {
677 --KillInst;
678 if (KillInst->isDebugInstr())
679 continue;
680 if (KillInst->readsRegister(Reg: SrcReg, /*TRI=*/nullptr))
681 break;
682 }
683 } else {
684 // We just inserted this copy.
685 KillInst = NewSrcInstr;
686 }
687 }
688 assert(KillInst->readsRegister(SrcReg, /*TRI=*/nullptr) &&
689 "Cannot find kill instruction");
690
691 // Finally, mark it killed.
692 LV->addVirtualRegisterKilled(IncomingReg: SrcReg, MI&: *KillInst);
693
694 // This vreg no longer lives all of the way through opBlock.
695 unsigned opBlockNum = opBlock.getNumber();
696 LV->getVarInfo(Reg: SrcReg).AliveBlocks.reset(Idx: opBlockNum);
697 } else if (LV && SrcUndef &&
698 !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)] &&
699 !LV->isLiveOut(Reg: SrcReg, MBB: opBlock)) {
700 // For undef sources we don't need a kill marker, but the register may
701 // no longer be live through intermediate blocks after the PHI use is
702 // removed. Recompute its LiveVariables info to clear stale AliveBlocks.
703 if (MRI->getVRegDef(Reg: SrcReg))
704 LV->recomputeForSingleDefVirtReg(Reg: SrcReg);
705 }
706
707 if (SI && NewSrcInstr)
708 SI->insertMachineInstrInMaps(MI&: *NewSrcInstr);
709
710 if (LIS) {
711 if (NewSrcInstr) {
712 assert(
713 SI &&
714 "Expected SI to be available to insert new MI if LIS is available");
715 LIS->addSegmentToEndOfBlock(Reg: IncomingReg, startInst&: *NewSrcInstr);
716 }
717
718 if (!SrcUndef &&
719 !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)]) {
720 LiveInterval &SrcLI = LIS->getInterval(Reg: SrcReg);
721
722 bool isLiveOut = false;
723 for (MachineBasicBlock *Succ : opBlock.successors()) {
724 SlotIndex startIdx = LIS->getMBBStartIdx(mbb: Succ);
725 VNInfo *VNI = SrcLI.getVNInfoAt(Idx: startIdx);
726
727 // Definitions by other PHIs are not truly live-in for our purposes.
728 if (VNI && VNI->def != startIdx) {
729 isLiveOut = true;
730 break;
731 }
732 }
733
734 if (!isLiveOut) {
735 MachineBasicBlock::iterator KillInst = opBlock.end();
736 for (MachineBasicBlock::iterator Term = InsertPos;
737 Term != opBlock.end(); ++Term) {
738 if (Term->readsRegister(Reg: SrcReg, /*TRI=*/nullptr))
739 KillInst = Term;
740 }
741
742 if (KillInst == opBlock.end()) {
743 // No terminator uses the register.
744
745 if (reusedIncoming || !IncomingReg) {
746 // We may have to rewind a bit if we didn't just insert a copy.
747 KillInst = InsertPos;
748 while (KillInst != opBlock.begin()) {
749 --KillInst;
750 if (KillInst->isDebugInstr())
751 continue;
752 if (KillInst->readsRegister(Reg: SrcReg, /*TRI=*/nullptr))
753 break;
754 }
755 } else {
756 // We just inserted this copy.
757 KillInst = std::prev(x: InsertPos);
758 }
759 }
760 assert(KillInst->readsRegister(SrcReg, /*TRI=*/nullptr) &&
761 "Cannot find kill instruction");
762
763 SlotIndex LastUseIndex = LIS->getInstructionIndex(Instr: *KillInst);
764 SrcLI.removeSegment(Start: LastUseIndex.getRegSlot(),
765 End: LIS->getMBBEndIdx(mbb: &opBlock));
766 for (auto &SR : SrcLI.subranges()) {
767 SR.removeSegment(Start: LastUseIndex.getRegSlot(),
768 End: LIS->getMBBEndIdx(mbb: &opBlock));
769 }
770 }
771 }
772 }
773 }
774
775 // Really delete the PHI instruction now, if it is not in the LoweredPHIs map.
776 if (EliminateNow) {
777 if (SI)
778 SI->removeMachineInstrFromMaps(MI&: *MPhi);
779 MF.deleteMachineInstr(MI: MPhi);
780 }
781}
782
783/// analyzePHINodes - Gather information about the PHI nodes in here. In
784/// particular, we want to map the number of uses of a virtual register which is
785/// used in a PHI node. We map that to the BB the vreg is coming from. This is
786/// used later to determine when the vreg is killed in the BB.
787void PHIEliminationImpl::analyzePHINodes(const MachineFunction &MF) {
788 for (const auto &MBB : MF) {
789 for (const auto &BBI : MBB) {
790 if (!BBI.isPHI())
791 break;
792 for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) {
793 if (!BBI.getOperand(i).isUndef()) {
794 ++VRegPHIUseCount[BBVRegPair(
795 BBI.getOperand(i: i + 1).getMBB()->getNumber(),
796 BBI.getOperand(i).getReg())];
797 }
798 }
799 }
800 }
801}
802
803bool PHIEliminationImpl::SplitPHIEdges(
804 MachineFunction &MF, MachineBasicBlock &MBB, MachineLoopInfo *MLI,
805 std::vector<SparseBitVector<>> *LiveInSets, MachineDomTreeUpdater &MDTU) {
806 if (MBB.empty() || !MBB.front().isPHI() || MBB.isEHPad())
807 return false; // Quick exit for basic blocks without PHIs.
808
809 const MachineLoop *CurLoop = MLI ? MLI->getLoopFor(BB: &MBB) : nullptr;
810 bool IsLoopHeader = CurLoop && &MBB == CurLoop->getHeader();
811
812 bool Changed = false;
813 for (MachineBasicBlock::iterator BBI = MBB.begin(), BBE = MBB.end();
814 BBI != BBE && BBI->isPHI(); ++BBI) {
815 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
816 Register Reg = BBI->getOperand(i).getReg();
817 MachineBasicBlock *PreMBB = BBI->getOperand(i: i + 1).getMBB();
818 // Is there a critical edge from PreMBB to MBB?
819 if (PreMBB->succ_size() == 1)
820 continue;
821
822 // Avoid splitting backedges of loops. It would introduce small
823 // out-of-line blocks into the loop which is very bad for code placement.
824 if (PreMBB == &MBB && !SplitAllCriticalEdges)
825 continue;
826 const MachineLoop *PreLoop = MLI ? MLI->getLoopFor(BB: PreMBB) : nullptr;
827 if (IsLoopHeader && PreLoop == CurLoop && !SplitAllCriticalEdges)
828 continue;
829
830 // LV doesn't consider a phi use live-out, so isLiveOut only returns true
831 // when the source register is live-out for some other reason than a phi
832 // use. That means the copy we will insert in PreMBB won't be a kill, and
833 // there is a risk it may not be coalesced away.
834 //
835 // If the copy would be a kill, there is no need to split the edge.
836 bool ShouldSplit = isLiveOutPastPHIs(Reg, MBB: PreMBB);
837 if (!ShouldSplit && !NoPhiElimLiveOutEarlyExit)
838 continue;
839 if (ShouldSplit) {
840 LLVM_DEBUG(dbgs() << printReg(Reg) << " live-out before critical edge "
841 << printMBBReference(*PreMBB) << " -> "
842 << printMBBReference(MBB) << ": " << *BBI);
843 }
844
845 // If Reg is not live-in to MBB, it means it must be live-in to some
846 // other PreMBB successor, and we can avoid the interference by splitting
847 // the edge.
848 //
849 // If Reg *is* live-in to MBB, the interference is inevitable and a copy
850 // is likely to be left after coalescing. If we are looking at a loop
851 // exiting edge, split it so we won't insert code in the loop, otherwise
852 // don't bother.
853 ShouldSplit = ShouldSplit && !isLiveIn(Reg, MBB: &MBB);
854
855 // Check for a loop exiting edge.
856 if (!ShouldSplit && CurLoop != PreLoop) {
857 LLVM_DEBUG({
858 dbgs() << "Split wouldn't help, maybe avoid loop copies?\n";
859 if (PreLoop)
860 dbgs() << "PreLoop: " << *PreLoop;
861 if (CurLoop)
862 dbgs() << "CurLoop: " << *CurLoop;
863 });
864 // This edge could be entering a loop, exiting a loop, or it could be
865 // both: Jumping directly form one loop to the header of a sibling
866 // loop.
867 // Split unless this edge is entering CurLoop from an outer loop.
868 ShouldSplit = PreLoop && !PreLoop->contains(L: CurLoop);
869 }
870 if (!ShouldSplit && !SplitAllCriticalEdges)
871 continue;
872 MachineBasicBlock *NewBB;
873 if (P)
874 NewBB = PreMBB->SplitCriticalEdge(Succ: &MBB, P&: *P, LiveInSets, MDTU: &MDTU);
875 else
876 NewBB = PreMBB->SplitCriticalEdge(Succ: &MBB, MFAM&: *MFAM, LiveInSets, MDTU: &MDTU);
877 if (!NewBB) {
878 LLVM_DEBUG(dbgs() << "Failed to split critical edge.\n");
879 continue;
880 }
881
882 // Patch up MBFI after split if it is available.
883 if (MBFI) {
884 assert(MBPI);
885 MBFI->onEdgeSplit(NewPredecessor: *PreMBB, NewSuccessor: *NewBB, MBPI: *MBPI);
886 }
887
888 Changed = true;
889 ++NumCriticalEdgesSplit;
890 }
891 }
892 return Changed;
893}
894
895bool PHIEliminationImpl::isLiveIn(Register Reg, const MachineBasicBlock *MBB) {
896 assert((LV || LIS) &&
897 "isLiveIn() requires either LiveVariables or LiveIntervals");
898 if (LIS)
899 return LIS->isLiveInToMBB(LR: LIS->getInterval(Reg), mbb: MBB);
900 else
901 return LV->isLiveIn(Reg, MBB: *MBB);
902}
903
904bool PHIEliminationImpl::isLiveOutPastPHIs(Register Reg,
905 const MachineBasicBlock *MBB) {
906 assert((LV || LIS) &&
907 "isLiveOutPastPHIs() requires either LiveVariables or LiveIntervals");
908 // LiveVariables considers uses in PHIs to be in the predecessor basic block,
909 // so that a register used only in a PHI is not live out of the block. In
910 // contrast, LiveIntervals considers uses in PHIs to be on the edge rather
911 // than in the predecessor basic block, so that a register used only in a PHI
912 // is live out of the block.
913 if (LIS) {
914 const LiveInterval &LI = LIS->getInterval(Reg);
915 for (const MachineBasicBlock *SI : MBB->successors())
916 if (LI.liveAt(index: LIS->getMBBStartIdx(mbb: SI)))
917 return true;
918 return false;
919 } else {
920 return LV->isLiveOut(Reg, MBB: *MBB);
921 }
922}
923