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 (OrigLI.hasSubRanges()) { 653 LaneMask = LaneBitmask::getNone(); 654 for (LiveInterval::SubRange &S : OrigLI.subranges()) { 655 if (S.liveAt(UseIdx)) 656 LaneMask |= S.LaneMask; 657 } 658 assert(LaneMask.any() && "Interval has no live subranges"); 659 } else { 660 LaneMask = LaneBitmask::getAll(); 661 } 662 663 ++NumCopies; 664 Def = buildCopy(Edit->getReg(), Reg, LaneMask, MBB, I, Late, RegIdx); 665 } 666 667 // Define the value in Reg. 668 return defValue(RegIdx, ParentVNI, Def, false); 669 } 670 671 /// Create a new virtual register and live interval. 672 unsigned SplitEditor::openIntv() { 673 // Create the complement as index 0. 674 if (Edit->empty()) 675 Edit->createEmptyInterval(); 676 677 // Create the open interval. 678 OpenIdx = Edit->size(); 679 Edit->createEmptyInterval(); 680 return OpenIdx; 681 } 682 683 void SplitEditor::selectIntv(unsigned Idx) { 684 assert(Idx != 0 && "Cannot select the complement interval"); 685 assert(Idx < Edit->size() && "Can only select previously opened interval"); 686 LLVM_DEBUG(dbgs() << " selectIntv " << OpenIdx << " -> " << Idx << '\n'); 687 OpenIdx = Idx; 688 } 689 690 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) { 691 assert(OpenIdx && "openIntv not called before enterIntvBefore"); 692 LLVM_DEBUG(dbgs() << " enterIntvBefore " << Idx); 693 Idx = Idx.getBaseIndex(); 694 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 695 if (!ParentVNI) { 696 LLVM_DEBUG(dbgs() << ": not live\n"); 697 return Idx; 698 } 699 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 700 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 701 assert(MI && "enterIntvBefore called with invalid index"); 702 703 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI); 704 return VNI->def; 705 } 706 707 SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) { 708 assert(OpenIdx && "openIntv not called before enterIntvAfter"); 709 LLVM_DEBUG(dbgs() << " enterIntvAfter " << Idx); 710 Idx = Idx.getBoundaryIndex(); 711 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 712 if (!ParentVNI) { 713 LLVM_DEBUG(dbgs() << ": not live\n"); 714 return Idx; 715 } 716 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 717 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 718 assert(MI && "enterIntvAfter called with invalid index"); 719 720 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), 721 std::next(MachineBasicBlock::iterator(MI))); 722 return VNI->def; 723 } 724 725 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) { 726 assert(OpenIdx && "openIntv not called before enterIntvAtEnd"); 727 SlotIndex End = LIS.getMBBEndIdx(&MBB); 728 SlotIndex Last = End.getPrevSlot(); 729 LLVM_DEBUG(dbgs() << " enterIntvAtEnd " << printMBBReference(MBB) << ", " 730 << Last); 731 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last); 732 if (!ParentVNI) { 733 LLVM_DEBUG(dbgs() << ": not live\n"); 734 return End; 735 } 736 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id); 737 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB, 738 SA.getLastSplitPointIter(&MBB)); 739 RegAssign.insert(VNI->def, End, OpenIdx); 740 LLVM_DEBUG(dump()); 741 return VNI->def; 742 } 743 744 /// useIntv - indicate that all instructions in MBB should use OpenLI. 745 void SplitEditor::useIntv(const MachineBasicBlock &MBB) { 746 useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB)); 747 } 748 749 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) { 750 assert(OpenIdx && "openIntv not called before useIntv"); 751 LLVM_DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):"); 752 RegAssign.insert(Start, End, OpenIdx); 753 LLVM_DEBUG(dump()); 754 } 755 756 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) { 757 assert(OpenIdx && "openIntv not called before leaveIntvAfter"); 758 LLVM_DEBUG(dbgs() << " leaveIntvAfter " << Idx); 759 760 // The interval must be live beyond the instruction at Idx. 761 SlotIndex Boundary = Idx.getBoundaryIndex(); 762 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary); 763 if (!ParentVNI) { 764 LLVM_DEBUG(dbgs() << ": not live\n"); 765 return Boundary.getNextSlot(); 766 } 767 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 768 MachineInstr *MI = LIS.getInstructionFromIndex(Boundary); 769 assert(MI && "No instruction at index"); 770 771 // In spill mode, make live ranges as short as possible by inserting the copy 772 // before MI. This is only possible if that instruction doesn't redefine the 773 // value. The inserted COPY is not a kill, and we don't need to recompute 774 // the source live range. The spiller also won't try to hoist this copy. 775 if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) && 776 MI->readsVirtualRegister(Edit->getReg())) { 777 forceRecompute(0, *ParentVNI); 778 defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); 779 return Idx; 780 } 781 782 VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(), 783 std::next(MachineBasicBlock::iterator(MI))); 784 return VNI->def; 785 } 786 787 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) { 788 assert(OpenIdx && "openIntv not called before leaveIntvBefore"); 789 LLVM_DEBUG(dbgs() << " leaveIntvBefore " << Idx); 790 791 // The interval must be live into the instruction at Idx. 792 Idx = Idx.getBaseIndex(); 793 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 794 if (!ParentVNI) { 795 LLVM_DEBUG(dbgs() << ": not live\n"); 796 return Idx.getNextSlot(); 797 } 798 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 799 800 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 801 assert(MI && "No instruction at index"); 802 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); 803 return VNI->def; 804 } 805 806 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) { 807 assert(OpenIdx && "openIntv not called before leaveIntvAtTop"); 808 SlotIndex Start = LIS.getMBBStartIdx(&MBB); 809 LLVM_DEBUG(dbgs() << " leaveIntvAtTop " << printMBBReference(MBB) << ", " 810 << Start); 811 812 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start); 813 if (!ParentVNI) { 814 LLVM_DEBUG(dbgs() << ": not live\n"); 815 return Start; 816 } 817 818 VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB, 819 MBB.SkipPHIsLabelsAndDebug(MBB.begin())); 820 RegAssign.insert(Start, VNI->def, OpenIdx); 821 LLVM_DEBUG(dump()); 822 return VNI->def; 823 } 824 825 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) { 826 assert(OpenIdx && "openIntv not called before overlapIntv"); 827 const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start); 828 assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) && 829 "Parent changes value in extended range"); 830 assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) && 831 "Range cannot span basic blocks"); 832 833 // The complement interval will be extended as needed by LICalc.extend(). 834 if (ParentVNI) 835 forceRecompute(0, *ParentVNI); 836 LLVM_DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):"); 837 RegAssign.insert(Start, End, OpenIdx); 838 LLVM_DEBUG(dump()); 839 } 840 841 //===----------------------------------------------------------------------===// 842 // Spill modes 843 //===----------------------------------------------------------------------===// 844 845 void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) { 846 LiveInterval *LI = &LIS.getInterval(Edit->get(0)); 847 LLVM_DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n"); 848 RegAssignMap::iterator AssignI; 849 AssignI.setMap(RegAssign); 850 851 for (unsigned i = 0, e = Copies.size(); i != e; ++i) { 852 SlotIndex Def = Copies[i]->def; 853 MachineInstr *MI = LIS.getInstructionFromIndex(Def); 854 assert(MI && "No instruction for back-copy"); 855 856 MachineBasicBlock *MBB = MI->getParent(); 857 MachineBasicBlock::iterator MBBI(MI); 858 bool AtBegin; 859 do AtBegin = MBBI == MBB->begin(); 860 while (!AtBegin && (--MBBI)->isDebugInstr()); 861 862 LLVM_DEBUG(dbgs() << "Removing " << Def << '\t' << *MI); 863 LIS.removeVRegDefAt(*LI, Def); 864 LIS.RemoveMachineInstrFromMaps(*MI); 865 MI->eraseFromParent(); 866 867 // Adjust RegAssign if a register assignment is killed at Def. We want to 868 // avoid calculating the live range of the source register if possible. 869 AssignI.find(Def.getPrevSlot()); 870 if (!AssignI.valid() || AssignI.start() >= Def) 871 continue; 872 // If MI doesn't kill the assigned register, just leave it. 873 if (AssignI.stop() != Def) 874 continue; 875 unsigned RegIdx = AssignI.value(); 876 if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg())) { 877 LLVM_DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx 878 << '\n'); 879 forceRecompute(RegIdx, *Edit->getParent().getVNInfoAt(Def)); 880 } else { 881 SlotIndex Kill = LIS.getInstructionIndex(*MBBI).getRegSlot(); 882 LLVM_DEBUG(dbgs() << " move kill to " << Kill << '\t' << *MBBI); 883 AssignI.setStop(Kill); 884 } 885 } 886 } 887 888 MachineBasicBlock* 889 SplitEditor::findShallowDominator(MachineBasicBlock *MBB, 890 MachineBasicBlock *DefMBB) { 891 if (MBB == DefMBB) 892 return MBB; 893 assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def."); 894 895 const MachineLoopInfo &Loops = SA.Loops; 896 const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB); 897 MachineDomTreeNode *DefDomNode = MDT[DefMBB]; 898 899 // Best candidate so far. 900 MachineBasicBlock *BestMBB = MBB; 901 unsigned BestDepth = std::numeric_limits<unsigned>::max(); 902 903 while (true) { 904 const MachineLoop *Loop = Loops.getLoopFor(MBB); 905 906 // MBB isn't in a loop, it doesn't get any better. All dominators have a 907 // higher frequency by definition. 908 if (!Loop) { 909 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB) 910 << " dominates " << printMBBReference(*MBB) 911 << " at depth 0\n"); 912 return MBB; 913 } 914 915 // We'll never be able to exit the DefLoop. 916 if (Loop == DefLoop) { 917 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB) 918 << " dominates " << printMBBReference(*MBB) 919 << " in the same loop\n"); 920 return MBB; 921 } 922 923 // Least busy dominator seen so far. 924 unsigned Depth = Loop->getLoopDepth(); 925 if (Depth < BestDepth) { 926 BestMBB = MBB; 927 BestDepth = Depth; 928 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB) 929 << " dominates " << printMBBReference(*MBB) 930 << " at depth " << Depth << '\n'); 931 } 932 933 // Leave loop by going to the immediate dominator of the loop header. 934 // This is a bigger stride than simply walking up the dominator tree. 935 MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom(); 936 937 // Too far up the dominator tree? 938 if (!IDom || !MDT.dominates(DefDomNode, IDom)) 939 return BestMBB; 940 941 MBB = IDom->getBlock(); 942 } 943 } 944 945 void SplitEditor::computeRedundantBackCopies( 946 DenseSet<unsigned> &NotToHoistSet, SmallVectorImpl<VNInfo *> &BackCopies) { 947 LiveInterval *LI = &LIS.getInterval(Edit->get(0)); 948 LiveInterval *Parent = &Edit->getParent(); 949 SmallVector<SmallPtrSet<VNInfo *, 8>, 8> EqualVNs(Parent->getNumValNums()); 950 SmallPtrSet<VNInfo *, 8> DominatedVNIs; 951 952 // Aggregate VNIs having the same value as ParentVNI. 953 for (VNInfo *VNI : LI->valnos) { 954 if (VNI->isUnused()) 955 continue; 956 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 957 EqualVNs[ParentVNI->id].insert(VNI); 958 } 959 960 // For VNI aggregation of each ParentVNI, collect dominated, i.e., 961 // redundant VNIs to BackCopies. 962 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) { 963 VNInfo *ParentVNI = Parent->getValNumInfo(i); 964 if (!NotToHoistSet.count(ParentVNI->id)) 965 continue; 966 SmallPtrSetIterator<VNInfo *> It1 = EqualVNs[ParentVNI->id].begin(); 967 SmallPtrSetIterator<VNInfo *> It2 = It1; 968 for (; It1 != EqualVNs[ParentVNI->id].end(); ++It1) { 969 It2 = It1; 970 for (++It2; It2 != EqualVNs[ParentVNI->id].end(); ++It2) { 971 if (DominatedVNIs.count(*It1) || DominatedVNIs.count(*It2)) 972 continue; 973 974 MachineBasicBlock *MBB1 = LIS.getMBBFromIndex((*It1)->def); 975 MachineBasicBlock *MBB2 = LIS.getMBBFromIndex((*It2)->def); 976 if (MBB1 == MBB2) { 977 DominatedVNIs.insert((*It1)->def < (*It2)->def ? (*It2) : (*It1)); 978 } else if (MDT.dominates(MBB1, MBB2)) { 979 DominatedVNIs.insert(*It2); 980 } else if (MDT.dominates(MBB2, MBB1)) { 981 DominatedVNIs.insert(*It1); 982 } 983 } 984 } 985 if (!DominatedVNIs.empty()) { 986 forceRecompute(0, *ParentVNI); 987 for (auto VNI : DominatedVNIs) { 988 BackCopies.push_back(VNI); 989 } 990 DominatedVNIs.clear(); 991 } 992 } 993 } 994 995 /// For SM_Size mode, find a common dominator for all the back-copies for 996 /// the same ParentVNI and hoist the backcopies to the dominator BB. 997 /// For SM_Speed mode, if the common dominator is hot and it is not beneficial 998 /// to do the hoisting, simply remove the dominated backcopies for the same 999 /// ParentVNI. 1000 void SplitEditor::hoistCopies() { 1001 // Get the complement interval, always RegIdx 0. 1002 LiveInterval *LI = &LIS.getInterval(Edit->get(0)); 1003 LiveInterval *Parent = &Edit->getParent(); 1004 1005 // Track the nearest common dominator for all back-copies for each ParentVNI, 1006 // indexed by ParentVNI->id. 1007 using DomPair = std::pair<MachineBasicBlock *, SlotIndex>; 1008 SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums()); 1009 // The total cost of all the back-copies for each ParentVNI. 1010 SmallVector<BlockFrequency, 8> Costs(Parent->getNumValNums()); 1011 // The ParentVNI->id set for which hoisting back-copies are not beneficial 1012 // for Speed. 1013 DenseSet<unsigned> NotToHoistSet; 1014 1015 // Find the nearest common dominator for parent values with multiple 1016 // back-copies. If a single back-copy dominates, put it in DomPair.second. 1017 for (VNInfo *VNI : LI->valnos) { 1018 if (VNI->isUnused()) 1019 continue; 1020 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 1021 assert(ParentVNI && "Parent not live at complement def"); 1022 1023 // Don't hoist remats. The complement is probably going to disappear 1024 // completely anyway. 1025 if (Edit->didRematerialize(ParentVNI)) 1026 continue; 1027 1028 MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def); 1029 1030 DomPair &Dom = NearestDom[ParentVNI->id]; 1031 1032 // Keep directly defined parent values. This is either a PHI or an 1033 // instruction in the complement range. All other copies of ParentVNI 1034 // should be eliminated. 1035 if (VNI->def == ParentVNI->def) { 1036 LLVM_DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n'); 1037 Dom = DomPair(ValMBB, VNI->def); 1038 continue; 1039 } 1040 // Skip the singly mapped values. There is nothing to gain from hoisting a 1041 // single back-copy. 1042 if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) { 1043 LLVM_DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n'); 1044 continue; 1045 } 1046 1047 if (!Dom.first) { 1048 // First time we see ParentVNI. VNI dominates itself. 1049 Dom = DomPair(ValMBB, VNI->def); 1050 } else if (Dom.first == ValMBB) { 1051 // Two defs in the same block. Pick the earlier def. 1052 if (!Dom.second.isValid() || VNI->def < Dom.second) 1053 Dom.second = VNI->def; 1054 } else { 1055 // Different basic blocks. Check if one dominates. 1056 MachineBasicBlock *Near = 1057 MDT.findNearestCommonDominator(Dom.first, ValMBB); 1058 if (Near == ValMBB) 1059 // Def ValMBB dominates. 1060 Dom = DomPair(ValMBB, VNI->def); 1061 else if (Near != Dom.first) 1062 // None dominate. Hoist to common dominator, need new def. 1063 Dom = DomPair(Near, SlotIndex()); 1064 Costs[ParentVNI->id] += MBFI.getBlockFreq(ValMBB); 1065 } 1066 1067 LLVM_DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@' 1068 << VNI->def << " for parent " << ParentVNI->id << '@' 1069 << ParentVNI->def << " hoist to " 1070 << printMBBReference(*Dom.first) << ' ' << Dom.second 1071 << '\n'); 1072 } 1073 1074 // Insert the hoisted copies. 1075 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) { 1076 DomPair &Dom = NearestDom[i]; 1077 if (!Dom.first || Dom.second.isValid()) 1078 continue; 1079 // This value needs a hoisted copy inserted at the end of Dom.first. 1080 VNInfo *ParentVNI = Parent->getValNumInfo(i); 1081 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def); 1082 // Get a less loopy dominator than Dom.first. 1083 Dom.first = findShallowDominator(Dom.first, DefMBB); 1084 if (SpillMode == SM_Speed && 1085 MBFI.getBlockFreq(Dom.first) > Costs[ParentVNI->id]) { 1086 NotToHoistSet.insert(ParentVNI->id); 1087 continue; 1088 } 1089 SlotIndex Last = LIS.getMBBEndIdx(Dom.first).getPrevSlot(); 1090 Dom.second = 1091 defFromParent(0, ParentVNI, Last, *Dom.first, 1092 SA.getLastSplitPointIter(Dom.first))->def; 1093 } 1094 1095 // Remove redundant back-copies that are now known to be dominated by another 1096 // def with the same value. 1097 SmallVector<VNInfo*, 8> BackCopies; 1098 for (VNInfo *VNI : LI->valnos) { 1099 if (VNI->isUnused()) 1100 continue; 1101 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 1102 const DomPair &Dom = NearestDom[ParentVNI->id]; 1103 if (!Dom.first || Dom.second == VNI->def || 1104 NotToHoistSet.count(ParentVNI->id)) 1105 continue; 1106 BackCopies.push_back(VNI); 1107 forceRecompute(0, *ParentVNI); 1108 } 1109 1110 // If it is not beneficial to hoist all the BackCopies, simply remove 1111 // redundant BackCopies in speed mode. 1112 if (SpillMode == SM_Speed && !NotToHoistSet.empty()) 1113 computeRedundantBackCopies(NotToHoistSet, BackCopies); 1114 1115 removeBackCopies(BackCopies); 1116 } 1117 1118 /// transferValues - Transfer all possible values to the new live ranges. 1119 /// Values that were rematerialized are left alone, they need LICalc.extend(). 1120 bool SplitEditor::transferValues() { 1121 bool Skipped = false; 1122 RegAssignMap::const_iterator AssignI = RegAssign.begin(); 1123 for (const LiveRange::Segment &S : Edit->getParent()) { 1124 LLVM_DEBUG(dbgs() << " blit " << S << ':'); 1125 VNInfo *ParentVNI = S.valno; 1126 // RegAssign has holes where RegIdx 0 should be used. 1127 SlotIndex Start = S.start; 1128 AssignI.advanceTo(Start); 1129 do { 1130 unsigned RegIdx; 1131 SlotIndex End = S.end; 1132 if (!AssignI.valid()) { 1133 RegIdx = 0; 1134 } else if (AssignI.start() <= Start) { 1135 RegIdx = AssignI.value(); 1136 if (AssignI.stop() < End) { 1137 End = AssignI.stop(); 1138 ++AssignI; 1139 } 1140 } else { 1141 RegIdx = 0; 1142 End = std::min(End, AssignI.start()); 1143 } 1144 1145 // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI. 1146 LLVM_DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx << '(' 1147 << printReg(Edit->get(RegIdx)) << ')'); 1148 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); 1149 1150 // Check for a simply defined value that can be blitted directly. 1151 ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id)); 1152 if (VNInfo *VNI = VFP.getPointer()) { 1153 LLVM_DEBUG(dbgs() << ':' << VNI->id); 1154 LI.addSegment(LiveInterval::Segment(Start, End, VNI)); 1155 Start = End; 1156 continue; 1157 } 1158 1159 // Skip values with forced recomputation. 1160 if (VFP.getInt()) { 1161 LLVM_DEBUG(dbgs() << "(recalc)"); 1162 Skipped = true; 1163 Start = End; 1164 continue; 1165 } 1166 1167 LiveIntervalCalc &LIC = getLICalc(RegIdx); 1168 1169 // This value has multiple defs in RegIdx, but it wasn't rematerialized, 1170 // so the live range is accurate. Add live-in blocks in [Start;End) to the 1171 // LiveInBlocks. 1172 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator(); 1173 SlotIndex BlockStart, BlockEnd; 1174 std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(&*MBB); 1175 1176 // The first block may be live-in, or it may have its own def. 1177 if (Start != BlockStart) { 1178 VNInfo *VNI = LI.extendInBlock(BlockStart, std::min(BlockEnd, End)); 1179 assert(VNI && "Missing def for complex mapped value"); 1180 LLVM_DEBUG(dbgs() << ':' << VNI->id << "*" << printMBBReference(*MBB)); 1181 // MBB has its own def. Is it also live-out? 1182 if (BlockEnd <= End) 1183 LIC.setLiveOutValue(&*MBB, VNI); 1184 1185 // Skip to the next block for live-in. 1186 ++MBB; 1187 BlockStart = BlockEnd; 1188 } 1189 1190 // Handle the live-in blocks covered by [Start;End). 1191 assert(Start <= BlockStart && "Expected live-in block"); 1192 while (BlockStart < End) { 1193 LLVM_DEBUG(dbgs() << ">" << printMBBReference(*MBB)); 1194 BlockEnd = LIS.getMBBEndIdx(&*MBB); 1195 if (BlockStart == ParentVNI->def) { 1196 // This block has the def of a parent PHI, so it isn't live-in. 1197 assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?"); 1198 VNInfo *VNI = LI.extendInBlock(BlockStart, std::min(BlockEnd, End)); 1199 assert(VNI && "Missing def for complex mapped parent PHI"); 1200 if (End >= BlockEnd) 1201 LIC.setLiveOutValue(&*MBB, VNI); // Live-out as well. 1202 } else { 1203 // This block needs a live-in value. The last block covered may not 1204 // be live-out. 1205 if (End < BlockEnd) 1206 LIC.addLiveInBlock(LI, MDT[&*MBB], End); 1207 else { 1208 // Live-through, and we don't know the value. 1209 LIC.addLiveInBlock(LI, MDT[&*MBB]); 1210 LIC.setLiveOutValue(&*MBB, nullptr); 1211 } 1212 } 1213 BlockStart = BlockEnd; 1214 ++MBB; 1215 } 1216 Start = End; 1217 } while (Start != S.end); 1218 LLVM_DEBUG(dbgs() << '\n'); 1219 } 1220 1221 LICalc[0].calculateValues(); 1222 if (SpillMode) 1223 LICalc[1].calculateValues(); 1224 1225 return Skipped; 1226 } 1227 1228 static bool removeDeadSegment(SlotIndex Def, LiveRange &LR) { 1229 const LiveRange::Segment *Seg = LR.getSegmentContaining(Def); 1230 if (Seg == nullptr) 1231 return true; 1232 if (Seg->end != Def.getDeadSlot()) 1233 return false; 1234 // This is a dead PHI. Remove it. 1235 LR.removeSegment(*Seg, true); 1236 return true; 1237 } 1238 1239 void SplitEditor::extendPHIRange(MachineBasicBlock &B, LiveIntervalCalc &LIC, 1240 LiveRange &LR, LaneBitmask LM, 1241 ArrayRef<SlotIndex> Undefs) { 1242 for (MachineBasicBlock *P : B.predecessors()) { 1243 SlotIndex End = LIS.getMBBEndIdx(P); 1244 SlotIndex LastUse = End.getPrevSlot(); 1245 // The predecessor may not have a live-out value. That is OK, like an 1246 // undef PHI operand. 1247 LiveInterval &PLI = Edit->getParent(); 1248 // Need the cast because the inputs to ?: would otherwise be deemed 1249 // "incompatible": SubRange vs LiveInterval. 1250 LiveRange &PSR = !LM.all() ? getSubRangeForMask(LM, PLI) 1251 : static_cast<LiveRange&>(PLI); 1252 if (PSR.liveAt(LastUse)) 1253 LIC.extend(LR, End, /*PhysReg=*/0, Undefs); 1254 } 1255 } 1256 1257 void SplitEditor::extendPHIKillRanges() { 1258 // Extend live ranges to be live-out for successor PHI values. 1259 1260 // Visit each PHI def slot in the parent live interval. If the def is dead, 1261 // remove it. Otherwise, extend the live interval to reach the end indexes 1262 // of all predecessor blocks. 1263 1264 LiveInterval &ParentLI = Edit->getParent(); 1265 for (const VNInfo *V : ParentLI.valnos) { 1266 if (V->isUnused() || !V->isPHIDef()) 1267 continue; 1268 1269 unsigned RegIdx = RegAssign.lookup(V->def); 1270 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); 1271 LiveIntervalCalc &LIC = getLICalc(RegIdx); 1272 MachineBasicBlock &B = *LIS.getMBBFromIndex(V->def); 1273 if (!removeDeadSegment(V->def, LI)) 1274 extendPHIRange(B, LIC, LI, LaneBitmask::getAll(), /*Undefs=*/{}); 1275 } 1276 1277 SmallVector<SlotIndex, 4> Undefs; 1278 LiveIntervalCalc SubLIC; 1279 1280 for (LiveInterval::SubRange &PS : ParentLI.subranges()) { 1281 for (const VNInfo *V : PS.valnos) { 1282 if (V->isUnused() || !V->isPHIDef()) 1283 continue; 1284 unsigned RegIdx = RegAssign.lookup(V->def); 1285 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); 1286 LiveInterval::SubRange &S = getSubRangeForMask(PS.LaneMask, LI); 1287 if (removeDeadSegment(V->def, S)) 1288 continue; 1289 1290 MachineBasicBlock &B = *LIS.getMBBFromIndex(V->def); 1291 SubLIC.reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 1292 &LIS.getVNInfoAllocator()); 1293 Undefs.clear(); 1294 LI.computeSubRangeUndefs(Undefs, PS.LaneMask, MRI, *LIS.getSlotIndexes()); 1295 extendPHIRange(B, SubLIC, S, PS.LaneMask, Undefs); 1296 } 1297 } 1298 } 1299 1300 /// rewriteAssigned - Rewrite all uses of Edit->getReg(). 1301 void SplitEditor::rewriteAssigned(bool ExtendRanges) { 1302 struct ExtPoint { 1303 ExtPoint(const MachineOperand &O, unsigned R, SlotIndex N) 1304 : MO(O), RegIdx(R), Next(N) {} 1305 1306 MachineOperand MO; 1307 unsigned RegIdx; 1308 SlotIndex Next; 1309 }; 1310 1311 SmallVector<ExtPoint,4> ExtPoints; 1312 1313 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()), 1314 RE = MRI.reg_end(); RI != RE;) { 1315 MachineOperand &MO = *RI; 1316 MachineInstr *MI = MO.getParent(); 1317 ++RI; 1318 // LiveDebugVariables should have handled all DBG_VALUE instructions. 1319 if (MI->isDebugValue()) { 1320 LLVM_DEBUG(dbgs() << "Zapping " << *MI); 1321 MO.setReg(0); 1322 continue; 1323 } 1324 1325 // <undef> operands don't really read the register, so it doesn't matter 1326 // which register we choose. When the use operand is tied to a def, we must 1327 // use the same register as the def, so just do that always. 1328 SlotIndex Idx = LIS.getInstructionIndex(*MI); 1329 if (MO.isDef() || MO.isUndef()) 1330 Idx = Idx.getRegSlot(MO.isEarlyClobber()); 1331 1332 // Rewrite to the mapped register at Idx. 1333 unsigned RegIdx = RegAssign.lookup(Idx); 1334 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); 1335 MO.setReg(LI.reg()); 1336 LLVM_DEBUG(dbgs() << " rewr " << printMBBReference(*MI->getParent()) 1337 << '\t' << Idx << ':' << RegIdx << '\t' << *MI); 1338 1339 // Extend liveness to Idx if the instruction reads reg. 1340 if (!ExtendRanges || MO.isUndef()) 1341 continue; 1342 1343 // Skip instructions that don't read Reg. 1344 if (MO.isDef()) { 1345 if (!MO.getSubReg() && !MO.isEarlyClobber()) 1346 continue; 1347 // We may want to extend a live range for a partial redef, or for a use 1348 // tied to an early clobber. 1349 Idx = Idx.getPrevSlot(); 1350 if (!Edit->getParent().liveAt(Idx)) 1351 continue; 1352 } else 1353 Idx = Idx.getRegSlot(true); 1354 1355 SlotIndex Next = Idx.getNextSlot(); 1356 if (LI.hasSubRanges()) { 1357 // We have to delay extending subranges until we have seen all operands 1358 // defining the register. This is because a <def,read-undef> operand 1359 // will create an "undef" point, and we cannot extend any subranges 1360 // until all of them have been accounted for. 1361 if (MO.isUse()) 1362 ExtPoints.push_back(ExtPoint(MO, RegIdx, Next)); 1363 } else { 1364 LiveIntervalCalc &LIC = getLICalc(RegIdx); 1365 LIC.extend(LI, Next, 0, ArrayRef<SlotIndex>()); 1366 } 1367 } 1368 1369 for (ExtPoint &EP : ExtPoints) { 1370 LiveInterval &LI = LIS.getInterval(Edit->get(EP.RegIdx)); 1371 assert(LI.hasSubRanges()); 1372 1373 LiveIntervalCalc SubLIC; 1374 Register Reg = EP.MO.getReg(), Sub = EP.MO.getSubReg(); 1375 LaneBitmask LM = Sub != 0 ? TRI.getSubRegIndexLaneMask(Sub) 1376 : MRI.getMaxLaneMaskForVReg(Reg); 1377 for (LiveInterval::SubRange &S : LI.subranges()) { 1378 if ((S.LaneMask & LM).none()) 1379 continue; 1380 // The problem here can be that the new register may have been created 1381 // for a partially defined original register. For example: 1382 // %0:subreg_hireg<def,read-undef> = ... 1383 // ... 1384 // %1 = COPY %0 1385 if (S.empty()) 1386 continue; 1387 SubLIC.reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 1388 &LIS.getVNInfoAllocator()); 1389 SmallVector<SlotIndex, 4> Undefs; 1390 LI.computeSubRangeUndefs(Undefs, S.LaneMask, MRI, *LIS.getSlotIndexes()); 1391 SubLIC.extend(S, EP.Next, 0, Undefs); 1392 } 1393 } 1394 1395 for (unsigned R : *Edit) { 1396 LiveInterval &LI = LIS.getInterval(R); 1397 if (!LI.hasSubRanges()) 1398 continue; 1399 LI.clear(); 1400 LI.removeEmptySubRanges(); 1401 LIS.constructMainRangeFromSubranges(LI); 1402 } 1403 } 1404 1405 void SplitEditor::deleteRematVictims() { 1406 SmallVector<MachineInstr*, 8> Dead; 1407 for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I){ 1408 LiveInterval *LI = &LIS.getInterval(*I); 1409 for (const LiveRange::Segment &S : LI->segments) { 1410 // Dead defs end at the dead slot. 1411 if (S.end != S.valno->def.getDeadSlot()) 1412 continue; 1413 if (S.valno->isPHIDef()) 1414 continue; 1415 MachineInstr *MI = LIS.getInstructionFromIndex(S.valno->def); 1416 assert(MI && "Missing instruction for dead def"); 1417 MI->addRegisterDead(LI->reg(), &TRI); 1418 1419 if (!MI->allDefsAreDead()) 1420 continue; 1421 1422 LLVM_DEBUG(dbgs() << "All defs dead: " << *MI); 1423 Dead.push_back(MI); 1424 } 1425 } 1426 1427 if (Dead.empty()) 1428 return; 1429 1430 Edit->eliminateDeadDefs(Dead, None, &AA); 1431 } 1432 1433 void SplitEditor::forceRecomputeVNI(const VNInfo &ParentVNI) { 1434 // Fast-path for common case. 1435 if (!ParentVNI.isPHIDef()) { 1436 for (unsigned I = 0, E = Edit->size(); I != E; ++I) 1437 forceRecompute(I, ParentVNI); 1438 return; 1439 } 1440 1441 // Trace value through phis. 1442 SmallPtrSet<const VNInfo *, 8> Visited; ///< whether VNI was/is in worklist. 1443 SmallVector<const VNInfo *, 4> WorkList; 1444 Visited.insert(&ParentVNI); 1445 WorkList.push_back(&ParentVNI); 1446 1447 const LiveInterval &ParentLI = Edit->getParent(); 1448 const SlotIndexes &Indexes = *LIS.getSlotIndexes(); 1449 do { 1450 const VNInfo &VNI = *WorkList.back(); 1451 WorkList.pop_back(); 1452 for (unsigned I = 0, E = Edit->size(); I != E; ++I) 1453 forceRecompute(I, VNI); 1454 if (!VNI.isPHIDef()) 1455 continue; 1456 1457 MachineBasicBlock &MBB = *Indexes.getMBBFromIndex(VNI.def); 1458 for (const MachineBasicBlock *Pred : MBB.predecessors()) { 1459 SlotIndex PredEnd = Indexes.getMBBEndIdx(Pred); 1460 VNInfo *PredVNI = ParentLI.getVNInfoBefore(PredEnd); 1461 assert(PredVNI && "Value available in PhiVNI predecessor"); 1462 if (Visited.insert(PredVNI).second) 1463 WorkList.push_back(PredVNI); 1464 } 1465 } while(!WorkList.empty()); 1466 } 1467 1468 void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) { 1469 ++NumFinished; 1470 1471 // At this point, the live intervals in Edit contain VNInfos corresponding to 1472 // the inserted copies. 1473 1474 // Add the original defs from the parent interval. 1475 for (const VNInfo *ParentVNI : Edit->getParent().valnos) { 1476 if (ParentVNI->isUnused()) 1477 continue; 1478 unsigned RegIdx = RegAssign.lookup(ParentVNI->def); 1479 defValue(RegIdx, ParentVNI, ParentVNI->def, true); 1480 1481 // Force rematted values to be recomputed everywhere. 1482 // The new live ranges may be truncated. 1483 if (Edit->didRematerialize(ParentVNI)) 1484 forceRecomputeVNI(*ParentVNI); 1485 } 1486 1487 // Hoist back-copies to the complement interval when in spill mode. 1488 switch (SpillMode) { 1489 case SM_Partition: 1490 // Leave all back-copies as is. 1491 break; 1492 case SM_Size: 1493 case SM_Speed: 1494 // hoistCopies will behave differently between size and speed. 1495 hoistCopies(); 1496 } 1497 1498 // Transfer the simply mapped values, check if any are skipped. 1499 bool Skipped = transferValues(); 1500 1501 // Rewrite virtual registers, possibly extending ranges. 1502 rewriteAssigned(Skipped); 1503 1504 if (Skipped) 1505 extendPHIKillRanges(); 1506 else 1507 ++NumSimple; 1508 1509 // Delete defs that were rematted everywhere. 1510 if (Skipped) 1511 deleteRematVictims(); 1512 1513 // Get rid of unused values and set phi-kill flags. 1514 for (unsigned Reg : *Edit) { 1515 LiveInterval &LI = LIS.getInterval(Reg); 1516 LI.removeEmptySubRanges(); 1517 LI.RenumberValues(); 1518 } 1519 1520 // Provide a reverse mapping from original indices to Edit ranges. 1521 if (LRMap) { 1522 LRMap->clear(); 1523 for (unsigned i = 0, e = Edit->size(); i != e; ++i) 1524 LRMap->push_back(i); 1525 } 1526 1527 // Now check if any registers were separated into multiple components. 1528 ConnectedVNInfoEqClasses ConEQ(LIS); 1529 for (unsigned i = 0, e = Edit->size(); i != e; ++i) { 1530 // Don't use iterators, they are invalidated by create() below. 1531 unsigned VReg = Edit->get(i); 1532 LiveInterval &LI = LIS.getInterval(VReg); 1533 SmallVector<LiveInterval*, 8> SplitLIs; 1534 LIS.splitSeparateComponents(LI, SplitLIs); 1535 unsigned Original = VRM.getOriginal(VReg); 1536 for (LiveInterval *SplitLI : SplitLIs) 1537 VRM.setIsSplitFromReg(SplitLI->reg(), Original); 1538 1539 // The new intervals all map back to i. 1540 if (LRMap) 1541 LRMap->resize(Edit->size(), i); 1542 } 1543 1544 // Calculate spill weight and allocation hints for new intervals. 1545 Edit->calculateRegClassAndHint(VRM.getMachineFunction(), SA.Loops, MBFI); 1546 1547 assert(!LRMap || LRMap->size() == Edit->size()); 1548 } 1549 1550 //===----------------------------------------------------------------------===// 1551 // Single Block Splitting 1552 //===----------------------------------------------------------------------===// 1553 1554 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI, 1555 bool SingleInstrs) const { 1556 // Always split for multiple instructions. 1557 if (!BI.isOneInstr()) 1558 return true; 1559 // Don't split for single instructions unless explicitly requested. 1560 if (!SingleInstrs) 1561 return false; 1562 // Splitting a live-through range always makes progress. 1563 if (BI.LiveIn && BI.LiveOut) 1564 return true; 1565 // No point in isolating a copy. It has no register class constraints. 1566 if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike()) 1567 return false; 1568 // Finally, don't isolate an end point that was created by earlier splits. 1569 return isOriginalEndpoint(BI.FirstInstr); 1570 } 1571 1572 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) { 1573 openIntv(); 1574 SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB->getNumber()); 1575 SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr, 1576 LastSplitPoint)); 1577 if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) { 1578 useIntv(SegStart, leaveIntvAfter(BI.LastInstr)); 1579 } else { 1580 // The last use is after the last valid split point. 1581 SlotIndex SegStop = leaveIntvBefore(LastSplitPoint); 1582 useIntv(SegStart, SegStop); 1583 overlapIntv(SegStop, BI.LastInstr); 1584 } 1585 } 1586 1587 //===----------------------------------------------------------------------===// 1588 // Global Live Range Splitting Support 1589 //===----------------------------------------------------------------------===// 1590 1591 // These methods support a method of global live range splitting that uses a 1592 // global algorithm to decide intervals for CFG edges. They will insert split 1593 // points and color intervals in basic blocks while avoiding interference. 1594 // 1595 // Note that splitSingleBlock is also useful for blocks where both CFG edges 1596 // are on the stack. 1597 1598 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum, 1599 unsigned IntvIn, SlotIndex LeaveBefore, 1600 unsigned IntvOut, SlotIndex EnterAfter){ 1601 SlotIndex Start, Stop; 1602 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum); 1603 1604 LLVM_DEBUG(dbgs() << "%bb." << MBBNum << " [" << Start << ';' << Stop 1605 << ") intf " << LeaveBefore << '-' << EnterAfter 1606 << ", live-through " << IntvIn << " -> " << IntvOut); 1607 1608 assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks"); 1609 1610 assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block"); 1611 assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf"); 1612 assert((!EnterAfter || EnterAfter >= Start) && "Interference before block"); 1613 1614 MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum); 1615 1616 if (!IntvOut) { 1617 LLVM_DEBUG(dbgs() << ", spill on entry.\n"); 1618 // 1619 // <<<<<<<<< Possible LeaveBefore interference. 1620 // |-----------| Live through. 1621 // -____________ Spill on entry. 1622 // 1623 selectIntv(IntvIn); 1624 SlotIndex Idx = leaveIntvAtTop(*MBB); 1625 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1626 (void)Idx; 1627 return; 1628 } 1629 1630 if (!IntvIn) { 1631 LLVM_DEBUG(dbgs() << ", reload on exit.\n"); 1632 // 1633 // >>>>>>> Possible EnterAfter interference. 1634 // |-----------| Live through. 1635 // ___________-- Reload on exit. 1636 // 1637 selectIntv(IntvOut); 1638 SlotIndex Idx = enterIntvAtEnd(*MBB); 1639 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1640 (void)Idx; 1641 return; 1642 } 1643 1644 if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) { 1645 LLVM_DEBUG(dbgs() << ", straight through.\n"); 1646 // 1647 // |-----------| Live through. 1648 // ------------- Straight through, same intv, no interference. 1649 // 1650 selectIntv(IntvOut); 1651 useIntv(Start, Stop); 1652 return; 1653 } 1654 1655 // We cannot legally insert splits after LSP. 1656 SlotIndex LSP = SA.getLastSplitPoint(MBBNum); 1657 assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf"); 1658 1659 if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter || 1660 LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) { 1661 LLVM_DEBUG(dbgs() << ", switch avoiding interference.\n"); 1662 // 1663 // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference. 1664 // |-----------| Live through. 1665 // ------======= Switch intervals between interference. 1666 // 1667 selectIntv(IntvOut); 1668 SlotIndex Idx; 1669 if (LeaveBefore && LeaveBefore < LSP) { 1670 Idx = enterIntvBefore(LeaveBefore); 1671 useIntv(Idx, Stop); 1672 } else { 1673 Idx = enterIntvAtEnd(*MBB); 1674 } 1675 selectIntv(IntvIn); 1676 useIntv(Start, Idx); 1677 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1678 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1679 return; 1680 } 1681 1682 LLVM_DEBUG(dbgs() << ", create local intv for interference.\n"); 1683 // 1684 // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference. 1685 // |-----------| Live through. 1686 // ==---------== Switch intervals before/after interference. 1687 // 1688 assert(LeaveBefore <= EnterAfter && "Missed case"); 1689 1690 selectIntv(IntvOut); 1691 SlotIndex Idx = enterIntvAfter(EnterAfter); 1692 useIntv(Idx, Stop); 1693 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1694 1695 selectIntv(IntvIn); 1696 Idx = leaveIntvBefore(LeaveBefore); 1697 useIntv(Start, Idx); 1698 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1699 } 1700 1701 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI, 1702 unsigned IntvIn, SlotIndex LeaveBefore) { 1703 SlotIndex Start, Stop; 1704 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 1705 1706 LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " [" << Start << ';' 1707 << Stop << "), uses " << BI.FirstInstr << '-' 1708 << BI.LastInstr << ", reg-in " << IntvIn 1709 << ", leave before " << LeaveBefore 1710 << (BI.LiveOut ? ", stack-out" : ", killed in block")); 1711 1712 assert(IntvIn && "Must have register in"); 1713 assert(BI.LiveIn && "Must be live-in"); 1714 assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference"); 1715 1716 if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) { 1717 LLVM_DEBUG(dbgs() << " before interference.\n"); 1718 // 1719 // <<< Interference after kill. 1720 // |---o---x | Killed in block. 1721 // ========= Use IntvIn everywhere. 1722 // 1723 selectIntv(IntvIn); 1724 useIntv(Start, BI.LastInstr); 1725 return; 1726 } 1727 1728 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber()); 1729 1730 if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) { 1731 // 1732 // <<< Possible interference after last use. 1733 // |---o---o---| Live-out on stack. 1734 // =========____ Leave IntvIn after last use. 1735 // 1736 // < Interference after last use. 1737 // |---o---o--o| Live-out on stack, late last use. 1738 // ============ Copy to stack after LSP, overlap IntvIn. 1739 // \_____ Stack interval is live-out. 1740 // 1741 if (BI.LastInstr < LSP) { 1742 LLVM_DEBUG(dbgs() << ", spill after last use before interference.\n"); 1743 selectIntv(IntvIn); 1744 SlotIndex Idx = leaveIntvAfter(BI.LastInstr); 1745 useIntv(Start, Idx); 1746 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1747 } else { 1748 LLVM_DEBUG(dbgs() << ", spill before last split point.\n"); 1749 selectIntv(IntvIn); 1750 SlotIndex Idx = leaveIntvBefore(LSP); 1751 overlapIntv(Idx, BI.LastInstr); 1752 useIntv(Start, Idx); 1753 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1754 } 1755 return; 1756 } 1757 1758 // The interference is overlapping somewhere we wanted to use IntvIn. That 1759 // means we need to create a local interval that can be allocated a 1760 // different register. 1761 unsigned LocalIntv = openIntv(); 1762 (void)LocalIntv; 1763 LLVM_DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n"); 1764 1765 if (!BI.LiveOut || BI.LastInstr < LSP) { 1766 // 1767 // <<<<<<< Interference overlapping uses. 1768 // |---o---o---| Live-out on stack. 1769 // =====----____ Leave IntvIn before interference, then spill. 1770 // 1771 SlotIndex To = leaveIntvAfter(BI.LastInstr); 1772 SlotIndex From = enterIntvBefore(LeaveBefore); 1773 useIntv(From, To); 1774 selectIntv(IntvIn); 1775 useIntv(Start, From); 1776 assert((!LeaveBefore || From <= LeaveBefore) && "Interference"); 1777 return; 1778 } 1779 1780 // <<<<<<< Interference overlapping uses. 1781 // |---o---o--o| Live-out on stack, late last use. 1782 // =====------- Copy to stack before LSP, overlap LocalIntv. 1783 // \_____ Stack interval is live-out. 1784 // 1785 SlotIndex To = leaveIntvBefore(LSP); 1786 overlapIntv(To, BI.LastInstr); 1787 SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore)); 1788 useIntv(From, To); 1789 selectIntv(IntvIn); 1790 useIntv(Start, From); 1791 assert((!LeaveBefore || From <= LeaveBefore) && "Interference"); 1792 } 1793 1794 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI, 1795 unsigned IntvOut, SlotIndex EnterAfter) { 1796 SlotIndex Start, Stop; 1797 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 1798 1799 LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " [" << Start << ';' 1800 << Stop << "), uses " << BI.FirstInstr << '-' 1801 << BI.LastInstr << ", reg-out " << IntvOut 1802 << ", enter after " << EnterAfter 1803 << (BI.LiveIn ? ", stack-in" : ", defined in block")); 1804 1805 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber()); 1806 1807 assert(IntvOut && "Must have register out"); 1808 assert(BI.LiveOut && "Must be live-out"); 1809 assert((!EnterAfter || EnterAfter < LSP) && "Bad interference"); 1810 1811 if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) { 1812 LLVM_DEBUG(dbgs() << " after interference.\n"); 1813 // 1814 // >>>> Interference before def. 1815 // | o---o---| Defined in block. 1816 // ========= Use IntvOut everywhere. 1817 // 1818 selectIntv(IntvOut); 1819 useIntv(BI.FirstInstr, Stop); 1820 return; 1821 } 1822 1823 if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) { 1824 LLVM_DEBUG(dbgs() << ", reload after interference.\n"); 1825 // 1826 // >>>> Interference before def. 1827 // |---o---o---| Live-through, stack-in. 1828 // ____========= Enter IntvOut before first use. 1829 // 1830 selectIntv(IntvOut); 1831 SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr)); 1832 useIntv(Idx, Stop); 1833 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1834 return; 1835 } 1836 1837 // The interference is overlapping somewhere we wanted to use IntvOut. That 1838 // means we need to create a local interval that can be allocated a 1839 // different register. 1840 LLVM_DEBUG(dbgs() << ", interference overlaps uses.\n"); 1841 // 1842 // >>>>>>> Interference overlapping uses. 1843 // |---o---o---| Live-through, stack-in. 1844 // ____---====== Create local interval for interference range. 1845 // 1846 selectIntv(IntvOut); 1847 SlotIndex Idx = enterIntvAfter(EnterAfter); 1848 useIntv(Idx, Stop); 1849 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1850 1851 openIntv(); 1852 SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr)); 1853 useIntv(From, Idx); 1854 } 1855