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