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 "splitter"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/CalcSpillWeights.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineLoopInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
32 AllowSplit("spiller-splits-edges",
33 cl::desc("Allow critical edge splitting during spilling"));
35 //===----------------------------------------------------------------------===//
37 //===----------------------------------------------------------------------===//
39 SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
40 const LiveIntervals &lis,
41 const MachineLoopInfo &mli)
45 tii_(*mf.getTarget().getInstrInfo()),
48 void SplitAnalysis::clear() {
55 bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
56 MachineBasicBlock *T, *F;
57 SmallVector<MachineOperand, 4> Cond;
58 return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
61 /// analyzeUses - Count instructions, basic blocks, and loops using curli.
62 void SplitAnalysis::analyzeUses() {
63 const MachineRegisterInfo &MRI = mf_.getRegInfo();
64 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
65 MachineInstr *MI = I.skipInstruction();) {
66 if (MI->isDebugValue() || !usingInstrs_.insert(MI))
68 MachineBasicBlock *MBB = MI->getParent();
69 if (usingBlocks_[MBB]++)
71 for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop;
72 Loop = Loop->getParentLoop())
75 DEBUG(dbgs() << " counted "
76 << usingInstrs_.size() << " instrs, "
77 << usingBlocks_.size() << " blocks, "
78 << usingLoops_.size() << " loops.\n");
81 // Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
82 // predecessor blocks, and exit blocks.
83 void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
86 // Blocks in the loop.
87 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
89 // Predecessor blocks.
90 const MachineBasicBlock *Header = Loop->getHeader();
91 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
92 E = Header->pred_end(); I != E; ++I)
93 if (!Blocks.Loop.count(*I))
94 Blocks.Preds.insert(*I);
97 for (MachineLoop::block_iterator I = Loop->block_begin(),
98 E = Loop->block_end(); I != E; ++I) {
99 const MachineBasicBlock *MBB = *I;
100 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
101 SE = MBB->succ_end(); SI != SE; ++SI)
102 if (!Blocks.Loop.count(*SI))
103 Blocks.Exits.insert(*SI);
107 /// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
108 /// and around the Loop.
109 SplitAnalysis::LoopPeripheralUse SplitAnalysis::
110 analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
111 LoopPeripheralUse use = ContainedInLoop;
112 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
114 const MachineBasicBlock *MBB = I->first;
115 // Is this a peripheral block?
116 if (use < MultiPeripheral &&
117 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
118 if (I->second > 1) use = MultiPeripheral;
119 else use = SinglePeripheral;
122 // Is it a loop block?
123 if (Blocks.Loop.count(MBB))
125 // It must be an unrelated block.
131 /// getCriticalExits - It may be necessary to partially break critical edges
132 /// leaving the loop if an exit block has phi uses of curli. Collect the exit
133 /// blocks that need special treatment into CriticalExits.
134 void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
135 BlockPtrSet &CriticalExits) {
136 CriticalExits.clear();
138 // A critical exit block contains a phi def of curli, and has a predecessor
139 // that is not in the loop nor a loop predecessor.
140 // For such an exit block, the edges carrying the new variable must be moved
141 // to a new pre-exit block.
142 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
144 const MachineBasicBlock *Succ = *I;
145 SlotIndex SuccIdx = lis_.getMBBStartIdx(Succ);
146 VNInfo *SuccVNI = curli_->getVNInfoAt(SuccIdx);
147 // This exit may not have curli live in at all. No need to split.
150 // If this is not a PHI def, it is either using a value from before the
151 // loop, or a value defined inside the loop. Both are safe.
152 if (!SuccVNI->isPHIDef() || SuccVNI->def.getBaseIndex() != SuccIdx)
154 // This exit block does have a PHI. Does it also have a predecessor that is
155 // not a loop block or loop predecessor?
156 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
157 PE = Succ->pred_end(); PI != PE; ++PI) {
158 const MachineBasicBlock *Pred = *PI;
159 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
161 // This is a critical exit block, and we need to split the exit edge.
162 CriticalExits.insert(Succ);
168 /// canSplitCriticalExits - Return true if it is possible to insert new exit
169 /// blocks before the blocks in CriticalExits.
171 SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
172 BlockPtrSet &CriticalExits) {
173 // If we don't allow critical edge splitting, require no critical exits.
175 return CriticalExits.empty();
177 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
179 const MachineBasicBlock *Succ = *I;
180 // We want to insert a new pre-exit MBB before Succ, and change all the
181 // in-loop blocks to branch to the pre-exit instead of Succ.
182 // Check that all the in-loop predecessors can be changed.
183 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
184 PE = Succ->pred_end(); PI != PE; ++PI) {
185 const MachineBasicBlock *Pred = *PI;
186 // The external predecessors won't be altered.
187 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
189 if (!canAnalyzeBranch(Pred))
193 // If Succ's layout predecessor falls through, that too must be analyzable.
194 // We need to insert the pre-exit block in the gap.
195 MachineFunction::const_iterator MFI = Succ;
196 if (MFI == mf_.begin())
198 if (!canAnalyzeBranch(--MFI))
201 // No problems found.
205 void SplitAnalysis::analyze(const LiveInterval *li) {
211 const MachineLoop *SplitAnalysis::getBestSplitLoop() {
212 assert(curli_ && "Call analyze() before getBestSplitLoop");
213 if (usingLoops_.empty())
216 LoopPtrSet Loops, SecondLoops;
218 BlockPtrSet CriticalExits;
220 // Find first-class and second class candidate loops.
221 // We prefer to split around loops where curli is used outside the periphery.
222 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
223 E = usingLoops_.end(); I != E; ++I) {
224 const MachineLoop *Loop = I->first;
225 getLoopBlocks(Loop, Blocks);
228 switch(analyzeLoopPeripheralUse(Blocks)) {
232 case MultiPeripheral:
235 case ContainedInLoop:
236 DEBUG(dbgs() << " contained in " << *Loop);
238 case SinglePeripheral:
239 DEBUG(dbgs() << " single peripheral use in " << *Loop);
242 // Will it be possible to split around this loop?
243 getCriticalExits(Blocks, CriticalExits);
244 DEBUG(dbgs() << " " << CriticalExits.size() << " critical exits from "
246 if (!canSplitCriticalExits(Blocks, CriticalExits))
248 // This is a possible split.
253 DEBUG(dbgs() << " getBestSplitLoop found " << Loops.size() << " + "
254 << SecondLoops.size() << " candidate loops.\n");
256 // If there are no first class loops available, look at second class loops.
263 // Pick the earliest loop.
264 // FIXME: Are there other heuristics to consider?
265 const MachineLoop *Best = 0;
267 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
269 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
270 if (!Best || Idx < BestIdx)
271 Best = *I, BestIdx = Idx;
273 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
277 /// getMultiUseBlocks - if curli has more than one use in a basic block, it
278 /// may be an advantage to split curli for the duration of the block.
279 bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
280 // If curli is local to one block, there is no point to splitting it.
281 if (usingBlocks_.size() <= 1)
283 // Add blocks with multiple uses.
284 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
291 // It doesn't pay to split a 2-instr block if it redefines curli.
292 VNInfo *VN1 = curli_->getVNInfoAt(lis_.getMBBStartIdx(I->first));
294 curli_->getVNInfoAt(lis_.getMBBEndIdx(I->first).getPrevIndex());
295 // live-in and live-out with a different value.
296 if (VN1 && VN2 && VN1 != VN2)
300 Blocks.insert(I->first);
302 return !Blocks.empty();
305 //===----------------------------------------------------------------------===//
307 //===----------------------------------------------------------------------===//
309 // Work around the fact that the std::pair constructors are broken for pointer
310 // pairs in some implementations. makeVV(x, 0) works.
311 static inline std::pair<const VNInfo*, VNInfo*>
312 makeVV(const VNInfo *a, VNInfo *b) {
313 return std::make_pair(a, b);
316 void LiveIntervalMap::reset(LiveInterval *li) {
321 bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
322 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
323 return i != valueMap_.end() && i->second == 0;
326 // defValue - Introduce a li_ def for ParentVNI that could be later than
328 VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
329 assert(li_ && "call reset first");
330 assert(ParentVNI && "Mapping NULL value");
331 assert(Idx.isValid() && "Invalid SlotIndex");
332 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
334 // Create a new value.
335 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
337 // Use insert for lookup, so we can add missing values with a second lookup.
338 std::pair<ValueMap::iterator,bool> InsP =
339 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
341 // This is now a complex def. Mark with a NULL in valueMap.
343 InsP.first->second = 0;
349 // mapValue - Find the mapped value for ParentVNI at Idx.
350 // Potentially create phi-def values.
351 VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
353 assert(li_ && "call reset first");
354 assert(ParentVNI && "Mapping NULL value");
355 assert(Idx.isValid() && "Invalid SlotIndex");
356 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
358 // Use insert for lookup, so we can add missing values with a second lookup.
359 std::pair<ValueMap::iterator,bool> InsP =
360 valueMap_.insert(makeVV(ParentVNI, 0));
362 // This was an unknown value. Create a simple mapping.
364 if (simple) *simple = true;
365 return InsP.first->second = li_->createValueCopy(ParentVNI,
366 lis_.getVNInfoAllocator());
369 // This was a simple mapped value.
370 if (InsP.first->second) {
371 if (simple) *simple = true;
372 return InsP.first->second;
375 // This is a complex mapped value. There may be multiple defs, and we may need
376 // to create phi-defs.
377 if (simple) *simple = false;
378 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
379 assert(IdxMBB && "No MBB at Idx");
381 // Is there a def in the same MBB we can extend?
382 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
385 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
386 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
387 // Perform a depth-first search for predecessor blocks where we know the
388 // dominating VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
390 // Track MBBs where we have created or learned the dominating value.
391 // This may change during the DFS as we create new phi-defs.
392 typedef DenseMap<MachineBasicBlock*, VNInfo*> MBBValueMap;
393 MBBValueMap DomValue;
394 typedef SplitAnalysis::BlockPtrSet BlockPtrSet;
397 // Iterate over IdxMBB predecessors in a depth-first order.
398 // Skip begin() since that is always IdxMBB.
399 for (idf_ext_iterator<MachineBasicBlock*, BlockPtrSet>
400 IDFI = llvm::next(idf_ext_begin(IdxMBB, Visited)),
401 IDFE = idf_ext_end(IdxMBB, Visited); IDFI != IDFE;) {
402 MachineBasicBlock *MBB = *IDFI;
403 SlotIndex End = lis_.getMBBEndIdx(MBB).getPrevSlot();
405 // We are operating on the restricted CFG where ParentVNI is live.
406 if (parentli_.getVNInfoAt(End) != ParentVNI) {
411 // Do we have a dominating value in this block?
412 VNInfo *VNI = extendTo(MBB, End);
418 // Yes, VNI dominates MBB. Make sure we visit MBB again from other paths.
421 // Track the path back to IdxMBB, creating phi-defs
422 // as needed along the way.
423 for (unsigned PI = IDFI.getPathLength()-1; PI != 0; --PI) {
424 // Start from MBB's immediate successor. End at IdxMBB.
425 MachineBasicBlock *Succ = IDFI.getPath(PI-1);
426 std::pair<MBBValueMap::iterator, bool> InsP =
427 DomValue.insert(MBBValueMap::value_type(Succ, VNI));
429 // This is the first time we backtrack to Succ.
433 // We reached Succ again with the same VNI. Nothing is going to change.
434 VNInfo *OVNI = InsP.first->second;
438 // Succ already has a phi-def. No need to continue.
439 SlotIndex Start = lis_.getMBBStartIdx(Succ);
440 if (OVNI->def == Start)
443 // We have a collision between the old and new VNI at Succ. That means
444 // neither dominates and we need a new phi-def.
445 VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
446 VNI->setIsPHIDef(true);
447 InsP.first->second = VNI;
449 // Replace OVNI with VNI in the remaining path.
450 for (; PI > 1 ; --PI) {
451 MBBValueMap::iterator I = DomValue.find(IDFI.getPath(PI-2));
452 if (I == DomValue.end() || I->second != OVNI)
458 // No need to search the children, we found a dominating value.
462 // The search should at least find a dominating value for IdxMBB.
463 assert(!DomValue.empty() && "Couldn't find a reaching definition");
465 // Since we went through the trouble of a full DFS visiting all reaching defs,
466 // the values in DomValue are now accurate. No more phi-defs are needed for
467 // these blocks, so we can color the live ranges.
468 // This makes the next mapValue call much faster.
470 for (MBBValueMap::iterator I = DomValue.begin(), E = DomValue.end(); I != E;
472 MachineBasicBlock *MBB = I->first;
473 VNInfo *VNI = I->second;
474 SlotIndex Start = lis_.getMBBStartIdx(MBB);
476 // Don't add full liveness to IdxMBB, stop at Idx.
478 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
479 // The caller had better add some liveness to IdxVNI, or it leaks.
482 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
485 assert(IdxVNI && "Didn't find value for Idx");
489 // extendTo - Find the last li_ value defined in MBB at or before Idx. The
490 // parentli_ is assumed to be live at Idx. Extend the live range to Idx.
491 // Return the found VNInfo, or NULL.
492 VNInfo *LiveIntervalMap::extendTo(MachineBasicBlock *MBB, SlotIndex Idx) {
493 assert(li_ && "call reset first");
494 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
495 if (I == li_->begin())
498 if (I->end <= lis_.getMBBStartIdx(MBB))
501 I->end = Idx.getNextSlot();
505 // addSimpleRange - Add a simple range from parentli_ to li_.
506 // ParentVNI must be live in the [Start;End) interval.
507 void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
508 const VNInfo *ParentVNI) {
509 assert(li_ && "call reset first");
511 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
512 // A simple mapping is easy.
514 li_->addRange(LiveRange(Start, End, VNI));
518 // ParentVNI is a complex value. We must map per MBB.
519 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
520 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
523 li_->addRange(LiveRange(Start, End, VNI));
528 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
530 // Run sequence of full blocks.
531 for (++MBB; MBB != MBBE; ++MBB) {
532 Start = lis_.getMBBStartIdx(MBB);
533 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
534 mapValue(ParentVNI, Start)));
538 Start = lis_.getMBBStartIdx(MBB);
540 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
543 /// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
544 /// All needed values whose def is not inside [Start;End) must be defined
545 /// beforehand so mapValue will work.
546 void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
547 assert(li_ && "call reset first");
548 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
549 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
551 // Check if --I begins before Start and overlaps.
555 addSimpleRange(Start, std::min(End, I->end), I->valno);
559 // The remaining ranges begin after Start.
560 for (;I != E && I->start < End; ++I)
561 addSimpleRange(I->start, std::min(End, I->end), I->valno);
564 VNInfo *LiveIntervalMap::defByCopyFrom(unsigned Reg,
565 const VNInfo *ParentVNI,
566 MachineBasicBlock &MBB,
567 MachineBasicBlock::iterator I) {
568 const TargetInstrDesc &TID = MBB.getParent()->getTarget().getInstrInfo()->
569 get(TargetOpcode::COPY);
570 MachineInstr *MI = BuildMI(MBB, I, DebugLoc(), TID, li_->reg).addReg(Reg);
571 SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
572 VNInfo *VNI = defValue(ParentVNI, DefIdx);
574 li_->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), VNI));
578 //===----------------------------------------------------------------------===//
580 //===----------------------------------------------------------------------===//
582 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
583 SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
584 SmallVectorImpl<LiveInterval*> &intervals)
585 : sa_(sa), lis_(lis), vrm_(vrm),
586 mri_(vrm.getMachineFunction().getRegInfo()),
587 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
588 curli_(sa_.getCurLI()),
589 dupli_(lis_, *curli_),
590 openli_(lis_, *curli_),
591 intervals_(intervals),
592 firstInterval(intervals_.size())
594 assert(curli_ && "SplitEditor created from empty SplitAnalysis");
596 // Make sure curli_ is assigned a stack slot, so all our intervals get the
597 // same slot as curli_.
598 if (vrm_.getStackSlot(curli_->reg) == VirtRegMap::NO_STACK_SLOT)
599 vrm_.assignVirt2StackSlot(curli_->reg);
603 LiveInterval *SplitEditor::createInterval() {
604 unsigned Reg = mri_.createVirtualRegister(mri_.getRegClass(curli_->reg));
605 LiveInterval &Intv = lis_.getOrCreateInterval(Reg);
607 vrm_.assignVirt2StackSlot(Reg, vrm_.getStackSlot(curli_->reg));
611 bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
612 for (int i = firstInterval, e = intervals_.size(); i != e; ++i)
613 if (intervals_[i]->liveAt(Idx))
618 /// Create a new virtual register and live interval.
619 void SplitEditor::openIntv() {
620 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
623 dupli_.reset(createInterval());
625 openli_.reset(createInterval());
626 intervals_.push_back(openli_.getLI());
629 /// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
630 /// not live before Idx, a COPY is not inserted.
631 void SplitEditor::enterIntvBefore(SlotIndex Idx) {
632 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
633 VNInfo *ParentVNI = curli_->getVNInfoAt(Idx.getUseIndex());
635 DEBUG(dbgs() << " enterIntvBefore " << Idx << ": not live\n");
638 truncatedValues.insert(ParentVNI);
639 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
640 assert(MI && "enterIntvBefore called with invalid index");
641 openli_.defByCopyFrom(curli_->reg, ParentVNI, *MI->getParent(), MI);
642 DEBUG(dbgs() << " enterIntvBefore " << Idx << ": " << *openli_.getLI()
646 /// enterIntvAtEnd - Enter openli at the end of MBB.
647 void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
648 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
649 SlotIndex End = lis_.getMBBEndIdx(&MBB);
650 VNInfo *ParentVNI = curli_->getVNInfoAt(End.getPrevSlot());
652 DEBUG(dbgs() << " enterIntvAtEnd " << End << ": not live\n");
655 truncatedValues.insert(ParentVNI);
656 VNInfo *VNI = openli_.defByCopyFrom(curli_->reg, ParentVNI,
657 MBB, MBB.getFirstTerminator());
658 // Make sure openli is live out of MBB.
659 openli_.getLI()->addRange(LiveRange(VNI->def, End, VNI));
660 DEBUG(dbgs() << " enterIntvAtEnd: " << *openli_.getLI() << '\n');
663 /// useIntv - indicate that all instructions in MBB should use openli.
664 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
665 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
668 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
669 assert(openli_.getLI() && "openIntv not called before useIntv");
670 openli_.addRange(Start, End);
671 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
672 << *openli_.getLI() << '\n');
675 /// leaveIntvAfter - Leave openli after the instruction at Idx.
676 void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
677 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
679 // The interval must be live beyond the instruction at Idx.
680 VNInfo *ParentVNI = curli_->getVNInfoAt(Idx.getBoundaryIndex());
682 DEBUG(dbgs() << " leaveIntvAfter " << Idx << ": not live\n");
686 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
687 MachineBasicBlock *MBB = MII->getParent();
688 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI, *MBB,
691 // Finally we must make sure that openli is properly extended from Idx to the
693 openli_.addSimpleRange(Idx.getBoundaryIndex(), VNI->def, ParentVNI);
694 DEBUG(dbgs() << " leaveIntvAfter " << Idx << ": " << *openli_.getLI()
698 /// leaveIntvAtTop - Leave the interval at the top of MBB.
699 /// Currently, only one value can leave the interval.
700 void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
701 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
703 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
704 VNInfo *ParentVNI = curli_->getVNInfoAt(Start);
706 // Is curli even live-in to MBB?
708 DEBUG(dbgs() << " leaveIntvAtTop at " << Start << ": not live\n");
712 // We are going to insert a back copy, so we must have a dupli_.
713 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI,
716 // Finally we must make sure that openli is properly extended from Start to
718 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
719 DEBUG(dbgs() << " leaveIntvAtTop at " << Start << ": " << *openli_.getLI()
723 /// closeIntv - Indicate that we are done editing the currently open
724 /// LiveInterval, and ranges can be trimmed.
725 void SplitEditor::closeIntv() {
726 assert(openli_.getLI() && "openIntv not called before closeIntv");
728 DEBUG(dbgs() << " closeIntv cleaning up\n");
729 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
734 SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
735 SlotIndex sidx = Start;
737 // Break [Start;End) into segments that don't overlap any intervals.
739 SlotIndex next = sidx, eidx = End;
740 // Find overlapping intervals.
741 for (int i = firstInterval, e = intervals_.size(); i != e && sidx < eidx;
743 LiveInterval::const_iterator I = intervals_[i]->find(sidx);
744 LiveInterval::const_iterator E = intervals_[i]->end();
747 // Interval I is overlapping [sidx;eidx). Trim sidx.
748 if (I->start <= sidx) {
753 // Trim eidx too if needed.
754 if (I->start >= eidx)
760 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
762 dupli_.addSimpleRange(sidx, eidx, VNI);
763 // If the interval end was truncated, we can try again from next.
770 /// rewrite - after all the new live ranges have been created, rewrite
771 /// instructions using curli to use the new intervals.
772 void SplitEditor::rewrite() {
773 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
774 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
776 // First we need to fill in the live ranges in dupli.
777 // If values were redefined, we need a full recoloring with SSA update.
778 // If values were truncated, we only need to truncate the ranges.
779 // If values were partially rematted, we should shrink to uses.
780 // If values were fully rematted, they should be omitted.
781 // FIXME: If a single value is redefined, just move the def and truncate.
783 // Values that are fully contained in the split intervals.
784 SmallPtrSet<const VNInfo*, 8> deadValues;
786 // Map all curli values that should have live defs in dupli.
787 for (LiveInterval::const_vni_iterator I = curli_->vni_begin(),
788 E = curli_->vni_end(); I != E; ++I) {
789 const VNInfo *VNI = *I;
790 // Original def is contained in the split intervals.
791 if (intervalsLiveAt(VNI->def)) {
792 // Did this value escape?
793 if (dupli_.isMapped(VNI))
794 truncatedValues.insert(VNI);
796 deadValues.insert(VNI);
799 // Add minimal live range at the definition.
800 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
801 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
804 // Add all ranges to dupli.
805 for (LiveInterval::const_iterator I = curli_->begin(), E = curli_->end();
807 const LiveRange &LR = *I;
808 if (truncatedValues.count(LR.valno)) {
809 // recolor after removing intervals_.
810 addTruncSimpleRange(LR.start, LR.end, LR.valno);
811 } else if (!deadValues.count(LR.valno)) {
812 // recolor without truncation.
813 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
818 const LiveInterval *curli = sa_.getCurLI();
819 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(curli->reg),
820 RE = mri_.reg_end(); RI != RE;) {
821 MachineOperand &MO = RI.getOperand();
822 MachineInstr *MI = MO.getParent();
824 if (MI->isDebugValue()) {
825 DEBUG(dbgs() << "Zapping " << *MI);
826 // FIXME: We can do much better with debug values.
830 SlotIndex Idx = lis_.getInstructionIndex(MI);
831 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
832 LiveInterval *LI = dupli_.getLI();
833 for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
834 LiveInterval *testli = intervals_[i];
835 if (testli->liveAt(Idx)) {
841 DEBUG(dbgs() << " rewrite " << Idx << '\t' << *MI);
844 // dupli_ goes in last, after rewriting.
845 if (dupli_.getLI()->empty()) {
846 DEBUG(dbgs() << " dupli became empty?\n");
847 lis_.removeInterval(dupli_.getLI()->reg);
850 dupli_.getLI()->RenumberValues(lis_);
851 intervals_.push_back(dupli_.getLI());
854 // Calculate spill weight and allocation hints for new intervals.
855 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
856 for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
857 LiveInterval &li = *intervals_[i];
858 vrai.CalculateRegClass(li.reg);
859 vrai.CalculateWeightAndHint(li);
860 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
861 << ":" << li << '\n');
866 //===----------------------------------------------------------------------===//
868 //===----------------------------------------------------------------------===//
870 void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
871 SplitAnalysis::LoopBlocks Blocks;
872 sa_.getLoopBlocks(Loop, Blocks);
874 // Break critical edges as needed.
875 SplitAnalysis::BlockPtrSet CriticalExits;
876 sa_.getCriticalExits(Blocks, CriticalExits);
877 assert(CriticalExits.empty() && "Cannot break critical exits yet");
879 // Create new live interval for the loop.
882 // Insert copies in the predecessors.
883 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
884 E = Blocks.Preds.end(); I != E; ++I) {
885 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
889 // Switch all loop blocks.
890 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
891 E = Blocks.Loop.end(); I != E; ++I)
894 // Insert back copies in the exit blocks.
895 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
896 E = Blocks.Exits.end(); I != E; ++I) {
897 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
907 //===----------------------------------------------------------------------===//
908 // Single Block Splitting
909 //===----------------------------------------------------------------------===//
911 /// splitSingleBlocks - Split curli into a separate live interval inside each
912 /// basic block in Blocks.
913 void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
914 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
915 // Determine the first and last instruction using curli in each block.
916 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
917 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
918 IndexPairMap MBBRange;
919 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
920 E = sa_.usingInstrs_.end(); I != E; ++I) {
921 const MachineBasicBlock *MBB = (*I)->getParent();
922 if (!Blocks.count(MBB))
924 SlotIndex Idx = lis_.getInstructionIndex(*I);
925 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
926 IndexPair &IP = MBBRange[MBB];
927 if (!IP.first.isValid() || Idx < IP.first)
929 if (!IP.second.isValid() || Idx > IP.second)
933 // Create a new interval for each block.
934 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
935 E = Blocks.end(); I != E; ++I) {
936 IndexPair &IP = MBBRange[*I];
937 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
938 << IP.first << ';' << IP.second << ")\n");
939 assert(IP.first.isValid() && IP.second.isValid());
942 enterIntvBefore(IP.first);
943 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
944 leaveIntvAfter(IP.second);
951 //===----------------------------------------------------------------------===//
952 // Sub Block Splitting
953 //===----------------------------------------------------------------------===//
955 /// getBlockForInsideSplit - If curli is contained inside a single basic block,
956 /// and it wou pay to subdivide the interval inside that block, return it.
957 /// Otherwise return NULL. The returned block can be passed to
958 /// SplitEditor::splitInsideBlock.
959 const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
960 // The interval must be exclusive to one block.
961 if (usingBlocks_.size() != 1)
963 // Don't to this for less than 4 instructions. We want to be sure that
964 // splitting actually reduces the instruction count per interval.
965 if (usingInstrs_.size() < 4)
967 return usingBlocks_.begin()->first;
970 /// splitInsideBlock - Split curli into multiple intervals inside MBB.
971 void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
972 SmallVector<SlotIndex, 32> Uses;
973 Uses.reserve(sa_.usingInstrs_.size());
974 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
975 E = sa_.usingInstrs_.end(); I != E; ++I)
976 if ((*I)->getParent() == MBB)
977 Uses.push_back(lis_.getInstructionIndex(*I));
978 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
979 << Uses.size() << " instructions.\n");
980 assert(Uses.size() >= 3 && "Need at least 3 instructions");
981 array_pod_sort(Uses.begin(), Uses.end());
983 // Simple algorithm: Find the largest gap between uses as determined by slot
984 // indices. Create new intervals for instructions before the gap and after the
986 unsigned bestPos = 0;
988 DEBUG(dbgs() << " dist (" << Uses[0]);
989 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
990 int g = Uses[i-1].distance(Uses[i]);
991 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
993 bestPos = i, bestGap = g;
995 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
997 // bestPos points to the first use after the best gap.
998 assert(bestPos > 0 && "Invalid gap");
1000 // FIXME: Don't create intervals for low densities.
1002 // First interval before the gap. Don't create single-instr intervals.
1005 enterIntvBefore(Uses.front());
1006 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1007 leaveIntvAfter(Uses[bestPos-1]);
1011 // Second interval after the gap.
1012 if (bestPos < Uses.size()-1) {
1014 enterIntvBefore(Uses[bestPos]);
1015 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1016 leaveIntvAfter(Uses.back());