blob: b9801c6fd97be0344383bdd3bd2249df6700cef2 [file] [log] [blame]
Eugene Zelenko8fd05042017-09-11 23:00:48 +00001//===- PhiElimination.cpp - Eliminate PHI nodes by inserting copies -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerbc40e892003-01-13 20:01:16 +00009//
10// This pass eliminates machine instruction PHI nodes by inserting copy
11// instructions. This destroys SSA information, but is the desired input for
12// some register allocators.
13//
14//===----------------------------------------------------------------------===//
15
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "PHIEliminationUtils.h"
Eugene Zelenko8fd05042017-09-11 23:00:48 +000017#include "llvm/ADT/DenseMap.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/Statistic.h"
Eugene Zelenko8fd05042017-09-11 23:00:48 +000020#include "llvm/Analysis/LoopInfo.h"
21#include "llvm/CodeGen/LiveInterval.h"
Matthias Braunfa621d22017-12-13 02:51:04 +000022#include "llvm/CodeGen/LiveIntervals.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/CodeGen/LiveVariables.h"
Eugene Zelenko8fd05042017-09-11 23:00:48 +000024#include "llvm/CodeGen/MachineBasicBlock.h"
Jakob Stoklund Olesen9aebb612009-11-14 00:38:06 +000025#include "llvm/CodeGen/MachineDominators.h"
Eugene Zelenko8fd05042017-09-11 23:00:48 +000026#include "llvm/CodeGen/MachineFunction.h"
27#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattnerbc40e892003-01-13 20:01:16 +000028#include "llvm/CodeGen/MachineInstr.h"
Evan Chengf870fbc2008-04-11 17:54:45 +000029#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng97b9b972010-08-17 01:20:36 +000030#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko8fd05042017-09-11 23:00:48 +000031#include "llvm/CodeGen/MachineOperand.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000032#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko8fd05042017-09-11 23:00:48 +000033#include "llvm/CodeGen/SlotIndexes.h"
David Blaikie48319232017-11-08 01:01:31 +000034#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000035#include "llvm/CodeGen/TargetOpcodes.h"
36#include "llvm/CodeGen/TargetRegisterInfo.h"
37#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko8fd05042017-09-11 23:00:48 +000038#include "llvm/Pass.h"
Cameron Zwarich6a951ac2011-03-10 05:59:17 +000039#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesenf235f132009-11-10 22:01:05 +000040#include "llvm/Support/Debug.h"
Benjamin Kramer1bfcd1f2015-03-23 19:32:43 +000041#include "llvm/Support/raw_ostream.h"
Eugene Zelenko8fd05042017-09-11 23:00:48 +000042#include <cassert>
43#include <iterator>
44#include <utility>
45
Chris Lattner0742b592004-02-23 18:38:20 +000046using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000047
Davide Italiano78f7d492017-05-10 23:13:26 +000048#define DEBUG_TYPE "phi-node-elimination"
Chandler Carruth8677f2f2014-04-22 02:02:50 +000049
Cameron Zwarich6a951ac2011-03-10 05:59:17 +000050static cl::opt<bool>
51DisableEdgeSplitting("disable-phi-elim-edge-splitting", cl::init(false),
52 cl::Hidden, cl::desc("Disable critical edge splitting "
53 "during PHI elimination"));
54
Cameron Zwarich5758a712013-02-12 03:49:25 +000055static cl::opt<bool>
56SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false),
57 cl::Hidden, cl::desc("Split all critical edges during "
58 "PHI elimination"));
59
Daniel Jasperbbaf4fd2015-03-03 10:23:11 +000060static cl::opt<bool> NoPhiElimLiveOutEarlyExit(
61 "no-phi-elim-live-out-early-exit", cl::init(false), cl::Hidden,
62 cl::desc("Do not use an early exit if isLiveOutPastPHIs returns true."));
63
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +000064namespace {
Eugene Zelenko8fd05042017-09-11 23:00:48 +000065
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +000066 class PHIElimination : public MachineFunctionPass {
67 MachineRegisterInfo *MRI; // Machine register information
Cameron Zwarichfe0fd352013-02-10 06:42:30 +000068 LiveVariables *LV;
Cameron Zwarichb7cfac32013-02-10 06:42:36 +000069 LiveIntervals *LIS;
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +000070
71 public:
72 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko8fd05042017-09-11 23:00:48 +000073
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +000074 PHIElimination() : MachineFunctionPass(ID) {
75 initializePHIEliminationPass(*PassRegistry::getPassRegistry());
76 }
77
Fangrui Song7d882862018-07-16 18:51:40 +000078 bool runOnMachineFunction(MachineFunction &MF) override;
Craig Topper9f998de2014-03-07 09:26:03 +000079 void getAnalysisUsage(AnalysisUsage &AU) const override;
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +000080
81 private:
82 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
83 /// in predecessor basic blocks.
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +000084 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
Eugene Zelenko8fd05042017-09-11 23:00:48 +000085
Cameron Zwarich02513c02013-02-10 06:42:32 +000086 void LowerPHINode(MachineBasicBlock &MBB,
Cameron Zwarich03fae502013-07-01 19:42:46 +000087 MachineBasicBlock::iterator LastPHIIt);
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +000088
89 /// analyzePHINodes - Gather information about the PHI nodes in
90 /// here. In particular, we want to map the number of uses of a virtual
91 /// register which is used in a PHI node. We map that to the BB the
92 /// vreg is coming from. This is used later to determine when the vreg
93 /// is killed in the BB.
Fangrui Song7d882862018-07-16 18:51:40 +000094 void analyzePHINodes(const MachineFunction& MF);
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +000095
96 /// Split critical edges where necessary for good coalescer performance.
97 bool SplitPHIEdges(MachineFunction &MF, MachineBasicBlock &MBB,
Cameron Zwarichfe0fd352013-02-10 06:42:30 +000098 MachineLoopInfo *MLI);
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +000099
Cameron Zwarich36f54482013-02-10 23:29:49 +0000100 // These functions are temporary abstractions around LiveVariables and
101 // LiveIntervals, so they can go away when LiveVariables does.
Arnaud A. de Grandmaisona2cdb8c2015-06-11 07:45:05 +0000102 bool isLiveIn(unsigned Reg, const MachineBasicBlock *MBB);
103 bool isLiveOutPastPHIs(unsigned Reg, const MachineBasicBlock *MBB);
Cameron Zwarich36f54482013-02-10 23:29:49 +0000104
Eugene Zelenko8fd05042017-09-11 23:00:48 +0000105 using BBVRegPair = std::pair<unsigned, unsigned>;
106 using VRegPHIUse = DenseMap<BBVRegPair, unsigned>;
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +0000107
108 VRegPHIUse VRegPHIUseCount;
109
110 // Defs of PHI sources which are implicit_def.
111 SmallPtrSet<MachineInstr*, 4> ImpDefs;
112
113 // Map reusable lowered PHI node -> incoming join register.
Eugene Zelenko8fd05042017-09-11 23:00:48 +0000114 using LoweredPHIMap =
115 DenseMap<MachineInstr*, unsigned, MachineInstrExpressionTrait>;
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +0000116 LoweredPHIMap LoweredPHIs;
117 };
Eugene Zelenko8fd05042017-09-11 23:00:48 +0000118
119} // end anonymous namespace
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +0000120
Cameron Zwarich02513c02013-02-10 06:42:32 +0000121STATISTIC(NumLowered, "Number of phis lowered");
Cameron Zwarich117be032011-02-14 02:09:11 +0000122STATISTIC(NumCriticalEdgesSplit, "Number of critical edges split");
Jakob Stoklund Olesen74215fc2009-12-16 18:55:53 +0000123STATISTIC(NumReused, "Number of reused lowered phis");
Jakob Stoklund Olesenf235f132009-11-10 22:01:05 +0000124
Lang Hamesfae02a22009-07-21 23:47:33 +0000125char PHIElimination::ID = 0;
Eugene Zelenko8fd05042017-09-11 23:00:48 +0000126
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +0000127char& llvm::PHIEliminationID = PHIElimination::ID;
Chris Lattnerbc40e892003-01-13 20:01:16 +0000128
Matthias Braun94c49042017-05-25 21:26:32 +0000129INITIALIZE_PASS_BEGIN(PHIElimination, DEBUG_TYPE,
Andrew Trick8dd26252012-02-10 04:10:36 +0000130 "Eliminate PHI nodes for register allocation",
131 false, false)
132INITIALIZE_PASS_DEPENDENCY(LiveVariables)
Matthias Braun94c49042017-05-25 21:26:32 +0000133INITIALIZE_PASS_END(PHIElimination, DEBUG_TYPE,
Andrew Trick8dd26252012-02-10 04:10:36 +0000134 "Eliminate PHI nodes for register allocation", false, false)
135
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +0000136void PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
Matthias Braun66bbcee2016-04-28 23:42:51 +0000137 AU.addUsedIfAvailable<LiveVariables>();
Dan Gohman845012e2009-07-31 23:37:33 +0000138 AU.addPreserved<LiveVariables>();
Cameron Zwarich4f659ec2013-02-20 06:46:28 +0000139 AU.addPreserved<SlotIndexes>();
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000140 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesen9aebb612009-11-14 00:38:06 +0000141 AU.addPreserved<MachineDominatorTree>();
Evan Cheng148341c2010-08-17 21:00:37 +0000142 AU.addPreserved<MachineLoopInfo>();
Dan Gohman845012e2009-07-31 23:37:33 +0000143 MachineFunctionPass::getAnalysisUsage(AU);
144}
Lang Hamesfae02a22009-07-21 23:47:33 +0000145
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +0000146bool PHIElimination::runOnMachineFunction(MachineFunction &MF) {
Evan Cheng28428cd2010-05-04 17:12:26 +0000147 MRI = &MF.getRegInfo();
Cameron Zwarichfe0fd352013-02-10 06:42:30 +0000148 LV = getAnalysisIfAvailable<LiveVariables>();
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000149 LIS = getAnalysisIfAvailable<LiveIntervals>();
Evan Cheng576a2702008-04-03 16:38:20 +0000150
Evan Cheng576a2702008-04-03 16:38:20 +0000151 bool Changed = false;
152
Jakob Stoklund Olesen73e7dce2011-07-29 22:51:22 +0000153 // This pass takes the function out of SSA form.
154 MRI->leaveSSA();
155
Matthias Braun5a629bf2018-10-08 23:47:35 +0000156 // Split critical edges to help the coalescer.
Cameron Zwarich8597c142013-02-11 09:24:47 +0000157 if (!DisableEdgeSplitting && (LV || LIS)) {
Cameron Zwarichfe0fd352013-02-10 06:42:30 +0000158 MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
Arnaud A. de Grandmaisona2cdb8c2015-06-11 07:45:05 +0000159 for (auto &MBB : MF)
160 Changed |= SplitPHIEdges(MF, MBB, MLI);
Evan Cheng148341c2010-08-17 21:00:37 +0000161 }
Jakob Stoklund Olesen3e204752009-11-11 19:31:31 +0000162
163 // Populate VRegPHIUseCount
Evan Cheng28428cd2010-05-04 17:12:26 +0000164 analyzePHINodes(MF);
Jakob Stoklund Olesen3e204752009-11-11 19:31:31 +0000165
Evan Cheng576a2702008-04-03 16:38:20 +0000166 // Eliminate PHI instructions by inserting copies into predecessor blocks.
Arnaud A. de Grandmaisona2cdb8c2015-06-11 07:45:05 +0000167 for (auto &MBB : MF)
168 Changed |= EliminatePHINodes(MF, MBB);
Evan Cheng576a2702008-04-03 16:38:20 +0000169
170 // Remove dead IMPLICIT_DEF instructions.
Craig Topper273fd112014-08-24 23:23:06 +0000171 for (MachineInstr *DefMI : ImpDefs) {
Evan Cheng576a2702008-04-03 16:38:20 +0000172 unsigned DefReg = DefMI->getOperand(0).getReg();
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000173 if (MRI->use_nodbg_empty(DefReg)) {
174 if (LIS)
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +0000175 LIS->RemoveMachineInstrFromMaps(*DefMI);
Evan Cheng576a2702008-04-03 16:38:20 +0000176 DefMI->eraseFromParent();
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000177 }
Evan Cheng576a2702008-04-03 16:38:20 +0000178 }
179
Jakob Stoklund Olesen74215fc2009-12-16 18:55:53 +0000180 // Clean up the lowered PHI instructions.
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +0000181 for (auto &I : LoweredPHIs) {
Cameron Zwarich8d491342013-02-12 05:48:56 +0000182 if (LIS)
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +0000183 LIS->RemoveMachineInstrFromMaps(*I.first);
184 MF.DeleteMachineInstr(I.first);
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000185 }
Jakob Stoklund Olesen74215fc2009-12-16 18:55:53 +0000186
Bill Wendling3de82492009-12-17 23:42:32 +0000187 LoweredPHIs.clear();
Evan Cheng576a2702008-04-03 16:38:20 +0000188 ImpDefs.clear();
189 VRegPHIUseCount.clear();
Evan Cheng28428cd2010-05-04 17:12:26 +0000190
Matthias Braundb9ce2f2016-08-23 21:19:49 +0000191 MF.getProperties().set(MachineFunctionProperties::Property::NoPHIs);
192
Evan Cheng576a2702008-04-03 16:38:20 +0000193 return Changed;
194}
195
Chris Lattnerbc40e892003-01-13 20:01:16 +0000196/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
197/// predecessor basic blocks.
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +0000198bool PHIElimination::EliminatePHINodes(MachineFunction &MF,
Bjorn Petterssone299be62018-09-30 17:23:21 +0000199 MachineBasicBlock &MBB) {
Chris Lattner518bb532010-02-09 19:54:29 +0000200 if (MBB.empty() || !MBB.front().isPHI())
Chris Lattner53a79aa2005-10-03 04:47:08 +0000201 return false; // Quick exit for basic blocks without PHIs.
Chris Lattnerbc40e892003-01-13 20:01:16 +0000202
Bjorn Petterssone299be62018-09-30 17:23:21 +0000203 // Get an iterator to the last PHI node.
Cameron Zwarich03fae502013-07-01 19:42:46 +0000204 MachineBasicBlock::iterator LastPHIIt =
Benjamin Kramerd628f192014-03-02 12:27:27 +0000205 std::prev(MBB.SkipPHIsAndLabels(MBB.begin()));
Chris Lattner791f8962004-05-10 18:47:18 +0000206
Chris Lattner518bb532010-02-09 19:54:29 +0000207 while (MBB.front().isPHI())
Cameron Zwarich03fae502013-07-01 19:42:46 +0000208 LowerPHINode(MBB, LastPHIIt);
Bill Wendlingca756d22006-09-28 07:10:24 +0000209
Chris Lattner53a79aa2005-10-03 04:47:08 +0000210 return true;
211}
Misha Brukmanedf128a2005-04-21 22:36:52 +0000212
Bjorn Petterssoncce9df62018-09-30 17:26:58 +0000213/// Return true if all defs of VirtReg are implicit-defs.
Jakob Stoklund Olesen52137502012-06-25 03:36:12 +0000214/// This includes registers with no defs.
215static bool isImplicitlyDefined(unsigned VirtReg,
Bjorn Petterssoncce9df62018-09-30 17:26:58 +0000216 const MachineRegisterInfo &MRI) {
217 for (MachineInstr &DI : MRI.def_instructions(VirtReg))
Owen Anderson92fca732014-03-17 19:36:09 +0000218 if (!DI.isImplicitDef())
Jakob Stoklund Olesen52137502012-06-25 03:36:12 +0000219 return false;
220 return true;
221}
222
Bjorn Petterssoncce9df62018-09-30 17:26:58 +0000223/// Return true if all sources of the phi node are implicit_def's, or undef's.
224static bool allPhiOperandsUndefined(const MachineInstr &MPhi,
225 const MachineRegisterInfo &MRI) {
226 for (unsigned I = 1, E = MPhi.getNumOperands(); I != E; I += 2) {
227 const MachineOperand &MO = MPhi.getOperand(I);
228 if (!isImplicitlyDefined(MO.getReg(), MRI) && !MO.isUndef())
Evan Chengb3e0a6d2008-05-10 00:17:50 +0000229 return false;
Bjorn Petterssoncce9df62018-09-30 17:26:58 +0000230 }
Evan Chengb3e0a6d2008-05-10 00:17:50 +0000231 return true;
Evan Chengf870fbc2008-04-11 17:54:45 +0000232}
Eugene Zelenko8fd05042017-09-11 23:00:48 +0000233/// LowerPHINode - Lower the PHI node at the top of the specified block.
Cameron Zwarich02513c02013-02-10 06:42:32 +0000234void PHIElimination::LowerPHINode(MachineBasicBlock &MBB,
Cameron Zwarich03fae502013-07-01 19:42:46 +0000235 MachineBasicBlock::iterator LastPHIIt) {
Cameron Zwarich02513c02013-02-10 06:42:32 +0000236 ++NumLowered;
Cameron Zwarich03fae502013-07-01 19:42:46 +0000237
Benjamin Kramerd628f192014-03-02 12:27:27 +0000238 MachineBasicBlock::iterator AfterPHIsIt = std::next(LastPHIIt);
Cameron Zwarich03fae502013-07-01 19:42:46 +0000239
Chris Lattner53a79aa2005-10-03 04:47:08 +0000240 // Unlink the PHI node from the basic block, but don't delete the PHI yet.
Duncan P. N. Exon Smith1b7dbea2016-07-01 01:27:19 +0000241 MachineInstr *MPhi = MBB.remove(&*MBB.begin());
Chris Lattnerbc40e892003-01-13 20:01:16 +0000242
Evan Chengf870fbc2008-04-11 17:54:45 +0000243 unsigned NumSrcs = (MPhi->getNumOperands() - 1) / 2;
Chris Lattner53a79aa2005-10-03 04:47:08 +0000244 unsigned DestReg = MPhi->getOperand(0).getReg();
Jakob Stoklund Olesen9ac24882010-08-18 16:09:47 +0000245 assert(MPhi->getOperand(0).getSubReg() == 0 && "Can't handle sub-reg PHIs");
Evan Cheng9f1c8312008-07-03 09:09:37 +0000246 bool isDead = MPhi->getOperand(0).isDead();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000247
Bill Wendlingca756d22006-09-28 07:10:24 +0000248 // Create a new register for the incoming PHI arguments.
Chris Lattner53a79aa2005-10-03 04:47:08 +0000249 MachineFunction &MF = *MBB.getParent();
Evan Cheng9f1c8312008-07-03 09:09:37 +0000250 unsigned IncomingReg = 0;
Jakob Stoklund Olesen74215fc2009-12-16 18:55:53 +0000251 bool reusedIncoming = false; // Is IncomingReg reused from an earlier PHI?
Chris Lattnerbc40e892003-01-13 20:01:16 +0000252
Bill Wendlingae94dda2008-05-12 22:15:05 +0000253 // Insert a register to register copy at the top of the current block (but
Chris Lattner53a79aa2005-10-03 04:47:08 +0000254 // after any remaining phi nodes) which copies the new incoming register
255 // into the phi node destination.
Eric Christopher60355182014-08-05 02:39:49 +0000256 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
Bjorn Petterssoncce9df62018-09-30 17:26:58 +0000257 if (allPhiOperandsUndefined(*MPhi, *MRI))
258 // If all sources of a PHI node are implicit_def or undef uses, just emit an
Evan Cheng9f1c8312008-07-03 09:09:37 +0000259 // implicit_def instead of a copy.
Bill Wendlingd62e06c2009-02-03 02:29:34 +0000260 BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
Chris Lattner518bb532010-02-09 19:54:29 +0000261 TII->get(TargetOpcode::IMPLICIT_DEF), DestReg);
Evan Cheng9f1c8312008-07-03 09:09:37 +0000262 else {
Jakob Stoklund Olesen74215fc2009-12-16 18:55:53 +0000263 // Can we reuse an earlier PHI node? This only happens for critical edges,
264 // typically those created by tail duplication.
265 unsigned &entry = LoweredPHIs[MPhi];
266 if (entry) {
267 // An identical PHI node was already lowered. Reuse the incoming register.
268 IncomingReg = entry;
269 reusedIncoming = true;
270 ++NumReused;
Nicola Zaghen0818e782018-05-14 12:53:11 +0000271 LLVM_DEBUG(dbgs() << "Reusing " << printReg(IncomingReg) << " for "
272 << *MPhi);
Jakob Stoklund Olesen74215fc2009-12-16 18:55:53 +0000273 } else {
Jakob Stoklund Olesen92c1f722010-07-10 19:08:25 +0000274 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(DestReg);
Jakob Stoklund Olesen74215fc2009-12-16 18:55:53 +0000275 entry = IncomingReg = MF.getRegInfo().createVirtualRegister(RC);
276 }
Jakob Stoklund Olesen92c1f722010-07-10 19:08:25 +0000277 BuildMI(MBB, AfterPHIsIt, MPhi->getDebugLoc(),
278 TII->get(TargetOpcode::COPY), DestReg)
279 .addReg(IncomingReg);
Evan Cheng9f1c8312008-07-03 09:09:37 +0000280 }
Chris Lattner53a79aa2005-10-03 04:47:08 +0000281
Bill Wendlingae94dda2008-05-12 22:15:05 +0000282 // Update live variable information if there is any.
Chris Lattner53a79aa2005-10-03 04:47:08 +0000283 if (LV) {
Duncan P. N. Exon Smith1b7dbea2016-07-01 01:27:19 +0000284 MachineInstr &PHICopy = *std::prev(AfterPHIsIt);
Chris Lattner53a79aa2005-10-03 04:47:08 +0000285
Evan Cheng9f1c8312008-07-03 09:09:37 +0000286 if (IncomingReg) {
Jakob Stoklund Olesen74215fc2009-12-16 18:55:53 +0000287 LiveVariables::VarInfo &VI = LV->getVarInfo(IncomingReg);
288
Evan Cheng9f1c8312008-07-03 09:09:37 +0000289 // Increment use count of the newly created virtual register.
Jakob Stoklund Olesendcfe5f32010-02-23 22:43:58 +0000290 LV->setPHIJoin(IncomingReg);
Jakob Stoklund Olesen74215fc2009-12-16 18:55:53 +0000291
292 // When we are reusing the incoming register, it may already have been
293 // killed in this block. The old kill will also have been inserted at
294 // AfterPHIsIt, so it appears before the current PHICopy.
295 if (reusedIncoming)
296 if (MachineInstr *OldKill = VI.findKill(&MBB)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000297 LLVM_DEBUG(dbgs() << "Remove old kill from " << *OldKill);
Duncan P. N. Exon Smith4383a512016-07-01 01:51:32 +0000298 LV->removeVirtualRegisterKilled(IncomingReg, *OldKill);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000299 LLVM_DEBUG(MBB.dump());
Jakob Stoklund Olesen74215fc2009-12-16 18:55:53 +0000300 }
Evan Cheng3fefc182007-04-18 00:36:11 +0000301
Evan Cheng9f1c8312008-07-03 09:09:37 +0000302 // Add information to LiveVariables to know that the incoming value is
303 // killed. Note that because the value is defined in several places (once
304 // each for each incoming block), the "def" block and instruction fields
305 // for the VarInfo is not filled in.
Duncan P. N. Exon Smith4383a512016-07-01 01:51:32 +0000306 LV->addVirtualRegisterKilled(IncomingReg, PHICopy);
Evan Cheng9f1c8312008-07-03 09:09:37 +0000307 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000308
Bill Wendlingae94dda2008-05-12 22:15:05 +0000309 // Since we are going to be deleting the PHI node, if it is the last use of
310 // any registers, or if the value itself is dead, we need to move this
Chris Lattner53a79aa2005-10-03 04:47:08 +0000311 // information over to the new copy we just inserted.
Duncan P. N. Exon Smith4383a512016-07-01 01:51:32 +0000312 LV->removeVirtualRegistersKilled(*MPhi);
Chris Lattnerbc40e892003-01-13 20:01:16 +0000313
Chris Lattner6db07562005-10-03 07:22:07 +0000314 // If the result is dead, update LV.
Evan Cheng9f1c8312008-07-03 09:09:37 +0000315 if (isDead) {
Duncan P. N. Exon Smith4383a512016-07-01 01:51:32 +0000316 LV->addVirtualRegisterDead(DestReg, PHICopy);
317 LV->removeVirtualRegisterDead(DestReg, *MPhi);
Chris Lattner53a79aa2005-10-03 04:47:08 +0000318 }
319 }
Chris Lattnerbc40e892003-01-13 20:01:16 +0000320
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000321 // Update LiveIntervals for the new copy or implicit def.
322 if (LIS) {
Duncan P. N. Exon Smith1b7dbea2016-07-01 01:27:19 +0000323 SlotIndex DestCopyIndex =
324 LIS->InsertMachineInstrInMaps(*std::prev(AfterPHIsIt));
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000325
326 SlotIndex MBBStartIndex = LIS->getMBBStartIdx(&MBB);
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000327 if (IncomingReg) {
328 // Add the region from the beginning of MBB to the copy instruction to
329 // IncomingReg's live interval.
Mark Laceye742d682013-08-14 23:50:16 +0000330 LiveInterval &IncomingLI = LIS->createEmptyInterval(IncomingReg);
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000331 VNInfo *IncomingVNI = IncomingLI.getVNInfoAt(MBBStartIndex);
332 if (!IncomingVNI)
333 IncomingVNI = IncomingLI.getNextValue(MBBStartIndex,
334 LIS->getVNInfoAllocator());
Matthias Braun331de112013-10-10 21:28:43 +0000335 IncomingLI.addSegment(LiveInterval::Segment(MBBStartIndex,
336 DestCopyIndex.getRegSlot(),
337 IncomingVNI));
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000338 }
339
Cameron Zwaricha566d632013-02-21 08:51:55 +0000340 LiveInterval &DestLI = LIS->getInterval(DestReg);
Cameron Zwarich197a60a2013-02-21 08:51:58 +0000341 assert(DestLI.begin() != DestLI.end() &&
342 "PHIs should have nonempty LiveIntervals.");
343 if (DestLI.endIndex().isDead()) {
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000344 // A dead PHI's live range begins and ends at the start of the MBB, but
345 // the lowered copy, which will still be dead, needs to begin and end at
346 // the copy instruction.
347 VNInfo *OrigDestVNI = DestLI.getVNInfoAt(MBBStartIndex);
348 assert(OrigDestVNI && "PHI destination should be live at block entry.");
Matthias Braun331de112013-10-10 21:28:43 +0000349 DestLI.removeSegment(MBBStartIndex, MBBStartIndex.getDeadSlot());
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000350 DestLI.createDeadDef(DestCopyIndex.getRegSlot(),
351 LIS->getVNInfoAllocator());
352 DestLI.removeValNo(OrigDestVNI);
353 } else {
354 // Otherwise, remove the region from the beginning of MBB to the copy
355 // instruction from DestReg's live interval.
Matthias Braun331de112013-10-10 21:28:43 +0000356 DestLI.removeSegment(MBBStartIndex, DestCopyIndex.getRegSlot());
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000357 VNInfo *DestVNI = DestLI.getVNInfoAt(DestCopyIndex.getRegSlot());
358 assert(DestVNI && "PHI destination should be live at its definition.");
359 DestVNI->def = DestCopyIndex.getRegSlot();
360 }
361 }
362
Bill Wendlingae94dda2008-05-12 22:15:05 +0000363 // Adjust the VRegPHIUseCount map to account for the removal of this PHI node.
Chris Lattner53a79aa2005-10-03 04:47:08 +0000364 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)
Jakob Stoklund Olesen74215fc2009-12-16 18:55:53 +0000365 --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i+1).getMBB()->getNumber(),
Chris Lattner8aa797a2007-12-30 23:10:15 +0000366 MPhi->getOperand(i).getReg())];
Chris Lattner572c7702003-05-12 14:28:28 +0000367
Bill Wendlingae94dda2008-05-12 22:15:05 +0000368 // Now loop over all of the incoming arguments, changing them to copy into the
369 // IncomingReg register in the corresponding predecessor basic block.
Evan Cheng576a2702008-04-03 16:38:20 +0000370 SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto;
Evan Chengf870fbc2008-04-11 17:54:45 +0000371 for (int i = NumSrcs - 1; i >= 0; --i) {
372 unsigned SrcReg = MPhi->getOperand(i*2+1).getReg();
Jakob Stoklund Olesen9ac24882010-08-18 16:09:47 +0000373 unsigned SrcSubReg = MPhi->getOperand(i*2+1).getSubReg();
Jakob Stoklund Olesen52137502012-06-25 03:36:12 +0000374 bool SrcUndef = MPhi->getOperand(i*2+1).isUndef() ||
Bjorn Petterssoncce9df62018-09-30 17:26:58 +0000375 isImplicitlyDefined(SrcReg, *MRI);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000376 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
Chris Lattner6db07562005-10-03 07:22:07 +0000377 "Machine PHI Operands must all be virtual registers!");
Chris Lattner53a79aa2005-10-03 04:47:08 +0000378
Lang Hames287b8b02009-07-23 04:34:03 +0000379 // Get the MachineBasicBlock equivalent of the BasicBlock that is the source
380 // path the PHI.
381 MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB();
382
Chris Lattner53a79aa2005-10-03 04:47:08 +0000383 // Check to make sure we haven't already emitted the copy for this block.
Bill Wendlingae94dda2008-05-12 22:15:05 +0000384 // This can happen because PHI nodes may have multiple entries for the same
385 // basic block.
David Blaikie5401ba72014-11-19 07:49:26 +0000386 if (!MBBsInsertedInto.insert(&opBlock).second)
Chris Lattner6db07562005-10-03 07:22:07 +0000387 continue; // If the copy has already been emitted, we're done.
Jakob Stoklund Olesene35e3c32009-11-10 22:00:56 +0000388
Bill Wendlingae94dda2008-05-12 22:15:05 +0000389 // Find a safe location to insert the copy, this may be the first terminator
390 // in the block (or end()).
Jakob Stoklund Olesen12222872009-11-13 21:56:15 +0000391 MachineBasicBlock::iterator InsertPos =
Cameron Zwaricha4746852010-12-05 19:51:05 +0000392 findPHICopyInsertPoint(&opBlock, &MBB, SrcReg);
Evan Chengfc0b80d2009-03-13 22:59:14 +0000393
Chris Lattner6db07562005-10-03 07:22:07 +0000394 // Insert the copy.
Craig Topper4ba84432014-04-14 00:51:57 +0000395 MachineInstr *NewSrcInstr = nullptr;
Jakob Stoklund Olesen52137502012-06-25 03:36:12 +0000396 if (!reusedIncoming && IncomingReg) {
397 if (SrcUndef) {
398 // The source register is undefined, so there is no need for a real
399 // COPY, but we still need to ensure joint dominance by defs.
400 // Insert an IMPLICIT_DEF instruction.
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000401 NewSrcInstr = BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(),
402 TII->get(TargetOpcode::IMPLICIT_DEF),
403 IncomingReg);
Jakob Stoklund Olesen52137502012-06-25 03:36:12 +0000404
405 // Clean up the old implicit-def, if there even was one.
406 if (MachineInstr *DefMI = MRI->getVRegDef(SrcReg))
407 if (DefMI->isImplicitDef())
408 ImpDefs.insert(DefMI);
409 } else {
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000410 NewSrcInstr = BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(),
411 TII->get(TargetOpcode::COPY), IncomingReg)
412 .addReg(SrcReg, 0, SrcSubReg);
Jakob Stoklund Olesen52137502012-06-25 03:36:12 +0000413 }
414 }
Chris Lattner53a79aa2005-10-03 04:47:08 +0000415
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000416 // We only need to update the LiveVariables kill of SrcReg if this was the
417 // last PHI use of SrcReg to be lowered on this CFG edge and it is not live
418 // out of the predecessor. We can also ignore undef sources.
419 if (LV && !SrcUndef &&
420 !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)] &&
421 !LV->isLiveOut(SrcReg, opBlock)) {
422 // We want to be able to insert a kill of the register if this PHI (aka,
423 // the copy we just inserted) is the last use of the source value. Live
424 // variable analysis conservatively handles this by saying that the value
425 // is live until the end of the block the PHI entry lives in. If the value
426 // really is dead at the PHI copy, there will be no successor blocks which
427 // have the value live-in.
Jakob Stoklund Olesene35e3c32009-11-10 22:00:56 +0000428
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000429 // Okay, if we now know that the value is not live out of the block, we
430 // can add a kill marker in this block saying that it kills the incoming
431 // value!
Chris Lattner6db07562005-10-03 07:22:07 +0000432
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000433 // In our final twist, we have to decide which instruction kills the
Jakob Stoklund Olesen9e51b142012-07-04 19:52:05 +0000434 // register. In most cases this is the copy, however, terminator
435 // instructions at the end of the block may also use the value. In this
436 // case, we should mark the last such terminator as being the killing
437 // block, not the copy.
438 MachineBasicBlock::iterator KillInst = opBlock.end();
439 MachineBasicBlock::iterator FirstTerm = opBlock.getFirstTerminator();
440 for (MachineBasicBlock::iterator Term = FirstTerm;
441 Term != opBlock.end(); ++Term) {
442 if (Term->readsRegister(SrcReg))
443 KillInst = Term;
444 }
Jakob Stoklund Olesene35e3c32009-11-10 22:00:56 +0000445
Jakob Stoklund Olesen9e51b142012-07-04 19:52:05 +0000446 if (KillInst == opBlock.end()) {
447 // No terminator uses the register.
448
449 if (reusedIncoming || !IncomingReg) {
450 // We may have to rewind a bit if we didn't insert a copy this time.
451 KillInst = FirstTerm;
452 while (KillInst != opBlock.begin()) {
453 --KillInst;
Shiva Chen24abe712018-05-09 02:42:00 +0000454 if (KillInst->isDebugInstr())
Jakob Stoklund Olesen9e51b142012-07-04 19:52:05 +0000455 continue;
456 if (KillInst->readsRegister(SrcReg))
457 break;
458 }
459 } else {
460 // We just inserted this copy.
Benjamin Kramerd628f192014-03-02 12:27:27 +0000461 KillInst = std::prev(InsertPos);
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000462 }
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000463 }
Jakob Stoklund Olesen74215fc2009-12-16 18:55:53 +0000464 assert(KillInst->readsRegister(SrcReg) && "Cannot find kill instruction");
Jakob Stoklund Olesene35e3c32009-11-10 22:00:56 +0000465
Chris Lattner2adfa7e2006-01-04 07:12:21 +0000466 // Finally, mark it killed.
Duncan P. N. Exon Smith4383a512016-07-01 01:51:32 +0000467 LV->addVirtualRegisterKilled(SrcReg, *KillInst);
Chris Lattner6db07562005-10-03 07:22:07 +0000468
469 // This vreg no longer lives all of the way through opBlock.
470 unsigned opBlockNum = opBlock.getNumber();
Jakob Stoklund Olesene35e3c32009-11-10 22:00:56 +0000471 LV->getVarInfo(SrcReg).AliveBlocks.reset(opBlockNum);
Chris Lattnerbc40e892003-01-13 20:01:16 +0000472 }
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000473
474 if (LIS) {
475 if (NewSrcInstr) {
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +0000476 LIS->InsertMachineInstrInMaps(*NewSrcInstr);
477 LIS->addSegmentToEndOfBlock(IncomingReg, *NewSrcInstr);
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000478 }
479
480 if (!SrcUndef &&
481 !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)]) {
482 LiveInterval &SrcLI = LIS->getInterval(SrcReg);
483
484 bool isLiveOut = false;
485 for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),
486 SE = opBlock.succ_end(); SI != SE; ++SI) {
Cameron Zwarich4930e722013-02-12 05:48:58 +0000487 SlotIndex startIdx = LIS->getMBBStartIdx(*SI);
488 VNInfo *VNI = SrcLI.getVNInfoAt(startIdx);
489
490 // Definitions by other PHIs are not truly live-in for our purposes.
491 if (VNI && VNI->def != startIdx) {
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000492 isLiveOut = true;
493 break;
494 }
495 }
496
497 if (!isLiveOut) {
498 MachineBasicBlock::iterator KillInst = opBlock.end();
499 MachineBasicBlock::iterator FirstTerm = opBlock.getFirstTerminator();
500 for (MachineBasicBlock::iterator Term = FirstTerm;
501 Term != opBlock.end(); ++Term) {
502 if (Term->readsRegister(SrcReg))
503 KillInst = Term;
504 }
505
506 if (KillInst == opBlock.end()) {
507 // No terminator uses the register.
508
509 if (reusedIncoming || !IncomingReg) {
510 // We may have to rewind a bit if we didn't just insert a copy.
511 KillInst = FirstTerm;
512 while (KillInst != opBlock.begin()) {
513 --KillInst;
Shiva Chen24abe712018-05-09 02:42:00 +0000514 if (KillInst->isDebugInstr())
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000515 continue;
516 if (KillInst->readsRegister(SrcReg))
517 break;
518 }
519 } else {
520 // We just inserted this copy.
Benjamin Kramerd628f192014-03-02 12:27:27 +0000521 KillInst = std::prev(InsertPos);
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000522 }
523 }
524 assert(KillInst->readsRegister(SrcReg) &&
525 "Cannot find kill instruction");
526
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +0000527 SlotIndex LastUseIndex = LIS->getInstructionIndex(*KillInst);
Matthias Braun331de112013-10-10 21:28:43 +0000528 SrcLI.removeSegment(LastUseIndex.getRegSlot(),
529 LIS->getMBBEndIdx(&opBlock));
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000530 }
531 }
532 }
Chris Lattnerbc40e892003-01-13 20:01:16 +0000533 }
Jakob Stoklund Olesene35e3c32009-11-10 22:00:56 +0000534
Jakob Stoklund Olesen74215fc2009-12-16 18:55:53 +0000535 // Really delete the PHI instruction now, if it is not in the LoweredPHIs map.
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000536 if (reusedIncoming || !IncomingReg) {
537 if (LIS)
Duncan P. N. Exon Smith42e18352016-02-27 06:40:41 +0000538 LIS->RemoveMachineInstrFromMaps(*MPhi);
Jakob Stoklund Olesen74215fc2009-12-16 18:55:53 +0000539 MF.DeleteMachineInstr(MPhi);
Cameron Zwarichb7cfac32013-02-10 06:42:36 +0000540 }
Chris Lattnerbc40e892003-01-13 20:01:16 +0000541}
Bill Wendlingca756d22006-09-28 07:10:24 +0000542
543/// analyzePHINodes - Gather information about the PHI nodes in here. In
544/// particular, we want to map the number of uses of a virtual register which is
545/// used in a PHI node. We map that to the BB the vreg is coming from. This is
546/// used later to determine when the vreg is killed in the BB.
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +0000547void PHIElimination::analyzePHINodes(const MachineFunction& MF) {
Alexey Samsonov4aef7272014-04-30 18:29:51 +0000548 for (const auto &MBB : MF)
Alexey Samsonov84678122014-04-30 22:17:38 +0000549 for (const auto &BBI : MBB) {
550 if (!BBI.isPHI())
551 break;
552 for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2)
553 ++VRegPHIUseCount[BBVRegPair(BBI.getOperand(i+1).getMBB()->getNumber(),
554 BBI.getOperand(i).getReg())];
555 }
Bill Wendlingca756d22006-09-28 07:10:24 +0000556}
Jakob Stoklund Olesene35e3c32009-11-10 22:00:56 +0000557
Cameron Zwarich0a3fdd62010-12-05 21:39:42 +0000558bool PHIElimination::SplitPHIEdges(MachineFunction &MF,
Cameron Zwarich61a73342011-02-17 06:13:46 +0000559 MachineBasicBlock &MBB,
Cameron Zwarich61a73342011-02-17 06:13:46 +0000560 MachineLoopInfo *MLI) {
Reid Klecknerc0e64ad2015-08-27 23:27:47 +0000561 if (MBB.empty() || !MBB.front().isPHI() || MBB.isEHPad())
Jakob Stoklund Olesen3e204752009-11-11 19:31:31 +0000562 return false; // Quick exit for basic blocks without PHIs.
Jakob Stoklund Olesen0257dd32009-11-18 18:01:35 +0000563
Craig Topper4ba84432014-04-14 00:51:57 +0000564 const MachineLoop *CurLoop = MLI ? MLI->getLoopFor(&MBB) : nullptr;
Jakob Stoklund Olesenc321a202012-07-20 20:49:53 +0000565 bool IsLoopHeader = CurLoop && &MBB == CurLoop->getHeader();
566
Evan Cheng97b9b972010-08-17 01:20:36 +0000567 bool Changed = false;
Evan Cheng7c2a4a32011-12-06 22:12:01 +0000568 for (MachineBasicBlock::iterator BBI = MBB.begin(), BBE = MBB.end();
Chris Lattner518bb532010-02-09 19:54:29 +0000569 BBI != BBE && BBI->isPHI(); ++BBI) {
Jakob Stoklund Olesenf235f132009-11-10 22:01:05 +0000570 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) {
571 unsigned Reg = BBI->getOperand(i).getReg();
572 MachineBasicBlock *PreMBB = BBI->getOperand(i+1).getMBB();
Jakob Stoklund Olesenc321a202012-07-20 20:49:53 +0000573 // Is there a critical edge from PreMBB to MBB?
574 if (PreMBB->succ_size() == 1)
575 continue;
576
Evan Chenge0083842010-08-17 17:43:50 +0000577 // Avoid splitting backedges of loops. It would introduce small
578 // out-of-line blocks into the loop which is very bad for code placement.
Cameron Zwarich5758a712013-02-12 03:49:25 +0000579 if (PreMBB == &MBB && !SplitAllCriticalEdges)
Jakob Stoklund Olesenc321a202012-07-20 20:49:53 +0000580 continue;
Craig Topper4ba84432014-04-14 00:51:57 +0000581 const MachineLoop *PreLoop = MLI ? MLI->getLoopFor(PreMBB) : nullptr;
Cameron Zwarich5758a712013-02-12 03:49:25 +0000582 if (IsLoopHeader && PreLoop == CurLoop && !SplitAllCriticalEdges)
Jakob Stoklund Olesenc321a202012-07-20 20:49:53 +0000583 continue;
584
585 // LV doesn't consider a phi use live-out, so isLiveOut only returns true
586 // when the source register is live-out for some other reason than a phi
587 // use. That means the copy we will insert in PreMBB won't be a kill, and
588 // there is a risk it may not be coalesced away.
589 //
590 // If the copy would be a kill, there is no need to split the edge.
Daniel Jasperbbaf4fd2015-03-03 10:23:11 +0000591 bool ShouldSplit = isLiveOutPastPHIs(Reg, PreMBB);
592 if (!ShouldSplit && !NoPhiElimLiveOutEarlyExit)
Jakob Stoklund Olesenc321a202012-07-20 20:49:53 +0000593 continue;
Daniel Jasperbbaf4fd2015-03-03 10:23:11 +0000594 if (ShouldSplit) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000595 LLVM_DEBUG(dbgs() << printReg(Reg) << " live-out before critical edge "
596 << printMBBReference(*PreMBB) << " -> "
597 << printMBBReference(MBB) << ": " << *BBI);
Daniel Jasperbbaf4fd2015-03-03 10:23:11 +0000598 }
Jakob Stoklund Olesenc321a202012-07-20 20:49:53 +0000599
600 // If Reg is not live-in to MBB, it means it must be live-in to some
601 // other PreMBB successor, and we can avoid the interference by splitting
602 // the edge.
603 //
604 // If Reg *is* live-in to MBB, the interference is inevitable and a copy
605 // is likely to be left after coalescing. If we are looking at a loop
606 // exiting edge, split it so we won't insert code in the loop, otherwise
607 // don't bother.
Daniel Jasperbbaf4fd2015-03-03 10:23:11 +0000608 ShouldSplit = ShouldSplit && !isLiveIn(Reg, &MBB);
Jakob Stoklund Olesenc321a202012-07-20 20:49:53 +0000609
610 // Check for a loop exiting edge.
611 if (!ShouldSplit && CurLoop != PreLoop) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000612 LLVM_DEBUG({
Jakob Stoklund Olesenc321a202012-07-20 20:49:53 +0000613 dbgs() << "Split wouldn't help, maybe avoid loop copies?\n";
Nicola Zaghen0818e782018-05-14 12:53:11 +0000614 if (PreLoop)
615 dbgs() << "PreLoop: " << *PreLoop;
616 if (CurLoop)
617 dbgs() << "CurLoop: " << *CurLoop;
Jakob Stoklund Olesenc321a202012-07-20 20:49:53 +0000618 });
619 // This edge could be entering a loop, exiting a loop, or it could be
620 // both: Jumping directly form one loop to the header of a sibling
621 // loop.
622 // Split unless this edge is entering CurLoop from an outer loop.
623 ShouldSplit = PreLoop && !PreLoop->contains(CurLoop);
Evan Chenge0083842010-08-17 17:43:50 +0000624 }
Daniel Jasperbbaf4fd2015-03-03 10:23:11 +0000625 if (!ShouldSplit && !SplitAllCriticalEdges)
Jakob Stoklund Olesenc321a202012-07-20 20:49:53 +0000626 continue;
Quentin Colombetf2cd1572016-04-21 21:01:13 +0000627 if (!PreMBB->SplitCriticalEdge(&MBB, *this)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000628 LLVM_DEBUG(dbgs() << "Failed to split critical edge.\n");
Jakob Stoklund Olesenc321a202012-07-20 20:49:53 +0000629 continue;
630 }
631 Changed = true;
632 ++NumCriticalEdgesSplit;
Jakob Stoklund Olesenf235f132009-11-10 22:01:05 +0000633 }
634 }
Cameron Zwarich688521c2011-02-17 06:13:43 +0000635 return Changed;
Jakob Stoklund Olesenf235f132009-11-10 22:01:05 +0000636}
Cameron Zwarich36f54482013-02-10 23:29:49 +0000637
Arnaud A. de Grandmaisona2cdb8c2015-06-11 07:45:05 +0000638bool PHIElimination::isLiveIn(unsigned Reg, const MachineBasicBlock *MBB) {
Cameron Zwarich36f54482013-02-10 23:29:49 +0000639 assert((LV || LIS) &&
640 "isLiveIn() requires either LiveVariables or LiveIntervals");
641 if (LIS)
642 return LIS->isLiveInToMBB(LIS->getInterval(Reg), MBB);
643 else
644 return LV->isLiveIn(Reg, *MBB);
645}
646
Arnaud A. de Grandmaisona2cdb8c2015-06-11 07:45:05 +0000647bool PHIElimination::isLiveOutPastPHIs(unsigned Reg,
648 const MachineBasicBlock *MBB) {
Cameron Zwarich36f54482013-02-10 23:29:49 +0000649 assert((LV || LIS) &&
650 "isLiveOutPastPHIs() requires either LiveVariables or LiveIntervals");
651 // LiveVariables considers uses in PHIs to be in the predecessor basic block,
652 // so that a register used only in a PHI is not live out of the block. In
653 // contrast, LiveIntervals considers uses in PHIs to be on the edge rather than
654 // in the predecessor basic block, so that a register used only in a PHI is live
655 // out of the block.
656 if (LIS) {
657 const LiveInterval &LI = LIS->getInterval(Reg);
Arnaud A. de Grandmaisona2cdb8c2015-06-11 07:45:05 +0000658 for (const MachineBasicBlock *SI : MBB->successors())
659 if (LI.liveAt(LIS->getMBBStartIdx(SI)))
Cameron Zwarich36f54482013-02-10 23:29:49 +0000660 return true;
Cameron Zwarich36f54482013-02-10 23:29:49 +0000661 return false;
662 } else {
663 return LV->isLiveOut(Reg, *MBB);
664 }
665}