1 //===- SplitKit.cpp - Toolkit for splitting live ranges -------------------===// 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 file contains the SplitAnalysis class as well as mutator functions for 10 // live range splitting. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SplitKit.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/Analysis/AliasAnalysis.h" 18 #include "llvm/CodeGen/LiveRangeEdit.h" 19 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 20 #include "llvm/CodeGen/MachineDominators.h" 21 #include "llvm/CodeGen/MachineInstr.h" 22 #include "llvm/CodeGen/MachineInstrBuilder.h" 23 #include "llvm/CodeGen/MachineLoopInfo.h" 24 #include "llvm/CodeGen/MachineOperand.h" 25 #include "llvm/CodeGen/MachineRegisterInfo.h" 26 #include "llvm/CodeGen/TargetInstrInfo.h" 27 #include "llvm/CodeGen/TargetOpcodes.h" 28 #include "llvm/CodeGen/TargetRegisterInfo.h" 29 #include "llvm/CodeGen/TargetSubtargetInfo.h" 30 #include "llvm/CodeGen/VirtRegMap.h" 31 #include "llvm/Config/llvm-config.h" 32 #include "llvm/IR/DebugLoc.h" 33 #include "llvm/Support/Allocator.h" 34 #include "llvm/Support/BlockFrequency.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include <algorithm> 39 #include <cassert> 40 #include <iterator> 41 #include <limits> 42 #include <tuple> 43 44 using namespace llvm; 45 46 #define DEBUG_TYPE "regalloc" 47 48 STATISTIC(NumFinished, "Number of splits finished"); 49 STATISTIC(NumSimple, "Number of splits that were simple"); 50 STATISTIC(NumCopies, "Number of copies inserted for splitting"); 51 STATISTIC(NumRemats, "Number of rematerialized defs for splitting"); 52 53 //===----------------------------------------------------------------------===// 54 // Last Insert Point Analysis 55 //===----------------------------------------------------------------------===// 56 57 InsertPointAnalysis::InsertPointAnalysis(const LiveIntervals &lis, 58 unsigned BBNum) 59 : LIS(lis), LastInsertPoint(BBNum) {} 60 61 SlotIndex 62 InsertPointAnalysis::computeLastInsertPoint(const LiveInterval &CurLI, 63 const MachineBasicBlock &MBB) { 64 unsigned Num = MBB.getNumber(); 65 std::pair<SlotIndex, SlotIndex> &LIP = LastInsertPoint[Num]; 66 SlotIndex MBBEnd = LIS.getMBBEndIdx(&MBB); 67 68 SmallVector<const MachineBasicBlock *, 1> ExceptionalSuccessors; 69 bool EHPadSuccessor = false; 70 for (const MachineBasicBlock *SMBB : MBB.successors()) { 71 if (SMBB->isEHPad()) { 72 ExceptionalSuccessors.push_back(SMBB); 73 EHPadSuccessor = true; 74 } else if (SMBB->isInlineAsmBrIndirectTarget()) 75 ExceptionalSuccessors.push_back(SMBB); 76 } 77 78 // Compute insert points on the first call. The pair is independent of the 79 // current live interval. 80 if (!LIP.first.isValid()) { 81 MachineBasicBlock::const_iterator FirstTerm = MBB.getFirstTerminator(); 82 if (FirstTerm == MBB.end()) 83 LIP.first = MBBEnd; 84 else 85 LIP.first = LIS.getInstructionIndex(*FirstTerm); 86 87 // If there is a landing pad or inlineasm_br successor, also find the 88 // instruction. If there is no such instruction, we don't need to do 89 // anything special. We assume there cannot be multiple instructions that 90 // are Calls with EHPad successors or INLINEASM_BR in a block. Further, we 91 // assume that if there are any, they will be after any other call 92 // instructions in the block. 93 if (ExceptionalSuccessors.empty()) 94 return LIP.first; 95 for (const MachineInstr &MI : llvm::reverse(MBB)) { 96 if ((EHPadSuccessor && MI.isCall()) || 97 MI.getOpcode() == TargetOpcode::INLINEASM_BR) { 98 LIP.second = LIS.getInstructionIndex(MI); 99 break; 100 } 101 } 102 } 103 104 // If CurLI is live into a landing pad successor, move the last insert point 105 // back to the call that may throw. 106 if (!LIP.second) 107 return LIP.first; 108 109 if (none_of(ExceptionalSuccessors, [&](const MachineBasicBlock *EHPad) { 110 return LIS.isLiveInToMBB(CurLI, EHPad); 111 })) 112 return LIP.first; 113 114 // Find the value leaving MBB. 115 const VNInfo *VNI = CurLI.getVNInfoBefore(MBBEnd); 116 if (!VNI) 117 return LIP.first; 118 119 // The def of statepoint instruction is a gc relocation and it should be alive 120 // in landing pad. So we cannot split interval after statepoint instruction. 121 if (SlotIndex::isSameInstr(VNI->def, LIP.second)) 122 if (auto *I = LIS.getInstructionFromIndex(LIP.second)) 123 if (I->getOpcode() == TargetOpcode::STATEPOINT) 124 return LIP.second; 125 126 // If the value leaving MBB was defined after the call in MBB, it can't 127 // really be live-in to the landing pad. This can happen if the landing pad 128 // has a PHI, and this register is undef on the exceptional edge. 129 if (!SlotIndex::isEarlierInstr(VNI->def, LIP.second) && VNI->def < MBBEnd) 130 return LIP.first; 131 132 // Value is properly live-in to the landing pad. 133 // Only allow inserts before the call. 134 return LIP.second; 135 } 136 137 MachineBasicBlock::iterator 138 InsertPointAnalysis::getLastInsertPointIter(const LiveInterval &CurLI, 139 MachineBasicBlock &MBB) { 140 SlotIndex LIP = getLastInsertPoint(CurLI, MBB); 141 if (LIP == LIS.getMBBEndIdx(&MBB)) 142 return MBB.end(); 143 return LIS.getInstructionFromIndex(LIP); 144 } 145 146 //===----------------------------------------------------------------------===// 147 // Split Analysis 148 //===----------------------------------------------------------------------===// 149 150 SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis, 151 const MachineLoopInfo &mli) 152 : MF(vrm.getMachineFunction()), VRM(vrm), LIS(lis), Loops(mli), 153 TII(*MF.getSubtarget().getInstrInfo()), IPA(lis, MF.getNumBlockIDs()) {} 154 155 void SplitAnalysis::clear() { 156 UseSlots.clear(); 157 UseBlocks.clear(); 158 ThroughBlocks.clear(); 159 CurLI = nullptr; 160 } 161 162 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI. 163 void SplitAnalysis::analyzeUses() { 164 assert(UseSlots.empty() && "Call clear first"); 165 166 // First get all the defs from the interval values. This provides the correct 167 // slots for early clobbers. 168 for (const VNInfo *VNI : CurLI->valnos) 169 if (!VNI->isPHIDef() && !VNI->isUnused()) 170 UseSlots.push_back(VNI->def); 171 172 // Get use slots form the use-def chain. 173 const MachineRegisterInfo &MRI = MF.getRegInfo(); 174 for (MachineOperand &MO : MRI.use_nodbg_operands(CurLI->reg())) 175 if (!MO.isUndef()) 176 UseSlots.push_back(LIS.getInstructionIndex(*MO.getParent()).getRegSlot()); 177 178 array_pod_sort(UseSlots.begin(), UseSlots.end()); 179 180 // Remove duplicates, keeping the smaller slot for each instruction. 181 // That is what we want for early clobbers. 182 UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(), 183 SlotIndex::isSameInstr), 184 UseSlots.end()); 185 186 // Compute per-live block info. 187 calcLiveBlockInfo(); 188 189 LLVM_DEBUG(dbgs() << "Analyze counted " << UseSlots.size() << " instrs in " 190 << UseBlocks.size() << " blocks, through " 191 << NumThroughBlocks << " blocks.\n"); 192 } 193 194 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks 195 /// where CurLI is live. 196 void SplitAnalysis::calcLiveBlockInfo() { 197 ThroughBlocks.resize(MF.getNumBlockIDs()); 198 NumThroughBlocks = NumGapBlocks = 0; 199 if (CurLI->empty()) 200 return; 201 202 LiveInterval::const_iterator LVI = CurLI->begin(); 203 LiveInterval::const_iterator LVE = CurLI->end(); 204 205 SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE; 206 UseI = UseSlots.begin(); 207 UseE = UseSlots.end(); 208 209 // Loop over basic blocks where CurLI is live. 210 MachineFunction::iterator MFI = 211 LIS.getMBBFromIndex(LVI->start)->getIterator(); 212 while (true) { 213 BlockInfo BI; 214 BI.MBB = &*MFI; 215 SlotIndex Start, Stop; 216 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 217 218 // If the block contains no uses, the range must be live through. At one 219 // point, RegisterCoalescer could create dangling ranges that ended 220 // mid-block. 221 if (UseI == UseE || *UseI >= Stop) { 222 ++NumThroughBlocks; 223 ThroughBlocks.set(BI.MBB->getNumber()); 224 // The range shouldn't end mid-block if there are no uses. This shouldn't 225 // happen. 226 assert(LVI->end >= Stop && "range ends mid block with no uses"); 227 } else { 228 // This block has uses. Find the first and last uses in the block. 229 BI.FirstInstr = *UseI; 230 assert(BI.FirstInstr >= Start); 231 do ++UseI; 232 while (UseI != UseE && *UseI < Stop); 233 BI.LastInstr = UseI[-1]; 234 assert(BI.LastInstr < Stop); 235 236 // LVI is the first live segment overlapping MBB. 237 BI.LiveIn = LVI->start <= Start; 238 239 // When not live in, the first use should be a def. 240 if (!BI.LiveIn) { 241 assert(LVI->start == LVI->valno->def && "Dangling Segment start"); 242 assert(LVI->start == BI.FirstInstr && "First instr should be a def"); 243 BI.FirstDef = BI.FirstInstr; 244 } 245 246 // Look for gaps in the live range. 247 BI.LiveOut = true; 248 while (LVI->end < Stop) { 249 SlotIndex LastStop = LVI->end; 250 if (++LVI == LVE || LVI->start >= Stop) { 251 BI.LiveOut = false; 252 BI.LastInstr = LastStop; 253 break; 254 } 255 256 if (LastStop < LVI->start) { 257 // There is a gap in the live range. Create duplicate entries for the 258 // live-in snippet and the live-out snippet. 259 ++NumGapBlocks; 260 261 // Push the Live-in part. 262 BI.LiveOut = false; 263 UseBlocks.push_back(BI); 264 UseBlocks.back().LastInstr = LastStop; 265 266 // Set up BI for the live-out part. 267 BI.LiveIn = false; 268 BI.LiveOut = true; 269 BI.FirstInstr = BI.FirstDef = LVI->start; 270 } 271 272 // A Segment that starts in the middle of the block must be a def. 273 assert(LVI->start == LVI->valno->def && "Dangling Segment start"); 274 if (!BI.FirstDef) 275 BI.FirstDef = LVI->start; 276 } 277 278 UseBlocks.push_back(BI); 279 280 // LVI is now at LVE or LVI->end >= Stop. 281 if (LVI == LVE) 282 break; 283 } 284 285 // Live segment ends exactly at Stop. Move to the next segment. 286 if (LVI->end == Stop && ++LVI == LVE) 287 break; 288 289 // Pick the next basic block. 290 if (LVI->start < Stop) 291 ++MFI; 292 else 293 MFI = LIS.getMBBFromIndex(LVI->start)->getIterator(); 294 } 295 296 assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count"); 297 } 298 299 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const { 300 if (cli->empty()) 301 return 0; 302 LiveInterval *li = const_cast<LiveInterval*>(cli); 303 LiveInterval::iterator LVI = li->begin(); 304 LiveInterval::iterator LVE = li->end(); 305 unsigned Count = 0; 306 307 // Loop over basic blocks where li is live. 308 MachineFunction::const_iterator MFI = 309 LIS.getMBBFromIndex(LVI->start)->getIterator(); 310 SlotIndex Stop = LIS.getMBBEndIdx(&*MFI); 311 while (true) { 312 ++Count; 313 LVI = li->advanceTo(LVI, Stop); 314 if (LVI == LVE) 315 return Count; 316 do { 317 ++MFI; 318 Stop = LIS.getMBBEndIdx(&*MFI); 319 } while (Stop <= LVI->start); 320 } 321 } 322 323 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const { 324 Register OrigReg = VRM.getOriginal(CurLI->reg()); 325 const LiveInterval &Orig = LIS.getInterval(OrigReg); 326 assert(!Orig.empty() && "Splitting empty interval?"); 327 LiveInterval::const_iterator I = Orig.find(Idx); 328 329 // Range containing Idx should begin at Idx. 330 if (I != Orig.end() && I->start <= Idx) 331 return I->start == Idx; 332 333 // Range does not contain Idx, previous must end at Idx. 334 return I != Orig.begin() && (--I)->end == Idx; 335 } 336 337 void SplitAnalysis::analyze(const LiveInterval *li) { 338 clear(); 339 CurLI = li; 340 analyzeUses(); 341 } 342 343 //===----------------------------------------------------------------------===// 344 // Split Editor 345 //===----------------------------------------------------------------------===// 346 347 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA. 348 SplitEditor::SplitEditor(SplitAnalysis &SA, LiveIntervals &LIS, VirtRegMap &VRM, 349 MachineDominatorTree &MDT, 350 MachineBlockFrequencyInfo &MBFI, VirtRegAuxInfo &VRAI) 351 : SA(SA), LIS(LIS), VRM(VRM), MRI(VRM.getMachineFunction().getRegInfo()), 352 MDT(MDT), TII(*VRM.getMachineFunction().getSubtarget().getInstrInfo()), 353 TRI(*VRM.getMachineFunction().getSubtarget().getRegisterInfo()), 354 MBFI(MBFI), VRAI(VRAI), RegAssign(Allocator) {} 355 356 void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) { 357 Edit = &LRE; 358 SpillMode = SM; 359 OpenIdx = 0; 360 RegAssign.clear(); 361 Values.clear(); 362 363 // Reset the LiveIntervalCalc instances needed for this spill mode. 364 LICalc[0].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 365 &LIS.getVNInfoAllocator()); 366 if (SpillMode) 367 LICalc[1].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 368 &LIS.getVNInfoAllocator()); 369 370 Edit->anyRematerializable(); 371 } 372 373 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 374 LLVM_DUMP_METHOD void SplitEditor::dump() const { 375 if (RegAssign.empty()) { 376 dbgs() << " empty\n"; 377 return; 378 } 379 380 for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I) 381 dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value(); 382 dbgs() << '\n'; 383 } 384 #endif 385 386 /// Find a subrange corresponding to the exact lane mask @p LM in the live 387 /// interval @p LI. The interval @p LI is assumed to contain such a subrange. 388 /// This function is used to find corresponding subranges between the 389 /// original interval and the new intervals. 390 template <typename T> auto &getSubrangeImpl(LaneBitmask LM, T &LI) { 391 for (auto &S : LI.subranges()) 392 if (S.LaneMask == LM) 393 return S; 394 llvm_unreachable("SubRange for this mask not found"); 395 } 396 397 LiveInterval::SubRange &getSubRangeForMaskExact(LaneBitmask LM, 398 LiveInterval &LI) { 399 return getSubrangeImpl(LM, LI); 400 } 401 402 const LiveInterval::SubRange &getSubRangeForMaskExact(LaneBitmask LM, 403 const LiveInterval &LI) { 404 return getSubrangeImpl(LM, LI); 405 } 406 407 /// Find a subrange corresponding to the lane mask @p LM, or a superset of it, 408 /// in the live interval @p LI. The interval @p LI is assumed to contain such 409 /// a subrange. This function is used to find corresponding subranges between 410 /// the original interval and the new intervals. 411 const LiveInterval::SubRange &getSubRangeForMask(LaneBitmask LM, 412 const LiveInterval &LI) { 413 for (const LiveInterval::SubRange &S : LI.subranges()) 414 if ((S.LaneMask & LM) == LM) 415 return S; 416 llvm_unreachable("SubRange for this mask not found"); 417 } 418 419 void SplitEditor::addDeadDef(LiveInterval &LI, VNInfo *VNI, bool Original) { 420 if (!LI.hasSubRanges()) { 421 LI.createDeadDef(VNI); 422 return; 423 } 424 425 SlotIndex Def = VNI->def; 426 if (Original) { 427 // If we are transferring a def from the original interval, make sure 428 // to only update the subranges for which the original subranges had 429 // a def at this location. 430 for (LiveInterval::SubRange &S : LI.subranges()) { 431 auto &PS = getSubRangeForMask(S.LaneMask, Edit->getParent()); 432 VNInfo *PV = PS.getVNInfoAt(Def); 433 if (PV != nullptr && PV->def == Def) 434 S.createDeadDef(Def, LIS.getVNInfoAllocator()); 435 } 436 } else { 437 // This is a new def: either from rematerialization, or from an inserted 438 // copy. Since rematerialization can regenerate a definition of a sub- 439 // register, we need to check which subranges need to be updated. 440 const MachineInstr *DefMI = LIS.getInstructionFromIndex(Def); 441 assert(DefMI != nullptr); 442 LaneBitmask LM; 443 for (const MachineOperand &DefOp : DefMI->defs()) { 444 Register R = DefOp.getReg(); 445 if (R != LI.reg()) 446 continue; 447 if (unsigned SR = DefOp.getSubReg()) 448 LM |= TRI.getSubRegIndexLaneMask(SR); 449 else { 450 LM = MRI.getMaxLaneMaskForVReg(R); 451 break; 452 } 453 } 454 for (LiveInterval::SubRange &S : LI.subranges()) 455 if ((S.LaneMask & LM).any()) 456 S.createDeadDef(Def, LIS.getVNInfoAllocator()); 457 } 458 } 459 460 VNInfo *SplitEditor::defValue(unsigned RegIdx, 461 const VNInfo *ParentVNI, 462 SlotIndex Idx, 463 bool Original) { 464 assert(ParentVNI && "Mapping NULL value"); 465 assert(Idx.isValid() && "Invalid SlotIndex"); 466 assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI"); 467 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx)); 468 469 // Create a new value. 470 VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator()); 471 472 bool Force = LI->hasSubRanges(); 473 ValueForcePair FP(Force ? nullptr : VNI, Force); 474 // Use insert for lookup, so we can add missing values with a second lookup. 475 std::pair<ValueMap::iterator, bool> InsP = 476 Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id), FP)); 477 478 // This was the first time (RegIdx, ParentVNI) was mapped, and it is not 479 // forced. Keep it as a simple def without any liveness. 480 if (!Force && InsP.second) 481 return VNI; 482 483 // If the previous value was a simple mapping, add liveness for it now. 484 if (VNInfo *OldVNI = InsP.first->second.getPointer()) { 485 addDeadDef(*LI, OldVNI, Original); 486 487 // No longer a simple mapping. Switch to a complex mapping. If the 488 // interval has subranges, make it a forced mapping. 489 InsP.first->second = ValueForcePair(nullptr, Force); 490 } 491 492 // This is a complex mapping, add liveness for VNI 493 addDeadDef(*LI, VNI, Original); 494 return VNI; 495 } 496 497 void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo &ParentVNI) { 498 ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI.id)]; 499 VNInfo *VNI = VFP.getPointer(); 500 501 // ParentVNI was either unmapped or already complex mapped. Either way, just 502 // set the force bit. 503 if (!VNI) { 504 VFP.setInt(true); 505 return; 506 } 507 508 // This was previously a single mapping. Make sure the old def is represented 509 // by a trivial live range. 510 addDeadDef(LIS.getInterval(Edit->get(RegIdx)), VNI, false); 511 512 // Mark as complex mapped, forced. 513 VFP = ValueForcePair(nullptr, true); 514 } 515 516 SlotIndex SplitEditor::buildSingleSubRegCopy( 517 Register FromReg, Register ToReg, MachineBasicBlock &MBB, 518 MachineBasicBlock::iterator InsertBefore, unsigned SubIdx, 519 LiveInterval &DestLI, bool Late, SlotIndex Def, const MCInstrDesc &Desc) { 520 bool FirstCopy = !Def.isValid(); 521 MachineInstr *CopyMI = BuildMI(MBB, InsertBefore, DebugLoc(), Desc) 522 .addReg(ToReg, RegState::Define | getUndefRegState(FirstCopy) 523 | getInternalReadRegState(!FirstCopy), SubIdx) 524 .addReg(FromReg, 0, SubIdx); 525 526 SlotIndexes &Indexes = *LIS.getSlotIndexes(); 527 if (FirstCopy) { 528 Def = Indexes.insertMachineInstrInMaps(*CopyMI, Late).getRegSlot(); 529 } else { 530 CopyMI->bundleWithPred(); 531 } 532 return Def; 533 } 534 535 SlotIndex SplitEditor::buildCopy(Register FromReg, Register ToReg, 536 LaneBitmask LaneMask, MachineBasicBlock &MBB, 537 MachineBasicBlock::iterator InsertBefore, bool Late, unsigned RegIdx) { 538 const MCInstrDesc &Desc = 539 TII.get(TII.getLiveRangeSplitOpcode(FromReg, *MBB.getParent())); 540 SlotIndexes &Indexes = *LIS.getSlotIndexes(); 541 if (LaneMask.all() || LaneMask == MRI.getMaxLaneMaskForVReg(FromReg)) { 542 // The full vreg is copied. 543 MachineInstr *CopyMI = 544 BuildMI(MBB, InsertBefore, DebugLoc(), Desc, ToReg).addReg(FromReg); 545 return Indexes.insertMachineInstrInMaps(*CopyMI, Late).getRegSlot(); 546 } 547 548 // Only a subset of lanes needs to be copied. The following is a simple 549 // heuristic to construct a sequence of COPYs. We could add a target 550 // specific callback if this turns out to be suboptimal. 551 LiveInterval &DestLI = LIS.getInterval(Edit->get(RegIdx)); 552 553 // First pass: Try to find a perfectly matching subregister index. If none 554 // exists find the one covering the most lanemask bits. 555 const TargetRegisterClass *RC = MRI.getRegClass(FromReg); 556 assert(RC == MRI.getRegClass(ToReg) && "Should have same reg class"); 557 558 SmallVector<unsigned, 8> SubIndexes; 559 560 // Abort if we cannot possibly implement the COPY with the given indexes. 561 if (!TRI.getCoveringSubRegIndexes(MRI, RC, LaneMask, SubIndexes)) 562 report_fatal_error("Impossible to implement partial COPY"); 563 564 SlotIndex Def; 565 for (unsigned BestIdx : SubIndexes) { 566 Def = buildSingleSubRegCopy(FromReg, ToReg, MBB, InsertBefore, BestIdx, 567 DestLI, Late, Def, Desc); 568 } 569 570 BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator(); 571 DestLI.refineSubRanges( 572 Allocator, LaneMask, 573 [Def, &Allocator](LiveInterval::SubRange &SR) { 574 SR.createDeadDef(Def, Allocator); 575 }, 576 Indexes, TRI); 577 578 return Def; 579 } 580 581 VNInfo *SplitEditor::defFromParent(unsigned RegIdx, const VNInfo *ParentVNI, 582 SlotIndex UseIdx, MachineBasicBlock &MBB, 583 MachineBasicBlock::iterator I) { 584 SlotIndex Def; 585 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx)); 586 587 // We may be trying to avoid interference that ends at a deleted instruction, 588 // so always begin RegIdx 0 early and all others late. 589 bool Late = RegIdx != 0; 590 591 // Attempt cheap-as-a-copy rematerialization. 592 Register Original = VRM.getOriginal(Edit->get(RegIdx)); 593 LiveInterval &OrigLI = LIS.getInterval(Original); 594 VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx); 595 596 Register Reg = LI->reg(); 597 bool DidRemat = false; 598 if (OrigVNI) { 599 LiveRangeEdit::Remat RM(ParentVNI); 600 RM.OrigMI = LIS.getInstructionFromIndex(OrigVNI->def); 601 if (Edit->canRematerializeAt(RM, OrigVNI, UseIdx, true)) { 602 Def = Edit->rematerializeAt(MBB, I, Reg, RM, TRI, Late); 603 ++NumRemats; 604 DidRemat = true; 605 } 606 } 607 if (!DidRemat) { 608 LaneBitmask LaneMask; 609 if (OrigLI.hasSubRanges()) { 610 LaneMask = LaneBitmask::getNone(); 611 for (LiveInterval::SubRange &S : OrigLI.subranges()) { 612 if (S.liveAt(UseIdx)) 613 LaneMask |= S.LaneMask; 614 } 615 } else { 616 LaneMask = LaneBitmask::getAll(); 617 } 618 619 if (LaneMask.none()) { 620 const MCInstrDesc &Desc = TII.get(TargetOpcode::IMPLICIT_DEF); 621 MachineInstr *ImplicitDef = BuildMI(MBB, I, DebugLoc(), Desc, Reg); 622 SlotIndexes &Indexes = *LIS.getSlotIndexes(); 623 Def = Indexes.insertMachineInstrInMaps(*ImplicitDef, Late).getRegSlot(); 624 } else { 625 ++NumCopies; 626 Def = buildCopy(Edit->getReg(), Reg, LaneMask, MBB, I, Late, RegIdx); 627 } 628 } 629 630 // Define the value in Reg. 631 return defValue(RegIdx, ParentVNI, Def, false); 632 } 633 634 /// Create a new virtual register and live interval. 635 unsigned SplitEditor::openIntv() { 636 // Create the complement as index 0. 637 if (Edit->empty()) 638 Edit->createEmptyInterval(); 639 640 // Create the open interval. 641 OpenIdx = Edit->size(); 642 Edit->createEmptyInterval(); 643 return OpenIdx; 644 } 645 646 void SplitEditor::selectIntv(unsigned Idx) { 647 assert(Idx != 0 && "Cannot select the complement interval"); 648 assert(Idx < Edit->size() && "Can only select previously opened interval"); 649 LLVM_DEBUG(dbgs() << " selectIntv " << OpenIdx << " -> " << Idx << '\n'); 650 OpenIdx = Idx; 651 } 652 653 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) { 654 assert(OpenIdx && "openIntv not called before enterIntvBefore"); 655 LLVM_DEBUG(dbgs() << " enterIntvBefore " << Idx); 656 Idx = Idx.getBaseIndex(); 657 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 658 if (!ParentVNI) { 659 LLVM_DEBUG(dbgs() << ": not live\n"); 660 return Idx; 661 } 662 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 663 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 664 assert(MI && "enterIntvBefore called with invalid index"); 665 666 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI); 667 return VNI->def; 668 } 669 670 SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) { 671 assert(OpenIdx && "openIntv not called before enterIntvAfter"); 672 LLVM_DEBUG(dbgs() << " enterIntvAfter " << Idx); 673 Idx = Idx.getBoundaryIndex(); 674 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 675 if (!ParentVNI) { 676 LLVM_DEBUG(dbgs() << ": not live\n"); 677 return Idx; 678 } 679 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 680 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 681 assert(MI && "enterIntvAfter called with invalid index"); 682 683 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), 684 std::next(MachineBasicBlock::iterator(MI))); 685 return VNI->def; 686 } 687 688 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) { 689 assert(OpenIdx && "openIntv not called before enterIntvAtEnd"); 690 SlotIndex End = LIS.getMBBEndIdx(&MBB); 691 SlotIndex Last = End.getPrevSlot(); 692 LLVM_DEBUG(dbgs() << " enterIntvAtEnd " << printMBBReference(MBB) << ", " 693 << Last); 694 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last); 695 if (!ParentVNI) { 696 LLVM_DEBUG(dbgs() << ": not live\n"); 697 return End; 698 } 699 SlotIndex LSP = SA.getLastSplitPoint(&MBB); 700 if (LSP < Last) { 701 // It could be that the use after LSP is a def, and thus the ParentVNI 702 // just selected starts at that def. For this case to exist, the def 703 // must be part of a tied def/use pair (as otherwise we'd have split 704 // distinct live ranges into individual live intervals), and thus we 705 // can insert the def into the VNI of the use and the tied def/use 706 // pair can live in the resulting interval. 707 Last = LSP; 708 ParentVNI = Edit->getParent().getVNInfoAt(Last); 709 if (!ParentVNI) { 710 // undef use --> undef tied def 711 LLVM_DEBUG(dbgs() << ": tied use not live\n"); 712 return End; 713 } 714 } 715 716 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id); 717 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB, 718 SA.getLastSplitPointIter(&MBB)); 719 RegAssign.insert(VNI->def, End, OpenIdx); 720 LLVM_DEBUG(dump()); 721 return VNI->def; 722 } 723 724 /// useIntv - indicate that all instructions in MBB should use OpenLI. 725 void SplitEditor::useIntv(const MachineBasicBlock &MBB) { 726 useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB)); 727 } 728 729 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) { 730 assert(OpenIdx && "openIntv not called before useIntv"); 731 LLVM_DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):"); 732 RegAssign.insert(Start, End, OpenIdx); 733 LLVM_DEBUG(dump()); 734 } 735 736 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) { 737 assert(OpenIdx && "openIntv not called before leaveIntvAfter"); 738 LLVM_DEBUG(dbgs() << " leaveIntvAfter " << Idx); 739 740 // The interval must be live beyond the instruction at Idx. 741 SlotIndex Boundary = Idx.getBoundaryIndex(); 742 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary); 743 if (!ParentVNI) { 744 LLVM_DEBUG(dbgs() << ": not live\n"); 745 return Boundary.getNextSlot(); 746 } 747 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 748 MachineInstr *MI = LIS.getInstructionFromIndex(Boundary); 749 assert(MI && "No instruction at index"); 750 751 // In spill mode, make live ranges as short as possible by inserting the copy 752 // before MI. This is only possible if that instruction doesn't redefine the 753 // value. The inserted COPY is not a kill, and we don't need to recompute 754 // the source live range. The spiller also won't try to hoist this copy. 755 if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) && 756 MI->readsVirtualRegister(Edit->getReg())) { 757 forceRecompute(0, *ParentVNI); 758 defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); 759 return Idx; 760 } 761 762 VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(), 763 std::next(MachineBasicBlock::iterator(MI))); 764 return VNI->def; 765 } 766 767 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) { 768 assert(OpenIdx && "openIntv not called before leaveIntvBefore"); 769 LLVM_DEBUG(dbgs() << " leaveIntvBefore " << Idx); 770 771 // The interval must be live into the instruction at Idx. 772 Idx = Idx.getBaseIndex(); 773 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 774 if (!ParentVNI) { 775 LLVM_DEBUG(dbgs() << ": not live\n"); 776 return Idx.getNextSlot(); 777 } 778 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 779 780 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 781 assert(MI && "No instruction at index"); 782 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); 783 return VNI->def; 784 } 785 786 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) { 787 assert(OpenIdx && "openIntv not called before leaveIntvAtTop"); 788 SlotIndex Start = LIS.getMBBStartIdx(&MBB); 789 LLVM_DEBUG(dbgs() << " leaveIntvAtTop " << printMBBReference(MBB) << ", " 790 << Start); 791 792 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start); 793 if (!ParentVNI) { 794 LLVM_DEBUG(dbgs() << ": not live\n"); 795 return Start; 796 } 797 798 unsigned RegIdx = 0; 799 Register Reg = LIS.getInterval(Edit->get(RegIdx)).reg(); 800 VNInfo *VNI = defFromParent(RegIdx, ParentVNI, Start, MBB, 801 MBB.SkipPHIsLabelsAndDebug(MBB.begin(), Reg)); 802 RegAssign.insert(Start, VNI->def, OpenIdx); 803 LLVM_DEBUG(dump()); 804 return VNI->def; 805 } 806 807 static bool hasTiedUseOf(MachineInstr &MI, unsigned Reg) { 808 return any_of(MI.defs(), [Reg](const MachineOperand &MO) { 809 return MO.isReg() && MO.isTied() && MO.getReg() == Reg; 810 }); 811 } 812 813 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) { 814 assert(OpenIdx && "openIntv not called before overlapIntv"); 815 const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start); 816 assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) && 817 "Parent changes value in extended range"); 818 assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) && 819 "Range cannot span basic blocks"); 820 821 // The complement interval will be extended as needed by LICalc.extend(). 822 if (ParentVNI) 823 forceRecompute(0, *ParentVNI); 824 825 // If the last use is tied to a def, we can't mark it as live for the 826 // interval which includes only the use. That would cause the tied pair 827 // to end up in two different intervals. 828 if (auto *MI = LIS.getInstructionFromIndex(End)) 829 if (hasTiedUseOf(*MI, Edit->getReg())) { 830 LLVM_DEBUG(dbgs() << "skip overlap due to tied def at end\n"); 831 return; 832 } 833 834 LLVM_DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):"); 835 RegAssign.insert(Start, End, OpenIdx); 836 LLVM_DEBUG(dump()); 837 } 838 839 //===----------------------------------------------------------------------===// 840 // Spill modes 841 //===----------------------------------------------------------------------===// 842 843 void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) { 844 LiveInterval *LI = &LIS.getInterval(Edit->get(0)); 845 LLVM_DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n"); 846 RegAssignMap::iterator AssignI; 847 AssignI.setMap(RegAssign); 848 849 for (const VNInfo *C : Copies) { 850 SlotIndex Def = C->def; 851 MachineInstr *MI = LIS.getInstructionFromIndex(Def); 852 assert(MI && "No instruction for back-copy"); 853 854 MachineBasicBlock *MBB = MI->getParent(); 855 MachineBasicBlock::iterator MBBI(MI); 856 bool AtBegin; 857 do AtBegin = MBBI == MBB->begin(); 858 while (!AtBegin && (--MBBI)->isDebugOrPseudoInstr()); 859 860 LLVM_DEBUG(dbgs() << "Removing " << Def << '\t' << *MI); 861 LIS.removeVRegDefAt(*LI, Def); 862 LIS.RemoveMachineInstrFromMaps(*MI); 863 MI->eraseFromParent(); 864 865 // Adjust RegAssign if a register assignment is killed at Def. We want to 866 // avoid calculating the live range of the source register if possible. 867 AssignI.find(Def.getPrevSlot()); 868 if (!AssignI.valid() || AssignI.start() >= Def) 869 continue; 870 // If MI doesn't kill the assigned register, just leave it. 871 if (AssignI.stop() != Def) 872 continue; 873 unsigned RegIdx = AssignI.value(); 874 // We could hoist back-copy right after another back-copy. As a result 875 // MMBI points to copy instruction which is actually dead now. 876 // We cannot set its stop to MBBI which will be the same as start and 877 // interval does not support that. 878 SlotIndex Kill = 879 AtBegin ? SlotIndex() : LIS.getInstructionIndex(*MBBI).getRegSlot(); 880 if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg()) || 881 Kill <= AssignI.start()) { 882 LLVM_DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx 883 << '\n'); 884 forceRecompute(RegIdx, *Edit->getParent().getVNInfoAt(Def)); 885 } else { 886 LLVM_DEBUG(dbgs() << " move kill to " << Kill << '\t' << *MBBI); 887 AssignI.setStop(Kill); 888 } 889 } 890 } 891 892 MachineBasicBlock* 893 SplitEditor::findShallowDominator(MachineBasicBlock *MBB, 894 MachineBasicBlock *DefMBB) { 895 if (MBB == DefMBB) 896 return MBB; 897 assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def."); 898 899 const MachineLoopInfo &Loops = SA.Loops; 900 const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB); 901 MachineDomTreeNode *DefDomNode = MDT[DefMBB]; 902 903 // Best candidate so far. 904 MachineBasicBlock *BestMBB = MBB; 905 unsigned BestDepth = std::numeric_limits<unsigned>::max(); 906 907 while (true) { 908 const MachineLoop *Loop = Loops.getLoopFor(MBB); 909 910 // MBB isn't in a loop, it doesn't get any better. All dominators have a 911 // higher frequency by definition. 912 if (!Loop) { 913 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB) 914 << " dominates " << printMBBReference(*MBB) 915 << " at depth 0\n"); 916 return MBB; 917 } 918 919 // We'll never be able to exit the DefLoop. 920 if (Loop == DefLoop) { 921 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB) 922 << " dominates " << printMBBReference(*MBB) 923 << " in the same loop\n"); 924 return MBB; 925 } 926 927 // Least busy dominator seen so far. 928 unsigned Depth = Loop->getLoopDepth(); 929 if (Depth < BestDepth) { 930 BestMBB = MBB; 931 BestDepth = Depth; 932 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB) 933 << " dominates " << printMBBReference(*MBB) 934 << " at depth " << Depth << '\n'); 935 } 936 937 // Leave loop by going to the immediate dominator of the loop header. 938 // This is a bigger stride than simply walking up the dominator tree. 939 MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom(); 940 941 // Too far up the dominator tree? 942 if (!IDom || !MDT.dominates(DefDomNode, IDom)) 943 return BestMBB; 944 945 MBB = IDom->getBlock(); 946 } 947 } 948 949 void SplitEditor::computeRedundantBackCopies( 950 DenseSet<unsigned> &NotToHoistSet, SmallVectorImpl<VNInfo *> &BackCopies) { 951 LiveInterval *LI = &LIS.getInterval(Edit->get(0)); 952 const LiveInterval *Parent = &Edit->getParent(); 953 SmallVector<SmallPtrSet<VNInfo *, 8>, 8> EqualVNs(Parent->getNumValNums()); 954 SmallPtrSet<VNInfo *, 8> DominatedVNIs; 955 956 // Aggregate VNIs having the same value as ParentVNI. 957 for (VNInfo *VNI : LI->valnos) { 958 if (VNI->isUnused()) 959 continue; 960 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 961 EqualVNs[ParentVNI->id].insert(VNI); 962 } 963 964 // For VNI aggregation of each ParentVNI, collect dominated, i.e., 965 // redundant VNIs to BackCopies. 966 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) { 967 const VNInfo *ParentVNI = Parent->getValNumInfo(i); 968 if (!NotToHoistSet.count(ParentVNI->id)) 969 continue; 970 SmallPtrSetIterator<VNInfo *> It1 = EqualVNs[ParentVNI->id].begin(); 971 SmallPtrSetIterator<VNInfo *> It2 = It1; 972 for (; It1 != EqualVNs[ParentVNI->id].end(); ++It1) { 973 It2 = It1; 974 for (++It2; It2 != EqualVNs[ParentVNI->id].end(); ++It2) { 975 if (DominatedVNIs.count(*It1) || DominatedVNIs.count(*It2)) 976 continue; 977 978 MachineBasicBlock *MBB1 = LIS.getMBBFromIndex((*It1)->def); 979 MachineBasicBlock *MBB2 = LIS.getMBBFromIndex((*It2)->def); 980 if (MBB1 == MBB2) { 981 DominatedVNIs.insert((*It1)->def < (*It2)->def ? (*It2) : (*It1)); 982 } else if (MDT.dominates(MBB1, MBB2)) { 983 DominatedVNIs.insert(*It2); 984 } else if (MDT.dominates(MBB2, MBB1)) { 985 DominatedVNIs.insert(*It1); 986 } 987 } 988 } 989 if (!DominatedVNIs.empty()) { 990 forceRecompute(0, *ParentVNI); 991 append_range(BackCopies, DominatedVNIs); 992 DominatedVNIs.clear(); 993 } 994 } 995 } 996 997 /// For SM_Size mode, find a common dominator for all the back-copies for 998 /// the same ParentVNI and hoist the backcopies to the dominator BB. 999 /// For SM_Speed mode, if the common dominator is hot and it is not beneficial 1000 /// to do the hoisting, simply remove the dominated backcopies for the same 1001 /// ParentVNI. 1002 void SplitEditor::hoistCopies() { 1003 // Get the complement interval, always RegIdx 0. 1004 LiveInterval *LI = &LIS.getInterval(Edit->get(0)); 1005 const LiveInterval *Parent = &Edit->getParent(); 1006 1007 // Track the nearest common dominator for all back-copies for each ParentVNI, 1008 // indexed by ParentVNI->id. 1009 using DomPair = std::pair<MachineBasicBlock *, SlotIndex>; 1010 SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums()); 1011 // The total cost of all the back-copies for each ParentVNI. 1012 SmallVector<BlockFrequency, 8> Costs(Parent->getNumValNums()); 1013 // The ParentVNI->id set for which hoisting back-copies are not beneficial 1014 // for Speed. 1015 DenseSet<unsigned> NotToHoistSet; 1016 1017 // Find the nearest common dominator for parent values with multiple 1018 // back-copies. If a single back-copy dominates, put it in DomPair.second. 1019 for (VNInfo *VNI : LI->valnos) { 1020 if (VNI->isUnused()) 1021 continue; 1022 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 1023 assert(ParentVNI && "Parent not live at complement def"); 1024 1025 // Don't hoist remats. The complement is probably going to disappear 1026 // completely anyway. 1027 if (Edit->didRematerialize(ParentVNI)) 1028 continue; 1029 1030 MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def); 1031 1032 DomPair &Dom = NearestDom[ParentVNI->id]; 1033 1034 // Keep directly defined parent values. This is either a PHI or an 1035 // instruction in the complement range. All other copies of ParentVNI 1036 // should be eliminated. 1037 if (VNI->def == ParentVNI->def) { 1038 LLVM_DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n'); 1039 Dom = DomPair(ValMBB, VNI->def); 1040 continue; 1041 } 1042 // Skip the singly mapped values. There is nothing to gain from hoisting a 1043 // single back-copy. 1044 if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) { 1045 LLVM_DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n'); 1046 continue; 1047 } 1048 1049 if (!Dom.first) { 1050 // First time we see ParentVNI. VNI dominates itself. 1051 Dom = DomPair(ValMBB, VNI->def); 1052 } else if (Dom.first == ValMBB) { 1053 // Two defs in the same block. Pick the earlier def. 1054 if (!Dom.second.isValid() || VNI->def < Dom.second) 1055 Dom.second = VNI->def; 1056 } else { 1057 // Different basic blocks. Check if one dominates. 1058 MachineBasicBlock *Near = 1059 MDT.findNearestCommonDominator(Dom.first, ValMBB); 1060 if (Near == ValMBB) 1061 // Def ValMBB dominates. 1062 Dom = DomPair(ValMBB, VNI->def); 1063 else if (Near != Dom.first) 1064 // None dominate. Hoist to common dominator, need new def. 1065 Dom = DomPair(Near, SlotIndex()); 1066 Costs[ParentVNI->id] += MBFI.getBlockFreq(ValMBB); 1067 } 1068 1069 LLVM_DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@' 1070 << VNI->def << " for parent " << ParentVNI->id << '@' 1071 << ParentVNI->def << " hoist to " 1072 << printMBBReference(*Dom.first) << ' ' << Dom.second 1073 << '\n'); 1074 } 1075 1076 // Insert the hoisted copies. 1077 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) { 1078 DomPair &Dom = NearestDom[i]; 1079 if (!Dom.first || Dom.second.isValid()) 1080 continue; 1081 // This value needs a hoisted copy inserted at the end of Dom.first. 1082 const VNInfo *ParentVNI = Parent->getValNumInfo(i); 1083 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def); 1084 // Get a less loopy dominator than Dom.first. 1085 Dom.first = findShallowDominator(Dom.first, DefMBB); 1086 if (SpillMode == SM_Speed && 1087 MBFI.getBlockFreq(Dom.first) > Costs[ParentVNI->id]) { 1088 NotToHoistSet.insert(ParentVNI->id); 1089 continue; 1090 } 1091 SlotIndex LSP = SA.getLastSplitPoint(Dom.first); 1092 if (LSP <= ParentVNI->def) { 1093 NotToHoistSet.insert(ParentVNI->id); 1094 continue; 1095 } 1096 Dom.second = defFromParent(0, ParentVNI, LSP, *Dom.first, 1097 SA.getLastSplitPointIter(Dom.first))->def; 1098 } 1099 1100 // Remove redundant back-copies that are now known to be dominated by another 1101 // def with the same value. 1102 SmallVector<VNInfo*, 8> BackCopies; 1103 for (VNInfo *VNI : LI->valnos) { 1104 if (VNI->isUnused()) 1105 continue; 1106 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 1107 const DomPair &Dom = NearestDom[ParentVNI->id]; 1108 if (!Dom.first || Dom.second == VNI->def || 1109 NotToHoistSet.count(ParentVNI->id)) 1110 continue; 1111 BackCopies.push_back(VNI); 1112 forceRecompute(0, *ParentVNI); 1113 } 1114 1115 // If it is not beneficial to hoist all the BackCopies, simply remove 1116 // redundant BackCopies in speed mode. 1117 if (SpillMode == SM_Speed && !NotToHoistSet.empty()) 1118 computeRedundantBackCopies(NotToHoistSet, BackCopies); 1119 1120 removeBackCopies(BackCopies); 1121 } 1122 1123 /// transferValues - Transfer all possible values to the new live ranges. 1124 /// Values that were rematerialized are left alone, they need LICalc.extend(). 1125 bool SplitEditor::transferValues() { 1126 bool Skipped = false; 1127 RegAssignMap::const_iterator AssignI = RegAssign.begin(); 1128 for (const LiveRange::Segment &S : Edit->getParent()) { 1129 LLVM_DEBUG(dbgs() << " blit " << S << ':'); 1130 VNInfo *ParentVNI = S.valno; 1131 // RegAssign has holes where RegIdx 0 should be used. 1132 SlotIndex Start = S.start; 1133 AssignI.advanceTo(Start); 1134 do { 1135 unsigned RegIdx; 1136 SlotIndex End = S.end; 1137 if (!AssignI.valid()) { 1138 RegIdx = 0; 1139 } else if (AssignI.start() <= Start) { 1140 RegIdx = AssignI.value(); 1141 if (AssignI.stop() < End) { 1142 End = AssignI.stop(); 1143 ++AssignI; 1144 } 1145 } else { 1146 RegIdx = 0; 1147 End = std::min(End, AssignI.start()); 1148 } 1149 1150 // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI. 1151 LLVM_DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx << '(' 1152 << printReg(Edit->get(RegIdx)) << ')'); 1153 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); 1154 1155 // Check for a simply defined value that can be blitted directly. 1156 ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id)); 1157 if (VNInfo *VNI = VFP.getPointer()) { 1158 LLVM_DEBUG(dbgs() << ':' << VNI->id); 1159 LI.addSegment(LiveInterval::Segment(Start, End, VNI)); 1160 Start = End; 1161 continue; 1162 } 1163 1164 // Skip values with forced recomputation. 1165 if (VFP.getInt()) { 1166 LLVM_DEBUG(dbgs() << "(recalc)"); 1167 Skipped = true; 1168 Start = End; 1169 continue; 1170 } 1171 1172 LiveIntervalCalc &LIC = getLICalc(RegIdx); 1173 1174 // This value has multiple defs in RegIdx, but it wasn't rematerialized, 1175 // so the live range is accurate. Add live-in blocks in [Start;End) to the 1176 // LiveInBlocks. 1177 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator(); 1178 SlotIndex BlockStart, BlockEnd; 1179 std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(&*MBB); 1180 1181 // The first block may be live-in, or it may have its own def. 1182 if (Start != BlockStart) { 1183 VNInfo *VNI = LI.extendInBlock(BlockStart, std::min(BlockEnd, End)); 1184 assert(VNI && "Missing def for complex mapped value"); 1185 LLVM_DEBUG(dbgs() << ':' << VNI->id << "*" << printMBBReference(*MBB)); 1186 // MBB has its own def. Is it also live-out? 1187 if (BlockEnd <= End) 1188 LIC.setLiveOutValue(&*MBB, VNI); 1189 1190 // Skip to the next block for live-in. 1191 ++MBB; 1192 BlockStart = BlockEnd; 1193 } 1194 1195 // Handle the live-in blocks covered by [Start;End). 1196 assert(Start <= BlockStart && "Expected live-in block"); 1197 while (BlockStart < End) { 1198 LLVM_DEBUG(dbgs() << ">" << printMBBReference(*MBB)); 1199 BlockEnd = LIS.getMBBEndIdx(&*MBB); 1200 if (BlockStart == ParentVNI->def) { 1201 // This block has the def of a parent PHI, so it isn't live-in. 1202 assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?"); 1203 VNInfo *VNI = LI.extendInBlock(BlockStart, std::min(BlockEnd, End)); 1204 assert(VNI && "Missing def for complex mapped parent PHI"); 1205 if (End >= BlockEnd) 1206 LIC.setLiveOutValue(&*MBB, VNI); // Live-out as well. 1207 } else { 1208 // This block needs a live-in value. The last block covered may not 1209 // be live-out. 1210 if (End < BlockEnd) 1211 LIC.addLiveInBlock(LI, MDT[&*MBB], End); 1212 else { 1213 // Live-through, and we don't know the value. 1214 LIC.addLiveInBlock(LI, MDT[&*MBB]); 1215 LIC.setLiveOutValue(&*MBB, nullptr); 1216 } 1217 } 1218 BlockStart = BlockEnd; 1219 ++MBB; 1220 } 1221 Start = End; 1222 } while (Start != S.end); 1223 LLVM_DEBUG(dbgs() << '\n'); 1224 } 1225 1226 LICalc[0].calculateValues(); 1227 if (SpillMode) 1228 LICalc[1].calculateValues(); 1229 1230 return Skipped; 1231 } 1232 1233 static bool removeDeadSegment(SlotIndex Def, LiveRange &LR) { 1234 const LiveRange::Segment *Seg = LR.getSegmentContaining(Def); 1235 if (Seg == nullptr) 1236 return true; 1237 if (Seg->end != Def.getDeadSlot()) 1238 return false; 1239 // This is a dead PHI. Remove it. 1240 LR.removeSegment(*Seg, true); 1241 return true; 1242 } 1243 1244 void SplitEditor::extendPHIRange(MachineBasicBlock &B, LiveIntervalCalc &LIC, 1245 LiveRange &LR, LaneBitmask LM, 1246 ArrayRef<SlotIndex> Undefs) { 1247 for (MachineBasicBlock *P : B.predecessors()) { 1248 SlotIndex End = LIS.getMBBEndIdx(P); 1249 SlotIndex LastUse = End.getPrevSlot(); 1250 // The predecessor may not have a live-out value. That is OK, like an 1251 // undef PHI operand. 1252 const LiveInterval &PLI = Edit->getParent(); 1253 // Need the cast because the inputs to ?: would otherwise be deemed 1254 // "incompatible": SubRange vs LiveInterval. 1255 const LiveRange &PSR = !LM.all() ? getSubRangeForMaskExact(LM, PLI) 1256 : static_cast<const LiveRange &>(PLI); 1257 if (PSR.liveAt(LastUse)) 1258 LIC.extend(LR, End, /*PhysReg=*/0, Undefs); 1259 } 1260 } 1261 1262 void SplitEditor::extendPHIKillRanges() { 1263 // Extend live ranges to be live-out for successor PHI values. 1264 1265 // Visit each PHI def slot in the parent live interval. If the def is dead, 1266 // remove it. Otherwise, extend the live interval to reach the end indexes 1267 // of all predecessor blocks. 1268 1269 const LiveInterval &ParentLI = Edit->getParent(); 1270 for (const VNInfo *V : ParentLI.valnos) { 1271 if (V->isUnused() || !V->isPHIDef()) 1272 continue; 1273 1274 unsigned RegIdx = RegAssign.lookup(V->def); 1275 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); 1276 LiveIntervalCalc &LIC = getLICalc(RegIdx); 1277 MachineBasicBlock &B = *LIS.getMBBFromIndex(V->def); 1278 if (!removeDeadSegment(V->def, LI)) 1279 extendPHIRange(B, LIC, LI, LaneBitmask::getAll(), /*Undefs=*/{}); 1280 } 1281 1282 SmallVector<SlotIndex, 4> Undefs; 1283 LiveIntervalCalc SubLIC; 1284 1285 for (const LiveInterval::SubRange &PS : ParentLI.subranges()) { 1286 for (const VNInfo *V : PS.valnos) { 1287 if (V->isUnused() || !V->isPHIDef()) 1288 continue; 1289 unsigned RegIdx = RegAssign.lookup(V->def); 1290 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); 1291 LiveInterval::SubRange &S = getSubRangeForMaskExact(PS.LaneMask, LI); 1292 if (removeDeadSegment(V->def, S)) 1293 continue; 1294 1295 MachineBasicBlock &B = *LIS.getMBBFromIndex(V->def); 1296 SubLIC.reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 1297 &LIS.getVNInfoAllocator()); 1298 Undefs.clear(); 1299 LI.computeSubRangeUndefs(Undefs, PS.LaneMask, MRI, *LIS.getSlotIndexes()); 1300 extendPHIRange(B, SubLIC, S, PS.LaneMask, Undefs); 1301 } 1302 } 1303 } 1304 1305 /// rewriteAssigned - Rewrite all uses of Edit->getReg(). 1306 void SplitEditor::rewriteAssigned(bool ExtendRanges) { 1307 struct ExtPoint { 1308 ExtPoint(const MachineOperand &O, unsigned R, SlotIndex N) 1309 : MO(O), RegIdx(R), Next(N) {} 1310 1311 MachineOperand MO; 1312 unsigned RegIdx; 1313 SlotIndex Next; 1314 }; 1315 1316 SmallVector<ExtPoint,4> ExtPoints; 1317 1318 for (MachineOperand &MO : 1319 llvm::make_early_inc_range(MRI.reg_operands(Edit->getReg()))) { 1320 MachineInstr *MI = MO.getParent(); 1321 // LiveDebugVariables should have handled all DBG_VALUE instructions. 1322 if (MI->isDebugValue()) { 1323 LLVM_DEBUG(dbgs() << "Zapping " << *MI); 1324 MO.setReg(0); 1325 continue; 1326 } 1327 1328 // <undef> operands don't really read the register, so it doesn't matter 1329 // which register we choose. When the use operand is tied to a def, we must 1330 // use the same register as the def, so just do that always. 1331 SlotIndex Idx = LIS.getInstructionIndex(*MI); 1332 if (MO.isDef() || MO.isUndef()) 1333 Idx = Idx.getRegSlot(MO.isEarlyClobber()); 1334 1335 // Rewrite to the mapped register at Idx. 1336 unsigned RegIdx = RegAssign.lookup(Idx); 1337 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); 1338 MO.setReg(LI.reg()); 1339 LLVM_DEBUG(dbgs() << " rewr " << printMBBReference(*MI->getParent()) 1340 << '\t' << Idx << ':' << RegIdx << '\t' << *MI); 1341 1342 // Extend liveness to Idx if the instruction reads reg. 1343 if (!ExtendRanges || MO.isUndef()) 1344 continue; 1345 1346 // Skip instructions that don't read Reg. 1347 if (MO.isDef()) { 1348 if (!MO.getSubReg() && !MO.isEarlyClobber()) 1349 continue; 1350 // We may want to extend a live range for a partial redef, or for a use 1351 // tied to an early clobber. 1352 if (!Edit->getParent().liveAt(Idx.getPrevSlot())) 1353 continue; 1354 } else { 1355 assert(MO.isUse()); 1356 bool IsEarlyClobber = false; 1357 if (MO.isTied()) { 1358 // We want to extend a live range into `e` slot rather than `r` slot if 1359 // tied-def is early clobber, because the `e` slot already contained 1360 // in the live range of early-clobber tied-def operand, give an example 1361 // here: 1362 // 0 %0 = ... 1363 // 16 early-clobber %0 = Op %0 (tied-def 0), ... 1364 // 32 ... = Op %0 1365 // Before extend: 1366 // %0 = [0r, 0d) [16e, 32d) 1367 // The point we want to extend is 0d to 16e not 16r in this case, but if 1368 // we use 16r here we will extend nothing because that already contained 1369 // in [16e, 32d). 1370 unsigned OpIdx = MO.getOperandNo(); 1371 unsigned DefOpIdx = MI->findTiedOperandIdx(OpIdx); 1372 const MachineOperand &DefOp = MI->getOperand(DefOpIdx); 1373 IsEarlyClobber = DefOp.isEarlyClobber(); 1374 } 1375 1376 Idx = Idx.getRegSlot(IsEarlyClobber); 1377 } 1378 1379 SlotIndex Next = Idx; 1380 if (LI.hasSubRanges()) { 1381 // We have to delay extending subranges until we have seen all operands 1382 // defining the register. This is because a <def,read-undef> operand 1383 // will create an "undef" point, and we cannot extend any subranges 1384 // until all of them have been accounted for. 1385 if (MO.isUse()) 1386 ExtPoints.push_back(ExtPoint(MO, RegIdx, Next)); 1387 } else { 1388 LiveIntervalCalc &LIC = getLICalc(RegIdx); 1389 LIC.extend(LI, Next, 0, ArrayRef<SlotIndex>()); 1390 } 1391 } 1392 1393 for (ExtPoint &EP : ExtPoints) { 1394 LiveInterval &LI = LIS.getInterval(Edit->get(EP.RegIdx)); 1395 assert(LI.hasSubRanges()); 1396 1397 LiveIntervalCalc SubLIC; 1398 Register Reg = EP.MO.getReg(), Sub = EP.MO.getSubReg(); 1399 LaneBitmask LM = Sub != 0 ? TRI.getSubRegIndexLaneMask(Sub) 1400 : MRI.getMaxLaneMaskForVReg(Reg); 1401 for (LiveInterval::SubRange &S : LI.subranges()) { 1402 if ((S.LaneMask & LM).none()) 1403 continue; 1404 // The problem here can be that the new register may have been created 1405 // for a partially defined original register. For example: 1406 // %0:subreg_hireg<def,read-undef> = ... 1407 // ... 1408 // %1 = COPY %0 1409 if (S.empty()) 1410 continue; 1411 SubLIC.reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 1412 &LIS.getVNInfoAllocator()); 1413 SmallVector<SlotIndex, 4> Undefs; 1414 LI.computeSubRangeUndefs(Undefs, S.LaneMask, MRI, *LIS.getSlotIndexes()); 1415 SubLIC.extend(S, EP.Next, 0, Undefs); 1416 } 1417 } 1418 1419 for (Register R : *Edit) { 1420 LiveInterval &LI = LIS.getInterval(R); 1421 if (!LI.hasSubRanges()) 1422 continue; 1423 LI.clear(); 1424 LI.removeEmptySubRanges(); 1425 LIS.constructMainRangeFromSubranges(LI); 1426 } 1427 } 1428 1429 void SplitEditor::deleteRematVictims() { 1430 SmallVector<MachineInstr*, 8> Dead; 1431 for (const Register &R : *Edit) { 1432 LiveInterval *LI = &LIS.getInterval(R); 1433 for (const LiveRange::Segment &S : LI->segments) { 1434 // Dead defs end at the dead slot. 1435 if (S.end != S.valno->def.getDeadSlot()) 1436 continue; 1437 if (S.valno->isPHIDef()) 1438 continue; 1439 MachineInstr *MI = LIS.getInstructionFromIndex(S.valno->def); 1440 assert(MI && "Missing instruction for dead def"); 1441 MI->addRegisterDead(LI->reg(), &TRI); 1442 1443 if (!MI->allDefsAreDead()) 1444 continue; 1445 1446 LLVM_DEBUG(dbgs() << "All defs dead: " << *MI); 1447 Dead.push_back(MI); 1448 } 1449 } 1450 1451 if (Dead.empty()) 1452 return; 1453 1454 Edit->eliminateDeadDefs(Dead, std::nullopt); 1455 } 1456 1457 void SplitEditor::forceRecomputeVNI(const VNInfo &ParentVNI) { 1458 // Fast-path for common case. 1459 if (!ParentVNI.isPHIDef()) { 1460 for (unsigned I = 0, E = Edit->size(); I != E; ++I) 1461 forceRecompute(I, ParentVNI); 1462 return; 1463 } 1464 1465 // Trace value through phis. 1466 SmallPtrSet<const VNInfo *, 8> Visited; ///< whether VNI was/is in worklist. 1467 SmallVector<const VNInfo *, 4> WorkList; 1468 Visited.insert(&ParentVNI); 1469 WorkList.push_back(&ParentVNI); 1470 1471 const LiveInterval &ParentLI = Edit->getParent(); 1472 const SlotIndexes &Indexes = *LIS.getSlotIndexes(); 1473 do { 1474 const VNInfo &VNI = *WorkList.back(); 1475 WorkList.pop_back(); 1476 for (unsigned I = 0, E = Edit->size(); I != E; ++I) 1477 forceRecompute(I, VNI); 1478 if (!VNI.isPHIDef()) 1479 continue; 1480 1481 MachineBasicBlock &MBB = *Indexes.getMBBFromIndex(VNI.def); 1482 for (const MachineBasicBlock *Pred : MBB.predecessors()) { 1483 SlotIndex PredEnd = Indexes.getMBBEndIdx(Pred); 1484 VNInfo *PredVNI = ParentLI.getVNInfoBefore(PredEnd); 1485 assert(PredVNI && "Value available in PhiVNI predecessor"); 1486 if (Visited.insert(PredVNI).second) 1487 WorkList.push_back(PredVNI); 1488 } 1489 } while(!WorkList.empty()); 1490 } 1491 1492 void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) { 1493 ++NumFinished; 1494 1495 // At this point, the live intervals in Edit contain VNInfos corresponding to 1496 // the inserted copies. 1497 1498 // Add the original defs from the parent interval. 1499 for (const VNInfo *ParentVNI : Edit->getParent().valnos) { 1500 if (ParentVNI->isUnused()) 1501 continue; 1502 unsigned RegIdx = RegAssign.lookup(ParentVNI->def); 1503 defValue(RegIdx, ParentVNI, ParentVNI->def, true); 1504 1505 // Force rematted values to be recomputed everywhere. 1506 // The new live ranges may be truncated. 1507 if (Edit->didRematerialize(ParentVNI)) 1508 forceRecomputeVNI(*ParentVNI); 1509 } 1510 1511 // Hoist back-copies to the complement interval when in spill mode. 1512 switch (SpillMode) { 1513 case SM_Partition: 1514 // Leave all back-copies as is. 1515 break; 1516 case SM_Size: 1517 case SM_Speed: 1518 // hoistCopies will behave differently between size and speed. 1519 hoistCopies(); 1520 } 1521 1522 // Transfer the simply mapped values, check if any are skipped. 1523 bool Skipped = transferValues(); 1524 1525 // Rewrite virtual registers, possibly extending ranges. 1526 rewriteAssigned(Skipped); 1527 1528 if (Skipped) 1529 extendPHIKillRanges(); 1530 else 1531 ++NumSimple; 1532 1533 // Delete defs that were rematted everywhere. 1534 if (Skipped) 1535 deleteRematVictims(); 1536 1537 // Get rid of unused values and set phi-kill flags. 1538 for (Register Reg : *Edit) { 1539 LiveInterval &LI = LIS.getInterval(Reg); 1540 LI.removeEmptySubRanges(); 1541 LI.RenumberValues(); 1542 } 1543 1544 // Provide a reverse mapping from original indices to Edit ranges. 1545 if (LRMap) { 1546 auto Seq = llvm::seq<unsigned>(0, Edit->size()); 1547 LRMap->assign(Seq.begin(), Seq.end()); 1548 } 1549 1550 // Now check if any registers were separated into multiple components. 1551 ConnectedVNInfoEqClasses ConEQ(LIS); 1552 for (unsigned i = 0, e = Edit->size(); i != e; ++i) { 1553 // Don't use iterators, they are invalidated by create() below. 1554 Register VReg = Edit->get(i); 1555 LiveInterval &LI = LIS.getInterval(VReg); 1556 SmallVector<LiveInterval*, 8> SplitLIs; 1557 LIS.splitSeparateComponents(LI, SplitLIs); 1558 Register Original = VRM.getOriginal(VReg); 1559 for (LiveInterval *SplitLI : SplitLIs) 1560 VRM.setIsSplitFromReg(SplitLI->reg(), Original); 1561 1562 // The new intervals all map back to i. 1563 if (LRMap) 1564 LRMap->resize(Edit->size(), i); 1565 } 1566 1567 // Calculate spill weight and allocation hints for new intervals. 1568 Edit->calculateRegClassAndHint(VRM.getMachineFunction(), VRAI); 1569 1570 assert(!LRMap || LRMap->size() == Edit->size()); 1571 } 1572 1573 //===----------------------------------------------------------------------===// 1574 // Single Block Splitting 1575 //===----------------------------------------------------------------------===// 1576 1577 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI, 1578 bool SingleInstrs) const { 1579 // Always split for multiple instructions. 1580 if (!BI.isOneInstr()) 1581 return true; 1582 // Don't split for single instructions unless explicitly requested. 1583 if (!SingleInstrs) 1584 return false; 1585 // Splitting a live-through range always makes progress. 1586 if (BI.LiveIn && BI.LiveOut) 1587 return true; 1588 // No point in isolating a copy. It has no register class constraints. 1589 MachineInstr *MI = LIS.getInstructionFromIndex(BI.FirstInstr); 1590 bool copyLike = TII.isCopyInstr(*MI) || MI->isSubregToReg(); 1591 if (copyLike) 1592 return false; 1593 // Finally, don't isolate an end point that was created by earlier splits. 1594 return isOriginalEndpoint(BI.FirstInstr); 1595 } 1596 1597 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) { 1598 openIntv(); 1599 SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB); 1600 SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr, 1601 LastSplitPoint)); 1602 if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) { 1603 useIntv(SegStart, leaveIntvAfter(BI.LastInstr)); 1604 } else { 1605 // The last use is after the last valid split point. 1606 SlotIndex SegStop = leaveIntvBefore(LastSplitPoint); 1607 useIntv(SegStart, SegStop); 1608 overlapIntv(SegStop, BI.LastInstr); 1609 } 1610 } 1611 1612 //===----------------------------------------------------------------------===// 1613 // Global Live Range Splitting Support 1614 //===----------------------------------------------------------------------===// 1615 1616 // These methods support a method of global live range splitting that uses a 1617 // global algorithm to decide intervals for CFG edges. They will insert split 1618 // points and color intervals in basic blocks while avoiding interference. 1619 // 1620 // Note that splitSingleBlock is also useful for blocks where both CFG edges 1621 // are on the stack. 1622 1623 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum, 1624 unsigned IntvIn, SlotIndex LeaveBefore, 1625 unsigned IntvOut, SlotIndex EnterAfter){ 1626 SlotIndex Start, Stop; 1627 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum); 1628 1629 LLVM_DEBUG(dbgs() << "%bb." << MBBNum << " [" << Start << ';' << Stop 1630 << ") intf " << LeaveBefore << '-' << EnterAfter 1631 << ", live-through " << IntvIn << " -> " << IntvOut); 1632 1633 assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks"); 1634 1635 assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block"); 1636 assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf"); 1637 assert((!EnterAfter || EnterAfter >= Start) && "Interference before block"); 1638 1639 MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum); 1640 1641 if (!IntvOut) { 1642 LLVM_DEBUG(dbgs() << ", spill on entry.\n"); 1643 // 1644 // <<<<<<<<< Possible LeaveBefore interference. 1645 // |-----------| Live through. 1646 // -____________ Spill on entry. 1647 // 1648 selectIntv(IntvIn); 1649 SlotIndex Idx = leaveIntvAtTop(*MBB); 1650 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1651 (void)Idx; 1652 return; 1653 } 1654 1655 if (!IntvIn) { 1656 LLVM_DEBUG(dbgs() << ", reload on exit.\n"); 1657 // 1658 // >>>>>>> Possible EnterAfter interference. 1659 // |-----------| Live through. 1660 // ___________-- Reload on exit. 1661 // 1662 selectIntv(IntvOut); 1663 SlotIndex Idx = enterIntvAtEnd(*MBB); 1664 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1665 (void)Idx; 1666 return; 1667 } 1668 1669 if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) { 1670 LLVM_DEBUG(dbgs() << ", straight through.\n"); 1671 // 1672 // |-----------| Live through. 1673 // ------------- Straight through, same intv, no interference. 1674 // 1675 selectIntv(IntvOut); 1676 useIntv(Start, Stop); 1677 return; 1678 } 1679 1680 // We cannot legally insert splits after LSP. 1681 SlotIndex LSP = SA.getLastSplitPoint(MBBNum); 1682 assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf"); 1683 1684 if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter || 1685 LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) { 1686 LLVM_DEBUG(dbgs() << ", switch avoiding interference.\n"); 1687 // 1688 // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference. 1689 // |-----------| Live through. 1690 // ------======= Switch intervals between interference. 1691 // 1692 selectIntv(IntvOut); 1693 SlotIndex Idx; 1694 if (LeaveBefore && LeaveBefore < LSP) { 1695 Idx = enterIntvBefore(LeaveBefore); 1696 useIntv(Idx, Stop); 1697 } else { 1698 Idx = enterIntvAtEnd(*MBB); 1699 } 1700 selectIntv(IntvIn); 1701 useIntv(Start, Idx); 1702 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1703 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1704 return; 1705 } 1706 1707 LLVM_DEBUG(dbgs() << ", create local intv for interference.\n"); 1708 // 1709 // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference. 1710 // |-----------| Live through. 1711 // ==---------== Switch intervals before/after interference. 1712 // 1713 assert(LeaveBefore <= EnterAfter && "Missed case"); 1714 1715 selectIntv(IntvOut); 1716 SlotIndex Idx = enterIntvAfter(EnterAfter); 1717 useIntv(Idx, Stop); 1718 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1719 1720 selectIntv(IntvIn); 1721 Idx = leaveIntvBefore(LeaveBefore); 1722 useIntv(Start, Idx); 1723 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1724 } 1725 1726 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI, 1727 unsigned IntvIn, SlotIndex LeaveBefore) { 1728 SlotIndex Start, Stop; 1729 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 1730 1731 LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " [" << Start << ';' 1732 << Stop << "), uses " << BI.FirstInstr << '-' 1733 << BI.LastInstr << ", reg-in " << IntvIn 1734 << ", leave before " << LeaveBefore 1735 << (BI.LiveOut ? ", stack-out" : ", killed in block")); 1736 1737 assert(IntvIn && "Must have register in"); 1738 assert(BI.LiveIn && "Must be live-in"); 1739 assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference"); 1740 1741 if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) { 1742 LLVM_DEBUG(dbgs() << " before interference.\n"); 1743 // 1744 // <<< Interference after kill. 1745 // |---o---x | Killed in block. 1746 // ========= Use IntvIn everywhere. 1747 // 1748 selectIntv(IntvIn); 1749 useIntv(Start, BI.LastInstr); 1750 return; 1751 } 1752 1753 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB); 1754 1755 if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) { 1756 // 1757 // <<< Possible interference after last use. 1758 // |---o---o---| Live-out on stack. 1759 // =========____ Leave IntvIn after last use. 1760 // 1761 // < Interference after last use. 1762 // |---o---o--o| Live-out on stack, late last use. 1763 // ============ Copy to stack after LSP, overlap IntvIn. 1764 // \_____ Stack interval is live-out. 1765 // 1766 if (BI.LastInstr < LSP) { 1767 LLVM_DEBUG(dbgs() << ", spill after last use before interference.\n"); 1768 selectIntv(IntvIn); 1769 SlotIndex Idx = leaveIntvAfter(BI.LastInstr); 1770 useIntv(Start, Idx); 1771 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1772 } else { 1773 LLVM_DEBUG(dbgs() << ", spill before last split point.\n"); 1774 selectIntv(IntvIn); 1775 SlotIndex Idx = leaveIntvBefore(LSP); 1776 overlapIntv(Idx, BI.LastInstr); 1777 useIntv(Start, Idx); 1778 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1779 } 1780 return; 1781 } 1782 1783 // The interference is overlapping somewhere we wanted to use IntvIn. That 1784 // means we need to create a local interval that can be allocated a 1785 // different register. 1786 unsigned LocalIntv = openIntv(); 1787 (void)LocalIntv; 1788 LLVM_DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n"); 1789 1790 if (!BI.LiveOut || BI.LastInstr < LSP) { 1791 // 1792 // <<<<<<< Interference overlapping uses. 1793 // |---o---o---| Live-out on stack. 1794 // =====----____ Leave IntvIn before interference, then spill. 1795 // 1796 SlotIndex To = leaveIntvAfter(BI.LastInstr); 1797 SlotIndex From = enterIntvBefore(LeaveBefore); 1798 useIntv(From, To); 1799 selectIntv(IntvIn); 1800 useIntv(Start, From); 1801 assert((!LeaveBefore || From <= LeaveBefore) && "Interference"); 1802 return; 1803 } 1804 1805 // <<<<<<< Interference overlapping uses. 1806 // |---o---o--o| Live-out on stack, late last use. 1807 // =====------- Copy to stack before LSP, overlap LocalIntv. 1808 // \_____ Stack interval is live-out. 1809 // 1810 SlotIndex To = leaveIntvBefore(LSP); 1811 overlapIntv(To, BI.LastInstr); 1812 SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore)); 1813 useIntv(From, To); 1814 selectIntv(IntvIn); 1815 useIntv(Start, From); 1816 assert((!LeaveBefore || From <= LeaveBefore) && "Interference"); 1817 } 1818 1819 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI, 1820 unsigned IntvOut, SlotIndex EnterAfter) { 1821 SlotIndex Start, Stop; 1822 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 1823 1824 LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " [" << Start << ';' 1825 << Stop << "), uses " << BI.FirstInstr << '-' 1826 << BI.LastInstr << ", reg-out " << IntvOut 1827 << ", enter after " << EnterAfter 1828 << (BI.LiveIn ? ", stack-in" : ", defined in block")); 1829 1830 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB); 1831 1832 assert(IntvOut && "Must have register out"); 1833 assert(BI.LiveOut && "Must be live-out"); 1834 assert((!EnterAfter || EnterAfter < LSP) && "Bad interference"); 1835 1836 if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) { 1837 LLVM_DEBUG(dbgs() << " after interference.\n"); 1838 // 1839 // >>>> Interference before def. 1840 // | o---o---| Defined in block. 1841 // ========= Use IntvOut everywhere. 1842 // 1843 selectIntv(IntvOut); 1844 useIntv(BI.FirstInstr, Stop); 1845 return; 1846 } 1847 1848 if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) { 1849 LLVM_DEBUG(dbgs() << ", reload after interference.\n"); 1850 // 1851 // >>>> Interference before def. 1852 // |---o---o---| Live-through, stack-in. 1853 // ____========= Enter IntvOut before first use. 1854 // 1855 selectIntv(IntvOut); 1856 SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr)); 1857 useIntv(Idx, Stop); 1858 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1859 return; 1860 } 1861 1862 // The interference is overlapping somewhere we wanted to use IntvOut. That 1863 // means we need to create a local interval that can be allocated a 1864 // different register. 1865 LLVM_DEBUG(dbgs() << ", interference overlaps uses.\n"); 1866 // 1867 // >>>>>>> Interference overlapping uses. 1868 // |---o---o---| Live-through, stack-in. 1869 // ____---====== Create local interval for interference range. 1870 // 1871 selectIntv(IntvOut); 1872 SlotIndex Idx = enterIntvAfter(EnterAfter); 1873 useIntv(Idx, Stop); 1874 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1875 1876 openIntv(); 1877 SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr)); 1878 useIntv(From, Idx); 1879 } 1880 1881 void SplitAnalysis::BlockInfo::print(raw_ostream &OS) const { 1882 OS << "{" << printMBBReference(*MBB) << ", " 1883 << "uses " << FirstInstr << " to " << LastInstr << ", " 1884 << "1st def " << FirstDef << ", " 1885 << (LiveIn ? "live in" : "dead in") << ", " 1886 << (LiveOut ? "live out" : "dead out") << "}"; 1887 } 1888 1889 void SplitAnalysis::BlockInfo::dump() const { 1890 print(dbgs()); 1891 dbgs() << "\n"; 1892 } 1893