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