1 //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the SplitAnalysis class as well as mutator functions for
11 // live range splitting.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
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/GraphWriter.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
35 AllowSplit("spiller-splits-edges",
36 cl::desc("Allow critical edge splitting during spilling"));
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 /// compute - Compute the edge bundles for MF. Bundles depend only on the CFG.
43 void EdgeBundles::compute(const MachineFunction *mf) {
46 EC.grow(2 * MF->size());
48 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
50 const MachineBasicBlock &MBB = *I;
51 unsigned OutE = 2 * MBB.getNumber() + 1;
52 // Join the outgoing bundle with the ingoing bundles of all successors.
53 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
54 SE = MBB.succ_end(); SI != SE; ++SI)
55 EC.join(OutE, 2 * (*SI)->getNumber());
60 /// view - Visualize the annotated bipartite CFG with Graphviz.
61 void EdgeBundles::view() const {
62 ViewGraph(*this, "EdgeBundles");
65 /// Specialize WriteGraph, the standard implementation won't work.
66 raw_ostream &llvm::WriteGraph(raw_ostream &O, const EdgeBundles &G,
68 const std::string &Title) {
69 const MachineFunction *MF = G.getMachineFunction();
72 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
74 unsigned BB = I->getNumber();
75 O << "\t\"BB#" << BB << "\" [ shape=box ]\n"
76 << '\t' << G.getBundle(BB, false) << " -> \"BB#" << BB << "\"\n"
77 << "\t\"BB#" << BB << "\" -> " << G.getBundle(BB, true) << '\n';
78 for (MachineBasicBlock::const_succ_iterator SI = I->succ_begin(),
79 SE = I->succ_end(); SI != SE; ++SI)
80 O << "\t\"BB#" << BB << "\" -> \"BB#" << (*SI)->getNumber()
81 << "\" [ color=lightgray ]\n";
88 //===----------------------------------------------------------------------===//
90 //===----------------------------------------------------------------------===//
92 SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
93 const LiveIntervals &lis,
94 const MachineLoopInfo &mli)
98 tii_(*mf.getTarget().getInstrInfo()),
101 void SplitAnalysis::clear() {
102 usingInstrs_.clear();
103 usingBlocks_.clear();
108 bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
109 MachineBasicBlock *T, *F;
110 SmallVector<MachineOperand, 4> Cond;
111 return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
114 /// analyzeUses - Count instructions, basic blocks, and loops using curli.
115 void SplitAnalysis::analyzeUses() {
116 const MachineRegisterInfo &MRI = mf_.getRegInfo();
117 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
118 MachineInstr *MI = I.skipInstruction();) {
119 if (MI->isDebugValue() || !usingInstrs_.insert(MI))
121 MachineBasicBlock *MBB = MI->getParent();
122 if (usingBlocks_[MBB]++)
124 for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop;
125 Loop = Loop->getParentLoop())
128 DEBUG(dbgs() << " counted "
129 << usingInstrs_.size() << " instrs, "
130 << usingBlocks_.size() << " blocks, "
131 << usingLoops_.size() << " loops.\n");
134 void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const {
135 for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) {
136 unsigned count = usingBlocks_.lookup(*I);
137 OS << " BB#" << (*I)->getNumber();
139 OS << '(' << count << ')';
143 // Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
144 // predecessor blocks, and exit blocks.
145 void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
148 // Blocks in the loop.
149 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
151 // Predecessor blocks.
152 const MachineBasicBlock *Header = Loop->getHeader();
153 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
154 E = Header->pred_end(); I != E; ++I)
155 if (!Blocks.Loop.count(*I))
156 Blocks.Preds.insert(*I);
159 for (MachineLoop::block_iterator I = Loop->block_begin(),
160 E = Loop->block_end(); I != E; ++I) {
161 const MachineBasicBlock *MBB = *I;
162 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
163 SE = MBB->succ_end(); SI != SE; ++SI)
164 if (!Blocks.Loop.count(*SI))
165 Blocks.Exits.insert(*SI);
169 void SplitAnalysis::print(const LoopBlocks &B, raw_ostream &OS) const {
178 /// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
179 /// and around the Loop.
180 SplitAnalysis::LoopPeripheralUse SplitAnalysis::
181 analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
182 LoopPeripheralUse use = ContainedInLoop;
183 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
185 const MachineBasicBlock *MBB = I->first;
186 // Is this a peripheral block?
187 if (use < MultiPeripheral &&
188 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
189 if (I->second > 1) use = MultiPeripheral;
190 else use = SinglePeripheral;
193 // Is it a loop block?
194 if (Blocks.Loop.count(MBB))
196 // It must be an unrelated block.
197 DEBUG(dbgs() << ", outside: BB#" << MBB->getNumber());
203 /// getCriticalExits - It may be necessary to partially break critical edges
204 /// leaving the loop if an exit block has predecessors from outside the loop
206 void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
207 BlockPtrSet &CriticalExits) {
208 CriticalExits.clear();
210 // A critical exit block has curli live-in, and has a predecessor that is not
211 // in the loop nor a loop predecessor. For such an exit block, the edges
212 // carrying the new variable must be moved to a new pre-exit block.
213 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
215 const MachineBasicBlock *Exit = *I;
216 // A single-predecessor exit block is definitely not a critical edge.
217 if (Exit->pred_size() == 1)
219 // This exit may not have curli live in at all. No need to split.
220 if (!lis_.isLiveInToMBB(*curli_, Exit))
222 // Does this exit block have a predecessor that is not a loop block or loop
224 for (MachineBasicBlock::const_pred_iterator PI = Exit->pred_begin(),
225 PE = Exit->pred_end(); PI != PE; ++PI) {
226 const MachineBasicBlock *Pred = *PI;
227 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
229 // This is a critical exit block, and we need to split the exit edge.
230 CriticalExits.insert(Exit);
236 void SplitAnalysis::getCriticalPreds(const SplitAnalysis::LoopBlocks &Blocks,
237 BlockPtrSet &CriticalPreds) {
238 CriticalPreds.clear();
240 // A critical predecessor block has curli live-out, and has a successor that
241 // has curli live-in and is not in the loop nor a loop exit block. For such a
242 // predecessor block, we must carry the value in both the 'inside' and
243 // 'outside' registers.
244 for (BlockPtrSet::iterator I = Blocks.Preds.begin(), E = Blocks.Preds.end();
246 const MachineBasicBlock *Pred = *I;
247 // Definitely not a critical edge.
248 if (Pred->succ_size() == 1)
250 // This block may not have curli live out at all if there is a PHI.
251 if (!lis_.isLiveOutOfMBB(*curli_, Pred))
253 // Does this block have a successor outside the loop?
254 for (MachineBasicBlock::const_pred_iterator SI = Pred->succ_begin(),
255 SE = Pred->succ_end(); SI != SE; ++SI) {
256 const MachineBasicBlock *Succ = *SI;
257 if (Blocks.Loop.count(Succ) || Blocks.Exits.count(Succ))
259 if (!lis_.isLiveInToMBB(*curli_, Succ))
261 // This is a critical predecessor block.
262 CriticalPreds.insert(Pred);
268 /// canSplitCriticalExits - Return true if it is possible to insert new exit
269 /// blocks before the blocks in CriticalExits.
271 SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
272 BlockPtrSet &CriticalExits) {
273 // If we don't allow critical edge splitting, require no critical exits.
275 return CriticalExits.empty();
277 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
279 const MachineBasicBlock *Succ = *I;
280 // We want to insert a new pre-exit MBB before Succ, and change all the
281 // in-loop blocks to branch to the pre-exit instead of Succ.
282 // Check that all the in-loop predecessors can be changed.
283 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
284 PE = Succ->pred_end(); PI != PE; ++PI) {
285 const MachineBasicBlock *Pred = *PI;
286 // The external predecessors won't be altered.
287 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
289 if (!canAnalyzeBranch(Pred))
293 // If Succ's layout predecessor falls through, that too must be analyzable.
294 // We need to insert the pre-exit block in the gap.
295 MachineFunction::const_iterator MFI = Succ;
296 if (MFI == mf_.begin())
298 if (!canAnalyzeBranch(--MFI))
301 // No problems found.
305 void SplitAnalysis::analyze(const LiveInterval *li) {
311 void SplitAnalysis::getSplitLoops(LoopPtrSet &Loops) {
312 assert(curli_ && "Call analyze() before getSplitLoops");
313 if (usingLoops_.empty())
317 BlockPtrSet CriticalExits;
319 // We split around loops where curli is used outside the periphery.
320 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
321 E = usingLoops_.end(); I != E; ++I) {
322 const MachineLoop *Loop = I->first;
323 getLoopBlocks(Loop, Blocks);
324 DEBUG({ dbgs() << " "; print(Blocks, dbgs()); });
326 switch(analyzeLoopPeripheralUse(Blocks)) {
329 case MultiPeripheral:
330 // FIXME: We could split a live range with multiple uses in a peripheral
331 // block and still make progress. However, it is possible that splitting
332 // another live range will insert copies into a peripheral block, and
333 // there is a small chance we can enter an infinite loop, inserting copies
335 // For safety, stick to splitting live ranges with uses outside the
337 DEBUG(dbgs() << ": multiple peripheral uses");
339 case ContainedInLoop:
340 DEBUG(dbgs() << ": fully contained\n");
342 case SinglePeripheral:
343 DEBUG(dbgs() << ": single peripheral use\n");
346 // Will it be possible to split around this loop?
347 getCriticalExits(Blocks, CriticalExits);
348 DEBUG(dbgs() << ": " << CriticalExits.size() << " critical exits\n");
349 if (!canSplitCriticalExits(Blocks, CriticalExits))
351 // This is a possible split.
355 DEBUG(dbgs() << " getSplitLoops found " << Loops.size()
356 << " candidate loops.\n");
359 const MachineLoop *SplitAnalysis::getBestSplitLoop() {
361 getSplitLoops(Loops);
365 // Pick the earliest loop.
366 // FIXME: Are there other heuristics to consider?
367 const MachineLoop *Best = 0;
369 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
371 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
372 if (!Best || Idx < BestIdx)
373 Best = *I, BestIdx = Idx;
375 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
379 /// isBypassLoop - Return true if curli is live through Loop and has no uses
380 /// inside the loop. Bypass loops are candidates for splitting because it can
381 /// prevent interference inside the loop.
382 bool SplitAnalysis::isBypassLoop(const MachineLoop *Loop) {
383 // If curli is live into the loop header and there are no uses in the loop, it
384 // must be live in the entire loop and live on at least one exiting edge.
385 return !usingLoops_.count(Loop) &&
386 lis_.isLiveInToMBB(*curli_, Loop->getHeader());
389 /// getBypassLoops - Get all the maximal bypass loops. These are the bypass
390 /// loops whose parent is not a bypass loop.
391 void SplitAnalysis::getBypassLoops(LoopPtrSet &BypassLoops) {
392 SmallVector<MachineLoop*, 8> Todo(loops_.begin(), loops_.end());
393 while (!Todo.empty()) {
394 MachineLoop *Loop = Todo.pop_back_val();
395 if (!usingLoops_.count(Loop)) {
396 // This is either a bypass loop or completely irrelevant.
397 if (lis_.isLiveInToMBB(*curli_, Loop->getHeader()))
398 BypassLoops.insert(Loop);
399 // Either way, skip the child loops.
403 // The child loops may be bypass loops.
404 Todo.append(Loop->begin(), Loop->end());
409 //===----------------------------------------------------------------------===//
411 //===----------------------------------------------------------------------===//
413 // Work around the fact that the std::pair constructors are broken for pointer
414 // pairs in some implementations. makeVV(x, 0) works.
415 static inline std::pair<const VNInfo*, VNInfo*>
416 makeVV(const VNInfo *a, VNInfo *b) {
417 return std::make_pair(a, b);
420 void LiveIntervalMap::reset(LiveInterval *li) {
423 liveOutCache_.clear();
426 bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
427 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
428 return i != valueMap_.end() && i->second == 0;
431 // defValue - Introduce a li_ def for ParentVNI that could be later than
433 VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
434 assert(li_ && "call reset first");
435 assert(ParentVNI && "Mapping NULL value");
436 assert(Idx.isValid() && "Invalid SlotIndex");
437 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
439 // Create a new value.
440 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
442 // Preserve the PHIDef bit.
443 if (ParentVNI->isPHIDef() && Idx == ParentVNI->def)
444 VNI->setIsPHIDef(true);
446 // Use insert for lookup, so we can add missing values with a second lookup.
447 std::pair<ValueMap::iterator,bool> InsP =
448 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
450 // This is now a complex def. Mark with a NULL in valueMap.
452 InsP.first->second = 0;
458 // mapValue - Find the mapped value for ParentVNI at Idx.
459 // Potentially create phi-def values.
460 VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
462 assert(li_ && "call reset first");
463 assert(ParentVNI && "Mapping NULL value");
464 assert(Idx.isValid() && "Invalid SlotIndex");
465 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
467 // Use insert for lookup, so we can add missing values with a second lookup.
468 std::pair<ValueMap::iterator,bool> InsP =
469 valueMap_.insert(makeVV(ParentVNI, 0));
471 // This was an unknown value. Create a simple mapping.
473 if (simple) *simple = true;
474 return InsP.first->second = li_->createValueCopy(ParentVNI,
475 lis_.getVNInfoAllocator());
478 // This was a simple mapped value.
479 if (InsP.first->second) {
480 if (simple) *simple = true;
481 return InsP.first->second;
484 // This is a complex mapped value. There may be multiple defs, and we may need
485 // to create phi-defs.
486 if (simple) *simple = false;
487 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
488 assert(IdxMBB && "No MBB at Idx");
490 // Is there a def in the same MBB we can extend?
491 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
494 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
495 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
496 // Perform a search for all predecessor blocks where we know the dominating
497 // VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
498 DEBUG(dbgs() << "\n Reaching defs for BB#" << IdxMBB->getNumber()
499 << " at " << Idx << " in " << *li_ << '\n');
501 // Blocks where li_ should be live-in.
502 SmallVector<MachineDomTreeNode*, 16> LiveIn;
503 LiveIn.push_back(mdt_[IdxMBB]);
505 // Using liveOutCache_ as a visited set, perform a BFS for all reaching defs.
506 for (unsigned i = 0; i != LiveIn.size(); ++i) {
507 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
508 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
509 PE = MBB->pred_end(); PI != PE; ++PI) {
510 MachineBasicBlock *Pred = *PI;
511 // Is this a known live-out block?
512 std::pair<LiveOutMap::iterator,bool> LOIP =
513 liveOutCache_.insert(std::make_pair(Pred, LiveOutPair()));
514 // Yes, we have been here before.
516 DEBUG(if (VNInfo *VNI = LOIP.first->second.first)
517 dbgs() << " known valno #" << VNI->id
518 << " at BB#" << Pred->getNumber() << '\n');
522 // Does Pred provide a live-out value?
523 SlotIndex Last = lis_.getMBBEndIdx(Pred).getPrevSlot();
524 if (VNInfo *VNI = extendTo(Pred, Last)) {
525 MachineBasicBlock *DefMBB = lis_.getMBBFromIndex(VNI->def);
526 DEBUG(dbgs() << " found valno #" << VNI->id
527 << " from BB#" << DefMBB->getNumber()
528 << " at BB#" << Pred->getNumber() << '\n');
529 LiveOutPair &LOP = LOIP.first->second;
531 LOP.second = mdt_[DefMBB];
534 // No, we need a live-in value for Pred as well
536 LiveIn.push_back(mdt_[Pred]);
540 // We may need to add phi-def values to preserve the SSA form.
541 // This is essentially the same iterative algorithm that SSAUpdater uses,
542 // except we already have a dominator tree, so we don't have to recompute it.
547 DEBUG(dbgs() << " Iterating over " << LiveIn.size() << " blocks.\n");
548 // Propagate live-out values down the dominator tree, inserting phi-defs when
549 // necessary. Since LiveIn was created by a BFS, going backwards makes it more
550 // likely for us to visit immediate dominators before their children.
551 for (unsigned i = LiveIn.size(); i; --i) {
552 MachineDomTreeNode *Node = LiveIn[i-1];
553 MachineBasicBlock *MBB = Node->getBlock();
554 MachineDomTreeNode *IDom = Node->getIDom();
555 LiveOutPair IDomValue;
556 // We need a live-in value to a block with no immediate dominator?
557 // This is probably an unreachable block that has survived somehow.
558 bool needPHI = !IDom;
560 // Get the IDom live-out value.
562 LiveOutMap::iterator I = liveOutCache_.find(IDom->getBlock());
563 if (I != liveOutCache_.end())
564 IDomValue = I->second;
566 // If IDom is outside our set of live-out blocks, there must be new
567 // defs, and we need a phi-def here.
571 // IDom dominates all of our predecessors, but it may not be the immediate
572 // dominator. Check if any of them have live-out values that are properly
573 // dominated by IDom. If so, we need a phi-def here.
575 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
576 PE = MBB->pred_end(); PI != PE; ++PI) {
577 LiveOutPair Value = liveOutCache_[*PI];
578 if (!Value.first || Value.first == IDomValue.first)
580 // This predecessor is carrying something other than IDomValue.
581 // It could be because IDomValue hasn't propagated yet, or it could be
582 // because MBB is in the dominance frontier of that value.
583 if (mdt_.dominates(IDom, Value.second)) {
590 // Create a phi-def if required.
593 SlotIndex Start = lis_.getMBBStartIdx(MBB);
594 VNInfo *VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
595 VNI->setIsPHIDef(true);
596 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
597 << " phi-def #" << VNI->id << " at " << Start << '\n');
598 // We no longer need li_ to be live-in.
599 LiveIn.erase(LiveIn.begin()+(i-1));
600 // Blocks in LiveIn are either IdxMBB, or have a value live-through.
603 // Check if we need to update live-out info.
604 LiveOutMap::iterator I = liveOutCache_.find(MBB);
605 if (I == liveOutCache_.end() || I->second.second == Node) {
606 // We already have a live-out defined in MBB, so this must be IdxMBB.
607 assert(MBB == IdxMBB && "Adding phi-def to known live-out");
608 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
610 // This phi-def is also live-out, so color the whole block.
611 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
612 I->second = LiveOutPair(VNI, Node);
614 } else if (IDomValue.first) {
615 // No phi-def here. Remember incoming value for IdxMBB.
617 IdxVNI = IDomValue.first;
618 // Propagate IDomValue if needed:
619 // MBB is live-out and doesn't define its own value.
620 LiveOutMap::iterator I = liveOutCache_.find(MBB);
621 if (I != liveOutCache_.end() && I->second.second != Node &&
622 I->second.first != IDomValue.first) {
624 I->second = IDomValue;
625 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
626 << " idom valno #" << IDomValue.first->id
627 << " from BB#" << IDom->getBlock()->getNumber() << '\n');
631 DEBUG(dbgs() << " - made " << Changes << " changes.\n");
634 assert(IdxVNI && "Didn't find value for Idx");
637 // Check the liveOutCache_ invariants.
638 for (LiveOutMap::iterator I = liveOutCache_.begin(), E = liveOutCache_.end();
640 assert(I->first && "Null MBB entry in cache");
641 assert(I->second.first && "Null VNInfo in cache");
642 assert(I->second.second && "Null DomTreeNode in cache");
643 if (I->second.second->getBlock() == I->first)
645 for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(),
646 PE = I->first->pred_end(); PI != PE; ++PI)
647 assert(liveOutCache_.lookup(*PI) == I->second && "Bad invariant");
651 // Since we went through the trouble of a full BFS visiting all reaching defs,
652 // the values in LiveIn are now accurate. No more phi-defs are needed
653 // for these blocks, so we can color the live ranges.
654 // This makes the next mapValue call much faster.
655 for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) {
656 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
657 SlotIndex Start = lis_.getMBBStartIdx(MBB);
659 li_->addRange(LiveRange(Start, Idx.getNextSlot(), IdxVNI));
662 // Anything in LiveIn other than IdxMBB is live-through.
663 VNInfo *VNI = liveOutCache_.lookup(MBB).first;
664 assert(VNI && "Missing block value");
665 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
671 // extendTo - Find the last li_ value defined in MBB at or before Idx. The
672 // parentli_ is assumed to be live at Idx. Extend the live range to Idx.
673 // Return the found VNInfo, or NULL.
674 VNInfo *LiveIntervalMap::extendTo(const MachineBasicBlock *MBB, SlotIndex Idx) {
675 assert(li_ && "call reset first");
676 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
677 if (I == li_->begin())
680 if (I->end <= lis_.getMBBStartIdx(MBB))
683 I->end = Idx.getNextSlot();
687 // addSimpleRange - Add a simple range from parentli_ to li_.
688 // ParentVNI must be live in the [Start;End) interval.
689 void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
690 const VNInfo *ParentVNI) {
691 assert(li_ && "call reset first");
693 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
694 // A simple mapping is easy.
696 li_->addRange(LiveRange(Start, End, VNI));
700 // ParentVNI is a complex value. We must map per MBB.
701 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
702 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
705 li_->addRange(LiveRange(Start, End, VNI));
710 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
712 // Run sequence of full blocks.
713 for (++MBB; MBB != MBBE; ++MBB) {
714 Start = lis_.getMBBStartIdx(MBB);
715 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
716 mapValue(ParentVNI, Start)));
720 Start = lis_.getMBBStartIdx(MBB);
722 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
725 /// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
726 /// All needed values whose def is not inside [Start;End) must be defined
727 /// beforehand so mapValue will work.
728 void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
729 assert(li_ && "call reset first");
730 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
731 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
733 // Check if --I begins before Start and overlaps.
737 addSimpleRange(Start, std::min(End, I->end), I->valno);
741 // The remaining ranges begin after Start.
742 for (;I != E && I->start < End; ++I)
743 addSimpleRange(I->start, std::min(End, I->end), I->valno);
747 //===----------------------------------------------------------------------===//
749 //===----------------------------------------------------------------------===//
751 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
752 SplitEditor::SplitEditor(SplitAnalysis &sa,
755 MachineDominatorTree &mdt,
757 : sa_(sa), lis_(lis), vrm_(vrm),
758 mri_(vrm.getMachineFunction().getRegInfo()),
759 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
760 tri_(*vrm.getMachineFunction().getTarget().getRegisterInfo()),
762 dupli_(lis_, mdt, edit.getParent()),
763 openli_(lis_, mdt, edit.getParent())
765 // We don't need an AliasAnalysis since we will only be performing
766 // cheap-as-a-copy remats anyway.
767 edit_.anyRematerializable(lis_, tii_, 0);
770 bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
771 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
772 if (*I != dupli_.getLI() && (*I)->liveAt(Idx))
777 VNInfo *SplitEditor::defFromParent(LiveIntervalMap &Reg,
780 MachineBasicBlock &MBB,
781 MachineBasicBlock::iterator I) {
783 MachineInstr *CopyMI = 0;
786 // Attempt cheap-as-a-copy rematerialization.
787 LiveRangeEdit::Remat RM(ParentVNI);
788 if (edit_.canRematerializeAt(RM, UseIdx, true, lis_)) {
789 Def = edit_.rematerializeAt(MBB, I, Reg.getLI()->reg, RM,
792 // Can't remat, just insert a copy from parent.
793 CopyMI = BuildMI(MBB, I, DebugLoc(), tii_.get(TargetOpcode::COPY),
794 Reg.getLI()->reg).addReg(edit_.getReg());
795 Def = lis_.InsertMachineInstrInMaps(CopyMI).getDefIndex();
798 // Define the value in Reg.
799 VNI = Reg.defValue(ParentVNI, Def);
800 VNI->setCopy(CopyMI);
802 // Add minimal liveness for the new value.
805 Reg.getLI()->addRange(LiveRange(Def, UseIdx.getNextSlot(), VNI));
809 /// Create a new virtual register and live interval.
810 void SplitEditor::openIntv() {
811 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
813 dupli_.reset(&edit_.create(mri_, lis_, vrm_));
815 openli_.reset(&edit_.create(mri_, lis_, vrm_));
818 /// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
819 /// not live before Idx, a COPY is not inserted.
820 void SplitEditor::enterIntvBefore(SlotIndex Idx) {
821 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
822 Idx = Idx.getUseIndex();
823 DEBUG(dbgs() << " enterIntvBefore " << Idx);
824 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
826 DEBUG(dbgs() << ": not live\n");
829 DEBUG(dbgs() << ": valno " << ParentVNI->id);
830 truncatedValues.insert(ParentVNI);
831 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
832 assert(MI && "enterIntvBefore called with invalid index");
834 defFromParent(openli_, ParentVNI, Idx, *MI->getParent(), MI);
836 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
839 /// enterIntvAtEnd - Enter openli at the end of MBB.
840 void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
841 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
842 SlotIndex End = lis_.getMBBEndIdx(&MBB).getPrevSlot();
843 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End);
844 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(End);
846 DEBUG(dbgs() << ": not live\n");
849 DEBUG(dbgs() << ": valno " << ParentVNI->id);
850 truncatedValues.insert(ParentVNI);
851 defFromParent(openli_, ParentVNI, End, MBB, MBB.getFirstTerminator());
852 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
855 /// useIntv - indicate that all instructions in MBB should use openli.
856 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
857 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
860 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
861 assert(openli_.getLI() && "openIntv not called before useIntv");
862 openli_.addRange(Start, End);
863 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
864 << *openli_.getLI() << '\n');
867 /// leaveIntvAfter - Leave openli after the instruction at Idx.
868 void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
869 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
870 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
872 // The interval must be live beyond the instruction at Idx.
873 Idx = Idx.getBoundaryIndex();
874 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
876 DEBUG(dbgs() << ": not live\n");
879 DEBUG(dbgs() << ": valno " << ParentVNI->id);
881 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
882 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Idx,
883 *MII->getParent(), llvm::next(MII));
885 // Make sure that openli is properly extended from Idx to the new copy.
886 // FIXME: This shouldn't be necessary for remats.
887 openli_.addSimpleRange(Idx, VNI->def, ParentVNI);
889 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
892 /// leaveIntvAtTop - Leave the interval at the top of MBB.
893 /// Currently, only one value can leave the interval.
894 void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
895 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
896 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
897 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
899 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Start);
901 DEBUG(dbgs() << ": not live\n");
905 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Start, MBB,
906 MBB.SkipPHIsAndLabels(MBB.begin()));
908 // Finally we must make sure that openli is properly extended from Start to
910 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
911 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
914 /// closeIntv - Indicate that we are done editing the currently open
915 /// LiveInterval, and ranges can be trimmed.
916 void SplitEditor::closeIntv() {
917 assert(openli_.getLI() && "openIntv not called before closeIntv");
919 DEBUG(dbgs() << " closeIntv cleaning up\n");
920 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
924 /// rewrite - Rewrite all uses of reg to use the new registers.
925 void SplitEditor::rewrite(unsigned reg) {
926 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg),
927 RE = mri_.reg_end(); RI != RE;) {
928 MachineOperand &MO = RI.getOperand();
929 unsigned OpNum = RI.getOperandNo();
930 MachineInstr *MI = MO.getParent();
932 if (MI->isDebugValue()) {
933 DEBUG(dbgs() << "Zapping " << *MI);
934 // FIXME: We can do much better with debug values.
938 SlotIndex Idx = lis_.getInstructionIndex(MI);
939 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
940 LiveInterval *LI = 0;
941 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E;
943 LiveInterval *testli = *I;
944 if (testli->liveAt(Idx)) {
949 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'<< Idx);
950 assert(LI && "No register was live at use");
952 if (MO.isUse() && !MI->isRegTiedToDefOperand(OpNum))
953 MO.setIsKill(LI->killedAt(Idx.getDefIndex()));
954 DEBUG(dbgs() << '\t' << *MI);
959 SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
960 // Build vector of iterator pairs from the intervals.
961 typedef std::pair<LiveInterval::const_iterator,
962 LiveInterval::const_iterator> IIPair;
963 SmallVector<IIPair, 8> Iters;
964 for (LiveRangeEdit::iterator LI = edit_.begin(), LE = edit_.end(); LI != LE;
966 if (*LI == dupli_.getLI())
968 LiveInterval::const_iterator I = (*LI)->find(Start);
969 LiveInterval::const_iterator E = (*LI)->end();
971 Iters.push_back(std::make_pair(I, E));
974 SlotIndex sidx = Start;
975 // Break [Start;End) into segments that don't overlap any intervals.
977 SlotIndex next = sidx, eidx = End;
978 // Find overlapping intervals.
979 for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) {
980 LiveInterval::const_iterator I = Iters[i].first;
981 // Interval I is overlapping [sidx;eidx). Trim sidx.
982 if (I->start <= sidx) {
984 // Move to the next run, remove iters when all are consumed.
985 I = ++Iters[i].first;
986 if (I == Iters[i].second) {
987 Iters.erase(Iters.begin() + i);
992 // Trim eidx too if needed.
993 if (I->start >= eidx)
998 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
1000 dupli_.addSimpleRange(sidx, eidx, VNI);
1001 // If the interval end was truncated, we can try again from next.
1008 void SplitEditor::computeRemainder() {
1009 // First we need to fill in the live ranges in dupli.
1010 // If values were redefined, we need a full recoloring with SSA update.
1011 // If values were truncated, we only need to truncate the ranges.
1012 // If values were partially rematted, we should shrink to uses.
1013 // If values were fully rematted, they should be omitted.
1014 // FIXME: If a single value is redefined, just move the def and truncate.
1015 LiveInterval &parent = edit_.getParent();
1017 // Values that are fully contained in the split intervals.
1018 SmallPtrSet<const VNInfo*, 8> deadValues;
1019 // Map all curli values that should have live defs in dupli.
1020 for (LiveInterval::const_vni_iterator I = parent.vni_begin(),
1021 E = parent.vni_end(); I != E; ++I) {
1022 const VNInfo *VNI = *I;
1023 // Don't transfer unused values to the new intervals.
1024 if (VNI->isUnused())
1026 // Original def is contained in the split intervals.
1027 if (intervalsLiveAt(VNI->def)) {
1028 // Did this value escape?
1029 if (dupli_.isMapped(VNI))
1030 truncatedValues.insert(VNI);
1032 deadValues.insert(VNI);
1035 // Add minimal live range at the definition.
1036 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
1037 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
1040 // Add all ranges to dupli.
1041 for (LiveInterval::const_iterator I = parent.begin(), E = parent.end();
1043 const LiveRange &LR = *I;
1044 if (truncatedValues.count(LR.valno)) {
1045 // recolor after removing intervals_.
1046 addTruncSimpleRange(LR.start, LR.end, LR.valno);
1047 } else if (!deadValues.count(LR.valno)) {
1048 // recolor without truncation.
1049 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
1053 // Extend dupli_ to be live out of any critical loop predecessors.
1054 // This means we have multiple registers live out of those blocks.
1055 // The alternative would be to split the critical edges.
1056 if (criticalPreds_.empty())
1058 for (SplitAnalysis::BlockPtrSet::iterator I = criticalPreds_.begin(),
1059 E = criticalPreds_.end(); I != E; ++I)
1060 dupli_.extendTo(*I, lis_.getMBBEndIdx(*I).getPrevSlot());
1061 criticalPreds_.clear();
1064 void SplitEditor::finish() {
1065 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
1066 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
1068 // Complete dupli liveness.
1071 // Get rid of unused values and set phi-kill flags.
1072 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
1073 (*I)->RenumberValues(lis_);
1075 // Rewrite instructions.
1076 rewrite(edit_.getReg());
1078 // Now check if any registers were separated into multiple components.
1079 ConnectedVNInfoEqClasses ConEQ(lis_);
1080 for (unsigned i = 0, e = edit_.size(); i != e; ++i) {
1081 // Don't use iterators, they are invalidated by create() below.
1082 LiveInterval *li = edit_.get(i);
1083 unsigned NumComp = ConEQ.Classify(li);
1086 DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n');
1087 SmallVector<LiveInterval*, 8> dups;
1089 for (unsigned i = 1; i != NumComp; ++i)
1090 dups.push_back(&edit_.create(mri_, lis_, vrm_));
1091 ConEQ.Distribute(&dups[0]);
1092 // Rewrite uses to the new regs.
1096 // Calculate spill weight and allocation hints for new intervals.
1097 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
1098 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I){
1099 LiveInterval &li = **I;
1100 vrai.CalculateRegClass(li.reg);
1101 vrai.CalculateWeightAndHint(li);
1102 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
1103 << ":" << li << '\n');
1108 //===----------------------------------------------------------------------===//
1110 //===----------------------------------------------------------------------===//
1112 void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
1113 SplitAnalysis::LoopBlocks Blocks;
1114 sa_.getLoopBlocks(Loop, Blocks);
1117 dbgs() << " splitAround"; sa_.print(Blocks, dbgs()); dbgs() << '\n';
1120 // Break critical edges as needed.
1121 SplitAnalysis::BlockPtrSet CriticalExits;
1122 sa_.getCriticalExits(Blocks, CriticalExits);
1123 assert(CriticalExits.empty() && "Cannot break critical exits yet");
1125 // Get critical predecessors so computeRemainder can deal with them.
1126 sa_.getCriticalPreds(Blocks, criticalPreds_);
1128 // Create new live interval for the loop.
1131 // Insert copies in the predecessors if live-in to the header.
1132 if (lis_.isLiveInToMBB(edit_.getParent(), Loop->getHeader())) {
1133 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
1134 E = Blocks.Preds.end(); I != E; ++I) {
1135 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
1136 enterIntvAtEnd(MBB);
1140 // Switch all loop blocks.
1141 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
1142 E = Blocks.Loop.end(); I != E; ++I)
1145 // Insert back copies in the exit blocks.
1146 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
1147 E = Blocks.Exits.end(); I != E; ++I) {
1148 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
1149 leaveIntvAtTop(MBB);
1158 //===----------------------------------------------------------------------===//
1159 // Single Block Splitting
1160 //===----------------------------------------------------------------------===//
1162 /// getMultiUseBlocks - if curli has more than one use in a basic block, it
1163 /// may be an advantage to split curli for the duration of the block.
1164 bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
1165 // If curli is local to one block, there is no point to splitting it.
1166 if (usingBlocks_.size() <= 1)
1168 // Add blocks with multiple uses.
1169 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
1171 switch (I->second) {
1176 // When there are only two uses and curli is both live in and live out,
1177 // we don't really win anything by isolating the block since we would be
1178 // inserting two copies.
1179 // The remaing register would still have two uses in the block. (Unless it
1180 // separates into disconnected components).
1181 if (lis_.isLiveInToMBB(*curli_, I->first) &&
1182 lis_.isLiveOutOfMBB(*curli_, I->first))
1186 Blocks.insert(I->first);
1188 return !Blocks.empty();
1191 /// splitSingleBlocks - Split curli into a separate live interval inside each
1192 /// basic block in Blocks.
1193 void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
1194 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
1195 // Determine the first and last instruction using curli in each block.
1196 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
1197 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
1198 IndexPairMap MBBRange;
1199 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1200 E = sa_.usingInstrs_.end(); I != E; ++I) {
1201 const MachineBasicBlock *MBB = (*I)->getParent();
1202 if (!Blocks.count(MBB))
1204 SlotIndex Idx = lis_.getInstructionIndex(*I);
1205 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
1206 IndexPair &IP = MBBRange[MBB];
1207 if (!IP.first.isValid() || Idx < IP.first)
1209 if (!IP.second.isValid() || Idx > IP.second)
1213 // Create a new interval for each block.
1214 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
1215 E = Blocks.end(); I != E; ++I) {
1216 IndexPair &IP = MBBRange[*I];
1217 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
1218 << IP.first << ';' << IP.second << ")\n");
1219 assert(IP.first.isValid() && IP.second.isValid());
1222 enterIntvBefore(IP.first);
1223 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
1224 leaveIntvAfter(IP.second);
1231 //===----------------------------------------------------------------------===//
1232 // Sub Block Splitting
1233 //===----------------------------------------------------------------------===//
1235 /// getBlockForInsideSplit - If curli is contained inside a single basic block,
1236 /// and it wou pay to subdivide the interval inside that block, return it.
1237 /// Otherwise return NULL. The returned block can be passed to
1238 /// SplitEditor::splitInsideBlock.
1239 const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1240 // The interval must be exclusive to one block.
1241 if (usingBlocks_.size() != 1)
1243 // Don't to this for less than 4 instructions. We want to be sure that
1244 // splitting actually reduces the instruction count per interval.
1245 if (usingInstrs_.size() < 4)
1247 return usingBlocks_.begin()->first;
1250 /// splitInsideBlock - Split curli into multiple intervals inside MBB.
1251 void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
1252 SmallVector<SlotIndex, 32> Uses;
1253 Uses.reserve(sa_.usingInstrs_.size());
1254 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1255 E = sa_.usingInstrs_.end(); I != E; ++I)
1256 if ((*I)->getParent() == MBB)
1257 Uses.push_back(lis_.getInstructionIndex(*I));
1258 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1259 << Uses.size() << " instructions.\n");
1260 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1261 array_pod_sort(Uses.begin(), Uses.end());
1263 // Simple algorithm: Find the largest gap between uses as determined by slot
1264 // indices. Create new intervals for instructions before the gap and after the
1266 unsigned bestPos = 0;
1268 DEBUG(dbgs() << " dist (" << Uses[0]);
1269 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1270 int g = Uses[i-1].distance(Uses[i]);
1271 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1273 bestPos = i, bestGap = g;
1275 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1277 // bestPos points to the first use after the best gap.
1278 assert(bestPos > 0 && "Invalid gap");
1280 // FIXME: Don't create intervals for low densities.
1282 // First interval before the gap. Don't create single-instr intervals.
1285 enterIntvBefore(Uses.front());
1286 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1287 leaveIntvAfter(Uses[bestPos-1]);
1291 // Second interval after the gap.
1292 if (bestPos < Uses.size()-1) {
1294 enterIntvBefore(Uses[bestPos]);
1295 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1296 leaveIntvAfter(Uses.back());