SplitKit.cpp revision b5f327b30f048b989c6f08d3bf84568d541b7644
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/MachineLoopInfo.h" 24#include "llvm/CodeGen/MachineRegisterInfo.h" 25#include "llvm/Support/CommandLine.h" 26#include "llvm/Support/Debug.h" 27#include "llvm/Support/raw_ostream.h" 28#include "llvm/Target/TargetInstrInfo.h" 29#include "llvm/Target/TargetMachine.h" 30 31using namespace llvm; 32 33static cl::opt<bool> 34AllowSplit("spiller-splits-edges", 35 cl::desc("Allow critical edge splitting during spilling")); 36 37//===----------------------------------------------------------------------===// 38// Split Analysis 39//===----------------------------------------------------------------------===// 40 41SplitAnalysis::SplitAnalysis(const MachineFunction &mf, 42 const LiveIntervals &lis, 43 const MachineLoopInfo &mli) 44 : mf_(mf), 45 lis_(lis), 46 loops_(mli), 47 tii_(*mf.getTarget().getInstrInfo()), 48 curli_(0) {} 49 50void SplitAnalysis::clear() { 51 usingInstrs_.clear(); 52 usingBlocks_.clear(); 53 usingLoops_.clear(); 54 curli_ = 0; 55} 56 57bool 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. 64void SplitAnalysis::analyzeUses() { 65 const MachineRegisterInfo &MRI = mf_.getRegInfo(); 66 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg); 67 MachineInstr *MI = I.skipInstruction();) { 68 if (MI->isDebugValue() || !usingInstrs_.insert(MI)) 69 continue; 70 MachineBasicBlock *MBB = MI->getParent(); 71 if (usingBlocks_[MBB]++) 72 continue; 73 for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop; 74 Loop = Loop->getParentLoop()) 75 usingLoops_[Loop]++; 76 } 77 DEBUG(dbgs() << " counted " 78 << usingInstrs_.size() << " instrs, " 79 << usingBlocks_.size() << " blocks, " 80 << usingLoops_.size() << " loops.\n"); 81} 82 83void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const { 84 for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) { 85 unsigned count = usingBlocks_.lookup(*I); 86 OS << " BB#" << (*I)->getNumber(); 87 if (count) 88 OS << '(' << count << ')'; 89 } 90} 91 92// Get three sets of basic blocks surrounding a loop: Blocks inside the loop, 93// predecessor blocks, and exit blocks. 94void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) { 95 Blocks.clear(); 96 97 // Blocks in the loop. 98 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end()); 99 100 // Predecessor blocks. 101 const MachineBasicBlock *Header = Loop->getHeader(); 102 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(), 103 E = Header->pred_end(); I != E; ++I) 104 if (!Blocks.Loop.count(*I)) 105 Blocks.Preds.insert(*I); 106 107 // Exit blocks. 108 for (MachineLoop::block_iterator I = Loop->block_begin(), 109 E = Loop->block_end(); I != E; ++I) { 110 const MachineBasicBlock *MBB = *I; 111 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(), 112 SE = MBB->succ_end(); SI != SE; ++SI) 113 if (!Blocks.Loop.count(*SI)) 114 Blocks.Exits.insert(*SI); 115 } 116} 117 118void SplitAnalysis::print(const LoopBlocks &B, raw_ostream &OS) const { 119 OS << "Loop:"; 120 print(B.Loop, OS); 121 OS << ", preds:"; 122 print(B.Preds, OS); 123 OS << ", exits:"; 124 print(B.Exits, OS); 125} 126 127/// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in 128/// and around the Loop. 129SplitAnalysis::LoopPeripheralUse SplitAnalysis:: 130analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) { 131 LoopPeripheralUse use = ContainedInLoop; 132 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end(); 133 I != E; ++I) { 134 const MachineBasicBlock *MBB = I->first; 135 // Is this a peripheral block? 136 if (use < MultiPeripheral && 137 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) { 138 if (I->second > 1) use = MultiPeripheral; 139 else use = SinglePeripheral; 140 continue; 141 } 142 // Is it a loop block? 143 if (Blocks.Loop.count(MBB)) 144 continue; 145 // It must be an unrelated block. 146 DEBUG(dbgs() << ", outside: BB#" << MBB->getNumber()); 147 return OutsideLoop; 148 } 149 return use; 150} 151 152/// getCriticalExits - It may be necessary to partially break critical edges 153/// leaving the loop if an exit block has predecessors from outside the loop 154/// periphery. 155void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks, 156 BlockPtrSet &CriticalExits) { 157 CriticalExits.clear(); 158 159 // A critical exit block has curli live-in, and has a predecessor that is not 160 // in the loop nor a loop predecessor. For such an exit block, the edges 161 // carrying the new variable must be moved to a new pre-exit block. 162 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end(); 163 I != E; ++I) { 164 const MachineBasicBlock *Exit = *I; 165 // A single-predecessor exit block is definitely not a critical edge. 166 if (Exit->pred_size() == 1) 167 continue; 168 // This exit may not have curli live in at all. No need to split. 169 if (!lis_.isLiveInToMBB(*curli_, Exit)) 170 continue; 171 // Does this exit block have a predecessor that is not a loop block or loop 172 // predecessor? 173 for (MachineBasicBlock::const_pred_iterator PI = Exit->pred_begin(), 174 PE = Exit->pred_end(); PI != PE; ++PI) { 175 const MachineBasicBlock *Pred = *PI; 176 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred)) 177 continue; 178 // This is a critical exit block, and we need to split the exit edge. 179 CriticalExits.insert(Exit); 180 break; 181 } 182 } 183} 184 185void SplitAnalysis::getCriticalPreds(const SplitAnalysis::LoopBlocks &Blocks, 186 BlockPtrSet &CriticalPreds) { 187 CriticalPreds.clear(); 188 189 // A critical predecessor block has curli live-out, and has a successor that 190 // has curli live-in and is not in the loop nor a loop exit block. For such a 191 // predecessor block, we must carry the value in both the 'inside' and 192 // 'outside' registers. 193 for (BlockPtrSet::iterator I = Blocks.Preds.begin(), E = Blocks.Preds.end(); 194 I != E; ++I) { 195 const MachineBasicBlock *Pred = *I; 196 // Definitely not a critical edge. 197 if (Pred->succ_size() == 1) 198 continue; 199 // This block may not have curli live out at all if there is a PHI. 200 if (!lis_.isLiveOutOfMBB(*curli_, Pred)) 201 continue; 202 // Does this block have a successor outside the loop? 203 for (MachineBasicBlock::const_pred_iterator SI = Pred->succ_begin(), 204 SE = Pred->succ_end(); SI != SE; ++SI) { 205 const MachineBasicBlock *Succ = *SI; 206 if (Blocks.Loop.count(Succ) || Blocks.Exits.count(Succ)) 207 continue; 208 if (!lis_.isLiveInToMBB(*curli_, Succ)) 209 continue; 210 // This is a critical predecessor block. 211 CriticalPreds.insert(Pred); 212 break; 213 } 214 } 215} 216 217/// canSplitCriticalExits - Return true if it is possible to insert new exit 218/// blocks before the blocks in CriticalExits. 219bool 220SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks, 221 BlockPtrSet &CriticalExits) { 222 // If we don't allow critical edge splitting, require no critical exits. 223 if (!AllowSplit) 224 return CriticalExits.empty(); 225 226 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end(); 227 I != E; ++I) { 228 const MachineBasicBlock *Succ = *I; 229 // We want to insert a new pre-exit MBB before Succ, and change all the 230 // in-loop blocks to branch to the pre-exit instead of Succ. 231 // Check that all the in-loop predecessors can be changed. 232 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(), 233 PE = Succ->pred_end(); PI != PE; ++PI) { 234 const MachineBasicBlock *Pred = *PI; 235 // The external predecessors won't be altered. 236 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred)) 237 continue; 238 if (!canAnalyzeBranch(Pred)) 239 return false; 240 } 241 242 // If Succ's layout predecessor falls through, that too must be analyzable. 243 // We need to insert the pre-exit block in the gap. 244 MachineFunction::const_iterator MFI = Succ; 245 if (MFI == mf_.begin()) 246 continue; 247 if (!canAnalyzeBranch(--MFI)) 248 return false; 249 } 250 // No problems found. 251 return true; 252} 253 254void SplitAnalysis::analyze(const LiveInterval *li) { 255 clear(); 256 curli_ = li; 257 analyzeUses(); 258} 259 260const MachineLoop *SplitAnalysis::getBestSplitLoop() { 261 assert(curli_ && "Call analyze() before getBestSplitLoop"); 262 if (usingLoops_.empty()) 263 return 0; 264 265 LoopPtrSet Loops; 266 LoopBlocks Blocks; 267 BlockPtrSet CriticalExits; 268 269 // We split around loops where curli is used outside the periphery. 270 for (LoopCountMap::const_iterator I = usingLoops_.begin(), 271 E = usingLoops_.end(); I != E; ++I) { 272 const MachineLoop *Loop = I->first; 273 getLoopBlocks(Loop, Blocks); 274 DEBUG({ dbgs() << " "; print(Blocks, dbgs()); }); 275 276 switch(analyzeLoopPeripheralUse(Blocks)) { 277 case OutsideLoop: 278 break; 279 case MultiPeripheral: 280 // FIXME: We could split a live range with multiple uses in a peripheral 281 // block and still make progress. However, it is possible that splitting 282 // another live range will insert copies into a peripheral block, and 283 // there is a small chance we can enter an infinity loop, inserting copies 284 // forever. 285 // For safety, stick to splitting live ranges with uses outside the 286 // periphery. 287 DEBUG(dbgs() << ": multiple peripheral uses\n"); 288 break; 289 case ContainedInLoop: 290 DEBUG(dbgs() << ": fully contained\n"); 291 continue; 292 case SinglePeripheral: 293 DEBUG(dbgs() << ": single peripheral use\n"); 294 continue; 295 } 296 // Will it be possible to split around this loop? 297 getCriticalExits(Blocks, CriticalExits); 298 DEBUG(dbgs() << ": " << CriticalExits.size() << " critical exits\n"); 299 if (!canSplitCriticalExits(Blocks, CriticalExits)) 300 continue; 301 // This is a possible split. 302 Loops.insert(Loop); 303 } 304 305 DEBUG(dbgs() << " getBestSplitLoop found " << Loops.size() 306 << " candidate loops.\n"); 307 308 if (Loops.empty()) 309 return 0; 310 311 // Pick the earliest loop. 312 // FIXME: Are there other heuristics to consider? 313 const MachineLoop *Best = 0; 314 SlotIndex BestIdx; 315 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E; 316 ++I) { 317 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader()); 318 if (!Best || Idx < BestIdx) 319 Best = *I, BestIdx = Idx; 320 } 321 DEBUG(dbgs() << " getBestSplitLoop found " << *Best); 322 return Best; 323} 324 325//===----------------------------------------------------------------------===// 326// LiveIntervalMap 327//===----------------------------------------------------------------------===// 328 329// Work around the fact that the std::pair constructors are broken for pointer 330// pairs in some implementations. makeVV(x, 0) works. 331static inline std::pair<const VNInfo*, VNInfo*> 332makeVV(const VNInfo *a, VNInfo *b) { 333 return std::make_pair(a, b); 334} 335 336void LiveIntervalMap::reset(LiveInterval *li) { 337 li_ = li; 338 valueMap_.clear(); 339 liveOutCache_.clear(); 340} 341 342bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const { 343 ValueMap::const_iterator i = valueMap_.find(ParentVNI); 344 return i != valueMap_.end() && i->second == 0; 345} 346 347// defValue - Introduce a li_ def for ParentVNI that could be later than 348// ParentVNI->def. 349VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) { 350 assert(li_ && "call reset first"); 351 assert(ParentVNI && "Mapping NULL value"); 352 assert(Idx.isValid() && "Invalid SlotIndex"); 353 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI"); 354 355 // Create a new value. 356 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator()); 357 358 // Preserve the PHIDef bit. 359 if (ParentVNI->isPHIDef() && Idx == ParentVNI->def) 360 VNI->setIsPHIDef(true); 361 362 // Use insert for lookup, so we can add missing values with a second lookup. 363 std::pair<ValueMap::iterator,bool> InsP = 364 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0)); 365 366 // This is now a complex def. Mark with a NULL in valueMap. 367 if (!InsP.second) 368 InsP.first->second = 0; 369 370 return VNI; 371} 372 373 374// mapValue - Find the mapped value for ParentVNI at Idx. 375// Potentially create phi-def values. 376VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx, 377 bool *simple) { 378 assert(li_ && "call reset first"); 379 assert(ParentVNI && "Mapping NULL value"); 380 assert(Idx.isValid() && "Invalid SlotIndex"); 381 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI"); 382 383 // Use insert for lookup, so we can add missing values with a second lookup. 384 std::pair<ValueMap::iterator,bool> InsP = 385 valueMap_.insert(makeVV(ParentVNI, 0)); 386 387 // This was an unknown value. Create a simple mapping. 388 if (InsP.second) { 389 if (simple) *simple = true; 390 return InsP.first->second = li_->createValueCopy(ParentVNI, 391 lis_.getVNInfoAllocator()); 392 } 393 394 // This was a simple mapped value. 395 if (InsP.first->second) { 396 if (simple) *simple = true; 397 return InsP.first->second; 398 } 399 400 // This is a complex mapped value. There may be multiple defs, and we may need 401 // to create phi-defs. 402 if (simple) *simple = false; 403 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx); 404 assert(IdxMBB && "No MBB at Idx"); 405 406 // Is there a def in the same MBB we can extend? 407 if (VNInfo *VNI = extendTo(IdxMBB, Idx)) 408 return VNI; 409 410 // Now for the fun part. We know that ParentVNI potentially has multiple defs, 411 // and we may need to create even more phi-defs to preserve VNInfo SSA form. 412 // Perform a search for all predecessor blocks where we know the dominating 413 // VNInfo. Insert phi-def VNInfos along the path back to IdxMBB. 414 DEBUG(dbgs() << "\n Reaching defs for BB#" << IdxMBB->getNumber() 415 << " at " << Idx << " in " << *li_ << '\n'); 416 417 // Blocks where li_ should be live-in. 418 SmallVector<MachineDomTreeNode*, 16> LiveIn; 419 LiveIn.push_back(mdt_[IdxMBB]); 420 421 // Using liveOutCache_ as a visited set, perform a BFS for all reaching defs. 422 for (unsigned i = 0; i != LiveIn.size(); ++i) { 423 MachineBasicBlock *MBB = LiveIn[i]->getBlock(); 424 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 425 PE = MBB->pred_end(); PI != PE; ++PI) { 426 MachineBasicBlock *Pred = *PI; 427 // Is this a known live-out block? 428 std::pair<LiveOutMap::iterator,bool> LOIP = 429 liveOutCache_.insert(std::make_pair(Pred, LiveOutPair())); 430 // Yes, we have been here before. 431 if (!LOIP.second) { 432 DEBUG(if (VNInfo *VNI = LOIP.first->second.first) 433 dbgs() << " known valno #" << VNI->id 434 << " at BB#" << Pred->getNumber() << '\n'); 435 continue; 436 } 437 438 // Does Pred provide a live-out value? 439 SlotIndex Last = lis_.getMBBEndIdx(Pred).getPrevSlot(); 440 if (VNInfo *VNI = extendTo(Pred, Last)) { 441 MachineBasicBlock *DefMBB = lis_.getMBBFromIndex(VNI->def); 442 DEBUG(dbgs() << " found valno #" << VNI->id 443 << " from BB#" << DefMBB->getNumber() 444 << " at BB#" << Pred->getNumber() << '\n'); 445 LiveOutPair &LOP = LOIP.first->second; 446 LOP.first = VNI; 447 LOP.second = mdt_[DefMBB]; 448 continue; 449 } 450 // No, we need a live-in value for Pred as well 451 if (Pred != IdxMBB) 452 LiveIn.push_back(mdt_[Pred]); 453 } 454 } 455 456 // We may need to add phi-def values to preserve the SSA form. 457 // This is essentially the same iterative algorithm that SSAUpdater uses, 458 // except we already have a dominator tree, so we don't have to recompute it. 459 VNInfo *IdxVNI = 0; 460 unsigned Changes; 461 do { 462 Changes = 0; 463 DEBUG(dbgs() << " Iterating over " << LiveIn.size() << " blocks.\n"); 464 // Propagate live-out values down the dominator tree, inserting phi-defs when 465 // necessary. Since LiveIn was created by a BFS, going backwards makes it more 466 // likely for us to visit immediate dominators before their children. 467 for (unsigned i = LiveIn.size(); i; --i) { 468 MachineDomTreeNode *Node = LiveIn[i-1]; 469 MachineBasicBlock *MBB = Node->getBlock(); 470 MachineDomTreeNode *IDom = Node->getIDom(); 471 LiveOutPair IDomValue; 472 // We need a live-in value to a block with no immediate dominator? 473 // This is probably an unreachable block that has survived somehow. 474 bool needPHI = !IDom; 475 476 // Get the IDom live-out value. 477 if (!needPHI) { 478 LiveOutMap::iterator I = liveOutCache_.find(IDom->getBlock()); 479 if (I != liveOutCache_.end()) 480 IDomValue = I->second; 481 else 482 // If IDom is outside our set of live-out blocks, there must be new 483 // defs, and we need a phi-def here. 484 needPHI = true; 485 } 486 487 // IDom dominates all of our predecessors, but it may not be the immediate 488 // dominator. Check if any of them have live-out values that are properly 489 // dominated by IDom. If so, we need a phi-def here. 490 if (!needPHI) { 491 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 492 PE = MBB->pred_end(); PI != PE; ++PI) { 493 LiveOutPair Value = liveOutCache_[*PI]; 494 if (!Value.first || Value.first == IDomValue.first) 495 continue; 496 // This predecessor is carrying something other than IDomValue. 497 // It could be because IDomValue hasn't propagated yet, or it could be 498 // because MBB is in the dominance frontier of that value. 499 if (mdt_.dominates(IDom, Value.second)) { 500 needPHI = true; 501 break; 502 } 503 } 504 } 505 506 // Create a phi-def if required. 507 if (needPHI) { 508 ++Changes; 509 SlotIndex Start = lis_.getMBBStartIdx(MBB); 510 VNInfo *VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator()); 511 VNI->setIsPHIDef(true); 512 DEBUG(dbgs() << " - BB#" << MBB->getNumber() 513 << " phi-def #" << VNI->id << " at " << Start << '\n'); 514 // We no longer need li_ to be live-in. 515 LiveIn.erase(LiveIn.begin()+(i-1)); 516 // Blocks in LiveIn are either IdxMBB, or have a value live-through. 517 if (MBB == IdxMBB) 518 IdxVNI = VNI; 519 // Check if we need to update live-out info. 520 LiveOutMap::iterator I = liveOutCache_.find(MBB); 521 if (I == liveOutCache_.end() || I->second.second == Node) { 522 // We already have a live-out defined in MBB, so this must be IdxMBB. 523 assert(MBB == IdxMBB && "Adding phi-def to known live-out"); 524 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI)); 525 } else { 526 // This phi-def is also live-out, so color the whole block. 527 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI)); 528 I->second = LiveOutPair(VNI, Node); 529 } 530 } else if (IDomValue.first) { 531 // No phi-def here. Remember incoming value for IdxMBB. 532 if (MBB == IdxMBB) 533 IdxVNI = IDomValue.first; 534 // Propagate IDomValue if needed: 535 // MBB is live-out and doesn't define its own value. 536 LiveOutMap::iterator I = liveOutCache_.find(MBB); 537 if (I != liveOutCache_.end() && I->second.second != Node && 538 I->second.first != IDomValue.first) { 539 ++Changes; 540 I->second = IDomValue; 541 DEBUG(dbgs() << " - BB#" << MBB->getNumber() 542 << " idom valno #" << IDomValue.first->id 543 << " from BB#" << IDom->getBlock()->getNumber() << '\n'); 544 } 545 } 546 } 547 DEBUG(dbgs() << " - made " << Changes << " changes.\n"); 548 } while (Changes); 549 550 assert(IdxVNI && "Didn't find value for Idx"); 551 552#ifndef NDEBUG 553 // Check the liveOutCache_ invariants. 554 for (LiveOutMap::iterator I = liveOutCache_.begin(), E = liveOutCache_.end(); 555 I != E; ++I) { 556 assert(I->first && "Null MBB entry in cache"); 557 assert(I->second.first && "Null VNInfo in cache"); 558 assert(I->second.second && "Null DomTreeNode in cache"); 559 if (I->second.second->getBlock() == I->first) 560 continue; 561 for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(), 562 PE = I->first->pred_end(); PI != PE; ++PI) 563 assert(liveOutCache_.lookup(*PI) == I->second && "Bad invariant"); 564 } 565#endif 566 567 // Since we went through the trouble of a full BFS visiting all reaching defs, 568 // the values in LiveIn are now accurate. No more phi-defs are needed 569 // for these blocks, so we can color the live ranges. 570 // This makes the next mapValue call much faster. 571 for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) { 572 MachineBasicBlock *MBB = LiveIn[i]->getBlock(); 573 SlotIndex Start = lis_.getMBBStartIdx(MBB); 574 if (MBB == IdxMBB) { 575 li_->addRange(LiveRange(Start, Idx.getNextSlot(), IdxVNI)); 576 continue; 577 } 578 // Anything in LiveIn other than IdxMBB is live-through. 579 VNInfo *VNI = liveOutCache_.lookup(MBB).first; 580 assert(VNI && "Missing block value"); 581 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI)); 582 } 583 584 return IdxVNI; 585} 586 587// extendTo - Find the last li_ value defined in MBB at or before Idx. The 588// parentli_ is assumed to be live at Idx. Extend the live range to Idx. 589// Return the found VNInfo, or NULL. 590VNInfo *LiveIntervalMap::extendTo(const MachineBasicBlock *MBB, SlotIndex Idx) { 591 assert(li_ && "call reset first"); 592 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx); 593 if (I == li_->begin()) 594 return 0; 595 --I; 596 if (I->end <= lis_.getMBBStartIdx(MBB)) 597 return 0; 598 if (I->end <= Idx) 599 I->end = Idx.getNextSlot(); 600 return I->valno; 601} 602 603// addSimpleRange - Add a simple range from parentli_ to li_. 604// ParentVNI must be live in the [Start;End) interval. 605void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End, 606 const VNInfo *ParentVNI) { 607 assert(li_ && "call reset first"); 608 bool simple; 609 VNInfo *VNI = mapValue(ParentVNI, Start, &simple); 610 // A simple mapping is easy. 611 if (simple) { 612 li_->addRange(LiveRange(Start, End, VNI)); 613 return; 614 } 615 616 // ParentVNI is a complex value. We must map per MBB. 617 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start); 618 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot()); 619 620 if (MBB == MBBE) { 621 li_->addRange(LiveRange(Start, End, VNI)); 622 return; 623 } 624 625 // First block. 626 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI)); 627 628 // Run sequence of full blocks. 629 for (++MBB; MBB != MBBE; ++MBB) { 630 Start = lis_.getMBBStartIdx(MBB); 631 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), 632 mapValue(ParentVNI, Start))); 633 } 634 635 // Final block. 636 Start = lis_.getMBBStartIdx(MBB); 637 if (Start != End) 638 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start))); 639} 640 641/// addRange - Add live ranges to li_ where [Start;End) intersects parentli_. 642/// All needed values whose def is not inside [Start;End) must be defined 643/// beforehand so mapValue will work. 644void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) { 645 assert(li_ && "call reset first"); 646 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end(); 647 LiveInterval::const_iterator I = std::lower_bound(B, E, Start); 648 649 // Check if --I begins before Start and overlaps. 650 if (I != B) { 651 --I; 652 if (I->end > Start) 653 addSimpleRange(Start, std::min(End, I->end), I->valno); 654 ++I; 655 } 656 657 // The remaining ranges begin after Start. 658 for (;I != E && I->start < End; ++I) 659 addSimpleRange(I->start, std::min(End, I->end), I->valno); 660} 661 662 663//===----------------------------------------------------------------------===// 664// Split Editor 665//===----------------------------------------------------------------------===// 666 667/// Create a new SplitEditor for editing the LiveInterval analyzed by SA. 668SplitEditor::SplitEditor(SplitAnalysis &sa, 669 LiveIntervals &lis, 670 VirtRegMap &vrm, 671 MachineDominatorTree &mdt, 672 LiveRangeEdit &edit) 673 : sa_(sa), lis_(lis), vrm_(vrm), 674 mri_(vrm.getMachineFunction().getRegInfo()), 675 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()), 676 tri_(*vrm.getMachineFunction().getTarget().getRegisterInfo()), 677 edit_(edit), 678 dupli_(lis_, mdt, edit.getParent()), 679 openli_(lis_, mdt, edit.getParent()) 680{ 681 // We don't need an AliasAnalysis since we will only be performing 682 // cheap-as-a-copy remats anyway. 683 edit_.anyRematerializable(lis_, tii_, 0); 684} 685 686bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const { 687 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I) 688 if (*I != dupli_.getLI() && (*I)->liveAt(Idx)) 689 return true; 690 return false; 691} 692 693VNInfo *SplitEditor::defFromParent(LiveIntervalMap &Reg, 694 VNInfo *ParentVNI, 695 SlotIndex UseIdx, 696 MachineBasicBlock &MBB, 697 MachineBasicBlock::iterator I) { 698 VNInfo *VNI = 0; 699 MachineInstr *CopyMI = 0; 700 SlotIndex Def; 701 702 // Attempt cheap-as-a-copy rematerialization. 703 LiveRangeEdit::Remat RM(ParentVNI); 704 if (edit_.canRematerializeAt(RM, UseIdx, true, lis_)) { 705 Def = edit_.rematerializeAt(MBB, I, Reg.getLI()->reg, RM, 706 lis_, tii_, tri_); 707 } else { 708 // Can't remat, just insert a copy from parent. 709 CopyMI = BuildMI(MBB, I, DebugLoc(), tii_.get(TargetOpcode::COPY), 710 Reg.getLI()->reg).addReg(edit_.getReg()); 711 Def = lis_.InsertMachineInstrInMaps(CopyMI).getDefIndex(); 712 } 713 714 // Define the value in Reg. 715 VNI = Reg.defValue(ParentVNI, Def); 716 VNI->setCopy(CopyMI); 717 718 // Add minimal liveness for the new value. 719 if (UseIdx < Def) 720 UseIdx = Def; 721 Reg.getLI()->addRange(LiveRange(Def, UseIdx.getNextSlot(), VNI)); 722 return VNI; 723} 724 725/// Create a new virtual register and live interval. 726void SplitEditor::openIntv() { 727 assert(!openli_.getLI() && "Previous LI not closed before openIntv"); 728 if (!dupli_.getLI()) 729 dupli_.reset(&edit_.create(mri_, lis_, vrm_)); 730 731 openli_.reset(&edit_.create(mri_, lis_, vrm_)); 732} 733 734/// enterIntvBefore - Enter openli before the instruction at Idx. If curli is 735/// not live before Idx, a COPY is not inserted. 736void SplitEditor::enterIntvBefore(SlotIndex Idx) { 737 assert(openli_.getLI() && "openIntv not called before enterIntvBefore"); 738 Idx = Idx.getUseIndex(); 739 DEBUG(dbgs() << " enterIntvBefore " << Idx); 740 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx); 741 if (!ParentVNI) { 742 DEBUG(dbgs() << ": not live\n"); 743 return; 744 } 745 DEBUG(dbgs() << ": valno " << ParentVNI->id); 746 truncatedValues.insert(ParentVNI); 747 MachineInstr *MI = lis_.getInstructionFromIndex(Idx); 748 assert(MI && "enterIntvBefore called with invalid index"); 749 750 defFromParent(openli_, ParentVNI, Idx, *MI->getParent(), MI); 751 752 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n'); 753} 754 755/// enterIntvAtEnd - Enter openli at the end of MBB. 756void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) { 757 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd"); 758 SlotIndex End = lis_.getMBBEndIdx(&MBB).getPrevSlot(); 759 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End); 760 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(End); 761 if (!ParentVNI) { 762 DEBUG(dbgs() << ": not live\n"); 763 return; 764 } 765 DEBUG(dbgs() << ": valno " << ParentVNI->id); 766 truncatedValues.insert(ParentVNI); 767 defFromParent(openli_, ParentVNI, End, MBB, MBB.getFirstTerminator()); 768 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n'); 769} 770 771/// useIntv - indicate that all instructions in MBB should use openli. 772void SplitEditor::useIntv(const MachineBasicBlock &MBB) { 773 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB)); 774} 775 776void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) { 777 assert(openli_.getLI() && "openIntv not called before useIntv"); 778 openli_.addRange(Start, End); 779 DEBUG(dbgs() << " use [" << Start << ';' << End << "): " 780 << *openli_.getLI() << '\n'); 781} 782 783/// leaveIntvAfter - Leave openli after the instruction at Idx. 784void SplitEditor::leaveIntvAfter(SlotIndex Idx) { 785 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter"); 786 DEBUG(dbgs() << " leaveIntvAfter " << Idx); 787 788 // The interval must be live beyond the instruction at Idx. 789 Idx = Idx.getBoundaryIndex(); 790 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx); 791 if (!ParentVNI) { 792 DEBUG(dbgs() << ": not live\n"); 793 return; 794 } 795 DEBUG(dbgs() << ": valno " << ParentVNI->id); 796 797 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx); 798 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Idx, 799 *MII->getParent(), llvm::next(MII)); 800 801 // Make sure that openli is properly extended from Idx to the new copy. 802 // FIXME: This shouldn't be necessary for remats. 803 openli_.addSimpleRange(Idx, VNI->def, ParentVNI); 804 805 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n'); 806} 807 808/// leaveIntvAtTop - Leave the interval at the top of MBB. 809/// Currently, only one value can leave the interval. 810void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) { 811 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop"); 812 SlotIndex Start = lis_.getMBBStartIdx(&MBB); 813 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start); 814 815 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Start); 816 if (!ParentVNI) { 817 DEBUG(dbgs() << ": not live\n"); 818 return; 819 } 820 821 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Start, MBB, 822 MBB.SkipPHIsAndLabels(MBB.begin())); 823 824 // Finally we must make sure that openli is properly extended from Start to 825 // the new copy. 826 openli_.addSimpleRange(Start, VNI->def, ParentVNI); 827 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n'); 828} 829 830/// closeIntv - Indicate that we are done editing the currently open 831/// LiveInterval, and ranges can be trimmed. 832void SplitEditor::closeIntv() { 833 assert(openli_.getLI() && "openIntv not called before closeIntv"); 834 835 DEBUG(dbgs() << " closeIntv cleaning up\n"); 836 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n'); 837 openli_.reset(0); 838} 839 840/// rewrite - Rewrite all uses of reg to use the new registers. 841void SplitEditor::rewrite(unsigned reg) { 842 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg), 843 RE = mri_.reg_end(); RI != RE;) { 844 MachineOperand &MO = RI.getOperand(); 845 unsigned OpNum = RI.getOperandNo(); 846 MachineInstr *MI = MO.getParent(); 847 ++RI; 848 if (MI->isDebugValue()) { 849 DEBUG(dbgs() << "Zapping " << *MI); 850 // FIXME: We can do much better with debug values. 851 MO.setReg(0); 852 continue; 853 } 854 SlotIndex Idx = lis_.getInstructionIndex(MI); 855 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex(); 856 LiveInterval *LI = 0; 857 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; 858 ++I) { 859 LiveInterval *testli = *I; 860 if (testli->liveAt(Idx)) { 861 LI = testli; 862 break; 863 } 864 } 865 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'<< Idx); 866 assert(LI && "No register was live at use"); 867 MO.setReg(LI->reg); 868 if (MO.isUse() && !MI->isRegTiedToDefOperand(OpNum)) 869 MO.setIsKill(LI->killedAt(Idx.getDefIndex())); 870 DEBUG(dbgs() << '\t' << *MI); 871 } 872} 873 874void 875SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) { 876 // Build vector of iterator pairs from the intervals. 877 typedef std::pair<LiveInterval::const_iterator, 878 LiveInterval::const_iterator> IIPair; 879 SmallVector<IIPair, 8> Iters; 880 for (LiveRangeEdit::iterator LI = edit_.begin(), LE = edit_.end(); LI != LE; 881 ++LI) { 882 if (*LI == dupli_.getLI()) 883 continue; 884 LiveInterval::const_iterator I = (*LI)->find(Start); 885 LiveInterval::const_iterator E = (*LI)->end(); 886 if (I != E) 887 Iters.push_back(std::make_pair(I, E)); 888 } 889 890 SlotIndex sidx = Start; 891 // Break [Start;End) into segments that don't overlap any intervals. 892 for (;;) { 893 SlotIndex next = sidx, eidx = End; 894 // Find overlapping intervals. 895 for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) { 896 LiveInterval::const_iterator I = Iters[i].first; 897 // Interval I is overlapping [sidx;eidx). Trim sidx. 898 if (I->start <= sidx) { 899 sidx = I->end; 900 // Move to the next run, remove iters when all are consumed. 901 I = ++Iters[i].first; 902 if (I == Iters[i].second) { 903 Iters.erase(Iters.begin() + i); 904 --i; 905 continue; 906 } 907 } 908 // Trim eidx too if needed. 909 if (I->start >= eidx) 910 continue; 911 eidx = I->start; 912 next = I->end; 913 } 914 // Now, [sidx;eidx) doesn't overlap anything in intervals_. 915 if (sidx < eidx) 916 dupli_.addSimpleRange(sidx, eidx, VNI); 917 // If the interval end was truncated, we can try again from next. 918 if (next <= sidx) 919 break; 920 sidx = next; 921 } 922} 923 924void SplitEditor::computeRemainder() { 925 // First we need to fill in the live ranges in dupli. 926 // If values were redefined, we need a full recoloring with SSA update. 927 // If values were truncated, we only need to truncate the ranges. 928 // If values were partially rematted, we should shrink to uses. 929 // If values were fully rematted, they should be omitted. 930 // FIXME: If a single value is redefined, just move the def and truncate. 931 LiveInterval &parent = edit_.getParent(); 932 933 // Values that are fully contained in the split intervals. 934 SmallPtrSet<const VNInfo*, 8> deadValues; 935 // Map all curli values that should have live defs in dupli. 936 for (LiveInterval::const_vni_iterator I = parent.vni_begin(), 937 E = parent.vni_end(); I != E; ++I) { 938 const VNInfo *VNI = *I; 939 // Don't transfer unused values to the new intervals. 940 if (VNI->isUnused()) 941 continue; 942 // Original def is contained in the split intervals. 943 if (intervalsLiveAt(VNI->def)) { 944 // Did this value escape? 945 if (dupli_.isMapped(VNI)) 946 truncatedValues.insert(VNI); 947 else 948 deadValues.insert(VNI); 949 continue; 950 } 951 // Add minimal live range at the definition. 952 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def); 953 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI)); 954 } 955 956 // Add all ranges to dupli. 957 for (LiveInterval::const_iterator I = parent.begin(), E = parent.end(); 958 I != E; ++I) { 959 const LiveRange &LR = *I; 960 if (truncatedValues.count(LR.valno)) { 961 // recolor after removing intervals_. 962 addTruncSimpleRange(LR.start, LR.end, LR.valno); 963 } else if (!deadValues.count(LR.valno)) { 964 // recolor without truncation. 965 dupli_.addSimpleRange(LR.start, LR.end, LR.valno); 966 } 967 } 968 969 // Extend dupli_ to be live out of any critical loop predecessors. 970 // This means we have multiple registers live out of those blocks. 971 // The alternative would be to split the critical edges. 972 if (criticalPreds_.empty()) 973 return; 974 for (SplitAnalysis::BlockPtrSet::iterator I = criticalPreds_.begin(), 975 E = criticalPreds_.end(); I != E; ++I) 976 dupli_.extendTo(*I, lis_.getMBBEndIdx(*I).getPrevSlot()); 977 criticalPreds_.clear(); 978} 979 980void SplitEditor::finish() { 981 assert(!openli_.getLI() && "Previous LI not closed before rewrite"); 982 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?"); 983 984 // Complete dupli liveness. 985 computeRemainder(); 986 987 // Get rid of unused values and set phi-kill flags. 988 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I) 989 (*I)->RenumberValues(lis_); 990 991 // Rewrite instructions. 992 rewrite(edit_.getReg()); 993 994 // Now check if any registers were separated into multiple components. 995 ConnectedVNInfoEqClasses ConEQ(lis_); 996 for (unsigned i = 0, e = edit_.size(); i != e; ++i) { 997 // Don't use iterators, they are invalidated by create() below. 998 LiveInterval *li = edit_.get(i); 999 unsigned NumComp = ConEQ.Classify(li); 1000 if (NumComp <= 1) 1001 continue; 1002 DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n'); 1003 SmallVector<LiveInterval*, 8> dups; 1004 dups.push_back(li); 1005 for (unsigned i = 1; i != NumComp; ++i) 1006 dups.push_back(&edit_.create(mri_, lis_, vrm_)); 1007 ConEQ.Distribute(&dups[0]); 1008 // Rewrite uses to the new regs. 1009 rewrite(li->reg); 1010 } 1011 1012 // Calculate spill weight and allocation hints for new intervals. 1013 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_); 1014 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I){ 1015 LiveInterval &li = **I; 1016 vrai.CalculateRegClass(li.reg); 1017 vrai.CalculateWeightAndHint(li); 1018 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName() 1019 << ":" << li << '\n'); 1020 } 1021} 1022 1023 1024//===----------------------------------------------------------------------===// 1025// Loop Splitting 1026//===----------------------------------------------------------------------===// 1027 1028void SplitEditor::splitAroundLoop(const MachineLoop *Loop) { 1029 SplitAnalysis::LoopBlocks Blocks; 1030 sa_.getLoopBlocks(Loop, Blocks); 1031 1032 DEBUG({ 1033 dbgs() << " splitAround"; sa_.print(Blocks, dbgs()); dbgs() << '\n'; 1034 }); 1035 1036 // Break critical edges as needed. 1037 SplitAnalysis::BlockPtrSet CriticalExits; 1038 sa_.getCriticalExits(Blocks, CriticalExits); 1039 assert(CriticalExits.empty() && "Cannot break critical exits yet"); 1040 1041 // Get critical predecessors so computeRemainder can deal with them. 1042 sa_.getCriticalPreds(Blocks, criticalPreds_); 1043 1044 // Create new live interval for the loop. 1045 openIntv(); 1046 1047 // Insert copies in the predecessors. 1048 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(), 1049 E = Blocks.Preds.end(); I != E; ++I) { 1050 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I); 1051 enterIntvAtEnd(MBB); 1052 } 1053 1054 // Switch all loop blocks. 1055 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(), 1056 E = Blocks.Loop.end(); I != E; ++I) 1057 useIntv(**I); 1058 1059 // Insert back copies in the exit blocks. 1060 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(), 1061 E = Blocks.Exits.end(); I != E; ++I) { 1062 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I); 1063 leaveIntvAtTop(MBB); 1064 } 1065 1066 // Done. 1067 closeIntv(); 1068 finish(); 1069} 1070 1071 1072//===----------------------------------------------------------------------===// 1073// Single Block Splitting 1074//===----------------------------------------------------------------------===// 1075 1076/// getMultiUseBlocks - if curli has more than one use in a basic block, it 1077/// may be an advantage to split curli for the duration of the block. 1078bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) { 1079 // If curli is local to one block, there is no point to splitting it. 1080 if (usingBlocks_.size() <= 1) 1081 return false; 1082 // Add blocks with multiple uses. 1083 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end(); 1084 I != E; ++I) 1085 switch (I->second) { 1086 case 0: 1087 case 1: 1088 continue; 1089 case 2: { 1090 // When there are only two uses and curli is both live in and live out, 1091 // we don't really win anything by isolating the block since we would be 1092 // inserting two copies. 1093 // The remaing register would still have two uses in the block. (Unless it 1094 // separates into disconnected components). 1095 if (lis_.isLiveInToMBB(*curli_, I->first) && 1096 lis_.isLiveOutOfMBB(*curli_, I->first)) 1097 continue; 1098 } // Fall through. 1099 default: 1100 Blocks.insert(I->first); 1101 } 1102 return !Blocks.empty(); 1103} 1104 1105/// splitSingleBlocks - Split curli into a separate live interval inside each 1106/// basic block in Blocks. 1107void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) { 1108 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n"); 1109 // Determine the first and last instruction using curli in each block. 1110 typedef std::pair<SlotIndex,SlotIndex> IndexPair; 1111 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap; 1112 IndexPairMap MBBRange; 1113 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(), 1114 E = sa_.usingInstrs_.end(); I != E; ++I) { 1115 const MachineBasicBlock *MBB = (*I)->getParent(); 1116 if (!Blocks.count(MBB)) 1117 continue; 1118 SlotIndex Idx = lis_.getInstructionIndex(*I); 1119 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I); 1120 IndexPair &IP = MBBRange[MBB]; 1121 if (!IP.first.isValid() || Idx < IP.first) 1122 IP.first = Idx; 1123 if (!IP.second.isValid() || Idx > IP.second) 1124 IP.second = Idx; 1125 } 1126 1127 // Create a new interval for each block. 1128 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(), 1129 E = Blocks.end(); I != E; ++I) { 1130 IndexPair &IP = MBBRange[*I]; 1131 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": [" 1132 << IP.first << ';' << IP.second << ")\n"); 1133 assert(IP.first.isValid() && IP.second.isValid()); 1134 1135 openIntv(); 1136 enterIntvBefore(IP.first); 1137 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex()); 1138 leaveIntvAfter(IP.second); 1139 closeIntv(); 1140 } 1141 finish(); 1142} 1143 1144 1145//===----------------------------------------------------------------------===// 1146// Sub Block Splitting 1147//===----------------------------------------------------------------------===// 1148 1149/// getBlockForInsideSplit - If curli is contained inside a single basic block, 1150/// and it wou pay to subdivide the interval inside that block, return it. 1151/// Otherwise return NULL. The returned block can be passed to 1152/// SplitEditor::splitInsideBlock. 1153const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() { 1154 // The interval must be exclusive to one block. 1155 if (usingBlocks_.size() != 1) 1156 return 0; 1157 // Don't to this for less than 4 instructions. We want to be sure that 1158 // splitting actually reduces the instruction count per interval. 1159 if (usingInstrs_.size() < 4) 1160 return 0; 1161 return usingBlocks_.begin()->first; 1162} 1163 1164/// splitInsideBlock - Split curli into multiple intervals inside MBB. 1165void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) { 1166 SmallVector<SlotIndex, 32> Uses; 1167 Uses.reserve(sa_.usingInstrs_.size()); 1168 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(), 1169 E = sa_.usingInstrs_.end(); I != E; ++I) 1170 if ((*I)->getParent() == MBB) 1171 Uses.push_back(lis_.getInstructionIndex(*I)); 1172 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for " 1173 << Uses.size() << " instructions.\n"); 1174 assert(Uses.size() >= 3 && "Need at least 3 instructions"); 1175 array_pod_sort(Uses.begin(), Uses.end()); 1176 1177 // Simple algorithm: Find the largest gap between uses as determined by slot 1178 // indices. Create new intervals for instructions before the gap and after the 1179 // gap. 1180 unsigned bestPos = 0; 1181 int bestGap = 0; 1182 DEBUG(dbgs() << " dist (" << Uses[0]); 1183 for (unsigned i = 1, e = Uses.size(); i != e; ++i) { 1184 int g = Uses[i-1].distance(Uses[i]); 1185 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]); 1186 if (g > bestGap) 1187 bestPos = i, bestGap = g; 1188 } 1189 DEBUG(dbgs() << "), best: -" << bestGap << "-\n"); 1190 1191 // bestPos points to the first use after the best gap. 1192 assert(bestPos > 0 && "Invalid gap"); 1193 1194 // FIXME: Don't create intervals for low densities. 1195 1196 // First interval before the gap. Don't create single-instr intervals. 1197 if (bestPos > 1) { 1198 openIntv(); 1199 enterIntvBefore(Uses.front()); 1200 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex()); 1201 leaveIntvAfter(Uses[bestPos-1]); 1202 closeIntv(); 1203 } 1204 1205 // Second interval after the gap. 1206 if (bestPos < Uses.size()-1) { 1207 openIntv(); 1208 enterIntvBefore(Uses[bestPos]); 1209 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex()); 1210 leaveIntvAfter(Uses.back()); 1211 closeIntv(); 1212 } 1213 1214 finish(); 1215} 1216