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