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