xref: /llvm-project/llvm/lib/CodeGen/PHIElimination.cpp (revision 3bff611068ae70e3273a46bbc72bc66b66f98c1c)
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 "PHIEliminationUtils.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/CodeGen/LiveInterval.h"
21 #include "llvm/CodeGen/LiveIntervals.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/CodeGen/MachineOperand.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SlotIndexes.h"
33 #include "llvm/CodeGen/TargetInstrInfo.h"
34 #include "llvm/CodeGen/TargetOpcodes.h"
35 #include "llvm/CodeGen/TargetRegisterInfo.h"
36 #include "llvm/CodeGen/TargetSubtargetInfo.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <cassert>
42 #include <iterator>
43 #include <utility>
44 
45 using namespace llvm;
46 
47 #define DEBUG_TYPE "phi-node-elimination"
48 
49 static cl::opt<bool>
50 DisableEdgeSplitting("disable-phi-elim-edge-splitting", cl::init(false),
51                      cl::Hidden, cl::desc("Disable critical edge splitting "
52                                           "during PHI elimination"));
53 
54 static cl::opt<bool>
55 SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false),
56                       cl::Hidden, cl::desc("Split all critical edges during "
57                                            "PHI elimination"));
58 
59 static cl::opt<bool> NoPhiElimLiveOutEarlyExit(
60     "no-phi-elim-live-out-early-exit", cl::init(false), cl::Hidden,
61     cl::desc("Do not use an early exit if isLiveOutPastPHIs returns true."));
62 
63 namespace {
64 
65   class PHIElimination : public MachineFunctionPass {
66     MachineRegisterInfo *MRI = nullptr; // Machine register information
67     LiveVariables *LV = nullptr;
68     LiveIntervals *LIS = nullptr;
69 
70   public:
71     static char ID; // Pass identification, replacement for typeid
72 
73     PHIElimination() : MachineFunctionPass(ID) {
74       initializePHIEliminationPass(*PassRegistry::getPassRegistry());
75     }
76 
77     bool runOnMachineFunction(MachineFunction &MF) override;
78     void getAnalysisUsage(AnalysisUsage &AU) const override;
79 
80   private:
81     /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
82     /// in predecessor basic blocks.
83     bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
84 
85     void LowerPHINode(MachineBasicBlock &MBB,
86                       MachineBasicBlock::iterator LastPHIIt);
87 
88     /// analyzePHINodes - Gather information about the PHI nodes in
89     /// here. In particular, we want to map the number of uses of a virtual
90     /// register which is used in a PHI node. We map that to the BB the
91     /// vreg is coming from. This is used later to determine when the vreg
92     /// is killed in the BB.
93     void analyzePHINodes(const MachineFunction& MF);
94 
95     /// Split critical edges where necessary for good coalescer performance.
96     bool SplitPHIEdges(MachineFunction &MF, MachineBasicBlock &MBB,
97                        MachineLoopInfo *MLI,
98                        std::vector<SparseBitVector<>> *LiveInSets);
99 
100     // These functions are temporary abstractions around LiveVariables and
101     // LiveIntervals, so they can go away when LiveVariables does.
102     bool isLiveIn(Register Reg, const MachineBasicBlock *MBB);
103     bool isLiveOutPastPHIs(Register Reg, const MachineBasicBlock *MBB);
104 
105     using BBVRegPair = std::pair<unsigned, Register>;
106     using VRegPHIUse = DenseMap<BBVRegPair, unsigned>;
107 
108     // Count the number of non-undef PHI uses of each register in each BB.
109     VRegPHIUse VRegPHIUseCount;
110 
111     // Defs of PHI sources which are implicit_def.
112     SmallPtrSet<MachineInstr*, 4> ImpDefs;
113 
114     // Map reusable lowered PHI node -> incoming join register.
115     using LoweredPHIMap =
116         DenseMap<MachineInstr*, unsigned, MachineInstrExpressionTrait>;
117     LoweredPHIMap LoweredPHIs;
118   };
119 
120 } // end anonymous namespace
121 
122 STATISTIC(NumLowered, "Number of phis lowered");
123 STATISTIC(NumCriticalEdgesSplit, "Number of critical edges split");
124 STATISTIC(NumReused, "Number of reused lowered phis");
125 
126 char PHIElimination::ID = 0;
127 
128 char& llvm::PHIEliminationID = PHIElimination::ID;
129 
130 INITIALIZE_PASS_BEGIN(PHIElimination, DEBUG_TYPE,
131                       "Eliminate PHI nodes for register allocation",
132                       false, false)
133 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
134 INITIALIZE_PASS_END(PHIElimination, DEBUG_TYPE,
135                     "Eliminate PHI nodes for register allocation", false, false)
136 
137 void PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
138   AU.addUsedIfAvailable<LiveVariables>();
139   AU.addUsedIfAvailable<LiveIntervals>();
140   AU.addPreserved<LiveVariables>();
141   AU.addPreserved<SlotIndexes>();
142   AU.addPreserved<LiveIntervals>();
143   AU.addPreserved<MachineDominatorTree>();
144   AU.addPreserved<MachineLoopInfo>();
145   MachineFunctionPass::getAnalysisUsage(AU);
146 }
147 
148 bool PHIElimination::runOnMachineFunction(MachineFunction &MF) {
149   MRI = &MF.getRegInfo();
150   LV = getAnalysisIfAvailable<LiveVariables>();
151   LIS = getAnalysisIfAvailable<LiveIntervals>();
152 
153   bool Changed = false;
154 
155   // Split critical edges to help the coalescer.
156   if (!DisableEdgeSplitting && (LV || LIS)) {
157     // A set of live-in regs for each MBB which is used to update LV
158     // efficiently also with large functions.
159     std::vector<SparseBitVector<>> LiveInSets;
160     if (LV) {
161       LiveInSets.resize(MF.size());
162       for (unsigned Index = 0, e = MRI->getNumVirtRegs(); Index != e; ++Index) {
163         // Set the bit for this register for each MBB where it is
164         // live-through or live-in (killed).
165         Register VirtReg = Register::index2VirtReg(Index);
166         MachineInstr *DefMI = MRI->getVRegDef(VirtReg);
167         if (!DefMI)
168           continue;
169         LiveVariables::VarInfo &VI = LV->getVarInfo(VirtReg);
170         SparseBitVector<>::iterator AliveBlockItr = VI.AliveBlocks.begin();
171         SparseBitVector<>::iterator EndItr = VI.AliveBlocks.end();
172         while (AliveBlockItr != EndItr) {
173           unsigned BlockNum = *(AliveBlockItr++);
174           LiveInSets[BlockNum].set(Index);
175         }
176         // The register is live into an MBB in which it is killed but not
177         // defined. See comment for VarInfo in LiveVariables.h.
178         MachineBasicBlock *DefMBB = DefMI->getParent();
179         if (VI.Kills.size() > 1 ||
180             (!VI.Kills.empty() && VI.Kills.front()->getParent() != DefMBB))
181           for (auto *MI : VI.Kills)
182             LiveInSets[MI->getParent()->getNumber()].set(Index);
183       }
184     }
185 
186     MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
187     for (auto &MBB : MF)
188       Changed |= SplitPHIEdges(MF, MBB, MLI, (LV ? &LiveInSets : nullptr));
189   }
190 
191   // This pass takes the function out of SSA form.
192   MRI->leaveSSA();
193 
194   // Populate VRegPHIUseCount
195   analyzePHINodes(MF);
196 
197   // Eliminate PHI instructions by inserting copies into predecessor blocks.
198   for (auto &MBB : MF)
199     Changed |= EliminatePHINodes(MF, MBB);
200 
201   // Remove dead IMPLICIT_DEF instructions.
202   for (MachineInstr *DefMI : ImpDefs) {
203     Register DefReg = DefMI->getOperand(0).getReg();
204     if (MRI->use_nodbg_empty(DefReg)) {
205       if (LIS)
206         LIS->RemoveMachineInstrFromMaps(*DefMI);
207       DefMI->eraseFromParent();
208     }
209   }
210 
211   // Clean up the lowered PHI instructions.
212   for (auto &I : LoweredPHIs) {
213     if (LIS)
214       LIS->RemoveMachineInstrFromMaps(*I.first);
215     MF.deleteMachineInstr(I.first);
216   }
217 
218   // TODO: we should use the incremental DomTree updater here.
219   if (Changed)
220     if (auto *MDT = getAnalysisIfAvailable<MachineDominatorTree>())
221       MDT->getBase().recalculate(MF);
222 
223   LoweredPHIs.clear();
224   ImpDefs.clear();
225   VRegPHIUseCount.clear();
226 
227   MF.getProperties().set(MachineFunctionProperties::Property::NoPHIs);
228 
229   return Changed;
230 }
231 
232 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
233 /// predecessor basic blocks.
234 bool PHIElimination::EliminatePHINodes(MachineFunction &MF,
235                                        MachineBasicBlock &MBB) {
236   if (MBB.empty() || !MBB.front().isPHI())
237     return false;   // Quick exit for basic blocks without PHIs.
238 
239   // Get an iterator to the last PHI node.
240   MachineBasicBlock::iterator LastPHIIt =
241     std::prev(MBB.SkipPHIsAndLabels(MBB.begin()));
242 
243   while (MBB.front().isPHI())
244     LowerPHINode(MBB, LastPHIIt);
245 
246   return true;
247 }
248 
249 /// Return true if all defs of VirtReg are implicit-defs.
250 /// This includes registers with no defs.
251 static bool isImplicitlyDefined(unsigned VirtReg,
252                                 const MachineRegisterInfo &MRI) {
253   for (MachineInstr &DI : MRI.def_instructions(VirtReg))
254     if (!DI.isImplicitDef())
255       return false;
256   return true;
257 }
258 
259 /// Return true if all sources of the phi node are implicit_def's, or undef's.
260 static bool allPhiOperandsUndefined(const MachineInstr &MPhi,
261                                     const MachineRegisterInfo &MRI) {
262   for (unsigned I = 1, E = MPhi.getNumOperands(); I != E; I += 2) {
263     const MachineOperand &MO = MPhi.getOperand(I);
264     if (!isImplicitlyDefined(MO.getReg(), MRI) && !MO.isUndef())
265       return false;
266   }
267   return true;
268 }
269 /// LowerPHINode - Lower the PHI node at the top of the specified block.
270 void PHIElimination::LowerPHINode(MachineBasicBlock &MBB,
271                                   MachineBasicBlock::iterator LastPHIIt) {
272   ++NumLowered;
273 
274   MachineBasicBlock::iterator AfterPHIsIt = std::next(LastPHIIt);
275 
276   // Unlink the PHI node from the basic block, but don't delete the PHI yet.
277   MachineInstr *MPhi = MBB.remove(&*MBB.begin());
278 
279   unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
280   Register DestReg = MPhi->getOperand(0).getReg();
281   assert(MPhi->getOperand(0).getSubReg() == 0 && "Can't handle sub-reg PHIs");
282   bool isDead = MPhi->getOperand(0).isDead();
283 
284   // Create a new register for the incoming PHI arguments.
285   MachineFunction &MF = *MBB.getParent();
286   unsigned IncomingReg = 0;
287   bool reusedIncoming = false;  // Is IncomingReg reused from an earlier PHI?
288 
289   // Insert a register to register copy at the top of the current block (but
290   // after any remaining phi nodes) which copies the new incoming register
291   // into the phi node destination.
292   MachineInstr *PHICopy = nullptr;
293   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
294   if (allPhiOperandsUndefined(*MPhi, *MRI))
295     // If all sources of a PHI node are implicit_def or undef uses, just emit an
296     // implicit_def instead of a copy.
297     PHICopy = BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
298             TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
299   else {
300     // Can we reuse an earlier PHI node? This only happens for critical edges,
301     // typically those created by tail duplication.
302     unsigned &entry = LoweredPHIs[MPhi];
303     if (entry) {
304       // An identical PHI node was already lowered. Reuse the incoming register.
305       IncomingReg = entry;
306       reusedIncoming = true;
307       ++NumReused;
308       LLVM_DEBUG(dbgs() << "Reusing " << printReg(IncomingReg) << " for "
309                         << *MPhi);
310     } else {
311       const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
312       entry = IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
313     }
314     // Give the target possiblity to handle special cases fallthrough otherwise
315     PHICopy = TII->createPHIDestinationCopy(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
316                                   IncomingReg, DestReg);
317   }
318 
319   if (MPhi->peekDebugInstrNum()) {
320     // If referred to by debug-info, store where this PHI was.
321     MachineFunction *MF = MBB.getParent();
322     unsigned ID = MPhi->peekDebugInstrNum();
323     auto P = MachineFunction::DebugPHIRegallocPos(&MBB, IncomingReg, 0);
324     auto Res = MF->DebugPHIPositions.insert({ID, P});
325     assert(Res.second);
326     (void)Res;
327   }
328 
329   // Update live variable information if there is any.
330   if (LV) {
331     if (IncomingReg) {
332       LiveVariables::VarInfo &VI = LV->getVarInfo(IncomingReg);
333 
334       // Increment use count of the newly created virtual register.
335       LV->setPHIJoin(IncomingReg);
336 
337       MachineInstr *OldKill = nullptr;
338       bool IsPHICopyAfterOldKill = false;
339 
340       if (reusedIncoming && (OldKill = VI.findKill(&MBB))) {
341         // Calculate whether the PHICopy is after the OldKill.
342         // In general, the PHICopy is inserted as the first non-phi instruction
343         // by default, so it's before the OldKill. But some Target hooks for
344         // createPHIDestinationCopy() may modify the default insert position of
345         // PHICopy.
346         for (auto I = MBB.SkipPHIsAndLabels(MBB.begin()), E = MBB.end();
347              I != E; ++I) {
348           if (I == PHICopy)
349             break;
350 
351           if (I == OldKill) {
352             IsPHICopyAfterOldKill = true;
353             break;
354           }
355         }
356       }
357 
358       // When we are reusing the incoming register and it has been marked killed
359       // by OldKill, if the PHICopy is after the OldKill, we should remove the
360       // killed flag from OldKill.
361       if (IsPHICopyAfterOldKill) {
362         LLVM_DEBUG(dbgs() << "Remove old kill from " << *OldKill);
363         LV->removeVirtualRegisterKilled(IncomingReg, *OldKill);
364         LLVM_DEBUG(MBB.dump());
365       }
366 
367       // Add information to LiveVariables to know that the first used incoming
368       // value or the resued incoming value whose PHICopy is after the OldKIll
369       // is killed. Note that because the value is defined in several places
370       // (once each for each incoming block), the "def" block and instruction
371       // fields for the VarInfo is not filled in.
372       if (!OldKill || IsPHICopyAfterOldKill)
373         LV->addVirtualRegisterKilled(IncomingReg, *PHICopy);
374     }
375 
376     // Since we are going to be deleting the PHI node, if it is the last use of
377     // any registers, or if the value itself is dead, we need to move this
378     // information over to the new copy we just inserted.
379     LV->removeVirtualRegistersKilled(*MPhi);
380 
381     // If the result is dead, update LV.
382     if (isDead) {
383       LV->addVirtualRegisterDead(DestReg, *PHICopy);
384       LV->removeVirtualRegisterDead(DestReg, *MPhi);
385     }
386   }
387 
388   // Update LiveIntervals for the new copy or implicit def.
389   if (LIS) {
390     SlotIndex DestCopyIndex = LIS->InsertMachineInstrInMaps(*PHICopy);
391 
392     SlotIndex MBBStartIndex = LIS->getMBBStartIdx(&MBB);
393     if (IncomingReg) {
394       // Add the region from the beginning of MBB to the copy instruction to
395       // IncomingReg's live interval.
396       LiveInterval &IncomingLI = LIS->getOrCreateEmptyInterval(IncomingReg);
397       VNInfo *IncomingVNI = IncomingLI.getVNInfoAt(MBBStartIndex);
398       if (!IncomingVNI)
399         IncomingVNI = IncomingLI.getNextValue(MBBStartIndex,
400                                               LIS->getVNInfoAllocator());
401       IncomingLI.addSegment(LiveInterval::Segment(MBBStartIndex,
402                                                   DestCopyIndex.getRegSlot(),
403                                                   IncomingVNI));
404     }
405 
406     LiveInterval &DestLI = LIS->getInterval(DestReg);
407     assert(!DestLI.empty() && "PHIs should have non-empty LiveIntervals.");
408 
409     SlotIndex NewStart = DestCopyIndex.getRegSlot();
410 
411     SmallVector<LiveRange*> ToUpdate;
412     ToUpdate.push_back(&DestLI);
413     for (auto &SR : DestLI.subranges())
414       ToUpdate.push_back(&SR);
415 
416     for (auto LR : ToUpdate) {
417       auto DestSegment = LR->find(MBBStartIndex);
418       assert(DestSegment != LR->end() && "PHI destination must be live in block");
419 
420       if (LR->endIndex().isDead()) {
421         // A dead PHI's live range begins and ends at the start of the MBB, but
422         // the lowered copy, which will still be dead, needs to begin and end at
423         // the copy instruction.
424         VNInfo *OrigDestVNI = LR->getVNInfoAt(DestSegment->start);
425         assert(OrigDestVNI && "PHI destination should be live at block entry.");
426         LR->removeSegment(DestSegment->start, DestSegment->start.getDeadSlot());
427         LR->createDeadDef(NewStart, LIS->getVNInfoAllocator());
428         LR->removeValNo(OrigDestVNI);
429         continue;
430       }
431 
432       if (DestSegment->start > NewStart) {
433         // With a single PHI removed from block the index of the copy may be
434         // lower than the original PHI. Extend live range backward to cover
435         // the copy.
436         VNInfo *VNI = LR->getVNInfoAt(DestSegment->start);
437         assert(VNI && "value should be defined for known segment");
438         LR->addSegment(LiveInterval::Segment(
439             NewStart, DestSegment->start, VNI));
440       } else if (DestSegment->start < NewStart) {
441         // Otherwise, remove the region from the beginning of MBB to the copy
442         // instruction from DestReg's live interval.
443         assert(DestSegment->start >= MBBStartIndex);
444         assert(DestSegment->end >= DestCopyIndex.getRegSlot());
445         LR->removeSegment(DestSegment->start, NewStart);
446       }
447       VNInfo *DestVNI = LR->getVNInfoAt(NewStart);
448       assert(DestVNI && "PHI destination should be live at its definition.");
449       DestVNI->def = NewStart;
450     }
451   }
452 
453   // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
454   for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) {
455     if (!MPhi->getOperand(i).isUndef()) {
456       --VRegPHIUseCount[BBVRegPair(
457           MPhi->getOperand(i + 1).getMBB()->getNumber(),
458           MPhi->getOperand(i).getReg())];
459     }
460   }
461 
462   // Now loop over all of the incoming arguments, changing them to copy into the
463   // IncomingReg register in the corresponding predecessor basic block.
464   SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
465   for (int i = NumSrcs - 1; i >= 0; --i) {
466     Register SrcReg = MPhi->getOperand(i * 2 + 1).getReg();
467     unsigned SrcSubReg = MPhi->getOperand(i*2+1).getSubReg();
468     bool SrcUndef = MPhi->getOperand(i*2+1).isUndef() ||
469       isImplicitlyDefined(SrcReg, *MRI);
470     assert(SrcReg.isVirtual() &&
471            "Machine PHI Operands must all be virtual registers!");
472 
473     // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
474     // path the PHI.
475     MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB();
476 
477     // Check to make sure we haven't already emitted the copy for this block.
478     // This can happen because PHI nodes may have multiple entries for the same
479     // basic block.
480     if (!MBBsInsertedInto.insert(&opBlock).second)
481       continue;  // If the copy has already been emitted, we're done.
482 
483     MachineInstr *SrcRegDef = MRI->getVRegDef(SrcReg);
484     if (SrcRegDef && TII->isUnspillableTerminator(SrcRegDef)) {
485       assert(SrcRegDef->getOperand(0).isReg() &&
486              SrcRegDef->getOperand(0).isDef() &&
487              "Expected operand 0 to be a reg def!");
488       // Now that the PHI's use has been removed (as the instruction was
489       // removed) there should be no other uses of the SrcReg.
490       assert(MRI->use_empty(SrcReg) &&
491              "Expected a single use from UnspillableTerminator");
492       SrcRegDef->getOperand(0).setReg(IncomingReg);
493 
494       // Update LiveVariables.
495       if (LV) {
496         LiveVariables::VarInfo &SrcVI = LV->getVarInfo(SrcReg);
497         LiveVariables::VarInfo &IncomingVI = LV->getVarInfo(IncomingReg);
498         IncomingVI.AliveBlocks = std::move(SrcVI.AliveBlocks);
499         SrcVI.AliveBlocks.clear();
500       }
501 
502       continue;
503     }
504 
505     // Find a safe location to insert the copy, this may be the first terminator
506     // in the block (or end()).
507     MachineBasicBlock::iterator InsertPos =
508       findPHICopyInsertPoint(&opBlock, &MBB, SrcReg);
509 
510     // Insert the copy.
511     MachineInstr *NewSrcInstr = nullptr;
512     if (!reusedIncoming && IncomingReg) {
513       if (SrcUndef) {
514         // The source register is undefined, so there is no need for a real
515         // COPY, but we still need to ensure joint dominance by defs.
516         // Insert an IMPLICIT_DEF instruction.
517         NewSrcInstr = BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(),
518                               TII->get(TargetOpcode::IMPLICIT_DEF),
519                               IncomingReg);
520 
521         // Clean up the old implicit-def, if there even was one.
522         if (MachineInstr *DefMI = MRI->getVRegDef(SrcReg))
523           if (DefMI->isImplicitDef())
524             ImpDefs.insert(DefMI);
525       } else {
526         // Delete the debug location, since the copy is inserted into a
527         // different basic block.
528         NewSrcInstr = TII->createPHISourceCopy(opBlock, InsertPos, nullptr,
529                                                SrcReg, SrcSubReg, IncomingReg);
530       }
531     }
532 
533     // We only need to update the LiveVariables kill of SrcReg if this was the
534     // last PHI use of SrcReg to be lowered on this CFG edge and it is not live
535     // out of the predecessor. We can also ignore undef sources.
536     if (LV && !SrcUndef &&
537         !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)] &&
538         !LV->isLiveOut(SrcReg, opBlock)) {
539       // We want to be able to insert a kill of the register if this PHI (aka,
540       // the copy we just inserted) is the last use of the source value. Live
541       // variable analysis conservatively handles this by saying that the value
542       // is live until the end of the block the PHI entry lives in. If the value
543       // really is dead at the PHI copy, there will be no successor blocks which
544       // have the value live-in.
545 
546       // Okay, if we now know that the value is not live out of the block, we
547       // can add a kill marker in this block saying that it kills the incoming
548       // value!
549 
550       // In our final twist, we have to decide which instruction kills the
551       // register.  In most cases this is the copy, however, terminator
552       // instructions at the end of the block may also use the value. In this
553       // case, we should mark the last such terminator as being the killing
554       // block, not the copy.
555       MachineBasicBlock::iterator KillInst = opBlock.end();
556       for (MachineBasicBlock::iterator Term = InsertPos; Term != opBlock.end();
557            ++Term) {
558         if (Term->readsRegister(SrcReg))
559           KillInst = Term;
560       }
561 
562       if (KillInst == opBlock.end()) {
563         // No terminator uses the register.
564 
565         if (reusedIncoming || !IncomingReg) {
566           // We may have to rewind a bit if we didn't insert a copy this time.
567           KillInst = InsertPos;
568           while (KillInst != opBlock.begin()) {
569             --KillInst;
570             if (KillInst->isDebugInstr())
571               continue;
572             if (KillInst->readsRegister(SrcReg))
573               break;
574           }
575         } else {
576           // We just inserted this copy.
577           KillInst = NewSrcInstr;
578         }
579       }
580       assert(KillInst->readsRegister(SrcReg) && "Cannot find kill instruction");
581 
582       // Finally, mark it killed.
583       LV->addVirtualRegisterKilled(SrcReg, *KillInst);
584 
585       // This vreg no longer lives all of the way through opBlock.
586       unsigned opBlockNum = opBlock.getNumber();
587       LV->getVarInfo(SrcReg).AliveBlocks.reset(opBlockNum);
588     }
589 
590     if (LIS) {
591       if (NewSrcInstr) {
592         LIS->InsertMachineInstrInMaps(*NewSrcInstr);
593         LIS->addSegmentToEndOfBlock(IncomingReg, *NewSrcInstr);
594       }
595 
596       if (!SrcUndef &&
597           !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)]) {
598         LiveInterval &SrcLI = LIS->getInterval(SrcReg);
599 
600         bool isLiveOut = false;
601         for (MachineBasicBlock *Succ : opBlock.successors()) {
602           SlotIndex startIdx = LIS->getMBBStartIdx(Succ);
603           VNInfo *VNI = SrcLI.getVNInfoAt(startIdx);
604 
605           // Definitions by other PHIs are not truly live-in for our purposes.
606           if (VNI && VNI->def != startIdx) {
607             isLiveOut = true;
608             break;
609           }
610         }
611 
612         if (!isLiveOut) {
613           MachineBasicBlock::iterator KillInst = opBlock.end();
614           for (MachineBasicBlock::iterator Term = InsertPos;
615                Term != opBlock.end(); ++Term) {
616             if (Term->readsRegister(SrcReg))
617               KillInst = Term;
618           }
619 
620           if (KillInst == opBlock.end()) {
621             // No terminator uses the register.
622 
623             if (reusedIncoming || !IncomingReg) {
624               // We may have to rewind a bit if we didn't just insert a copy.
625               KillInst = InsertPos;
626               while (KillInst != opBlock.begin()) {
627                 --KillInst;
628                 if (KillInst->isDebugInstr())
629                   continue;
630                 if (KillInst->readsRegister(SrcReg))
631                   break;
632               }
633             } else {
634               // We just inserted this copy.
635               KillInst = std::prev(InsertPos);
636             }
637           }
638           assert(KillInst->readsRegister(SrcReg) &&
639                  "Cannot find kill instruction");
640 
641           SlotIndex LastUseIndex = LIS->getInstructionIndex(*KillInst);
642           SrcLI.removeSegment(LastUseIndex.getRegSlot(),
643                               LIS->getMBBEndIdx(&opBlock));
644           for (auto &SR : SrcLI.subranges()) {
645             SR.removeSegment(LastUseIndex.getRegSlot(),
646                                 LIS->getMBBEndIdx(&opBlock));
647           }
648         }
649       }
650     }
651   }
652 
653   // Really delete the PHI instruction now, if it is not in the LoweredPHIs map.
654   if (reusedIncoming || !IncomingReg) {
655     if (LIS)
656       LIS->RemoveMachineInstrFromMaps(*MPhi);
657     MF.deleteMachineInstr(MPhi);
658   }
659 }
660 
661 /// analyzePHINodes - Gather information about the PHI nodes in here. In
662 /// particular, we want to map the number of uses of a virtual register which is
663 /// used in a PHI node. We map that to the BB the vreg is coming from. This is
664 /// used later to determine when the vreg is killed in the BB.
665 void PHIElimination::analyzePHINodes(const MachineFunction& MF) {
666   for (const auto &MBB : MF) {
667     for (const auto &BBI : MBB) {
668       if (!BBI.isPHI())
669         break;
670       for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) {
671         if (!BBI.getOperand(i).isUndef()) {
672           ++VRegPHIUseCount[BBVRegPair(
673               BBI.getOperand(i + 1).getMBB()->getNumber(),
674               BBI.getOperand(i).getReg())];
675         }
676       }
677     }
678   }
679 }
680 
681 bool PHIElimination::SplitPHIEdges(MachineFunction &MF,
682                                    MachineBasicBlock &MBB,
683                                    MachineLoopInfo *MLI,
684                                    std::vector<SparseBitVector<>> *LiveInSets) {
685   if (MBB.empty() || !MBB.front().isPHI() || MBB.isEHPad())
686     return false;   // Quick exit for basic blocks without PHIs.
687 
688   const MachineLoop *CurLoop = MLI ? MLI->getLoopFor(&MBB) : nullptr;
689   bool IsLoopHeader = CurLoop && &MBB == CurLoop->getHeader();
690 
691   bool Changed = false;
692   for (MachineBasicBlock::iterator BBI = MBB.begin(), BBE = MBB.end();
693        BBI != BBE && BBI->isPHI(); ++BBI) {
694     for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
695       Register Reg = BBI->getOperand(i).getReg();
696       MachineBasicBlock *PreMBB = BBI->getOperand(i+1).getMBB();
697       // Is there a critical edge from PreMBB to MBB?
698       if (PreMBB->succ_size() == 1)
699         continue;
700 
701       // Avoid splitting backedges of loops. It would introduce small
702       // out-of-line blocks into the loop which is very bad for code placement.
703       if (PreMBB == &MBB && !SplitAllCriticalEdges)
704         continue;
705       const MachineLoop *PreLoop = MLI ? MLI->getLoopFor(PreMBB) : nullptr;
706       if (IsLoopHeader && PreLoop == CurLoop && !SplitAllCriticalEdges)
707         continue;
708 
709       // LV doesn't consider a phi use live-out, so isLiveOut only returns true
710       // when the source register is live-out for some other reason than a phi
711       // use. That means the copy we will insert in PreMBB won't be a kill, and
712       // there is a risk it may not be coalesced away.
713       //
714       // If the copy would be a kill, there is no need to split the edge.
715       bool ShouldSplit = isLiveOutPastPHIs(Reg, PreMBB);
716       if (!ShouldSplit && !NoPhiElimLiveOutEarlyExit)
717         continue;
718       if (ShouldSplit) {
719         LLVM_DEBUG(dbgs() << printReg(Reg) << " live-out before critical edge "
720                           << printMBBReference(*PreMBB) << " -> "
721                           << printMBBReference(MBB) << ": " << *BBI);
722       }
723 
724       // If Reg is not live-in to MBB, it means it must be live-in to some
725       // other PreMBB successor, and we can avoid the interference by splitting
726       // the edge.
727       //
728       // If Reg *is* live-in to MBB, the interference is inevitable and a copy
729       // is likely to be left after coalescing. If we are looking at a loop
730       // exiting edge, split it so we won't insert code in the loop, otherwise
731       // don't bother.
732       ShouldSplit = ShouldSplit && !isLiveIn(Reg, &MBB);
733 
734       // Check for a loop exiting edge.
735       if (!ShouldSplit && CurLoop != PreLoop) {
736         LLVM_DEBUG({
737           dbgs() << "Split wouldn't help, maybe avoid loop copies?\n";
738           if (PreLoop)
739             dbgs() << "PreLoop: " << *PreLoop;
740           if (CurLoop)
741             dbgs() << "CurLoop: " << *CurLoop;
742         });
743         // This edge could be entering a loop, exiting a loop, or it could be
744         // both: Jumping directly form one loop to the header of a sibling
745         // loop.
746         // Split unless this edge is entering CurLoop from an outer loop.
747         ShouldSplit = PreLoop && !PreLoop->contains(CurLoop);
748       }
749       if (!ShouldSplit && !SplitAllCriticalEdges)
750         continue;
751       if (!PreMBB->SplitCriticalEdge(&MBB, *this, LiveInSets)) {
752         LLVM_DEBUG(dbgs() << "Failed to split critical edge.\n");
753         continue;
754       }
755       Changed = true;
756       ++NumCriticalEdgesSplit;
757     }
758   }
759   return Changed;
760 }
761 
762 bool PHIElimination::isLiveIn(Register Reg, const MachineBasicBlock *MBB) {
763   assert((LV || LIS) &&
764          "isLiveIn() requires either LiveVariables or LiveIntervals");
765   if (LIS)
766     return LIS->isLiveInToMBB(LIS->getInterval(Reg), MBB);
767   else
768     return LV->isLiveIn(Reg, *MBB);
769 }
770 
771 bool PHIElimination::isLiveOutPastPHIs(Register Reg,
772                                        const MachineBasicBlock *MBB) {
773   assert((LV || LIS) &&
774          "isLiveOutPastPHIs() requires either LiveVariables or LiveIntervals");
775   // LiveVariables considers uses in PHIs to be in the predecessor basic block,
776   // so that a register used only in a PHI is not live out of the block. In
777   // contrast, LiveIntervals considers uses in PHIs to be on the edge rather than
778   // in the predecessor basic block, so that a register used only in a PHI is live
779   // out of the block.
780   if (LIS) {
781     const LiveInterval &LI = LIS->getInterval(Reg);
782     for (const MachineBasicBlock *SI : MBB->successors())
783       if (LI.liveAt(LIS->getMBBStartIdx(SI)))
784         return true;
785     return false;
786   } else {
787     return LV->isLiveOut(Reg, *MBB);
788   }
789 }
790