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 "LiveRangeEdit.h" 18 #include "VirtRegMap.h" 19 #include "llvm/CodeGen/CalcSpillWeights.h" 20 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 21 #include "llvm/CodeGen/MachineDominators.h" 22 #include "llvm/CodeGen/MachineInstrBuilder.h" 23 #include "llvm/CodeGen/MachineRegisterInfo.h" 24 #include "llvm/Support/CommandLine.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 static cl::opt<bool> 33 AllowSplit("spiller-splits-edges", 34 cl::desc("Allow critical edge splitting during spilling")); 35 36 //===----------------------------------------------------------------------===// 37 // Split Analysis 38 //===----------------------------------------------------------------------===// 39 40 SplitAnalysis::SplitAnalysis(const MachineFunction &mf, 41 const LiveIntervals &lis, 42 const MachineLoopInfo &mli) 43 : MF(mf), 44 LIS(lis), 45 Loops(mli), 46 TII(*mf.getTarget().getInstrInfo()), 47 CurLI(0) {} 48 49 void SplitAnalysis::clear() { 50 UseSlots.clear(); 51 UsingInstrs.clear(); 52 UsingBlocks.clear(); 53 LiveBlocks.clear(); 54 CurLI = 0; 55 } 56 57 bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) { 58 MachineBasicBlock *T, *F; 59 SmallVector<MachineOperand, 4> Cond; 60 return !TII.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond); 61 } 62 63 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI. 64 void SplitAnalysis::analyzeUses() { 65 const MachineRegisterInfo &MRI = MF.getRegInfo(); 66 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(CurLI->reg), 67 E = MRI.reg_end(); I != E; ++I) { 68 MachineOperand &MO = I.getOperand(); 69 if (MO.isUse() && MO.isUndef()) 70 continue; 71 MachineInstr *MI = MO.getParent(); 72 if (MI->isDebugValue() || !UsingInstrs.insert(MI)) 73 continue; 74 UseSlots.push_back(LIS.getInstructionIndex(MI).getDefIndex()); 75 MachineBasicBlock *MBB = MI->getParent(); 76 UsingBlocks[MBB]++; 77 } 78 array_pod_sort(UseSlots.begin(), UseSlots.end()); 79 calcLiveBlockInfo(); 80 DEBUG(dbgs() << " counted " 81 << UsingInstrs.size() << " instrs, " 82 << UsingBlocks.size() << " blocks.\n"); 83 } 84 85 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks 86 /// where CurLI is live. 87 void SplitAnalysis::calcLiveBlockInfo() { 88 if (CurLI->empty()) 89 return; 90 91 LiveInterval::const_iterator LVI = CurLI->begin(); 92 LiveInterval::const_iterator LVE = CurLI->end(); 93 94 SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE; 95 UseI = UseSlots.begin(); 96 UseE = UseSlots.end(); 97 98 // Loop over basic blocks where CurLI is live. 99 MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start); 100 for (;;) { 101 BlockInfo BI; 102 BI.MBB = MFI; 103 SlotIndex Start, Stop; 104 tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 105 106 // The last split point is the latest possible insertion point that dominates 107 // all successor blocks. If interference reaches LastSplitPoint, it is not 108 // possible to insert a split or reload that makes CurLI live in the 109 // outgoing bundle. 110 MachineBasicBlock::iterator LSP = LIS.getLastSplitPoint(*CurLI, BI.MBB); 111 if (LSP == BI.MBB->end()) 112 BI.LastSplitPoint = Stop; 113 else 114 BI.LastSplitPoint = LIS.getInstructionIndex(LSP); 115 116 // LVI is the first live segment overlapping MBB. 117 BI.LiveIn = LVI->start <= Start; 118 if (!BI.LiveIn) 119 BI.Def = LVI->start; 120 121 // Find the first and last uses in the block. 122 BI.Uses = hasUses(MFI); 123 if (BI.Uses && UseI != UseE) { 124 BI.FirstUse = *UseI; 125 assert(BI.FirstUse >= Start); 126 do ++UseI; 127 while (UseI != UseE && *UseI < Stop); 128 BI.LastUse = UseI[-1]; 129 assert(BI.LastUse < Stop); 130 } 131 132 // Look for gaps in the live range. 133 bool hasGap = false; 134 BI.LiveOut = true; 135 while (LVI->end < Stop) { 136 SlotIndex LastStop = LVI->end; 137 if (++LVI == LVE || LVI->start >= Stop) { 138 BI.Kill = LastStop; 139 BI.LiveOut = false; 140 break; 141 } 142 if (LastStop < LVI->start) { 143 hasGap = true; 144 BI.Kill = LastStop; 145 BI.Def = LVI->start; 146 } 147 } 148 149 // Don't set LiveThrough when the block has a gap. 150 BI.LiveThrough = !hasGap && BI.LiveIn && BI.LiveOut; 151 LiveBlocks.push_back(BI); 152 153 // LVI is now at LVE or LVI->end >= Stop. 154 if (LVI == LVE) 155 break; 156 157 // Live segment ends exactly at Stop. Move to the next segment. 158 if (LVI->end == Stop && ++LVI == LVE) 159 break; 160 161 // Pick the next basic block. 162 if (LVI->start < Stop) 163 ++MFI; 164 else 165 MFI = LIS.getMBBFromIndex(LVI->start); 166 } 167 } 168 169 void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const { 170 for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) { 171 unsigned count = UsingBlocks.lookup(*I); 172 OS << " BB#" << (*I)->getNumber(); 173 if (count) 174 OS << '(' << count << ')'; 175 } 176 } 177 178 void SplitAnalysis::analyze(const LiveInterval *li) { 179 clear(); 180 CurLI = li; 181 analyzeUses(); 182 } 183 184 185 //===----------------------------------------------------------------------===// 186 // LiveIntervalMap 187 //===----------------------------------------------------------------------===// 188 189 // Work around the fact that the std::pair constructors are broken for pointer 190 // pairs in some implementations. makeVV(x, 0) works. 191 static inline std::pair<const VNInfo*, VNInfo*> 192 makeVV(const VNInfo *a, VNInfo *b) { 193 return std::make_pair(a, b); 194 } 195 196 void LiveIntervalMap::reset(LiveInterval *li) { 197 LI = li; 198 Values.clear(); 199 LiveOutCache.clear(); 200 } 201 202 bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const { 203 ValueMap::const_iterator i = Values.find(ParentVNI); 204 return i != Values.end() && i->second == 0; 205 } 206 207 // defValue - Introduce a LI def for ParentVNI that could be later than 208 // ParentVNI->def. 209 VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) { 210 assert(LI && "call reset first"); 211 assert(ParentVNI && "Mapping NULL value"); 212 assert(Idx.isValid() && "Invalid SlotIndex"); 213 assert(ParentLI.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI"); 214 215 // Create a new value. 216 VNInfo *VNI = LI->getNextValue(Idx, 0, LIS.getVNInfoAllocator()); 217 218 // Preserve the PHIDef bit. 219 if (ParentVNI->isPHIDef() && Idx == ParentVNI->def) 220 VNI->setIsPHIDef(true); 221 222 // Use insert for lookup, so we can add missing values with a second lookup. 223 std::pair<ValueMap::iterator,bool> InsP = 224 Values.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0)); 225 226 // This is now a complex def. Mark with a NULL in valueMap. 227 if (!InsP.second) 228 InsP.first->second = 0; 229 230 return VNI; 231 } 232 233 234 // mapValue - Find the mapped value for ParentVNI at Idx. 235 // Potentially create phi-def values. 236 VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx, 237 bool *simple) { 238 assert(LI && "call reset first"); 239 assert(ParentVNI && "Mapping NULL value"); 240 assert(Idx.isValid() && "Invalid SlotIndex"); 241 assert(ParentLI.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI"); 242 243 // Use insert for lookup, so we can add missing values with a second lookup. 244 std::pair<ValueMap::iterator,bool> InsP = 245 Values.insert(makeVV(ParentVNI, 0)); 246 247 // This was an unknown value. Create a simple mapping. 248 if (InsP.second) { 249 if (simple) *simple = true; 250 return InsP.first->second = LI->createValueCopy(ParentVNI, 251 LIS.getVNInfoAllocator()); 252 } 253 254 // This was a simple mapped value. 255 if (InsP.first->second) { 256 if (simple) *simple = true; 257 return InsP.first->second; 258 } 259 260 // This is a complex mapped value. There may be multiple defs, and we may need 261 // to create phi-defs. 262 if (simple) *simple = false; 263 MachineBasicBlock *IdxMBB = LIS.getMBBFromIndex(Idx); 264 assert(IdxMBB && "No MBB at Idx"); 265 266 // Is there a def in the same MBB we can extend? 267 if (VNInfo *VNI = extendTo(IdxMBB, Idx)) 268 return VNI; 269 270 // Now for the fun part. We know that ParentVNI potentially has multiple defs, 271 // and we may need to create even more phi-defs to preserve VNInfo SSA form. 272 // Perform a search for all predecessor blocks where we know the dominating 273 // VNInfo. Insert phi-def VNInfos along the path back to IdxMBB. 274 DEBUG(dbgs() << "\n Reaching defs for BB#" << IdxMBB->getNumber() 275 << " at " << Idx << " in " << *LI << '\n'); 276 277 // Blocks where LI should be live-in. 278 SmallVector<MachineDomTreeNode*, 16> LiveIn; 279 LiveIn.push_back(MDT[IdxMBB]); 280 281 // Using LiveOutCache as a visited set, perform a BFS for all reaching defs. 282 for (unsigned i = 0; i != LiveIn.size(); ++i) { 283 MachineBasicBlock *MBB = LiveIn[i]->getBlock(); 284 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 285 PE = MBB->pred_end(); PI != PE; ++PI) { 286 MachineBasicBlock *Pred = *PI; 287 // Is this a known live-out block? 288 std::pair<LiveOutMap::iterator,bool> LOIP = 289 LiveOutCache.insert(std::make_pair(Pred, LiveOutPair())); 290 // Yes, we have been here before. 291 if (!LOIP.second) { 292 DEBUG(if (VNInfo *VNI = LOIP.first->second.first) 293 dbgs() << " known valno #" << VNI->id 294 << " at BB#" << Pred->getNumber() << '\n'); 295 continue; 296 } 297 298 // Does Pred provide a live-out value? 299 SlotIndex Last = LIS.getMBBEndIdx(Pred).getPrevSlot(); 300 if (VNInfo *VNI = extendTo(Pred, Last)) { 301 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(VNI->def); 302 DEBUG(dbgs() << " found valno #" << VNI->id 303 << " from BB#" << DefMBB->getNumber() 304 << " at BB#" << Pred->getNumber() << '\n'); 305 LiveOutPair &LOP = LOIP.first->second; 306 LOP.first = VNI; 307 LOP.second = MDT[DefMBB]; 308 continue; 309 } 310 // No, we need a live-in value for Pred as well 311 if (Pred != IdxMBB) 312 LiveIn.push_back(MDT[Pred]); 313 } 314 } 315 316 // We may need to add phi-def values to preserve the SSA form. 317 // This is essentially the same iterative algorithm that SSAUpdater uses, 318 // except we already have a dominator tree, so we don't have to recompute it. 319 VNInfo *IdxVNI = 0; 320 unsigned Changes; 321 do { 322 Changes = 0; 323 DEBUG(dbgs() << " Iterating over " << LiveIn.size() << " blocks.\n"); 324 // Propagate live-out values down the dominator tree, inserting phi-defs when 325 // necessary. Since LiveIn was created by a BFS, going backwards makes it more 326 // likely for us to visit immediate dominators before their children. 327 for (unsigned i = LiveIn.size(); i; --i) { 328 MachineDomTreeNode *Node = LiveIn[i-1]; 329 MachineBasicBlock *MBB = Node->getBlock(); 330 MachineDomTreeNode *IDom = Node->getIDom(); 331 LiveOutPair IDomValue; 332 // We need a live-in value to a block with no immediate dominator? 333 // This is probably an unreachable block that has survived somehow. 334 bool needPHI = !IDom; 335 336 // Get the IDom live-out value. 337 if (!needPHI) { 338 LiveOutMap::iterator I = LiveOutCache.find(IDom->getBlock()); 339 if (I != LiveOutCache.end()) 340 IDomValue = I->second; 341 else 342 // If IDom is outside our set of live-out blocks, there must be new 343 // defs, and we need a phi-def here. 344 needPHI = true; 345 } 346 347 // IDom dominates all of our predecessors, but it may not be the immediate 348 // dominator. Check if any of them have live-out values that are properly 349 // dominated by IDom. If so, we need a phi-def here. 350 if (!needPHI) { 351 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 352 PE = MBB->pred_end(); PI != PE; ++PI) { 353 LiveOutPair Value = LiveOutCache[*PI]; 354 if (!Value.first || Value.first == IDomValue.first) 355 continue; 356 // This predecessor is carrying something other than IDomValue. 357 // It could be because IDomValue hasn't propagated yet, or it could be 358 // because MBB is in the dominance frontier of that value. 359 if (MDT.dominates(IDom, Value.second)) { 360 needPHI = true; 361 break; 362 } 363 } 364 } 365 366 // Create a phi-def if required. 367 if (needPHI) { 368 ++Changes; 369 SlotIndex Start = LIS.getMBBStartIdx(MBB); 370 VNInfo *VNI = LI->getNextValue(Start, 0, LIS.getVNInfoAllocator()); 371 VNI->setIsPHIDef(true); 372 DEBUG(dbgs() << " - BB#" << MBB->getNumber() 373 << " phi-def #" << VNI->id << " at " << Start << '\n'); 374 // We no longer need LI to be live-in. 375 LiveIn.erase(LiveIn.begin()+(i-1)); 376 // Blocks in LiveIn are either IdxMBB, or have a value live-through. 377 if (MBB == IdxMBB) 378 IdxVNI = VNI; 379 // Check if we need to update live-out info. 380 LiveOutMap::iterator I = LiveOutCache.find(MBB); 381 if (I == LiveOutCache.end() || I->second.second == Node) { 382 // We already have a live-out defined in MBB, so this must be IdxMBB. 383 assert(MBB == IdxMBB && "Adding phi-def to known live-out"); 384 LI->addRange(LiveRange(Start, Idx.getNextSlot(), VNI)); 385 } else { 386 // This phi-def is also live-out, so color the whole block. 387 LI->addRange(LiveRange(Start, LIS.getMBBEndIdx(MBB), VNI)); 388 I->second = LiveOutPair(VNI, Node); 389 } 390 } else if (IDomValue.first) { 391 // No phi-def here. Remember incoming value for IdxMBB. 392 if (MBB == IdxMBB) 393 IdxVNI = IDomValue.first; 394 // Propagate IDomValue if needed: 395 // MBB is live-out and doesn't define its own value. 396 LiveOutMap::iterator I = LiveOutCache.find(MBB); 397 if (I != LiveOutCache.end() && I->second.second != Node && 398 I->second.first != IDomValue.first) { 399 ++Changes; 400 I->second = IDomValue; 401 DEBUG(dbgs() << " - BB#" << MBB->getNumber() 402 << " idom valno #" << IDomValue.first->id 403 << " from BB#" << IDom->getBlock()->getNumber() << '\n'); 404 } 405 } 406 } 407 DEBUG(dbgs() << " - made " << Changes << " changes.\n"); 408 } while (Changes); 409 410 assert(IdxVNI && "Didn't find value for Idx"); 411 412 #ifndef NDEBUG 413 // Check the LiveOutCache invariants. 414 for (LiveOutMap::iterator I = LiveOutCache.begin(), E = LiveOutCache.end(); 415 I != E; ++I) { 416 assert(I->first && "Null MBB entry in cache"); 417 assert(I->second.first && "Null VNInfo in cache"); 418 assert(I->second.second && "Null DomTreeNode in cache"); 419 if (I->second.second->getBlock() == I->first) 420 continue; 421 for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(), 422 PE = I->first->pred_end(); PI != PE; ++PI) 423 assert(LiveOutCache.lookup(*PI) == I->second && "Bad invariant"); 424 } 425 #endif 426 427 // Since we went through the trouble of a full BFS visiting all reaching defs, 428 // the values in LiveIn are now accurate. No more phi-defs are needed 429 // for these blocks, so we can color the live ranges. 430 // This makes the next mapValue call much faster. 431 for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) { 432 MachineBasicBlock *MBB = LiveIn[i]->getBlock(); 433 SlotIndex Start = LIS.getMBBStartIdx(MBB); 434 VNInfo *VNI = LiveOutCache.lookup(MBB).first; 435 436 // Anything in LiveIn other than IdxMBB is live-through. 437 // In IdxMBB, we should stop at Idx unless the same value is live-out. 438 if (MBB == IdxMBB && IdxVNI != VNI) 439 LI->addRange(LiveRange(Start, Idx.getNextSlot(), IdxVNI)); 440 else 441 LI->addRange(LiveRange(Start, LIS.getMBBEndIdx(MBB), VNI)); 442 } 443 444 return IdxVNI; 445 } 446 447 #ifndef NDEBUG 448 void LiveIntervalMap::dumpCache() { 449 for (LiveOutMap::iterator I = LiveOutCache.begin(), E = LiveOutCache.end(); 450 I != E; ++I) { 451 assert(I->first && "Null MBB entry in cache"); 452 assert(I->second.first && "Null VNInfo in cache"); 453 assert(I->second.second && "Null DomTreeNode in cache"); 454 dbgs() << " cache: BB#" << I->first->getNumber() 455 << " has valno #" << I->second.first->id << " from BB#" 456 << I->second.second->getBlock()->getNumber() << ", preds"; 457 for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(), 458 PE = I->first->pred_end(); PI != PE; ++PI) 459 dbgs() << " BB#" << (*PI)->getNumber(); 460 dbgs() << '\n'; 461 } 462 dbgs() << " cache: " << LiveOutCache.size() << " entries.\n"; 463 } 464 #endif 465 466 // extendTo - Find the last LI value defined in MBB at or before Idx. The 467 // ParentLI is assumed to be live at Idx. Extend the live range to Idx. 468 // Return the found VNInfo, or NULL. 469 VNInfo *LiveIntervalMap::extendTo(const MachineBasicBlock *MBB, SlotIndex Idx) { 470 assert(LI && "call reset first"); 471 LiveInterval::iterator I = std::upper_bound(LI->begin(), LI->end(), Idx); 472 if (I == LI->begin()) 473 return 0; 474 --I; 475 if (I->end <= LIS.getMBBStartIdx(MBB)) 476 return 0; 477 if (I->end <= Idx) 478 I->end = Idx.getNextSlot(); 479 return I->valno; 480 } 481 482 // addSimpleRange - Add a simple range from ParentLI to LI. 483 // ParentVNI must be live in the [Start;End) interval. 484 void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End, 485 const VNInfo *ParentVNI) { 486 assert(LI && "call reset first"); 487 bool simple; 488 VNInfo *VNI = mapValue(ParentVNI, Start, &simple); 489 // A simple mapping is easy. 490 if (simple) { 491 LI->addRange(LiveRange(Start, End, VNI)); 492 return; 493 } 494 495 // ParentVNI is a complex value. We must map per MBB. 496 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start); 497 MachineFunction::iterator MBBE = LIS.getMBBFromIndex(End.getPrevSlot()); 498 499 if (MBB == MBBE) { 500 LI->addRange(LiveRange(Start, End, VNI)); 501 return; 502 } 503 504 // First block. 505 LI->addRange(LiveRange(Start, LIS.getMBBEndIdx(MBB), VNI)); 506 507 // Run sequence of full blocks. 508 for (++MBB; MBB != MBBE; ++MBB) { 509 Start = LIS.getMBBStartIdx(MBB); 510 LI->addRange(LiveRange(Start, LIS.getMBBEndIdx(MBB), 511 mapValue(ParentVNI, Start))); 512 } 513 514 // Final block. 515 Start = LIS.getMBBStartIdx(MBB); 516 if (Start != End) 517 LI->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start))); 518 } 519 520 /// addRange - Add live ranges to LI where [Start;End) intersects ParentLI. 521 /// All needed values whose def is not inside [Start;End) must be defined 522 /// beforehand so mapValue will work. 523 void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) { 524 assert(LI && "call reset first"); 525 LiveInterval::const_iterator B = ParentLI.begin(), E = ParentLI.end(); 526 LiveInterval::const_iterator I = std::lower_bound(B, E, Start); 527 528 // Check if --I begins before Start and overlaps. 529 if (I != B) { 530 --I; 531 if (I->end > Start) 532 addSimpleRange(Start, std::min(End, I->end), I->valno); 533 ++I; 534 } 535 536 // The remaining ranges begin after Start. 537 for (;I != E && I->start < End; ++I) 538 addSimpleRange(I->start, std::min(End, I->end), I->valno); 539 } 540 541 542 //===----------------------------------------------------------------------===// 543 // Split Editor 544 //===----------------------------------------------------------------------===// 545 546 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA. 547 SplitEditor::SplitEditor(SplitAnalysis &sa, 548 LiveIntervals &lis, 549 VirtRegMap &vrm, 550 MachineDominatorTree &mdt, 551 LiveRangeEdit &edit) 552 : SA(sa), LIS(lis), VRM(vrm), 553 MRI(vrm.getMachineFunction().getRegInfo()), 554 MDT(mdt), 555 TII(*vrm.getMachineFunction().getTarget().getInstrInfo()), 556 TRI(*vrm.getMachineFunction().getTarget().getRegisterInfo()), 557 Edit(edit), 558 OpenIdx(0), 559 RegAssign(Allocator) 560 { 561 // We don't need an AliasAnalysis since we will only be performing 562 // cheap-as-a-copy remats anyway. 563 Edit.anyRematerializable(LIS, TII, 0); 564 } 565 566 void SplitEditor::dump() const { 567 if (RegAssign.empty()) { 568 dbgs() << " empty\n"; 569 return; 570 } 571 572 for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I) 573 dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value(); 574 dbgs() << '\n'; 575 } 576 577 VNInfo *SplitEditor::defFromParent(unsigned RegIdx, 578 VNInfo *ParentVNI, 579 SlotIndex UseIdx, 580 MachineBasicBlock &MBB, 581 MachineBasicBlock::iterator I) { 582 MachineInstr *CopyMI = 0; 583 SlotIndex Def; 584 LiveInterval *LI = Edit.get(RegIdx); 585 586 // Attempt cheap-as-a-copy rematerialization. 587 LiveRangeEdit::Remat RM(ParentVNI); 588 if (Edit.canRematerializeAt(RM, UseIdx, true, LIS)) { 589 Def = Edit.rematerializeAt(MBB, I, LI->reg, RM, LIS, TII, TRI); 590 } else { 591 // Can't remat, just insert a copy from parent. 592 CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg) 593 .addReg(Edit.getReg()); 594 Def = LIS.InsertMachineInstrInMaps(CopyMI).getDefIndex(); 595 } 596 597 // Define the value in Reg. 598 VNInfo *VNI = LIMappers[RegIdx].defValue(ParentVNI, Def); 599 VNI->setCopy(CopyMI); 600 601 // Add minimal liveness for the new value. 602 Edit.get(RegIdx)->addRange(LiveRange(Def, Def.getNextSlot(), VNI)); 603 return VNI; 604 } 605 606 /// Create a new virtual register and live interval. 607 void SplitEditor::openIntv() { 608 assert(!OpenIdx && "Previous LI not closed before openIntv"); 609 610 // Create the complement as index 0. 611 if (Edit.empty()) { 612 Edit.create(MRI, LIS, VRM); 613 LIMappers.push_back(LiveIntervalMap(LIS, MDT, Edit.getParent())); 614 LIMappers.back().reset(Edit.get(0)); 615 } 616 617 // Create the open interval. 618 OpenIdx = Edit.size(); 619 Edit.create(MRI, LIS, VRM); 620 LIMappers.push_back(LiveIntervalMap(LIS, MDT, Edit.getParent())); 621 LIMappers[OpenIdx].reset(Edit.get(OpenIdx)); 622 } 623 624 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) { 625 assert(OpenIdx && "openIntv not called before enterIntvBefore"); 626 DEBUG(dbgs() << " enterIntvBefore " << Idx); 627 Idx = Idx.getBaseIndex(); 628 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Idx); 629 if (!ParentVNI) { 630 DEBUG(dbgs() << ": not live\n"); 631 return Idx; 632 } 633 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 634 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 635 assert(MI && "enterIntvBefore called with invalid index"); 636 637 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI); 638 return VNI->def; 639 } 640 641 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) { 642 assert(OpenIdx && "openIntv not called before enterIntvAtEnd"); 643 SlotIndex End = LIS.getMBBEndIdx(&MBB); 644 SlotIndex Last = End.getPrevSlot(); 645 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << Last); 646 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Last); 647 if (!ParentVNI) { 648 DEBUG(dbgs() << ": not live\n"); 649 return End; 650 } 651 DEBUG(dbgs() << ": valno " << ParentVNI->id); 652 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB, 653 LIS.getLastSplitPoint(Edit.getParent(), &MBB)); 654 RegAssign.insert(VNI->def, End, OpenIdx); 655 DEBUG(dump()); 656 return VNI->def; 657 } 658 659 /// useIntv - indicate that all instructions in MBB should use OpenLI. 660 void SplitEditor::useIntv(const MachineBasicBlock &MBB) { 661 useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB)); 662 } 663 664 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) { 665 assert(OpenIdx && "openIntv not called before useIntv"); 666 DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):"); 667 RegAssign.insert(Start, End, OpenIdx); 668 DEBUG(dump()); 669 } 670 671 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) { 672 assert(OpenIdx && "openIntv not called before leaveIntvAfter"); 673 DEBUG(dbgs() << " leaveIntvAfter " << Idx); 674 675 // The interval must be live beyond the instruction at Idx. 676 Idx = Idx.getBoundaryIndex(); 677 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Idx); 678 if (!ParentVNI) { 679 DEBUG(dbgs() << ": not live\n"); 680 return Idx.getNextSlot(); 681 } 682 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 683 684 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 685 assert(MI && "No instruction at index"); 686 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), 687 llvm::next(MachineBasicBlock::iterator(MI))); 688 return VNI->def; 689 } 690 691 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) { 692 assert(OpenIdx && "openIntv not called before leaveIntvBefore"); 693 DEBUG(dbgs() << " leaveIntvBefore " << Idx); 694 695 // The interval must be live into the instruction at Idx. 696 Idx = Idx.getBoundaryIndex(); 697 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Idx); 698 if (!ParentVNI) { 699 DEBUG(dbgs() << ": not live\n"); 700 return Idx.getNextSlot(); 701 } 702 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 703 704 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 705 assert(MI && "No instruction at index"); 706 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); 707 return VNI->def; 708 } 709 710 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) { 711 assert(OpenIdx && "openIntv not called before leaveIntvAtTop"); 712 SlotIndex Start = LIS.getMBBStartIdx(&MBB); 713 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start); 714 715 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Start); 716 if (!ParentVNI) { 717 DEBUG(dbgs() << ": not live\n"); 718 return Start; 719 } 720 721 VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB, 722 MBB.SkipPHIsAndLabels(MBB.begin())); 723 RegAssign.insert(Start, VNI->def, OpenIdx); 724 DEBUG(dump()); 725 return VNI->def; 726 } 727 728 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) { 729 assert(OpenIdx && "openIntv not called before overlapIntv"); 730 assert(Edit.getParent().getVNInfoAt(Start) == 731 Edit.getParent().getVNInfoAt(End.getPrevSlot()) && 732 "Parent changes value in extended range"); 733 assert(Edit.get(0)->getVNInfoAt(Start) && "Start must come from leaveIntv*"); 734 assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) && 735 "Range cannot span basic blocks"); 736 737 // Treat this as useIntv() for now. The complement interval will be extended 738 // as needed by mapValue(). 739 DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):"); 740 RegAssign.insert(Start, End, OpenIdx); 741 DEBUG(dump()); 742 } 743 744 /// closeIntv - Indicate that we are done editing the currently open 745 /// LiveInterval, and ranges can be trimmed. 746 void SplitEditor::closeIntv() { 747 assert(OpenIdx && "openIntv not called before closeIntv"); 748 OpenIdx = 0; 749 } 750 751 /// rewriteAssigned - Rewrite all uses of Edit.getReg(). 752 void SplitEditor::rewriteAssigned() { 753 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit.getReg()), 754 RE = MRI.reg_end(); RI != RE;) { 755 MachineOperand &MO = RI.getOperand(); 756 MachineInstr *MI = MO.getParent(); 757 ++RI; 758 // LiveDebugVariables should have handled all DBG_VALUE instructions. 759 if (MI->isDebugValue()) { 760 DEBUG(dbgs() << "Zapping " << *MI); 761 MO.setReg(0); 762 continue; 763 } 764 765 // <undef> operands don't really read the register, so just assign them to 766 // the complement. 767 if (MO.isUse() && MO.isUndef()) { 768 MO.setReg(Edit.get(0)->reg); 769 continue; 770 } 771 772 SlotIndex Idx = LIS.getInstructionIndex(MI); 773 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex(); 774 775 // Rewrite to the mapped register at Idx. 776 unsigned RegIdx = RegAssign.lookup(Idx); 777 MO.setReg(Edit.get(RegIdx)->reg); 778 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t' 779 << Idx << ':' << RegIdx << '\t' << *MI); 780 781 // Extend liveness to Idx. 782 const VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Idx); 783 LIMappers[RegIdx].mapValue(ParentVNI, Idx); 784 } 785 } 786 787 /// rewriteSplit - Rewrite uses of Intvs[0] according to the ConEQ mapping. 788 void SplitEditor::rewriteComponents(const SmallVectorImpl<LiveInterval*> &Intvs, 789 const ConnectedVNInfoEqClasses &ConEq) { 790 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Intvs[0]->reg), 791 RE = MRI.reg_end(); RI != RE;) { 792 MachineOperand &MO = RI.getOperand(); 793 MachineInstr *MI = MO.getParent(); 794 ++RI; 795 if (MO.isUse() && MO.isUndef()) 796 continue; 797 // DBG_VALUE instructions should have been eliminated earlier. 798 SlotIndex Idx = LIS.getInstructionIndex(MI); 799 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex(); 800 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t' 801 << Idx << ':'); 802 const VNInfo *VNI = Intvs[0]->getVNInfoAt(Idx); 803 assert(VNI && "Interval not live at use."); 804 MO.setReg(Intvs[ConEq.getEqClass(VNI)]->reg); 805 DEBUG(dbgs() << VNI->id << '\t' << *MI); 806 } 807 } 808 809 void SplitEditor::finish() { 810 assert(OpenIdx == 0 && "Previous LI not closed before rewrite"); 811 812 // At this point, the live intervals in Edit contain VNInfos corresponding to 813 // the inserted copies. 814 815 // Add the original defs from the parent interval. 816 for (LiveInterval::const_vni_iterator I = Edit.getParent().vni_begin(), 817 E = Edit.getParent().vni_end(); I != E; ++I) { 818 const VNInfo *ParentVNI = *I; 819 if (ParentVNI->isUnused()) 820 continue; 821 LiveIntervalMap &LIM = LIMappers[RegAssign.lookup(ParentVNI->def)]; 822 VNInfo *VNI = LIM.defValue(ParentVNI, ParentVNI->def); 823 LIM.getLI()->addRange(LiveRange(ParentVNI->def, 824 ParentVNI->def.getNextSlot(), VNI)); 825 // Mark all values as complex to force liveness computation. 826 // This should really only be necessary for remat victims, but we are lazy. 827 LIM.markComplexMapped(ParentVNI); 828 } 829 830 #ifndef NDEBUG 831 // Every new interval must have a def by now, otherwise the split is bogus. 832 for (LiveRangeEdit::iterator I = Edit.begin(), E = Edit.end(); I != E; ++I) 833 assert((*I)->hasAtLeastOneValue() && "Split interval has no value"); 834 #endif 835 836 // FIXME: Don't recompute the liveness of all values, infer it from the 837 // overlaps between the parent live interval and RegAssign. 838 // The mapValue algorithm is only necessary when: 839 // - The parent value maps to multiple defs, and new phis are needed, or 840 // - The value has been rematerialized before some uses, and we want to 841 // minimize the live range so it only reaches the remaining uses. 842 // All other values have simple liveness that can be computed from RegAssign 843 // and the parent live interval. 844 845 // Extend live ranges to be live-out for successor PHI values. 846 for (LiveInterval::const_vni_iterator I = Edit.getParent().vni_begin(), 847 E = Edit.getParent().vni_end(); I != E; ++I) { 848 const VNInfo *PHIVNI = *I; 849 if (PHIVNI->isUnused() || !PHIVNI->isPHIDef()) 850 continue; 851 unsigned RegIdx = RegAssign.lookup(PHIVNI->def); 852 LiveIntervalMap &LIM = LIMappers[RegIdx]; 853 MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def); 854 DEBUG(dbgs() << " map phi in BB#" << MBB->getNumber() << '@' << PHIVNI->def 855 << " -> " << RegIdx << '\n'); 856 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 857 PE = MBB->pred_end(); PI != PE; ++PI) { 858 SlotIndex End = LIS.getMBBEndIdx(*PI).getPrevSlot(); 859 DEBUG(dbgs() << " pred BB#" << (*PI)->getNumber() << '@' << End); 860 // The predecessor may not have a live-out value. That is OK, like an 861 // undef PHI operand. 862 if (VNInfo *VNI = Edit.getParent().getVNInfoAt(End)) { 863 DEBUG(dbgs() << " has parent valno #" << VNI->id << " live out\n"); 864 assert(RegAssign.lookup(End) == RegIdx && 865 "Different register assignment in phi predecessor"); 866 LIM.mapValue(VNI, End); 867 } 868 else 869 DEBUG(dbgs() << " is not live-out\n"); 870 } 871 DEBUG(dbgs() << " " << *LIM.getLI() << '\n'); 872 } 873 874 // Rewrite instructions. 875 rewriteAssigned(); 876 877 // FIXME: Delete defs that were rematted everywhere. 878 879 // Get rid of unused values and set phi-kill flags. 880 for (LiveRangeEdit::iterator I = Edit.begin(), E = Edit.end(); I != E; ++I) 881 (*I)->RenumberValues(LIS); 882 883 // Now check if any registers were separated into multiple components. 884 ConnectedVNInfoEqClasses ConEQ(LIS); 885 for (unsigned i = 0, e = Edit.size(); i != e; ++i) { 886 // Don't use iterators, they are invalidated by create() below. 887 LiveInterval *li = Edit.get(i); 888 unsigned NumComp = ConEQ.Classify(li); 889 if (NumComp <= 1) 890 continue; 891 DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n'); 892 SmallVector<LiveInterval*, 8> dups; 893 dups.push_back(li); 894 for (unsigned i = 1; i != NumComp; ++i) 895 dups.push_back(&Edit.create(MRI, LIS, VRM)); 896 rewriteComponents(dups, ConEQ); 897 ConEQ.Distribute(&dups[0]); 898 } 899 900 // Calculate spill weight and allocation hints for new intervals. 901 VirtRegAuxInfo vrai(VRM.getMachineFunction(), LIS, SA.Loops); 902 for (LiveRangeEdit::iterator I = Edit.begin(), E = Edit.end(); I != E; ++I){ 903 LiveInterval &li = **I; 904 vrai.CalculateRegClass(li.reg); 905 vrai.CalculateWeightAndHint(li); 906 DEBUG(dbgs() << " new interval " << MRI.getRegClass(li.reg)->getName() 907 << ":" << li << '\n'); 908 } 909 } 910 911 912 //===----------------------------------------------------------------------===// 913 // Single Block Splitting 914 //===----------------------------------------------------------------------===// 915 916 /// getMultiUseBlocks - if CurLI has more than one use in a basic block, it 917 /// may be an advantage to split CurLI for the duration of the block. 918 bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) { 919 // If CurLI is local to one block, there is no point to splitting it. 920 if (LiveBlocks.size() <= 1) 921 return false; 922 // Add blocks with multiple uses. 923 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) { 924 const BlockInfo &BI = LiveBlocks[i]; 925 if (!BI.Uses) 926 continue; 927 unsigned Instrs = UsingBlocks.lookup(BI.MBB); 928 if (Instrs <= 1) 929 continue; 930 if (Instrs == 2 && BI.LiveIn && BI.LiveOut && !BI.LiveThrough) 931 continue; 932 Blocks.insert(BI.MBB); 933 } 934 return !Blocks.empty(); 935 } 936 937 /// splitSingleBlocks - Split CurLI into a separate live interval inside each 938 /// basic block in Blocks. 939 void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) { 940 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n"); 941 942 for (unsigned i = 0, e = SA.LiveBlocks.size(); i != e; ++i) { 943 const SplitAnalysis::BlockInfo &BI = SA.LiveBlocks[i]; 944 if (!BI.Uses || !Blocks.count(BI.MBB)) 945 continue; 946 947 openIntv(); 948 SlotIndex SegStart = enterIntvBefore(BI.FirstUse); 949 if (BI.LastUse < BI.LastSplitPoint) { 950 useIntv(SegStart, leaveIntvAfter(BI.LastUse)); 951 } else { 952 // THe last use os after tha last valid split point. 953 SlotIndex SegStop = leaveIntvBefore(BI.LastSplitPoint); 954 useIntv(SegStart, SegStop); 955 overlapIntv(SegStop, BI.LastUse); 956 } 957 closeIntv(); 958 } 959 finish(); 960 } 961 962 963 //===----------------------------------------------------------------------===// 964 // Sub Block Splitting 965 //===----------------------------------------------------------------------===// 966 967 /// getBlockForInsideSplit - If CurLI is contained inside a single basic block, 968 /// and it wou pay to subdivide the interval inside that block, return it. 969 /// Otherwise return NULL. The returned block can be passed to 970 /// SplitEditor::splitInsideBlock. 971 const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() { 972 // The interval must be exclusive to one block. 973 if (UsingBlocks.size() != 1) 974 return 0; 975 // Don't to this for less than 4 instructions. We want to be sure that 976 // splitting actually reduces the instruction count per interval. 977 if (UsingInstrs.size() < 4) 978 return 0; 979 return UsingBlocks.begin()->first; 980 } 981 982 /// splitInsideBlock - Split CurLI into multiple intervals inside MBB. 983 void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) { 984 SmallVector<SlotIndex, 32> Uses; 985 Uses.reserve(SA.UsingInstrs.size()); 986 for (SplitAnalysis::InstrPtrSet::const_iterator I = SA.UsingInstrs.begin(), 987 E = SA.UsingInstrs.end(); I != E; ++I) 988 if ((*I)->getParent() == MBB) 989 Uses.push_back(LIS.getInstructionIndex(*I)); 990 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for " 991 << Uses.size() << " instructions.\n"); 992 assert(Uses.size() >= 3 && "Need at least 3 instructions"); 993 array_pod_sort(Uses.begin(), Uses.end()); 994 995 // Simple algorithm: Find the largest gap between uses as determined by slot 996 // indices. Create new intervals for instructions before the gap and after the 997 // gap. 998 unsigned bestPos = 0; 999 int bestGap = 0; 1000 DEBUG(dbgs() << " dist (" << Uses[0]); 1001 for (unsigned i = 1, e = Uses.size(); i != e; ++i) { 1002 int g = Uses[i-1].distance(Uses[i]); 1003 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]); 1004 if (g > bestGap) 1005 bestPos = i, bestGap = g; 1006 } 1007 DEBUG(dbgs() << "), best: -" << bestGap << "-\n"); 1008 1009 // bestPos points to the first use after the best gap. 1010 assert(bestPos > 0 && "Invalid gap"); 1011 1012 // FIXME: Don't create intervals for low densities. 1013 1014 // First interval before the gap. Don't create single-instr intervals. 1015 if (bestPos > 1) { 1016 openIntv(); 1017 useIntv(enterIntvBefore(Uses.front()), leaveIntvAfter(Uses[bestPos-1])); 1018 closeIntv(); 1019 } 1020 1021 // Second interval after the gap. 1022 if (bestPos < Uses.size()-1) { 1023 openIntv(); 1024 useIntv(enterIntvBefore(Uses[bestPos]), leaveIntvAfter(Uses.back())); 1025 closeIntv(); 1026 } 1027 1028 finish(); 1029 } 1030