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