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