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/raw_ostream.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
34 AllowSplit("spiller-splits-edges",
35 cl::desc("Allow critical edge splitting during spilling"));
37 //===----------------------------------------------------------------------===//
39 //===----------------------------------------------------------------------===//
41 SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
42 const LiveIntervals &lis,
43 const MachineLoopInfo &mli)
47 tii_(*mf.getTarget().getInstrInfo()),
50 void SplitAnalysis::clear() {
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);
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 MachineInstr *MI = I.skipInstruction();) {
68 if (MI->isDebugValue() || !usingInstrs_.insert(MI))
70 MachineBasicBlock *MBB = MI->getParent();
71 if (usingBlocks_[MBB]++)
73 for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop;
74 Loop = Loop->getParentLoop())
77 DEBUG(dbgs() << " counted "
78 << usingInstrs_.size() << " instrs, "
79 << usingBlocks_.size() << " blocks, "
80 << usingLoops_.size() << " loops.\n");
83 void 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();
88 OS << '(' << count << ')';
92 // Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
93 // predecessor blocks, and exit blocks.
94 void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
97 // Blocks in the loop.
98 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
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);
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);
118 void SplitAnalysis::print(const LoopBlocks &B, raw_ostream &OS) const {
127 /// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
128 /// and around the Loop.
129 SplitAnalysis::LoopPeripheralUse SplitAnalysis::
130 analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
131 LoopPeripheralUse use = ContainedInLoop;
132 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
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;
142 // Is it a loop block?
143 if (Blocks.Loop.count(MBB))
145 // It must be an unrelated block.
146 DEBUG(dbgs() << ", outside: BB#" << MBB->getNumber());
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
155 void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
156 BlockPtrSet &CriticalExits) {
157 CriticalExits.clear();
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();
164 const MachineBasicBlock *Exit = *I;
165 // A single-predecessor exit block is definitely not a critical edge.
166 if (Exit->pred_size() == 1)
168 // This exit may not have curli live in at all. No need to split.
169 if (!lis_.isLiveInToMBB(*curli_, Exit))
171 // Does this exit block have a predecessor that is not a loop block or loop
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))
178 // This is a critical exit block, and we need to split the exit edge.
179 CriticalExits.insert(Exit);
185 void SplitAnalysis::getCriticalPreds(const SplitAnalysis::LoopBlocks &Blocks,
186 BlockPtrSet &CriticalPreds) {
187 CriticalPreds.clear();
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();
195 const MachineBasicBlock *Pred = *I;
196 // Definitely not a critical edge.
197 if (Pred->succ_size() == 1)
199 // This block may not have curli live out at all if there is a PHI.
200 if (!lis_.isLiveOutOfMBB(*curli_, Pred))
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))
208 if (!lis_.isLiveInToMBB(*curli_, Succ))
210 // This is a critical predecessor block.
211 CriticalPreds.insert(Pred);
217 /// canSplitCriticalExits - Return true if it is possible to insert new exit
218 /// blocks before the blocks in CriticalExits.
220 SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
221 BlockPtrSet &CriticalExits) {
222 // If we don't allow critical edge splitting, require no critical exits.
224 return CriticalExits.empty();
226 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
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))
238 if (!canAnalyzeBranch(Pred))
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())
247 if (!canAnalyzeBranch(--MFI))
250 // No problems found.
254 void SplitAnalysis::analyze(const LiveInterval *li) {
260 void SplitAnalysis::getSplitLoops(LoopPtrSet &Loops) {
261 assert(curli_ && "Call analyze() before getSplitLoops");
262 if (usingLoops_.empty())
266 BlockPtrSet CriticalExits;
268 // We split around loops where curli is used outside the periphery.
269 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
270 E = usingLoops_.end(); I != E; ++I) {
271 const MachineLoop *Loop = I->first;
272 getLoopBlocks(Loop, Blocks);
273 DEBUG({ dbgs() << " "; print(Blocks, dbgs()); });
275 switch(analyzeLoopPeripheralUse(Blocks)) {
278 case MultiPeripheral:
279 // FIXME: We could split a live range with multiple uses in a peripheral
280 // block and still make progress. However, it is possible that splitting
281 // another live range will insert copies into a peripheral block, and
282 // there is a small chance we can enter an infinite loop, inserting copies
284 // For safety, stick to splitting live ranges with uses outside the
286 DEBUG(dbgs() << ": multiple peripheral uses");
288 case ContainedInLoop:
289 DEBUG(dbgs() << ": fully contained\n");
291 case SinglePeripheral:
292 DEBUG(dbgs() << ": single peripheral use\n");
295 // Will it be possible to split around this loop?
296 getCriticalExits(Blocks, CriticalExits);
297 DEBUG(dbgs() << ": " << CriticalExits.size() << " critical exits\n");
298 if (!canSplitCriticalExits(Blocks, CriticalExits))
300 // This is a possible split.
304 DEBUG(dbgs() << " getSplitLoops found " << Loops.size()
305 << " candidate loops.\n");
308 const MachineLoop *SplitAnalysis::getBestSplitLoop() {
310 getSplitLoops(Loops);
314 // Pick the earliest loop.
315 // FIXME: Are there other heuristics to consider?
316 const MachineLoop *Best = 0;
318 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
320 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
321 if (!Best || Idx < BestIdx)
322 Best = *I, BestIdx = Idx;
324 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
328 /// isBypassLoop - Return true if curli is live through Loop and has no uses
329 /// inside the loop. Bypass loops are candidates for splitting because it can
330 /// prevent interference inside the loop.
331 bool SplitAnalysis::isBypassLoop(const MachineLoop *Loop) {
332 // If curli is live into the loop header and there are no uses in the loop, it
333 // must be live in the entire loop and live on at least one exiting edge.
334 return !usingLoops_.count(Loop) &&
335 lis_.isLiveInToMBB(*curli_, Loop->getHeader());
338 /// getBypassLoops - Get all the maximal bypass loops. These are the bypass
339 /// loops whose parent is not a bypass loop.
340 void SplitAnalysis::getBypassLoops(LoopPtrSet &BypassLoops) {
341 SmallVector<MachineLoop*, 8> Todo(loops_.begin(), loops_.end());
342 while (!Todo.empty()) {
343 MachineLoop *Loop = Todo.pop_back_val();
344 if (!usingLoops_.count(Loop)) {
345 // This is either a bypass loop or completely irrelevant.
346 if (lis_.isLiveInToMBB(*curli_, Loop->getHeader()))
347 BypassLoops.insert(Loop);
348 // Either way, skip the child loops.
352 // The child loops may be bypass loops.
353 Todo.append(Loop->begin(), Loop->end());
358 //===----------------------------------------------------------------------===//
360 //===----------------------------------------------------------------------===//
362 // Work around the fact that the std::pair constructors are broken for pointer
363 // pairs in some implementations. makeVV(x, 0) works.
364 static inline std::pair<const VNInfo*, VNInfo*>
365 makeVV(const VNInfo *a, VNInfo *b) {
366 return std::make_pair(a, b);
369 void LiveIntervalMap::reset(LiveInterval *li) {
372 liveOutCache_.clear();
375 bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
376 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
377 return i != valueMap_.end() && i->second == 0;
380 // defValue - Introduce a li_ def for ParentVNI that could be later than
382 VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
383 assert(li_ && "call reset first");
384 assert(ParentVNI && "Mapping NULL value");
385 assert(Idx.isValid() && "Invalid SlotIndex");
386 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
388 // Create a new value.
389 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
391 // Preserve the PHIDef bit.
392 if (ParentVNI->isPHIDef() && Idx == ParentVNI->def)
393 VNI->setIsPHIDef(true);
395 // Use insert for lookup, so we can add missing values with a second lookup.
396 std::pair<ValueMap::iterator,bool> InsP =
397 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
399 // This is now a complex def. Mark with a NULL in valueMap.
401 InsP.first->second = 0;
407 // mapValue - Find the mapped value for ParentVNI at Idx.
408 // Potentially create phi-def values.
409 VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
411 assert(li_ && "call reset first");
412 assert(ParentVNI && "Mapping NULL value");
413 assert(Idx.isValid() && "Invalid SlotIndex");
414 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
416 // Use insert for lookup, so we can add missing values with a second lookup.
417 std::pair<ValueMap::iterator,bool> InsP =
418 valueMap_.insert(makeVV(ParentVNI, 0));
420 // This was an unknown value. Create a simple mapping.
422 if (simple) *simple = true;
423 return InsP.first->second = li_->createValueCopy(ParentVNI,
424 lis_.getVNInfoAllocator());
427 // This was a simple mapped value.
428 if (InsP.first->second) {
429 if (simple) *simple = true;
430 return InsP.first->second;
433 // This is a complex mapped value. There may be multiple defs, and we may need
434 // to create phi-defs.
435 if (simple) *simple = false;
436 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
437 assert(IdxMBB && "No MBB at Idx");
439 // Is there a def in the same MBB we can extend?
440 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
443 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
444 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
445 // Perform a search for all predecessor blocks where we know the dominating
446 // VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
447 DEBUG(dbgs() << "\n Reaching defs for BB#" << IdxMBB->getNumber()
448 << " at " << Idx << " in " << *li_ << '\n');
450 // Blocks where li_ should be live-in.
451 SmallVector<MachineDomTreeNode*, 16> LiveIn;
452 LiveIn.push_back(mdt_[IdxMBB]);
454 // Using liveOutCache_ as a visited set, perform a BFS for all reaching defs.
455 for (unsigned i = 0; i != LiveIn.size(); ++i) {
456 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
457 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
458 PE = MBB->pred_end(); PI != PE; ++PI) {
459 MachineBasicBlock *Pred = *PI;
460 // Is this a known live-out block?
461 std::pair<LiveOutMap::iterator,bool> LOIP =
462 liveOutCache_.insert(std::make_pair(Pred, LiveOutPair()));
463 // Yes, we have been here before.
465 DEBUG(if (VNInfo *VNI = LOIP.first->second.first)
466 dbgs() << " known valno #" << VNI->id
467 << " at BB#" << Pred->getNumber() << '\n');
471 // Does Pred provide a live-out value?
472 SlotIndex Last = lis_.getMBBEndIdx(Pred).getPrevSlot();
473 if (VNInfo *VNI = extendTo(Pred, Last)) {
474 MachineBasicBlock *DefMBB = lis_.getMBBFromIndex(VNI->def);
475 DEBUG(dbgs() << " found valno #" << VNI->id
476 << " from BB#" << DefMBB->getNumber()
477 << " at BB#" << Pred->getNumber() << '\n');
478 LiveOutPair &LOP = LOIP.first->second;
480 LOP.second = mdt_[DefMBB];
483 // No, we need a live-in value for Pred as well
485 LiveIn.push_back(mdt_[Pred]);
489 // We may need to add phi-def values to preserve the SSA form.
490 // This is essentially the same iterative algorithm that SSAUpdater uses,
491 // except we already have a dominator tree, so we don't have to recompute it.
496 DEBUG(dbgs() << " Iterating over " << LiveIn.size() << " blocks.\n");
497 // Propagate live-out values down the dominator tree, inserting phi-defs when
498 // necessary. Since LiveIn was created by a BFS, going backwards makes it more
499 // likely for us to visit immediate dominators before their children.
500 for (unsigned i = LiveIn.size(); i; --i) {
501 MachineDomTreeNode *Node = LiveIn[i-1];
502 MachineBasicBlock *MBB = Node->getBlock();
503 MachineDomTreeNode *IDom = Node->getIDom();
504 LiveOutPair IDomValue;
505 // We need a live-in value to a block with no immediate dominator?
506 // This is probably an unreachable block that has survived somehow.
507 bool needPHI = !IDom;
509 // Get the IDom live-out value.
511 LiveOutMap::iterator I = liveOutCache_.find(IDom->getBlock());
512 if (I != liveOutCache_.end())
513 IDomValue = I->second;
515 // If IDom is outside our set of live-out blocks, there must be new
516 // defs, and we need a phi-def here.
520 // IDom dominates all of our predecessors, but it may not be the immediate
521 // dominator. Check if any of them have live-out values that are properly
522 // dominated by IDom. If so, we need a phi-def here.
524 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
525 PE = MBB->pred_end(); PI != PE; ++PI) {
526 LiveOutPair Value = liveOutCache_[*PI];
527 if (!Value.first || Value.first == IDomValue.first)
529 // This predecessor is carrying something other than IDomValue.
530 // It could be because IDomValue hasn't propagated yet, or it could be
531 // because MBB is in the dominance frontier of that value.
532 if (mdt_.dominates(IDom, Value.second)) {
539 // Create a phi-def if required.
542 SlotIndex Start = lis_.getMBBStartIdx(MBB);
543 VNInfo *VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
544 VNI->setIsPHIDef(true);
545 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
546 << " phi-def #" << VNI->id << " at " << Start << '\n');
547 // We no longer need li_ to be live-in.
548 LiveIn.erase(LiveIn.begin()+(i-1));
549 // Blocks in LiveIn are either IdxMBB, or have a value live-through.
552 // Check if we need to update live-out info.
553 LiveOutMap::iterator I = liveOutCache_.find(MBB);
554 if (I == liveOutCache_.end() || I->second.second == Node) {
555 // We already have a live-out defined in MBB, so this must be IdxMBB.
556 assert(MBB == IdxMBB && "Adding phi-def to known live-out");
557 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
559 // This phi-def is also live-out, so color the whole block.
560 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
561 I->second = LiveOutPair(VNI, Node);
563 } else if (IDomValue.first) {
564 // No phi-def here. Remember incoming value for IdxMBB.
566 IdxVNI = IDomValue.first;
567 // Propagate IDomValue if needed:
568 // MBB is live-out and doesn't define its own value.
569 LiveOutMap::iterator I = liveOutCache_.find(MBB);
570 if (I != liveOutCache_.end() && I->second.second != Node &&
571 I->second.first != IDomValue.first) {
573 I->second = IDomValue;
574 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
575 << " idom valno #" << IDomValue.first->id
576 << " from BB#" << IDom->getBlock()->getNumber() << '\n');
580 DEBUG(dbgs() << " - made " << Changes << " changes.\n");
583 assert(IdxVNI && "Didn't find value for Idx");
586 // Check the liveOutCache_ invariants.
587 for (LiveOutMap::iterator I = liveOutCache_.begin(), E = liveOutCache_.end();
589 assert(I->first && "Null MBB entry in cache");
590 assert(I->second.first && "Null VNInfo in cache");
591 assert(I->second.second && "Null DomTreeNode in cache");
592 if (I->second.second->getBlock() == I->first)
594 for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(),
595 PE = I->first->pred_end(); PI != PE; ++PI)
596 assert(liveOutCache_.lookup(*PI) == I->second && "Bad invariant");
600 // Since we went through the trouble of a full BFS visiting all reaching defs,
601 // the values in LiveIn are now accurate. No more phi-defs are needed
602 // for these blocks, so we can color the live ranges.
603 // This makes the next mapValue call much faster.
604 for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) {
605 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
606 SlotIndex Start = lis_.getMBBStartIdx(MBB);
608 li_->addRange(LiveRange(Start, Idx.getNextSlot(), IdxVNI));
611 // Anything in LiveIn other than IdxMBB is live-through.
612 VNInfo *VNI = liveOutCache_.lookup(MBB).first;
613 assert(VNI && "Missing block value");
614 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
620 // extendTo - Find the last li_ value defined in MBB at or before Idx. The
621 // parentli_ is assumed to be live at Idx. Extend the live range to Idx.
622 // Return the found VNInfo, or NULL.
623 VNInfo *LiveIntervalMap::extendTo(const MachineBasicBlock *MBB, SlotIndex Idx) {
624 assert(li_ && "call reset first");
625 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
626 if (I == li_->begin())
629 if (I->end <= lis_.getMBBStartIdx(MBB))
632 I->end = Idx.getNextSlot();
636 // addSimpleRange - Add a simple range from parentli_ to li_.
637 // ParentVNI must be live in the [Start;End) interval.
638 void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
639 const VNInfo *ParentVNI) {
640 assert(li_ && "call reset first");
642 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
643 // A simple mapping is easy.
645 li_->addRange(LiveRange(Start, End, VNI));
649 // ParentVNI is a complex value. We must map per MBB.
650 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
651 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
654 li_->addRange(LiveRange(Start, End, VNI));
659 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
661 // Run sequence of full blocks.
662 for (++MBB; MBB != MBBE; ++MBB) {
663 Start = lis_.getMBBStartIdx(MBB);
664 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
665 mapValue(ParentVNI, Start)));
669 Start = lis_.getMBBStartIdx(MBB);
671 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
674 /// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
675 /// All needed values whose def is not inside [Start;End) must be defined
676 /// beforehand so mapValue will work.
677 void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
678 assert(li_ && "call reset first");
679 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
680 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
682 // Check if --I begins before Start and overlaps.
686 addSimpleRange(Start, std::min(End, I->end), I->valno);
690 // The remaining ranges begin after Start.
691 for (;I != E && I->start < End; ++I)
692 addSimpleRange(I->start, std::min(End, I->end), I->valno);
696 //===----------------------------------------------------------------------===//
698 //===----------------------------------------------------------------------===//
700 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
701 SplitEditor::SplitEditor(SplitAnalysis &sa,
704 MachineDominatorTree &mdt,
706 : sa_(sa), lis_(lis), vrm_(vrm),
707 mri_(vrm.getMachineFunction().getRegInfo()),
708 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
709 tri_(*vrm.getMachineFunction().getTarget().getRegisterInfo()),
711 dupli_(lis_, mdt, edit.getParent()),
712 openli_(lis_, mdt, edit.getParent())
714 // We don't need an AliasAnalysis since we will only be performing
715 // cheap-as-a-copy remats anyway.
716 edit_.anyRematerializable(lis_, tii_, 0);
719 bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
720 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
721 if (*I != dupli_.getLI() && (*I)->liveAt(Idx))
726 VNInfo *SplitEditor::defFromParent(LiveIntervalMap &Reg,
729 MachineBasicBlock &MBB,
730 MachineBasicBlock::iterator I) {
732 MachineInstr *CopyMI = 0;
735 // Attempt cheap-as-a-copy rematerialization.
736 LiveRangeEdit::Remat RM(ParentVNI);
737 if (edit_.canRematerializeAt(RM, UseIdx, true, lis_)) {
738 Def = edit_.rematerializeAt(MBB, I, Reg.getLI()->reg, RM,
741 // Can't remat, just insert a copy from parent.
742 CopyMI = BuildMI(MBB, I, DebugLoc(), tii_.get(TargetOpcode::COPY),
743 Reg.getLI()->reg).addReg(edit_.getReg());
744 Def = lis_.InsertMachineInstrInMaps(CopyMI).getDefIndex();
747 // Define the value in Reg.
748 VNI = Reg.defValue(ParentVNI, Def);
749 VNI->setCopy(CopyMI);
751 // Add minimal liveness for the new value.
754 Reg.getLI()->addRange(LiveRange(Def, UseIdx.getNextSlot(), VNI));
758 /// Create a new virtual register and live interval.
759 void SplitEditor::openIntv() {
760 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
762 dupli_.reset(&edit_.create(mri_, lis_, vrm_));
764 openli_.reset(&edit_.create(mri_, lis_, vrm_));
767 /// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
768 /// not live before Idx, a COPY is not inserted.
769 void SplitEditor::enterIntvBefore(SlotIndex Idx) {
770 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
771 Idx = Idx.getUseIndex();
772 DEBUG(dbgs() << " enterIntvBefore " << Idx);
773 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
775 DEBUG(dbgs() << ": not live\n");
778 DEBUG(dbgs() << ": valno " << ParentVNI->id);
779 truncatedValues.insert(ParentVNI);
780 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
781 assert(MI && "enterIntvBefore called with invalid index");
783 defFromParent(openli_, ParentVNI, Idx, *MI->getParent(), MI);
785 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
788 /// enterIntvAtEnd - Enter openli at the end of MBB.
789 void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
790 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
791 SlotIndex End = lis_.getMBBEndIdx(&MBB).getPrevSlot();
792 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End);
793 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(End);
795 DEBUG(dbgs() << ": not live\n");
798 DEBUG(dbgs() << ": valno " << ParentVNI->id);
799 truncatedValues.insert(ParentVNI);
800 defFromParent(openli_, ParentVNI, End, MBB, MBB.getFirstTerminator());
801 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
804 /// useIntv - indicate that all instructions in MBB should use openli.
805 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
806 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
809 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
810 assert(openli_.getLI() && "openIntv not called before useIntv");
811 openli_.addRange(Start, End);
812 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
813 << *openli_.getLI() << '\n');
816 /// leaveIntvAfter - Leave openli after the instruction at Idx.
817 void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
818 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
819 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
821 // The interval must be live beyond the instruction at Idx.
822 Idx = Idx.getBoundaryIndex();
823 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
825 DEBUG(dbgs() << ": not live\n");
828 DEBUG(dbgs() << ": valno " << ParentVNI->id);
830 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
831 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Idx,
832 *MII->getParent(), llvm::next(MII));
834 // Make sure that openli is properly extended from Idx to the new copy.
835 // FIXME: This shouldn't be necessary for remats.
836 openli_.addSimpleRange(Idx, VNI->def, ParentVNI);
838 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
841 /// leaveIntvAtTop - Leave the interval at the top of MBB.
842 /// Currently, only one value can leave the interval.
843 void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
844 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
845 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
846 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
848 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Start);
850 DEBUG(dbgs() << ": not live\n");
854 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Start, MBB,
855 MBB.SkipPHIsAndLabels(MBB.begin()));
857 // Finally we must make sure that openli is properly extended from Start to
859 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
860 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
863 /// closeIntv - Indicate that we are done editing the currently open
864 /// LiveInterval, and ranges can be trimmed.
865 void SplitEditor::closeIntv() {
866 assert(openli_.getLI() && "openIntv not called before closeIntv");
868 DEBUG(dbgs() << " closeIntv cleaning up\n");
869 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
873 /// rewrite - Rewrite all uses of reg to use the new registers.
874 void SplitEditor::rewrite(unsigned reg) {
875 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg),
876 RE = mri_.reg_end(); RI != RE;) {
877 MachineOperand &MO = RI.getOperand();
878 unsigned OpNum = RI.getOperandNo();
879 MachineInstr *MI = MO.getParent();
881 if (MI->isDebugValue()) {
882 DEBUG(dbgs() << "Zapping " << *MI);
883 // FIXME: We can do much better with debug values.
887 SlotIndex Idx = lis_.getInstructionIndex(MI);
888 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
889 LiveInterval *LI = 0;
890 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E;
892 LiveInterval *testli = *I;
893 if (testli->liveAt(Idx)) {
898 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'<< Idx);
899 assert(LI && "No register was live at use");
901 if (MO.isUse() && !MI->isRegTiedToDefOperand(OpNum))
902 MO.setIsKill(LI->killedAt(Idx.getDefIndex()));
903 DEBUG(dbgs() << '\t' << *MI);
908 SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
909 // Build vector of iterator pairs from the intervals.
910 typedef std::pair<LiveInterval::const_iterator,
911 LiveInterval::const_iterator> IIPair;
912 SmallVector<IIPair, 8> Iters;
913 for (LiveRangeEdit::iterator LI = edit_.begin(), LE = edit_.end(); LI != LE;
915 if (*LI == dupli_.getLI())
917 LiveInterval::const_iterator I = (*LI)->find(Start);
918 LiveInterval::const_iterator E = (*LI)->end();
920 Iters.push_back(std::make_pair(I, E));
923 SlotIndex sidx = Start;
924 // Break [Start;End) into segments that don't overlap any intervals.
926 SlotIndex next = sidx, eidx = End;
927 // Find overlapping intervals.
928 for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) {
929 LiveInterval::const_iterator I = Iters[i].first;
930 // Interval I is overlapping [sidx;eidx). Trim sidx.
931 if (I->start <= sidx) {
933 // Move to the next run, remove iters when all are consumed.
934 I = ++Iters[i].first;
935 if (I == Iters[i].second) {
936 Iters.erase(Iters.begin() + i);
941 // Trim eidx too if needed.
942 if (I->start >= eidx)
947 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
949 dupli_.addSimpleRange(sidx, eidx, VNI);
950 // If the interval end was truncated, we can try again from next.
957 void SplitEditor::computeRemainder() {
958 // First we need to fill in the live ranges in dupli.
959 // If values were redefined, we need a full recoloring with SSA update.
960 // If values were truncated, we only need to truncate the ranges.
961 // If values were partially rematted, we should shrink to uses.
962 // If values were fully rematted, they should be omitted.
963 // FIXME: If a single value is redefined, just move the def and truncate.
964 LiveInterval &parent = edit_.getParent();
966 // Values that are fully contained in the split intervals.
967 SmallPtrSet<const VNInfo*, 8> deadValues;
968 // Map all curli values that should have live defs in dupli.
969 for (LiveInterval::const_vni_iterator I = parent.vni_begin(),
970 E = parent.vni_end(); I != E; ++I) {
971 const VNInfo *VNI = *I;
972 // Don't transfer unused values to the new intervals.
975 // Original def is contained in the split intervals.
976 if (intervalsLiveAt(VNI->def)) {
977 // Did this value escape?
978 if (dupli_.isMapped(VNI))
979 truncatedValues.insert(VNI);
981 deadValues.insert(VNI);
984 // Add minimal live range at the definition.
985 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
986 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
989 // Add all ranges to dupli.
990 for (LiveInterval::const_iterator I = parent.begin(), E = parent.end();
992 const LiveRange &LR = *I;
993 if (truncatedValues.count(LR.valno)) {
994 // recolor after removing intervals_.
995 addTruncSimpleRange(LR.start, LR.end, LR.valno);
996 } else if (!deadValues.count(LR.valno)) {
997 // recolor without truncation.
998 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
1002 // Extend dupli_ to be live out of any critical loop predecessors.
1003 // This means we have multiple registers live out of those blocks.
1004 // The alternative would be to split the critical edges.
1005 if (criticalPreds_.empty())
1007 for (SplitAnalysis::BlockPtrSet::iterator I = criticalPreds_.begin(),
1008 E = criticalPreds_.end(); I != E; ++I)
1009 dupli_.extendTo(*I, lis_.getMBBEndIdx(*I).getPrevSlot());
1010 criticalPreds_.clear();
1013 void SplitEditor::finish() {
1014 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
1015 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
1017 // Complete dupli liveness.
1020 // Get rid of unused values and set phi-kill flags.
1021 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
1022 (*I)->RenumberValues(lis_);
1024 // Rewrite instructions.
1025 rewrite(edit_.getReg());
1027 // Now check if any registers were separated into multiple components.
1028 ConnectedVNInfoEqClasses ConEQ(lis_);
1029 for (unsigned i = 0, e = edit_.size(); i != e; ++i) {
1030 // Don't use iterators, they are invalidated by create() below.
1031 LiveInterval *li = edit_.get(i);
1032 unsigned NumComp = ConEQ.Classify(li);
1035 DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n');
1036 SmallVector<LiveInterval*, 8> dups;
1038 for (unsigned i = 1; i != NumComp; ++i)
1039 dups.push_back(&edit_.create(mri_, lis_, vrm_));
1040 ConEQ.Distribute(&dups[0]);
1041 // Rewrite uses to the new regs.
1045 // Calculate spill weight and allocation hints for new intervals.
1046 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
1047 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I){
1048 LiveInterval &li = **I;
1049 vrai.CalculateRegClass(li.reg);
1050 vrai.CalculateWeightAndHint(li);
1051 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
1052 << ":" << li << '\n');
1057 //===----------------------------------------------------------------------===//
1059 //===----------------------------------------------------------------------===//
1061 void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
1062 SplitAnalysis::LoopBlocks Blocks;
1063 sa_.getLoopBlocks(Loop, Blocks);
1066 dbgs() << " splitAround"; sa_.print(Blocks, dbgs()); dbgs() << '\n';
1069 // Break critical edges as needed.
1070 SplitAnalysis::BlockPtrSet CriticalExits;
1071 sa_.getCriticalExits(Blocks, CriticalExits);
1072 assert(CriticalExits.empty() && "Cannot break critical exits yet");
1074 // Get critical predecessors so computeRemainder can deal with them.
1075 sa_.getCriticalPreds(Blocks, criticalPreds_);
1077 // Create new live interval for the loop.
1080 // Insert copies in the predecessors.
1081 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
1082 E = Blocks.Preds.end(); I != E; ++I) {
1083 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
1084 enterIntvAtEnd(MBB);
1087 // Switch all loop blocks.
1088 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
1089 E = Blocks.Loop.end(); I != E; ++I)
1092 // Insert back copies in the exit blocks.
1093 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
1094 E = Blocks.Exits.end(); I != E; ++I) {
1095 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
1096 leaveIntvAtTop(MBB);
1105 //===----------------------------------------------------------------------===//
1106 // Single Block Splitting
1107 //===----------------------------------------------------------------------===//
1109 /// getMultiUseBlocks - if curli has more than one use in a basic block, it
1110 /// may be an advantage to split curli for the duration of the block.
1111 bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
1112 // If curli is local to one block, there is no point to splitting it.
1113 if (usingBlocks_.size() <= 1)
1115 // Add blocks with multiple uses.
1116 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
1118 switch (I->second) {
1123 // When there are only two uses and curli is both live in and live out,
1124 // we don't really win anything by isolating the block since we would be
1125 // inserting two copies.
1126 // The remaing register would still have two uses in the block. (Unless it
1127 // separates into disconnected components).
1128 if (lis_.isLiveInToMBB(*curli_, I->first) &&
1129 lis_.isLiveOutOfMBB(*curli_, I->first))
1133 Blocks.insert(I->first);
1135 return !Blocks.empty();
1138 /// splitSingleBlocks - Split curli into a separate live interval inside each
1139 /// basic block in Blocks.
1140 void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
1141 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
1142 // Determine the first and last instruction using curli in each block.
1143 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
1144 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
1145 IndexPairMap MBBRange;
1146 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1147 E = sa_.usingInstrs_.end(); I != E; ++I) {
1148 const MachineBasicBlock *MBB = (*I)->getParent();
1149 if (!Blocks.count(MBB))
1151 SlotIndex Idx = lis_.getInstructionIndex(*I);
1152 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
1153 IndexPair &IP = MBBRange[MBB];
1154 if (!IP.first.isValid() || Idx < IP.first)
1156 if (!IP.second.isValid() || Idx > IP.second)
1160 // Create a new interval for each block.
1161 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
1162 E = Blocks.end(); I != E; ++I) {
1163 IndexPair &IP = MBBRange[*I];
1164 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
1165 << IP.first << ';' << IP.second << ")\n");
1166 assert(IP.first.isValid() && IP.second.isValid());
1169 enterIntvBefore(IP.first);
1170 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
1171 leaveIntvAfter(IP.second);
1178 //===----------------------------------------------------------------------===//
1179 // Sub Block Splitting
1180 //===----------------------------------------------------------------------===//
1182 /// getBlockForInsideSplit - If curli is contained inside a single basic block,
1183 /// and it wou pay to subdivide the interval inside that block, return it.
1184 /// Otherwise return NULL. The returned block can be passed to
1185 /// SplitEditor::splitInsideBlock.
1186 const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1187 // The interval must be exclusive to one block.
1188 if (usingBlocks_.size() != 1)
1190 // Don't to this for less than 4 instructions. We want to be sure that
1191 // splitting actually reduces the instruction count per interval.
1192 if (usingInstrs_.size() < 4)
1194 return usingBlocks_.begin()->first;
1197 /// splitInsideBlock - Split curli into multiple intervals inside MBB.
1198 void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
1199 SmallVector<SlotIndex, 32> Uses;
1200 Uses.reserve(sa_.usingInstrs_.size());
1201 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1202 E = sa_.usingInstrs_.end(); I != E; ++I)
1203 if ((*I)->getParent() == MBB)
1204 Uses.push_back(lis_.getInstructionIndex(*I));
1205 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1206 << Uses.size() << " instructions.\n");
1207 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1208 array_pod_sort(Uses.begin(), Uses.end());
1210 // Simple algorithm: Find the largest gap between uses as determined by slot
1211 // indices. Create new intervals for instructions before the gap and after the
1213 unsigned bestPos = 0;
1215 DEBUG(dbgs() << " dist (" << Uses[0]);
1216 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1217 int g = Uses[i-1].distance(Uses[i]);
1218 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1220 bestPos = i, bestGap = g;
1222 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1224 // bestPos points to the first use after the best gap.
1225 assert(bestPos > 0 && "Invalid gap");
1227 // FIXME: Don't create intervals for low densities.
1229 // First interval before the gap. Don't create single-instr intervals.
1232 enterIntvBefore(Uses.front());
1233 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1234 leaveIntvAfter(Uses[bestPos-1]);
1238 // Second interval after the gap.
1239 if (bestPos < Uses.size()-1) {
1241 enterIntvBefore(Uses[bestPos]);
1242 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1243 leaveIntvAfter(Uses.back());