1 //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the SplitAnalysis class as well as mutator functions for 11 // live range splitting. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "SplitKit.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 18 #include "llvm/CodeGen/LiveRangeEdit.h" 19 #include "llvm/CodeGen/MachineDominators.h" 20 #include "llvm/CodeGen/MachineInstrBuilder.h" 21 #include "llvm/CodeGen/MachineLoopInfo.h" 22 #include "llvm/CodeGen/MachineRegisterInfo.h" 23 #include "llvm/CodeGen/VirtRegMap.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/Target/TargetInstrInfo.h" 27 #include "llvm/Target/TargetMachine.h" 28 29 using namespace llvm; 30 31 #define DEBUG_TYPE "regalloc" 32 33 STATISTIC(NumFinished, "Number of splits finished"); 34 STATISTIC(NumSimple, "Number of splits that were simple"); 35 STATISTIC(NumCopies, "Number of copies inserted for splitting"); 36 STATISTIC(NumRemats, "Number of rematerialized defs for splitting"); 37 STATISTIC(NumRepairs, "Number of invalid live ranges repaired"); 38 39 //===----------------------------------------------------------------------===// 40 // Split Analysis 41 //===----------------------------------------------------------------------===// 42 43 SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis, 44 const MachineLoopInfo &mli) 45 : MF(vrm.getMachineFunction()), VRM(vrm), LIS(lis), Loops(mli), 46 TII(*MF.getSubtarget().getInstrInfo()), CurLI(nullptr), 47 LastSplitPoint(MF.getNumBlockIDs()) {} 48 49 void SplitAnalysis::clear() { 50 UseSlots.clear(); 51 UseBlocks.clear(); 52 ThroughBlocks.clear(); 53 CurLI = nullptr; 54 DidRepairRange = false; 55 } 56 57 SlotIndex SplitAnalysis::computeLastSplitPoint(unsigned Num) { 58 const MachineBasicBlock *MBB = MF.getBlockNumbered(Num); 59 // FIXME: Handle multiple EH pad successors. 60 const MachineBasicBlock *LPad = MBB->getLandingPadSuccessor(); 61 std::pair<SlotIndex, SlotIndex> &LSP = LastSplitPoint[Num]; 62 SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB); 63 64 // Compute split points on the first call. The pair is independent of the 65 // current live interval. 66 if (!LSP.first.isValid()) { 67 MachineBasicBlock::const_iterator FirstTerm = MBB->getFirstTerminator(); 68 if (FirstTerm == MBB->end()) 69 LSP.first = MBBEnd; 70 else 71 LSP.first = LIS.getInstructionIndex(FirstTerm); 72 73 // If there is a landing pad successor, also find the call instruction. 74 if (!LPad) 75 return LSP.first; 76 // There may not be a call instruction (?) in which case we ignore LPad. 77 LSP.second = LSP.first; 78 for (MachineBasicBlock::const_iterator I = MBB->end(), E = MBB->begin(); 79 I != E;) { 80 --I; 81 if (I->isCall()) { 82 LSP.second = LIS.getInstructionIndex(I); 83 break; 84 } 85 } 86 } 87 88 // If CurLI is live into a landing pad successor, move the last split point 89 // back to the call that may throw. 90 if (!LPad || !LSP.second || !LIS.isLiveInToMBB(*CurLI, LPad)) 91 return LSP.first; 92 93 // Find the value leaving MBB. 94 const VNInfo *VNI = CurLI->getVNInfoBefore(MBBEnd); 95 if (!VNI) 96 return LSP.first; 97 98 // If the value leaving MBB was defined after the call in MBB, it can't 99 // really be live-in to the landing pad. This can happen if the landing pad 100 // has a PHI, and this register is undef on the exceptional edge. 101 // <rdar://problem/10664933> 102 if (!SlotIndex::isEarlierInstr(VNI->def, LSP.second) && VNI->def < MBBEnd) 103 return LSP.first; 104 105 // Value is properly live-in to the landing pad. 106 // Only allow splits before the call. 107 return LSP.second; 108 } 109 110 MachineBasicBlock::iterator 111 SplitAnalysis::getLastSplitPointIter(MachineBasicBlock *MBB) { 112 SlotIndex LSP = getLastSplitPoint(MBB->getNumber()); 113 if (LSP == LIS.getMBBEndIdx(MBB)) 114 return MBB->end(); 115 return LIS.getInstructionFromIndex(LSP); 116 } 117 118 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI. 119 void SplitAnalysis::analyzeUses() { 120 assert(UseSlots.empty() && "Call clear first"); 121 122 // First get all the defs from the interval values. This provides the correct 123 // slots for early clobbers. 124 for (const VNInfo *VNI : CurLI->valnos) 125 if (!VNI->isPHIDef() && !VNI->isUnused()) 126 UseSlots.push_back(VNI->def); 127 128 // Get use slots form the use-def chain. 129 const MachineRegisterInfo &MRI = MF.getRegInfo(); 130 for (MachineOperand &MO : MRI.use_nodbg_operands(CurLI->reg)) 131 if (!MO.isUndef()) 132 UseSlots.push_back(LIS.getInstructionIndex(MO.getParent()).getRegSlot()); 133 134 array_pod_sort(UseSlots.begin(), UseSlots.end()); 135 136 // Remove duplicates, keeping the smaller slot for each instruction. 137 // That is what we want for early clobbers. 138 UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(), 139 SlotIndex::isSameInstr), 140 UseSlots.end()); 141 142 // Compute per-live block info. 143 if (!calcLiveBlockInfo()) { 144 // FIXME: calcLiveBlockInfo found inconsistencies in the live range. 145 // I am looking at you, RegisterCoalescer! 146 DidRepairRange = true; 147 ++NumRepairs; 148 DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n"); 149 const_cast<LiveIntervals&>(LIS) 150 .shrinkToUses(const_cast<LiveInterval*>(CurLI)); 151 UseBlocks.clear(); 152 ThroughBlocks.clear(); 153 bool fixed = calcLiveBlockInfo(); 154 (void)fixed; 155 assert(fixed && "Couldn't fix broken live interval"); 156 } 157 158 DEBUG(dbgs() << "Analyze counted " 159 << UseSlots.size() << " instrs in " 160 << UseBlocks.size() << " blocks, through " 161 << NumThroughBlocks << " blocks.\n"); 162 } 163 164 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks 165 /// where CurLI is live. 166 bool SplitAnalysis::calcLiveBlockInfo() { 167 ThroughBlocks.resize(MF.getNumBlockIDs()); 168 NumThroughBlocks = NumGapBlocks = 0; 169 if (CurLI->empty()) 170 return true; 171 172 LiveInterval::const_iterator LVI = CurLI->begin(); 173 LiveInterval::const_iterator LVE = CurLI->end(); 174 175 SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE; 176 UseI = UseSlots.begin(); 177 UseE = UseSlots.end(); 178 179 // Loop over basic blocks where CurLI is live. 180 MachineFunction::iterator MFI = 181 LIS.getMBBFromIndex(LVI->start)->getIterator(); 182 for (;;) { 183 BlockInfo BI; 184 BI.MBB = &*MFI; 185 SlotIndex Start, Stop; 186 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 187 188 // If the block contains no uses, the range must be live through. At one 189 // point, RegisterCoalescer could create dangling ranges that ended 190 // mid-block. 191 if (UseI == UseE || *UseI >= Stop) { 192 ++NumThroughBlocks; 193 ThroughBlocks.set(BI.MBB->getNumber()); 194 // The range shouldn't end mid-block if there are no uses. This shouldn't 195 // happen. 196 if (LVI->end < Stop) 197 return false; 198 } else { 199 // This block has uses. Find the first and last uses in the block. 200 BI.FirstInstr = *UseI; 201 assert(BI.FirstInstr >= Start); 202 do ++UseI; 203 while (UseI != UseE && *UseI < Stop); 204 BI.LastInstr = UseI[-1]; 205 assert(BI.LastInstr < Stop); 206 207 // LVI is the first live segment overlapping MBB. 208 BI.LiveIn = LVI->start <= Start; 209 210 // When not live in, the first use should be a def. 211 if (!BI.LiveIn) { 212 assert(LVI->start == LVI->valno->def && "Dangling Segment start"); 213 assert(LVI->start == BI.FirstInstr && "First instr should be a def"); 214 BI.FirstDef = BI.FirstInstr; 215 } 216 217 // Look for gaps in the live range. 218 BI.LiveOut = true; 219 while (LVI->end < Stop) { 220 SlotIndex LastStop = LVI->end; 221 if (++LVI == LVE || LVI->start >= Stop) { 222 BI.LiveOut = false; 223 BI.LastInstr = LastStop; 224 break; 225 } 226 227 if (LastStop < LVI->start) { 228 // There is a gap in the live range. Create duplicate entries for the 229 // live-in snippet and the live-out snippet. 230 ++NumGapBlocks; 231 232 // Push the Live-in part. 233 BI.LiveOut = false; 234 UseBlocks.push_back(BI); 235 UseBlocks.back().LastInstr = LastStop; 236 237 // Set up BI for the live-out part. 238 BI.LiveIn = false; 239 BI.LiveOut = true; 240 BI.FirstInstr = BI.FirstDef = LVI->start; 241 } 242 243 // A Segment that starts in the middle of the block must be a def. 244 assert(LVI->start == LVI->valno->def && "Dangling Segment start"); 245 if (!BI.FirstDef) 246 BI.FirstDef = LVI->start; 247 } 248 249 UseBlocks.push_back(BI); 250 251 // LVI is now at LVE or LVI->end >= Stop. 252 if (LVI == LVE) 253 break; 254 } 255 256 // Live segment ends exactly at Stop. Move to the next segment. 257 if (LVI->end == Stop && ++LVI == LVE) 258 break; 259 260 // Pick the next basic block. 261 if (LVI->start < Stop) 262 ++MFI; 263 else 264 MFI = LIS.getMBBFromIndex(LVI->start)->getIterator(); 265 } 266 267 assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count"); 268 return true; 269 } 270 271 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const { 272 if (cli->empty()) 273 return 0; 274 LiveInterval *li = const_cast<LiveInterval*>(cli); 275 LiveInterval::iterator LVI = li->begin(); 276 LiveInterval::iterator LVE = li->end(); 277 unsigned Count = 0; 278 279 // Loop over basic blocks where li is live. 280 MachineFunction::const_iterator MFI = 281 LIS.getMBBFromIndex(LVI->start)->getIterator(); 282 SlotIndex Stop = LIS.getMBBEndIdx(&*MFI); 283 for (;;) { 284 ++Count; 285 LVI = li->advanceTo(LVI, Stop); 286 if (LVI == LVE) 287 return Count; 288 do { 289 ++MFI; 290 Stop = LIS.getMBBEndIdx(&*MFI); 291 } while (Stop <= LVI->start); 292 } 293 } 294 295 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const { 296 unsigned OrigReg = VRM.getOriginal(CurLI->reg); 297 const LiveInterval &Orig = LIS.getInterval(OrigReg); 298 assert(!Orig.empty() && "Splitting empty interval?"); 299 LiveInterval::const_iterator I = Orig.find(Idx); 300 301 // Range containing Idx should begin at Idx. 302 if (I != Orig.end() && I->start <= Idx) 303 return I->start == Idx; 304 305 // Range does not contain Idx, previous must end at Idx. 306 return I != Orig.begin() && (--I)->end == Idx; 307 } 308 309 void SplitAnalysis::analyze(const LiveInterval *li) { 310 clear(); 311 CurLI = li; 312 analyzeUses(); 313 } 314 315 316 //===----------------------------------------------------------------------===// 317 // Split Editor 318 //===----------------------------------------------------------------------===// 319 320 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA. 321 SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm, 322 MachineDominatorTree &mdt, 323 MachineBlockFrequencyInfo &mbfi) 324 : SA(sa), LIS(lis), VRM(vrm), MRI(vrm.getMachineFunction().getRegInfo()), 325 MDT(mdt), TII(*vrm.getMachineFunction().getSubtarget().getInstrInfo()), 326 TRI(*vrm.getMachineFunction().getSubtarget().getRegisterInfo()), 327 MBFI(mbfi), Edit(nullptr), OpenIdx(0), SpillMode(SM_Partition), 328 RegAssign(Allocator) {} 329 330 void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) { 331 Edit = &LRE; 332 SpillMode = SM; 333 OpenIdx = 0; 334 RegAssign.clear(); 335 Values.clear(); 336 337 // Reset the LiveRangeCalc instances needed for this spill mode. 338 LRCalc[0].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 339 &LIS.getVNInfoAllocator()); 340 if (SpillMode) 341 LRCalc[1].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 342 &LIS.getVNInfoAllocator()); 343 344 // We don't need an AliasAnalysis since we will only be performing 345 // cheap-as-a-copy remats anyway. 346 Edit->anyRematerializable(nullptr); 347 } 348 349 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 350 void SplitEditor::dump() const { 351 if (RegAssign.empty()) { 352 dbgs() << " empty\n"; 353 return; 354 } 355 356 for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I) 357 dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value(); 358 dbgs() << '\n'; 359 } 360 #endif 361 362 VNInfo *SplitEditor::defValue(unsigned RegIdx, 363 const VNInfo *ParentVNI, 364 SlotIndex Idx) { 365 assert(ParentVNI && "Mapping NULL value"); 366 assert(Idx.isValid() && "Invalid SlotIndex"); 367 assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI"); 368 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx)); 369 370 // Create a new value. 371 VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator()); 372 373 // Use insert for lookup, so we can add missing values with a second lookup. 374 std::pair<ValueMap::iterator, bool> InsP = 375 Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id), 376 ValueForcePair(VNI, false))); 377 378 // This was the first time (RegIdx, ParentVNI) was mapped. 379 // Keep it as a simple def without any liveness. 380 if (InsP.second) 381 return VNI; 382 383 // If the previous value was a simple mapping, add liveness for it now. 384 if (VNInfo *OldVNI = InsP.first->second.getPointer()) { 385 SlotIndex Def = OldVNI->def; 386 LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), OldVNI)); 387 // No longer a simple mapping. Switch to a complex, non-forced mapping. 388 InsP.first->second = ValueForcePair(); 389 } 390 391 // This is a complex mapping, add liveness for VNI 392 SlotIndex Def = VNI->def; 393 LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), VNI)); 394 395 return VNI; 396 } 397 398 void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo *ParentVNI) { 399 assert(ParentVNI && "Mapping NULL value"); 400 ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI->id)]; 401 VNInfo *VNI = VFP.getPointer(); 402 403 // ParentVNI was either unmapped or already complex mapped. Either way, just 404 // set the force bit. 405 if (!VNI) { 406 VFP.setInt(true); 407 return; 408 } 409 410 // This was previously a single mapping. Make sure the old def is represented 411 // by a trivial live range. 412 SlotIndex Def = VNI->def; 413 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx)); 414 LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), VNI)); 415 // Mark as complex mapped, forced. 416 VFP = ValueForcePair(nullptr, true); 417 } 418 419 VNInfo *SplitEditor::defFromParent(unsigned RegIdx, 420 VNInfo *ParentVNI, 421 SlotIndex UseIdx, 422 MachineBasicBlock &MBB, 423 MachineBasicBlock::iterator I) { 424 MachineInstr *CopyMI = nullptr; 425 SlotIndex Def; 426 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx)); 427 428 // We may be trying to avoid interference that ends at a deleted instruction, 429 // so always begin RegIdx 0 early and all others late. 430 bool Late = RegIdx != 0; 431 432 // Attempt cheap-as-a-copy rematerialization. 433 LiveRangeEdit::Remat RM(ParentVNI); 434 if (Edit->canRematerializeAt(RM, UseIdx, true)) { 435 Def = Edit->rematerializeAt(MBB, I, LI->reg, RM, TRI, Late); 436 ++NumRemats; 437 } else { 438 // Can't remat, just insert a copy from parent. 439 CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg) 440 .addReg(Edit->getReg()); 441 Def = LIS.getSlotIndexes()->insertMachineInstrInMaps(CopyMI, Late) 442 .getRegSlot(); 443 ++NumCopies; 444 } 445 446 // Define the value in Reg. 447 return defValue(RegIdx, ParentVNI, Def); 448 } 449 450 /// Create a new virtual register and live interval. 451 unsigned SplitEditor::openIntv() { 452 // Create the complement as index 0. 453 if (Edit->empty()) 454 Edit->createEmptyInterval(); 455 456 // Create the open interval. 457 OpenIdx = Edit->size(); 458 Edit->createEmptyInterval(); 459 return OpenIdx; 460 } 461 462 void SplitEditor::selectIntv(unsigned Idx) { 463 assert(Idx != 0 && "Cannot select the complement interval"); 464 assert(Idx < Edit->size() && "Can only select previously opened interval"); 465 DEBUG(dbgs() << " selectIntv " << OpenIdx << " -> " << Idx << '\n'); 466 OpenIdx = Idx; 467 } 468 469 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) { 470 assert(OpenIdx && "openIntv not called before enterIntvBefore"); 471 DEBUG(dbgs() << " enterIntvBefore " << Idx); 472 Idx = Idx.getBaseIndex(); 473 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 474 if (!ParentVNI) { 475 DEBUG(dbgs() << ": not live\n"); 476 return Idx; 477 } 478 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 479 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 480 assert(MI && "enterIntvBefore called with invalid index"); 481 482 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI); 483 return VNI->def; 484 } 485 486 SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) { 487 assert(OpenIdx && "openIntv not called before enterIntvAfter"); 488 DEBUG(dbgs() << " enterIntvAfter " << Idx); 489 Idx = Idx.getBoundaryIndex(); 490 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 491 if (!ParentVNI) { 492 DEBUG(dbgs() << ": not live\n"); 493 return Idx; 494 } 495 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 496 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 497 assert(MI && "enterIntvAfter called with invalid index"); 498 499 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), 500 std::next(MachineBasicBlock::iterator(MI))); 501 return VNI->def; 502 } 503 504 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) { 505 assert(OpenIdx && "openIntv not called before enterIntvAtEnd"); 506 SlotIndex End = LIS.getMBBEndIdx(&MBB); 507 SlotIndex Last = End.getPrevSlot(); 508 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << Last); 509 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last); 510 if (!ParentVNI) { 511 DEBUG(dbgs() << ": not live\n"); 512 return End; 513 } 514 DEBUG(dbgs() << ": valno " << ParentVNI->id); 515 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB, 516 SA.getLastSplitPointIter(&MBB)); 517 RegAssign.insert(VNI->def, End, OpenIdx); 518 DEBUG(dump()); 519 return VNI->def; 520 } 521 522 /// useIntv - indicate that all instructions in MBB should use OpenLI. 523 void SplitEditor::useIntv(const MachineBasicBlock &MBB) { 524 useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB)); 525 } 526 527 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) { 528 assert(OpenIdx && "openIntv not called before useIntv"); 529 DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):"); 530 RegAssign.insert(Start, End, OpenIdx); 531 DEBUG(dump()); 532 } 533 534 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) { 535 assert(OpenIdx && "openIntv not called before leaveIntvAfter"); 536 DEBUG(dbgs() << " leaveIntvAfter " << Idx); 537 538 // The interval must be live beyond the instruction at Idx. 539 SlotIndex Boundary = Idx.getBoundaryIndex(); 540 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary); 541 if (!ParentVNI) { 542 DEBUG(dbgs() << ": not live\n"); 543 return Boundary.getNextSlot(); 544 } 545 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 546 MachineInstr *MI = LIS.getInstructionFromIndex(Boundary); 547 assert(MI && "No instruction at index"); 548 549 // In spill mode, make live ranges as short as possible by inserting the copy 550 // before MI. This is only possible if that instruction doesn't redefine the 551 // value. The inserted COPY is not a kill, and we don't need to recompute 552 // the source live range. The spiller also won't try to hoist this copy. 553 if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) && 554 MI->readsVirtualRegister(Edit->getReg())) { 555 forceRecompute(0, ParentVNI); 556 defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); 557 return Idx; 558 } 559 560 VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(), 561 std::next(MachineBasicBlock::iterator(MI))); 562 return VNI->def; 563 } 564 565 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) { 566 assert(OpenIdx && "openIntv not called before leaveIntvBefore"); 567 DEBUG(dbgs() << " leaveIntvBefore " << Idx); 568 569 // The interval must be live into the instruction at Idx. 570 Idx = Idx.getBaseIndex(); 571 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 572 if (!ParentVNI) { 573 DEBUG(dbgs() << ": not live\n"); 574 return Idx.getNextSlot(); 575 } 576 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 577 578 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 579 assert(MI && "No instruction at index"); 580 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); 581 return VNI->def; 582 } 583 584 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) { 585 assert(OpenIdx && "openIntv not called before leaveIntvAtTop"); 586 SlotIndex Start = LIS.getMBBStartIdx(&MBB); 587 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start); 588 589 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start); 590 if (!ParentVNI) { 591 DEBUG(dbgs() << ": not live\n"); 592 return Start; 593 } 594 595 VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB, 596 MBB.SkipPHIsAndLabels(MBB.begin())); 597 RegAssign.insert(Start, VNI->def, OpenIdx); 598 DEBUG(dump()); 599 return VNI->def; 600 } 601 602 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) { 603 assert(OpenIdx && "openIntv not called before overlapIntv"); 604 const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start); 605 assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) && 606 "Parent changes value in extended range"); 607 assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) && 608 "Range cannot span basic blocks"); 609 610 // The complement interval will be extended as needed by LRCalc.extend(). 611 if (ParentVNI) 612 forceRecompute(0, ParentVNI); 613 DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):"); 614 RegAssign.insert(Start, End, OpenIdx); 615 DEBUG(dump()); 616 } 617 618 //===----------------------------------------------------------------------===// 619 // Spill modes 620 //===----------------------------------------------------------------------===// 621 622 void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) { 623 LiveInterval *LI = &LIS.getInterval(Edit->get(0)); 624 DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n"); 625 RegAssignMap::iterator AssignI; 626 AssignI.setMap(RegAssign); 627 628 for (unsigned i = 0, e = Copies.size(); i != e; ++i) { 629 SlotIndex Def = Copies[i]->def; 630 MachineInstr *MI = LIS.getInstructionFromIndex(Def); 631 assert(MI && "No instruction for back-copy"); 632 633 MachineBasicBlock *MBB = MI->getParent(); 634 MachineBasicBlock::iterator MBBI(MI); 635 bool AtBegin; 636 do AtBegin = MBBI == MBB->begin(); 637 while (!AtBegin && (--MBBI)->isDebugValue()); 638 639 DEBUG(dbgs() << "Removing " << Def << '\t' << *MI); 640 LIS.removeVRegDefAt(*LI, Def); 641 LIS.RemoveMachineInstrFromMaps(MI); 642 MI->eraseFromParent(); 643 644 // Adjust RegAssign if a register assignment is killed at Def. We want to 645 // avoid calculating the live range of the source register if possible. 646 AssignI.find(Def.getPrevSlot()); 647 if (!AssignI.valid() || AssignI.start() >= Def) 648 continue; 649 // If MI doesn't kill the assigned register, just leave it. 650 if (AssignI.stop() != Def) 651 continue; 652 unsigned RegIdx = AssignI.value(); 653 if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg())) { 654 DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx << '\n'); 655 forceRecompute(RegIdx, Edit->getParent().getVNInfoAt(Def)); 656 } else { 657 SlotIndex Kill = LIS.getInstructionIndex(MBBI).getRegSlot(); 658 DEBUG(dbgs() << " move kill to " << Kill << '\t' << *MBBI); 659 AssignI.setStop(Kill); 660 } 661 } 662 } 663 664 MachineBasicBlock* 665 SplitEditor::findShallowDominator(MachineBasicBlock *MBB, 666 MachineBasicBlock *DefMBB) { 667 if (MBB == DefMBB) 668 return MBB; 669 assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def."); 670 671 const MachineLoopInfo &Loops = SA.Loops; 672 const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB); 673 MachineDomTreeNode *DefDomNode = MDT[DefMBB]; 674 675 // Best candidate so far. 676 MachineBasicBlock *BestMBB = MBB; 677 unsigned BestDepth = UINT_MAX; 678 679 for (;;) { 680 const MachineLoop *Loop = Loops.getLoopFor(MBB); 681 682 // MBB isn't in a loop, it doesn't get any better. All dominators have a 683 // higher frequency by definition. 684 if (!Loop) { 685 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#" 686 << MBB->getNumber() << " at depth 0\n"); 687 return MBB; 688 } 689 690 // We'll never be able to exit the DefLoop. 691 if (Loop == DefLoop) { 692 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#" 693 << MBB->getNumber() << " in the same loop\n"); 694 return MBB; 695 } 696 697 // Least busy dominator seen so far. 698 unsigned Depth = Loop->getLoopDepth(); 699 if (Depth < BestDepth) { 700 BestMBB = MBB; 701 BestDepth = Depth; 702 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#" 703 << MBB->getNumber() << " at depth " << Depth << '\n'); 704 } 705 706 // Leave loop by going to the immediate dominator of the loop header. 707 // This is a bigger stride than simply walking up the dominator tree. 708 MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom(); 709 710 // Too far up the dominator tree? 711 if (!IDom || !MDT.dominates(DefDomNode, IDom)) 712 return BestMBB; 713 714 MBB = IDom->getBlock(); 715 } 716 } 717 718 void SplitEditor::hoistCopiesForSize() { 719 // Get the complement interval, always RegIdx 0. 720 LiveInterval *LI = &LIS.getInterval(Edit->get(0)); 721 LiveInterval *Parent = &Edit->getParent(); 722 723 // Track the nearest common dominator for all back-copies for each ParentVNI, 724 // indexed by ParentVNI->id. 725 typedef std::pair<MachineBasicBlock*, SlotIndex> DomPair; 726 SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums()); 727 728 // Find the nearest common dominator for parent values with multiple 729 // back-copies. If a single back-copy dominates, put it in DomPair.second. 730 for (VNInfo *VNI : LI->valnos) { 731 if (VNI->isUnused()) 732 continue; 733 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 734 assert(ParentVNI && "Parent not live at complement def"); 735 736 // Don't hoist remats. The complement is probably going to disappear 737 // completely anyway. 738 if (Edit->didRematerialize(ParentVNI)) 739 continue; 740 741 MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def); 742 DomPair &Dom = NearestDom[ParentVNI->id]; 743 744 // Keep directly defined parent values. This is either a PHI or an 745 // instruction in the complement range. All other copies of ParentVNI 746 // should be eliminated. 747 if (VNI->def == ParentVNI->def) { 748 DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n'); 749 Dom = DomPair(ValMBB, VNI->def); 750 continue; 751 } 752 // Skip the singly mapped values. There is nothing to gain from hoisting a 753 // single back-copy. 754 if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) { 755 DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n'); 756 continue; 757 } 758 759 if (!Dom.first) { 760 // First time we see ParentVNI. VNI dominates itself. 761 Dom = DomPair(ValMBB, VNI->def); 762 } else if (Dom.first == ValMBB) { 763 // Two defs in the same block. Pick the earlier def. 764 if (!Dom.second.isValid() || VNI->def < Dom.second) 765 Dom.second = VNI->def; 766 } else { 767 // Different basic blocks. Check if one dominates. 768 MachineBasicBlock *Near = 769 MDT.findNearestCommonDominator(Dom.first, ValMBB); 770 if (Near == ValMBB) 771 // Def ValMBB dominates. 772 Dom = DomPair(ValMBB, VNI->def); 773 else if (Near != Dom.first) 774 // None dominate. Hoist to common dominator, need new def. 775 Dom = DomPair(Near, SlotIndex()); 776 } 777 778 DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@' << VNI->def 779 << " for parent " << ParentVNI->id << '@' << ParentVNI->def 780 << " hoist to BB#" << Dom.first->getNumber() << ' ' 781 << Dom.second << '\n'); 782 } 783 784 // Insert the hoisted copies. 785 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) { 786 DomPair &Dom = NearestDom[i]; 787 if (!Dom.first || Dom.second.isValid()) 788 continue; 789 // This value needs a hoisted copy inserted at the end of Dom.first. 790 VNInfo *ParentVNI = Parent->getValNumInfo(i); 791 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def); 792 // Get a less loopy dominator than Dom.first. 793 Dom.first = findShallowDominator(Dom.first, DefMBB); 794 SlotIndex Last = LIS.getMBBEndIdx(Dom.first).getPrevSlot(); 795 Dom.second = 796 defFromParent(0, ParentVNI, Last, *Dom.first, 797 SA.getLastSplitPointIter(Dom.first))->def; 798 } 799 800 // Remove redundant back-copies that are now known to be dominated by another 801 // def with the same value. 802 SmallVector<VNInfo*, 8> BackCopies; 803 for (VNInfo *VNI : LI->valnos) { 804 if (VNI->isUnused()) 805 continue; 806 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 807 const DomPair &Dom = NearestDom[ParentVNI->id]; 808 if (!Dom.first || Dom.second == VNI->def) 809 continue; 810 BackCopies.push_back(VNI); 811 forceRecompute(0, ParentVNI); 812 } 813 removeBackCopies(BackCopies); 814 } 815 816 817 /// transferValues - Transfer all possible values to the new live ranges. 818 /// Values that were rematerialized are left alone, they need LRCalc.extend(). 819 bool SplitEditor::transferValues() { 820 bool Skipped = false; 821 RegAssignMap::const_iterator AssignI = RegAssign.begin(); 822 for (const LiveRange::Segment &S : Edit->getParent()) { 823 DEBUG(dbgs() << " blit " << S << ':'); 824 VNInfo *ParentVNI = S.valno; 825 // RegAssign has holes where RegIdx 0 should be used. 826 SlotIndex Start = S.start; 827 AssignI.advanceTo(Start); 828 do { 829 unsigned RegIdx; 830 SlotIndex End = S.end; 831 if (!AssignI.valid()) { 832 RegIdx = 0; 833 } else if (AssignI.start() <= Start) { 834 RegIdx = AssignI.value(); 835 if (AssignI.stop() < End) { 836 End = AssignI.stop(); 837 ++AssignI; 838 } 839 } else { 840 RegIdx = 0; 841 End = std::min(End, AssignI.start()); 842 } 843 844 // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI. 845 DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx); 846 LiveRange &LR = LIS.getInterval(Edit->get(RegIdx)); 847 848 // Check for a simply defined value that can be blitted directly. 849 ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id)); 850 if (VNInfo *VNI = VFP.getPointer()) { 851 DEBUG(dbgs() << ':' << VNI->id); 852 LR.addSegment(LiveInterval::Segment(Start, End, VNI)); 853 Start = End; 854 continue; 855 } 856 857 // Skip values with forced recomputation. 858 if (VFP.getInt()) { 859 DEBUG(dbgs() << "(recalc)"); 860 Skipped = true; 861 Start = End; 862 continue; 863 } 864 865 LiveRangeCalc &LRC = getLRCalc(RegIdx); 866 867 // This value has multiple defs in RegIdx, but it wasn't rematerialized, 868 // so the live range is accurate. Add live-in blocks in [Start;End) to the 869 // LiveInBlocks. 870 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator(); 871 SlotIndex BlockStart, BlockEnd; 872 std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(&*MBB); 873 874 // The first block may be live-in, or it may have its own def. 875 if (Start != BlockStart) { 876 VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End)); 877 assert(VNI && "Missing def for complex mapped value"); 878 DEBUG(dbgs() << ':' << VNI->id << "*BB#" << MBB->getNumber()); 879 // MBB has its own def. Is it also live-out? 880 if (BlockEnd <= End) 881 LRC.setLiveOutValue(&*MBB, VNI); 882 883 // Skip to the next block for live-in. 884 ++MBB; 885 BlockStart = BlockEnd; 886 } 887 888 // Handle the live-in blocks covered by [Start;End). 889 assert(Start <= BlockStart && "Expected live-in block"); 890 while (BlockStart < End) { 891 DEBUG(dbgs() << ">BB#" << MBB->getNumber()); 892 BlockEnd = LIS.getMBBEndIdx(&*MBB); 893 if (BlockStart == ParentVNI->def) { 894 // This block has the def of a parent PHI, so it isn't live-in. 895 assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?"); 896 VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End)); 897 assert(VNI && "Missing def for complex mapped parent PHI"); 898 if (End >= BlockEnd) 899 LRC.setLiveOutValue(&*MBB, VNI); // Live-out as well. 900 } else { 901 // This block needs a live-in value. The last block covered may not 902 // be live-out. 903 if (End < BlockEnd) 904 LRC.addLiveInBlock(LR, MDT[&*MBB], End); 905 else { 906 // Live-through, and we don't know the value. 907 LRC.addLiveInBlock(LR, MDT[&*MBB]); 908 LRC.setLiveOutValue(&*MBB, nullptr); 909 } 910 } 911 BlockStart = BlockEnd; 912 ++MBB; 913 } 914 Start = End; 915 } while (Start != S.end); 916 DEBUG(dbgs() << '\n'); 917 } 918 919 LRCalc[0].calculateValues(); 920 if (SpillMode) 921 LRCalc[1].calculateValues(); 922 923 return Skipped; 924 } 925 926 void SplitEditor::extendPHIKillRanges() { 927 // Extend live ranges to be live-out for successor PHI values. 928 for (const VNInfo *PHIVNI : Edit->getParent().valnos) { 929 if (PHIVNI->isUnused() || !PHIVNI->isPHIDef()) 930 continue; 931 unsigned RegIdx = RegAssign.lookup(PHIVNI->def); 932 LiveRange &LR = LIS.getInterval(Edit->get(RegIdx)); 933 LiveRangeCalc &LRC = getLRCalc(RegIdx); 934 MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def); 935 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 936 PE = MBB->pred_end(); PI != PE; ++PI) { 937 SlotIndex End = LIS.getMBBEndIdx(*PI); 938 SlotIndex LastUse = End.getPrevSlot(); 939 // The predecessor may not have a live-out value. That is OK, like an 940 // undef PHI operand. 941 if (Edit->getParent().liveAt(LastUse)) { 942 assert(RegAssign.lookup(LastUse) == RegIdx && 943 "Different register assignment in phi predecessor"); 944 LRC.extend(LR, End); 945 } 946 } 947 } 948 } 949 950 /// rewriteAssigned - Rewrite all uses of Edit->getReg(). 951 void SplitEditor::rewriteAssigned(bool ExtendRanges) { 952 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()), 953 RE = MRI.reg_end(); RI != RE;) { 954 MachineOperand &MO = *RI; 955 MachineInstr *MI = MO.getParent(); 956 ++RI; 957 // LiveDebugVariables should have handled all DBG_VALUE instructions. 958 if (MI->isDebugValue()) { 959 DEBUG(dbgs() << "Zapping " << *MI); 960 MO.setReg(0); 961 continue; 962 } 963 964 // <undef> operands don't really read the register, so it doesn't matter 965 // which register we choose. When the use operand is tied to a def, we must 966 // use the same register as the def, so just do that always. 967 SlotIndex Idx = LIS.getInstructionIndex(MI); 968 if (MO.isDef() || MO.isUndef()) 969 Idx = Idx.getRegSlot(MO.isEarlyClobber()); 970 971 // Rewrite to the mapped register at Idx. 972 unsigned RegIdx = RegAssign.lookup(Idx); 973 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx)); 974 MO.setReg(LI->reg); 975 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t' 976 << Idx << ':' << RegIdx << '\t' << *MI); 977 978 // Extend liveness to Idx if the instruction reads reg. 979 if (!ExtendRanges || MO.isUndef()) 980 continue; 981 982 // Skip instructions that don't read Reg. 983 if (MO.isDef()) { 984 if (!MO.getSubReg() && !MO.isEarlyClobber()) 985 continue; 986 // We may wan't to extend a live range for a partial redef, or for a use 987 // tied to an early clobber. 988 Idx = Idx.getPrevSlot(); 989 if (!Edit->getParent().liveAt(Idx)) 990 continue; 991 } else 992 Idx = Idx.getRegSlot(true); 993 994 getLRCalc(RegIdx).extend(*LI, Idx.getNextSlot()); 995 } 996 } 997 998 void SplitEditor::deleteRematVictims() { 999 SmallVector<MachineInstr*, 8> Dead; 1000 for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I){ 1001 LiveInterval *LI = &LIS.getInterval(*I); 1002 for (const LiveRange::Segment &S : LI->segments) { 1003 // Dead defs end at the dead slot. 1004 if (S.end != S.valno->def.getDeadSlot()) 1005 continue; 1006 MachineInstr *MI = LIS.getInstructionFromIndex(S.valno->def); 1007 assert(MI && "Missing instruction for dead def"); 1008 MI->addRegisterDead(LI->reg, &TRI); 1009 1010 if (!MI->allDefsAreDead()) 1011 continue; 1012 1013 DEBUG(dbgs() << "All defs dead: " << *MI); 1014 Dead.push_back(MI); 1015 } 1016 } 1017 1018 if (Dead.empty()) 1019 return; 1020 1021 Edit->eliminateDeadDefs(Dead); 1022 } 1023 1024 void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) { 1025 ++NumFinished; 1026 1027 // At this point, the live intervals in Edit contain VNInfos corresponding to 1028 // the inserted copies. 1029 1030 // Add the original defs from the parent interval. 1031 for (const VNInfo *ParentVNI : Edit->getParent().valnos) { 1032 if (ParentVNI->isUnused()) 1033 continue; 1034 unsigned RegIdx = RegAssign.lookup(ParentVNI->def); 1035 defValue(RegIdx, ParentVNI, ParentVNI->def); 1036 1037 // Force rematted values to be recomputed everywhere. 1038 // The new live ranges may be truncated. 1039 if (Edit->didRematerialize(ParentVNI)) 1040 for (unsigned i = 0, e = Edit->size(); i != e; ++i) 1041 forceRecompute(i, ParentVNI); 1042 } 1043 1044 // Hoist back-copies to the complement interval when in spill mode. 1045 switch (SpillMode) { 1046 case SM_Partition: 1047 // Leave all back-copies as is. 1048 break; 1049 case SM_Size: 1050 hoistCopiesForSize(); 1051 break; 1052 case SM_Speed: 1053 llvm_unreachable("Spill mode 'speed' not implemented yet"); 1054 } 1055 1056 // Transfer the simply mapped values, check if any are skipped. 1057 bool Skipped = transferValues(); 1058 if (Skipped) 1059 extendPHIKillRanges(); 1060 else 1061 ++NumSimple; 1062 1063 // Rewrite virtual registers, possibly extending ranges. 1064 rewriteAssigned(Skipped); 1065 1066 // Delete defs that were rematted everywhere. 1067 if (Skipped) 1068 deleteRematVictims(); 1069 1070 // Get rid of unused values and set phi-kill flags. 1071 for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I) { 1072 LiveInterval &LI = LIS.getInterval(*I); 1073 LI.RenumberValues(); 1074 } 1075 1076 // Provide a reverse mapping from original indices to Edit ranges. 1077 if (LRMap) { 1078 LRMap->clear(); 1079 for (unsigned i = 0, e = Edit->size(); i != e; ++i) 1080 LRMap->push_back(i); 1081 } 1082 1083 // Now check if any registers were separated into multiple components. 1084 ConnectedVNInfoEqClasses ConEQ(LIS); 1085 for (unsigned i = 0, e = Edit->size(); i != e; ++i) { 1086 // Don't use iterators, they are invalidated by create() below. 1087 unsigned VReg = Edit->get(i); 1088 LiveInterval &LI = LIS.getInterval(VReg); 1089 SmallVector<LiveInterval*, 8> SplitLIs; 1090 LIS.splitSeparateComponents(LI, SplitLIs); 1091 unsigned Original = VRM.getOriginal(VReg); 1092 for (LiveInterval *SplitLI : SplitLIs) 1093 VRM.setIsSplitFromReg(SplitLI->reg, Original); 1094 1095 // The new intervals all map back to i. 1096 if (LRMap) 1097 LRMap->resize(Edit->size(), i); 1098 } 1099 1100 // Calculate spill weight and allocation hints for new intervals. 1101 Edit->calculateRegClassAndHint(VRM.getMachineFunction(), SA.Loops, MBFI); 1102 1103 assert(!LRMap || LRMap->size() == Edit->size()); 1104 } 1105 1106 1107 //===----------------------------------------------------------------------===// 1108 // Single Block Splitting 1109 //===----------------------------------------------------------------------===// 1110 1111 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI, 1112 bool SingleInstrs) const { 1113 // Always split for multiple instructions. 1114 if (!BI.isOneInstr()) 1115 return true; 1116 // Don't split for single instructions unless explicitly requested. 1117 if (!SingleInstrs) 1118 return false; 1119 // Splitting a live-through range always makes progress. 1120 if (BI.LiveIn && BI.LiveOut) 1121 return true; 1122 // No point in isolating a copy. It has no register class constraints. 1123 if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike()) 1124 return false; 1125 // Finally, don't isolate an end point that was created by earlier splits. 1126 return isOriginalEndpoint(BI.FirstInstr); 1127 } 1128 1129 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) { 1130 openIntv(); 1131 SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB->getNumber()); 1132 SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr, 1133 LastSplitPoint)); 1134 if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) { 1135 useIntv(SegStart, leaveIntvAfter(BI.LastInstr)); 1136 } else { 1137 // The last use is after the last valid split point. 1138 SlotIndex SegStop = leaveIntvBefore(LastSplitPoint); 1139 useIntv(SegStart, SegStop); 1140 overlapIntv(SegStop, BI.LastInstr); 1141 } 1142 } 1143 1144 1145 //===----------------------------------------------------------------------===// 1146 // Global Live Range Splitting Support 1147 //===----------------------------------------------------------------------===// 1148 1149 // These methods support a method of global live range splitting that uses a 1150 // global algorithm to decide intervals for CFG edges. They will insert split 1151 // points and color intervals in basic blocks while avoiding interference. 1152 // 1153 // Note that splitSingleBlock is also useful for blocks where both CFG edges 1154 // are on the stack. 1155 1156 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum, 1157 unsigned IntvIn, SlotIndex LeaveBefore, 1158 unsigned IntvOut, SlotIndex EnterAfter){ 1159 SlotIndex Start, Stop; 1160 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum); 1161 1162 DEBUG(dbgs() << "BB#" << MBBNum << " [" << Start << ';' << Stop 1163 << ") intf " << LeaveBefore << '-' << EnterAfter 1164 << ", live-through " << IntvIn << " -> " << IntvOut); 1165 1166 assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks"); 1167 1168 assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block"); 1169 assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf"); 1170 assert((!EnterAfter || EnterAfter >= Start) && "Interference before block"); 1171 1172 MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum); 1173 1174 if (!IntvOut) { 1175 DEBUG(dbgs() << ", spill on entry.\n"); 1176 // 1177 // <<<<<<<<< Possible LeaveBefore interference. 1178 // |-----------| Live through. 1179 // -____________ Spill on entry. 1180 // 1181 selectIntv(IntvIn); 1182 SlotIndex Idx = leaveIntvAtTop(*MBB); 1183 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1184 (void)Idx; 1185 return; 1186 } 1187 1188 if (!IntvIn) { 1189 DEBUG(dbgs() << ", reload on exit.\n"); 1190 // 1191 // >>>>>>> Possible EnterAfter interference. 1192 // |-----------| Live through. 1193 // ___________-- Reload on exit. 1194 // 1195 selectIntv(IntvOut); 1196 SlotIndex Idx = enterIntvAtEnd(*MBB); 1197 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1198 (void)Idx; 1199 return; 1200 } 1201 1202 if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) { 1203 DEBUG(dbgs() << ", straight through.\n"); 1204 // 1205 // |-----------| Live through. 1206 // ------------- Straight through, same intv, no interference. 1207 // 1208 selectIntv(IntvOut); 1209 useIntv(Start, Stop); 1210 return; 1211 } 1212 1213 // We cannot legally insert splits after LSP. 1214 SlotIndex LSP = SA.getLastSplitPoint(MBBNum); 1215 assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf"); 1216 1217 if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter || 1218 LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) { 1219 DEBUG(dbgs() << ", switch avoiding interference.\n"); 1220 // 1221 // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference. 1222 // |-----------| Live through. 1223 // ------======= Switch intervals between interference. 1224 // 1225 selectIntv(IntvOut); 1226 SlotIndex Idx; 1227 if (LeaveBefore && LeaveBefore < LSP) { 1228 Idx = enterIntvBefore(LeaveBefore); 1229 useIntv(Idx, Stop); 1230 } else { 1231 Idx = enterIntvAtEnd(*MBB); 1232 } 1233 selectIntv(IntvIn); 1234 useIntv(Start, Idx); 1235 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1236 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1237 return; 1238 } 1239 1240 DEBUG(dbgs() << ", create local intv for interference.\n"); 1241 // 1242 // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference. 1243 // |-----------| Live through. 1244 // ==---------== Switch intervals before/after interference. 1245 // 1246 assert(LeaveBefore <= EnterAfter && "Missed case"); 1247 1248 selectIntv(IntvOut); 1249 SlotIndex Idx = enterIntvAfter(EnterAfter); 1250 useIntv(Idx, Stop); 1251 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1252 1253 selectIntv(IntvIn); 1254 Idx = leaveIntvBefore(LeaveBefore); 1255 useIntv(Start, Idx); 1256 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1257 } 1258 1259 1260 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI, 1261 unsigned IntvIn, SlotIndex LeaveBefore) { 1262 SlotIndex Start, Stop; 1263 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 1264 1265 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop 1266 << "), uses " << BI.FirstInstr << '-' << BI.LastInstr 1267 << ", reg-in " << IntvIn << ", leave before " << LeaveBefore 1268 << (BI.LiveOut ? ", stack-out" : ", killed in block")); 1269 1270 assert(IntvIn && "Must have register in"); 1271 assert(BI.LiveIn && "Must be live-in"); 1272 assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference"); 1273 1274 if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) { 1275 DEBUG(dbgs() << " before interference.\n"); 1276 // 1277 // <<< Interference after kill. 1278 // |---o---x | Killed in block. 1279 // ========= Use IntvIn everywhere. 1280 // 1281 selectIntv(IntvIn); 1282 useIntv(Start, BI.LastInstr); 1283 return; 1284 } 1285 1286 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber()); 1287 1288 if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) { 1289 // 1290 // <<< Possible interference after last use. 1291 // |---o---o---| Live-out on stack. 1292 // =========____ Leave IntvIn after last use. 1293 // 1294 // < Interference after last use. 1295 // |---o---o--o| Live-out on stack, late last use. 1296 // ============ Copy to stack after LSP, overlap IntvIn. 1297 // \_____ Stack interval is live-out. 1298 // 1299 if (BI.LastInstr < LSP) { 1300 DEBUG(dbgs() << ", spill after last use before interference.\n"); 1301 selectIntv(IntvIn); 1302 SlotIndex Idx = leaveIntvAfter(BI.LastInstr); 1303 useIntv(Start, Idx); 1304 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1305 } else { 1306 DEBUG(dbgs() << ", spill before last split point.\n"); 1307 selectIntv(IntvIn); 1308 SlotIndex Idx = leaveIntvBefore(LSP); 1309 overlapIntv(Idx, BI.LastInstr); 1310 useIntv(Start, Idx); 1311 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1312 } 1313 return; 1314 } 1315 1316 // The interference is overlapping somewhere we wanted to use IntvIn. That 1317 // means we need to create a local interval that can be allocated a 1318 // different register. 1319 unsigned LocalIntv = openIntv(); 1320 (void)LocalIntv; 1321 DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n"); 1322 1323 if (!BI.LiveOut || BI.LastInstr < LSP) { 1324 // 1325 // <<<<<<< Interference overlapping uses. 1326 // |---o---o---| Live-out on stack. 1327 // =====----____ Leave IntvIn before interference, then spill. 1328 // 1329 SlotIndex To = leaveIntvAfter(BI.LastInstr); 1330 SlotIndex From = enterIntvBefore(LeaveBefore); 1331 useIntv(From, To); 1332 selectIntv(IntvIn); 1333 useIntv(Start, From); 1334 assert((!LeaveBefore || From <= LeaveBefore) && "Interference"); 1335 return; 1336 } 1337 1338 // <<<<<<< Interference overlapping uses. 1339 // |---o---o--o| Live-out on stack, late last use. 1340 // =====------- Copy to stack before LSP, overlap LocalIntv. 1341 // \_____ Stack interval is live-out. 1342 // 1343 SlotIndex To = leaveIntvBefore(LSP); 1344 overlapIntv(To, BI.LastInstr); 1345 SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore)); 1346 useIntv(From, To); 1347 selectIntv(IntvIn); 1348 useIntv(Start, From); 1349 assert((!LeaveBefore || From <= LeaveBefore) && "Interference"); 1350 } 1351 1352 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI, 1353 unsigned IntvOut, SlotIndex EnterAfter) { 1354 SlotIndex Start, Stop; 1355 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 1356 1357 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop 1358 << "), uses " << BI.FirstInstr << '-' << BI.LastInstr 1359 << ", reg-out " << IntvOut << ", enter after " << EnterAfter 1360 << (BI.LiveIn ? ", stack-in" : ", defined in block")); 1361 1362 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber()); 1363 1364 assert(IntvOut && "Must have register out"); 1365 assert(BI.LiveOut && "Must be live-out"); 1366 assert((!EnterAfter || EnterAfter < LSP) && "Bad interference"); 1367 1368 if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) { 1369 DEBUG(dbgs() << " after interference.\n"); 1370 // 1371 // >>>> Interference before def. 1372 // | o---o---| Defined in block. 1373 // ========= Use IntvOut everywhere. 1374 // 1375 selectIntv(IntvOut); 1376 useIntv(BI.FirstInstr, Stop); 1377 return; 1378 } 1379 1380 if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) { 1381 DEBUG(dbgs() << ", reload after interference.\n"); 1382 // 1383 // >>>> Interference before def. 1384 // |---o---o---| Live-through, stack-in. 1385 // ____========= Enter IntvOut before first use. 1386 // 1387 selectIntv(IntvOut); 1388 SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr)); 1389 useIntv(Idx, Stop); 1390 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1391 return; 1392 } 1393 1394 // The interference is overlapping somewhere we wanted to use IntvOut. That 1395 // means we need to create a local interval that can be allocated a 1396 // different register. 1397 DEBUG(dbgs() << ", interference overlaps uses.\n"); 1398 // 1399 // >>>>>>> Interference overlapping uses. 1400 // |---o---o---| Live-through, stack-in. 1401 // ____---====== Create local interval for interference range. 1402 // 1403 selectIntv(IntvOut); 1404 SlotIndex Idx = enterIntvAfter(EnterAfter); 1405 useIntv(Idx, Stop); 1406 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1407 1408 openIntv(); 1409 SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr)); 1410 useIntv(From, Idx); 1411 } 1412