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/TargetLowering.h" 35 #include "llvm/CodeGen/TargetOpcodes.h" 36 #include "llvm/CodeGen/TargetPassConfig.h" 37 #include "llvm/CodeGen/TargetRegisterInfo.h" 38 #include "llvm/CodeGen/TargetSubtargetInfo.h" 39 #include "llvm/Pass.h" 40 #include "llvm/Support/CommandLine.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include <cassert> 44 #include <iterator> 45 #include <utility> 46 47 using namespace llvm; 48 49 #define DEBUG_TYPE "phi-node-elimination" 50 51 static cl::opt<bool> 52 DisableEdgeSplitting("disable-phi-elim-edge-splitting", cl::init(false), 53 cl::Hidden, cl::desc("Disable critical edge splitting " 54 "during PHI elimination")); 55 56 static cl::opt<bool> 57 SplitAllCriticalEdges("phi-elim-split-all-critical-edges", cl::init(false), 58 cl::Hidden, cl::desc("Split all critical edges during " 59 "PHI elimination")); 60 61 static cl::opt<bool> NoPhiElimLiveOutEarlyExit( 62 "no-phi-elim-live-out-early-exit", cl::init(false), cl::Hidden, 63 cl::desc("Do not use an early exit if isLiveOutPastPHIs returns true.")); 64 65 namespace { 66 67 class PHIElimination : public MachineFunctionPass { 68 MachineRegisterInfo *MRI; // Machine register information 69 LiveVariables *LV; 70 LiveIntervals *LIS; 71 72 public: 73 static char ID; // Pass identification, replacement for typeid 74 75 PHIElimination() : MachineFunctionPass(ID) { 76 initializePHIEliminationPass(*PassRegistry::getPassRegistry()); 77 } 78 79 bool runOnMachineFunction(MachineFunction &MF) override; 80 void getAnalysisUsage(AnalysisUsage &AU) const override; 81 82 private: 83 /// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions 84 /// in predecessor basic blocks. 85 bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB); 86 87 void LowerPHINode(MachineBasicBlock &MBB, 88 MachineBasicBlock::iterator LastPHIIt); 89 90 /// analyzePHINodes - Gather information about the PHI nodes in 91 /// here. In particular, we want to map the number of uses of a virtual 92 /// register which is used in a PHI node. We map that to the BB the 93 /// vreg is coming from. This is used later to determine when the vreg 94 /// is killed in the BB. 95 void analyzePHINodes(const MachineFunction& MF); 96 97 /// Split critical edges where necessary for good coalescer performance. 98 bool SplitPHIEdges(MachineFunction &MF, MachineBasicBlock &MBB, 99 MachineLoopInfo *MLI, 100 std::vector<SparseBitVector<>> *LiveInSets); 101 102 // These functions are temporary abstractions around LiveVariables and 103 // LiveIntervals, so they can go away when LiveVariables does. 104 bool isLiveIn(unsigned Reg, const MachineBasicBlock *MBB); 105 bool isLiveOutPastPHIs(unsigned Reg, const MachineBasicBlock *MBB); 106 107 using BBVRegPair = std::pair<unsigned, unsigned>; 108 using VRegPHIUse = DenseMap<BBVRegPair, unsigned>; 109 110 VRegPHIUse VRegPHIUseCount; 111 112 // Defs of PHI sources which are implicit_def. 113 SmallPtrSet<MachineInstr*, 4> ImpDefs; 114 115 // Map reusable lowered PHI node -> incoming join register. 116 using LoweredPHIMap = 117 DenseMap<MachineInstr*, unsigned, MachineInstrExpressionTrait>; 118 LoweredPHIMap LoweredPHIs; 119 }; 120 121 } // end anonymous namespace 122 123 STATISTIC(NumLowered, "Number of phis lowered"); 124 STATISTIC(NumCriticalEdgesSplit, "Number of critical edges split"); 125 STATISTIC(NumReused, "Number of reused lowered phis"); 126 127 char PHIElimination::ID = 0; 128 129 char& llvm::PHIEliminationID = PHIElimination::ID; 130 131 INITIALIZE_PASS_BEGIN(PHIElimination, DEBUG_TYPE, 132 "Eliminate PHI nodes for register allocation", 133 false, false) 134 INITIALIZE_PASS_DEPENDENCY(LiveVariables) 135 INITIALIZE_PASS_END(PHIElimination, DEBUG_TYPE, 136 "Eliminate PHI nodes for register allocation", false, false) 137 138 void PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const { 139 AU.addUsedIfAvailable<LiveVariables>(); 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 unsigned 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 // Update live variable information if there is any. 320 if (LV) { 321 if (IncomingReg) { 322 LiveVariables::VarInfo &VI = LV->getVarInfo(IncomingReg); 323 324 // Increment use count of the newly created virtual register. 325 LV->setPHIJoin(IncomingReg); 326 327 // When we are reusing the incoming register, it may already have been 328 // killed in this block. The old kill will also have been inserted at 329 // AfterPHIsIt, so it appears before the current PHICopy. 330 if (reusedIncoming) 331 if (MachineInstr *OldKill = VI.findKill(&MBB)) { 332 LLVM_DEBUG(dbgs() << "Remove old kill from " << *OldKill); 333 LV->removeVirtualRegisterKilled(IncomingReg, *OldKill); 334 LLVM_DEBUG(MBB.dump()); 335 } 336 337 // Add information to LiveVariables to know that the incoming value is 338 // killed. Note that because the value is defined in several places (once 339 // each for each incoming block), the "def" block and instruction fields 340 // for the VarInfo is not filled in. 341 LV->addVirtualRegisterKilled(IncomingReg, *PHICopy); 342 } 343 344 // Since we are going to be deleting the PHI node, if it is the last use of 345 // any registers, or if the value itself is dead, we need to move this 346 // information over to the new copy we just inserted. 347 LV->removeVirtualRegistersKilled(*MPhi); 348 349 // If the result is dead, update LV. 350 if (isDead) { 351 LV->addVirtualRegisterDead(DestReg, *PHICopy); 352 LV->removeVirtualRegisterDead(DestReg, *MPhi); 353 } 354 } 355 356 // Update LiveIntervals for the new copy or implicit def. 357 if (LIS) { 358 SlotIndex DestCopyIndex = LIS->InsertMachineInstrInMaps(*PHICopy); 359 360 SlotIndex MBBStartIndex = LIS->getMBBStartIdx(&MBB); 361 if (IncomingReg) { 362 // Add the region from the beginning of MBB to the copy instruction to 363 // IncomingReg's live interval. 364 LiveInterval &IncomingLI = LIS->createEmptyInterval(IncomingReg); 365 VNInfo *IncomingVNI = IncomingLI.getVNInfoAt(MBBStartIndex); 366 if (!IncomingVNI) 367 IncomingVNI = IncomingLI.getNextValue(MBBStartIndex, 368 LIS->getVNInfoAllocator()); 369 IncomingLI.addSegment(LiveInterval::Segment(MBBStartIndex, 370 DestCopyIndex.getRegSlot(), 371 IncomingVNI)); 372 } 373 374 LiveInterval &DestLI = LIS->getInterval(DestReg); 375 assert(DestLI.begin() != DestLI.end() && 376 "PHIs should have nonempty LiveIntervals."); 377 if (DestLI.endIndex().isDead()) { 378 // A dead PHI's live range begins and ends at the start of the MBB, but 379 // the lowered copy, which will still be dead, needs to begin and end at 380 // the copy instruction. 381 VNInfo *OrigDestVNI = DestLI.getVNInfoAt(MBBStartIndex); 382 assert(OrigDestVNI && "PHI destination should be live at block entry."); 383 DestLI.removeSegment(MBBStartIndex, MBBStartIndex.getDeadSlot()); 384 DestLI.createDeadDef(DestCopyIndex.getRegSlot(), 385 LIS->getVNInfoAllocator()); 386 DestLI.removeValNo(OrigDestVNI); 387 } else { 388 // Otherwise, remove the region from the beginning of MBB to the copy 389 // instruction from DestReg's live interval. 390 DestLI.removeSegment(MBBStartIndex, DestCopyIndex.getRegSlot()); 391 VNInfo *DestVNI = DestLI.getVNInfoAt(DestCopyIndex.getRegSlot()); 392 assert(DestVNI && "PHI destination should be live at its definition."); 393 DestVNI->def = DestCopyIndex.getRegSlot(); 394 } 395 } 396 397 // Adjust the VRegPHIUseCount map to account for the removal of this PHI node. 398 for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2) 399 --VRegPHIUseCount[BBVRegPair(MPhi->getOperand(i+1).getMBB()->getNumber(), 400 MPhi->getOperand(i).getReg())]; 401 402 // Now loop over all of the incoming arguments, changing them to copy into the 403 // IncomingReg register in the corresponding predecessor basic block. 404 SmallPtrSet<MachineBasicBlock*, 8> MBBsInsertedInto; 405 for (int i = NumSrcs - 1; i >= 0; --i) { 406 Register SrcReg = MPhi->getOperand(i * 2 + 1).getReg(); 407 unsigned SrcSubReg = MPhi->getOperand(i*2+1).getSubReg(); 408 bool SrcUndef = MPhi->getOperand(i*2+1).isUndef() || 409 isImplicitlyDefined(SrcReg, *MRI); 410 assert(Register::isVirtualRegister(SrcReg) && 411 "Machine PHI Operands must all be virtual registers!"); 412 413 // Get the MachineBasicBlock equivalent of the BasicBlock that is the source 414 // path the PHI. 415 MachineBasicBlock &opBlock = *MPhi->getOperand(i*2+2).getMBB(); 416 417 // Check to make sure we haven't already emitted the copy for this block. 418 // This can happen because PHI nodes may have multiple entries for the same 419 // basic block. 420 if (!MBBsInsertedInto.insert(&opBlock).second) 421 continue; // If the copy has already been emitted, we're done. 422 423 // Find a safe location to insert the copy, this may be the first terminator 424 // in the block (or end()). 425 MachineBasicBlock::iterator InsertPos = 426 findPHICopyInsertPoint(&opBlock, &MBB, SrcReg); 427 428 // Insert the copy. 429 MachineInstr *NewSrcInstr = nullptr; 430 if (!reusedIncoming && IncomingReg) { 431 if (SrcUndef) { 432 // The source register is undefined, so there is no need for a real 433 // COPY, but we still need to ensure joint dominance by defs. 434 // Insert an IMPLICIT_DEF instruction. 435 NewSrcInstr = BuildMI(opBlock, InsertPos, MPhi->getDebugLoc(), 436 TII->get(TargetOpcode::IMPLICIT_DEF), 437 IncomingReg); 438 439 // Clean up the old implicit-def, if there even was one. 440 if (MachineInstr *DefMI = MRI->getVRegDef(SrcReg)) 441 if (DefMI->isImplicitDef()) 442 ImpDefs.insert(DefMI); 443 } else { 444 NewSrcInstr = 445 TII->createPHISourceCopy(opBlock, InsertPos, MPhi->getDebugLoc(), 446 SrcReg, SrcSubReg, IncomingReg); 447 } 448 } 449 450 // We only need to update the LiveVariables kill of SrcReg if this was the 451 // last PHI use of SrcReg to be lowered on this CFG edge and it is not live 452 // out of the predecessor. We can also ignore undef sources. 453 if (LV && !SrcUndef && 454 !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)] && 455 !LV->isLiveOut(SrcReg, opBlock)) { 456 // We want to be able to insert a kill of the register if this PHI (aka, 457 // the copy we just inserted) is the last use of the source value. Live 458 // variable analysis conservatively handles this by saying that the value 459 // is live until the end of the block the PHI entry lives in. If the value 460 // really is dead at the PHI copy, there will be no successor blocks which 461 // have the value live-in. 462 463 // Okay, if we now know that the value is not live out of the block, we 464 // can add a kill marker in this block saying that it kills the incoming 465 // value! 466 467 // In our final twist, we have to decide which instruction kills the 468 // register. In most cases this is the copy, however, terminator 469 // instructions at the end of the block may also use the value. In this 470 // case, we should mark the last such terminator as being the killing 471 // block, not the copy. 472 MachineBasicBlock::iterator KillInst = opBlock.end(); 473 MachineBasicBlock::iterator FirstTerm = opBlock.getFirstTerminator(); 474 for (MachineBasicBlock::iterator Term = FirstTerm; 475 Term != opBlock.end(); ++Term) { 476 if (Term->readsRegister(SrcReg)) 477 KillInst = Term; 478 } 479 480 if (KillInst == opBlock.end()) { 481 // No terminator uses the register. 482 483 if (reusedIncoming || !IncomingReg) { 484 // We may have to rewind a bit if we didn't insert a copy this time. 485 KillInst = FirstTerm; 486 while (KillInst != opBlock.begin()) { 487 --KillInst; 488 if (KillInst->isDebugInstr()) 489 continue; 490 if (KillInst->readsRegister(SrcReg)) 491 break; 492 } 493 } else { 494 // We just inserted this copy. 495 KillInst = NewSrcInstr; 496 } 497 } 498 assert(KillInst->readsRegister(SrcReg) && "Cannot find kill instruction"); 499 500 // Finally, mark it killed. 501 LV->addVirtualRegisterKilled(SrcReg, *KillInst); 502 503 // This vreg no longer lives all of the way through opBlock. 504 unsigned opBlockNum = opBlock.getNumber(); 505 LV->getVarInfo(SrcReg).AliveBlocks.reset(opBlockNum); 506 } 507 508 if (LIS) { 509 if (NewSrcInstr) { 510 LIS->InsertMachineInstrInMaps(*NewSrcInstr); 511 LIS->addSegmentToEndOfBlock(IncomingReg, *NewSrcInstr); 512 } 513 514 if (!SrcUndef && 515 !VRegPHIUseCount[BBVRegPair(opBlock.getNumber(), SrcReg)]) { 516 LiveInterval &SrcLI = LIS->getInterval(SrcReg); 517 518 bool isLiveOut = false; 519 for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(), 520 SE = opBlock.succ_end(); SI != SE; ++SI) { 521 SlotIndex startIdx = LIS->getMBBStartIdx(*SI); 522 VNInfo *VNI = SrcLI.getVNInfoAt(startIdx); 523 524 // Definitions by other PHIs are not truly live-in for our purposes. 525 if (VNI && VNI->def != startIdx) { 526 isLiveOut = true; 527 break; 528 } 529 } 530 531 if (!isLiveOut) { 532 MachineBasicBlock::iterator KillInst = opBlock.end(); 533 MachineBasicBlock::iterator FirstTerm = opBlock.getFirstTerminator(); 534 for (MachineBasicBlock::iterator Term = FirstTerm; 535 Term != opBlock.end(); ++Term) { 536 if (Term->readsRegister(SrcReg)) 537 KillInst = Term; 538 } 539 540 if (KillInst == opBlock.end()) { 541 // No terminator uses the register. 542 543 if (reusedIncoming || !IncomingReg) { 544 // We may have to rewind a bit if we didn't just insert a copy. 545 KillInst = FirstTerm; 546 while (KillInst != opBlock.begin()) { 547 --KillInst; 548 if (KillInst->isDebugInstr()) 549 continue; 550 if (KillInst->readsRegister(SrcReg)) 551 break; 552 } 553 } else { 554 // We just inserted this copy. 555 KillInst = std::prev(InsertPos); 556 } 557 } 558 assert(KillInst->readsRegister(SrcReg) && 559 "Cannot find kill instruction"); 560 561 SlotIndex LastUseIndex = LIS->getInstructionIndex(*KillInst); 562 SrcLI.removeSegment(LastUseIndex.getRegSlot(), 563 LIS->getMBBEndIdx(&opBlock)); 564 } 565 } 566 } 567 } 568 569 // Really delete the PHI instruction now, if it is not in the LoweredPHIs map. 570 if (reusedIncoming || !IncomingReg) { 571 if (LIS) 572 LIS->RemoveMachineInstrFromMaps(*MPhi); 573 MF.DeleteMachineInstr(MPhi); 574 } 575 } 576 577 /// analyzePHINodes - Gather information about the PHI nodes in here. In 578 /// particular, we want to map the number of uses of a virtual register which is 579 /// used in a PHI node. We map that to the BB the vreg is coming from. This is 580 /// used later to determine when the vreg is killed in the BB. 581 void PHIElimination::analyzePHINodes(const MachineFunction& MF) { 582 for (const auto &MBB : MF) 583 for (const auto &BBI : MBB) { 584 if (!BBI.isPHI()) 585 break; 586 for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) 587 ++VRegPHIUseCount[BBVRegPair(BBI.getOperand(i+1).getMBB()->getNumber(), 588 BBI.getOperand(i).getReg())]; 589 } 590 } 591 592 bool PHIElimination::SplitPHIEdges(MachineFunction &MF, 593 MachineBasicBlock &MBB, 594 MachineLoopInfo *MLI, 595 std::vector<SparseBitVector<>> *LiveInSets) { 596 if (MBB.empty() || !MBB.front().isPHI() || MBB.isEHPad()) 597 return false; // Quick exit for basic blocks without PHIs. 598 599 const MachineLoop *CurLoop = MLI ? MLI->getLoopFor(&MBB) : nullptr; 600 bool IsLoopHeader = CurLoop && &MBB == CurLoop->getHeader(); 601 602 bool Changed = false; 603 for (MachineBasicBlock::iterator BBI = MBB.begin(), BBE = MBB.end(); 604 BBI != BBE && BBI->isPHI(); ++BBI) { 605 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) { 606 Register Reg = BBI->getOperand(i).getReg(); 607 MachineBasicBlock *PreMBB = BBI->getOperand(i+1).getMBB(); 608 // Is there a critical edge from PreMBB to MBB? 609 if (PreMBB->succ_size() == 1) 610 continue; 611 612 // Avoid splitting backedges of loops. It would introduce small 613 // out-of-line blocks into the loop which is very bad for code placement. 614 if (PreMBB == &MBB && !SplitAllCriticalEdges) 615 continue; 616 const MachineLoop *PreLoop = MLI ? MLI->getLoopFor(PreMBB) : nullptr; 617 if (IsLoopHeader && PreLoop == CurLoop && !SplitAllCriticalEdges) 618 continue; 619 620 // LV doesn't consider a phi use live-out, so isLiveOut only returns true 621 // when the source register is live-out for some other reason than a phi 622 // use. That means the copy we will insert in PreMBB won't be a kill, and 623 // there is a risk it may not be coalesced away. 624 // 625 // If the copy would be a kill, there is no need to split the edge. 626 bool ShouldSplit = isLiveOutPastPHIs(Reg, PreMBB); 627 if (!ShouldSplit && !NoPhiElimLiveOutEarlyExit) 628 continue; 629 if (ShouldSplit) { 630 LLVM_DEBUG(dbgs() << printReg(Reg) << " live-out before critical edge " 631 << printMBBReference(*PreMBB) << " -> " 632 << printMBBReference(MBB) << ": " << *BBI); 633 } 634 635 // If Reg is not live-in to MBB, it means it must be live-in to some 636 // other PreMBB successor, and we can avoid the interference by splitting 637 // the edge. 638 // 639 // If Reg *is* live-in to MBB, the interference is inevitable and a copy 640 // is likely to be left after coalescing. If we are looking at a loop 641 // exiting edge, split it so we won't insert code in the loop, otherwise 642 // don't bother. 643 ShouldSplit = ShouldSplit && !isLiveIn(Reg, &MBB); 644 645 // Check for a loop exiting edge. 646 if (!ShouldSplit && CurLoop != PreLoop) { 647 LLVM_DEBUG({ 648 dbgs() << "Split wouldn't help, maybe avoid loop copies?\n"; 649 if (PreLoop) 650 dbgs() << "PreLoop: " << *PreLoop; 651 if (CurLoop) 652 dbgs() << "CurLoop: " << *CurLoop; 653 }); 654 // This edge could be entering a loop, exiting a loop, or it could be 655 // both: Jumping directly form one loop to the header of a sibling 656 // loop. 657 // Split unless this edge is entering CurLoop from an outer loop. 658 ShouldSplit = PreLoop && !PreLoop->contains(CurLoop); 659 } 660 if (!ShouldSplit && !SplitAllCriticalEdges) 661 continue; 662 if (!PreMBB->SplitCriticalEdge(&MBB, *this, LiveInSets)) { 663 LLVM_DEBUG(dbgs() << "Failed to split critical edge.\n"); 664 continue; 665 } 666 Changed = true; 667 ++NumCriticalEdgesSplit; 668 } 669 } 670 return Changed; 671 } 672 673 bool PHIElimination::isLiveIn(unsigned Reg, const MachineBasicBlock *MBB) { 674 assert((LV || LIS) && 675 "isLiveIn() requires either LiveVariables or LiveIntervals"); 676 if (LIS) 677 return LIS->isLiveInToMBB(LIS->getInterval(Reg), MBB); 678 else 679 return LV->isLiveIn(Reg, *MBB); 680 } 681 682 bool PHIElimination::isLiveOutPastPHIs(unsigned Reg, 683 const MachineBasicBlock *MBB) { 684 assert((LV || LIS) && 685 "isLiveOutPastPHIs() requires either LiveVariables or LiveIntervals"); 686 // LiveVariables considers uses in PHIs to be in the predecessor basic block, 687 // so that a register used only in a PHI is not live out of the block. In 688 // contrast, LiveIntervals considers uses in PHIs to be on the edge rather than 689 // in the predecessor basic block, so that a register used only in a PHI is live 690 // out of the block. 691 if (LIS) { 692 const LiveInterval &LI = LIS->getInterval(Reg); 693 for (const MachineBasicBlock *SI : MBB->successors()) 694 if (LI.liveAt(LIS->getMBBStartIdx(SI))) 695 return true; 696 return false; 697 } else { 698 return LV->isLiveOut(Reg, *MBB); 699 } 700 } 701