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 "LiveRangeEdit.h"
18 #include "VirtRegMap.h"
19 #include "llvm/CodeGen/CalcSpillWeights.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
33 AllowSplit("spiller-splits-edges",
34 cl::desc("Allow critical edge splitting during spilling"));
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
41 const LiveIntervals &lis,
42 const MachineLoopInfo &mli)
46 tii_(*mf.getTarget().getInstrInfo()),
49 void SplitAnalysis::clear() {
56 bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
57 MachineBasicBlock *T, *F;
58 SmallVector<MachineOperand, 4> Cond;
59 return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
62 /// analyzeUses - Count instructions, basic blocks, and loops using curli.
63 void SplitAnalysis::analyzeUses() {
64 const MachineRegisterInfo &MRI = mf_.getRegInfo();
65 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
66 MachineInstr *MI = I.skipInstruction();) {
67 if (MI->isDebugValue() || !usingInstrs_.insert(MI))
69 MachineBasicBlock *MBB = MI->getParent();
70 if (usingBlocks_[MBB]++)
72 for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop;
73 Loop = Loop->getParentLoop())
76 DEBUG(dbgs() << " counted "
77 << usingInstrs_.size() << " instrs, "
78 << usingBlocks_.size() << " blocks, "
79 << usingLoops_.size() << " loops.\n");
82 void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const {
83 for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) {
84 unsigned count = usingBlocks_.lookup(*I);
85 OS << " BB#" << (*I)->getNumber();
87 OS << '(' << count << ')';
91 // Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
92 // predecessor blocks, and exit blocks.
93 void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
96 // Blocks in the loop.
97 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
99 // Predecessor blocks.
100 const MachineBasicBlock *Header = Loop->getHeader();
101 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
102 E = Header->pred_end(); I != E; ++I)
103 if (!Blocks.Loop.count(*I))
104 Blocks.Preds.insert(*I);
107 for (MachineLoop::block_iterator I = Loop->block_begin(),
108 E = Loop->block_end(); I != E; ++I) {
109 const MachineBasicBlock *MBB = *I;
110 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
111 SE = MBB->succ_end(); SI != SE; ++SI)
112 if (!Blocks.Loop.count(*SI))
113 Blocks.Exits.insert(*SI);
117 void SplitAnalysis::print(const LoopBlocks &B, raw_ostream &OS) const {
126 /// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
127 /// and around the Loop.
128 SplitAnalysis::LoopPeripheralUse SplitAnalysis::
129 analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
130 LoopPeripheralUse use = ContainedInLoop;
131 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
133 const MachineBasicBlock *MBB = I->first;
134 // Is this a peripheral block?
135 if (use < MultiPeripheral &&
136 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
137 if (I->second > 1) use = MultiPeripheral;
138 else use = SinglePeripheral;
141 // Is it a loop block?
142 if (Blocks.Loop.count(MBB))
144 // It must be an unrelated block.
145 DEBUG(dbgs() << ", outside: BB#" << MBB->getNumber());
151 /// getCriticalExits - It may be necessary to partially break critical edges
152 /// leaving the loop if an exit block has phi uses of curli. Collect the exit
153 /// blocks that need special treatment into CriticalExits.
154 void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
155 BlockPtrSet &CriticalExits) {
156 CriticalExits.clear();
158 // A critical exit block contains a phi def of curli, and has a predecessor
159 // that is not in the loop nor a loop predecessor.
160 // For such an exit block, the edges carrying the new variable must be moved
161 // to a new pre-exit block.
162 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
164 const MachineBasicBlock *Succ = *I;
165 SlotIndex SuccIdx = lis_.getMBBStartIdx(Succ);
166 VNInfo *SuccVNI = curli_->getVNInfoAt(SuccIdx);
167 // This exit may not have curli live in at all. No need to split.
170 // If this is not a PHI def, it is either using a value from before the
171 // loop, or a value defined inside the loop. Both are safe.
172 if (!SuccVNI->isPHIDef() || SuccVNI->def.getBaseIndex() != SuccIdx)
174 // This exit block does have a PHI. Does it also have a predecessor that is
175 // not a loop block or loop predecessor?
176 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
177 PE = Succ->pred_end(); PI != PE; ++PI) {
178 const MachineBasicBlock *Pred = *PI;
179 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
181 // This is a critical exit block, and we need to split the exit edge.
182 CriticalExits.insert(Succ);
188 /// canSplitCriticalExits - Return true if it is possible to insert new exit
189 /// blocks before the blocks in CriticalExits.
191 SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
192 BlockPtrSet &CriticalExits) {
193 // If we don't allow critical edge splitting, require no critical exits.
195 return CriticalExits.empty();
197 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
199 const MachineBasicBlock *Succ = *I;
200 // We want to insert a new pre-exit MBB before Succ, and change all the
201 // in-loop blocks to branch to the pre-exit instead of Succ.
202 // Check that all the in-loop predecessors can be changed.
203 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
204 PE = Succ->pred_end(); PI != PE; ++PI) {
205 const MachineBasicBlock *Pred = *PI;
206 // The external predecessors won't be altered.
207 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
209 if (!canAnalyzeBranch(Pred))
213 // If Succ's layout predecessor falls through, that too must be analyzable.
214 // We need to insert the pre-exit block in the gap.
215 MachineFunction::const_iterator MFI = Succ;
216 if (MFI == mf_.begin())
218 if (!canAnalyzeBranch(--MFI))
221 // No problems found.
225 void SplitAnalysis::analyze(const LiveInterval *li) {
231 const MachineLoop *SplitAnalysis::getBestSplitLoop() {
232 assert(curli_ && "Call analyze() before getBestSplitLoop");
233 if (usingLoops_.empty())
238 BlockPtrSet CriticalExits;
240 // We split around loops where curli is used outside the periphery.
241 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
242 E = usingLoops_.end(); I != E; ++I) {
243 const MachineLoop *Loop = I->first;
244 getLoopBlocks(Loop, Blocks);
245 DEBUG({ dbgs() << " "; print(Blocks, dbgs()); });
247 switch(analyzeLoopPeripheralUse(Blocks)) {
250 case MultiPeripheral:
251 // FIXME: We could split a live range with multiple uses in a peripheral
252 // block and still make progress. However, it is possible that splitting
253 // another live range will insert copies into a peripheral block, and
254 // there is a small chance we can enter an infinity loop, inserting copies
256 // For safety, stick to splitting live ranges with uses outside the
258 DEBUG(dbgs() << ": multiple peripheral uses\n");
260 case ContainedInLoop:
261 DEBUG(dbgs() << ": fully contained\n");
263 case SinglePeripheral:
264 DEBUG(dbgs() << ": single peripheral use\n");
267 // Will it be possible to split around this loop?
268 getCriticalExits(Blocks, CriticalExits);
269 DEBUG(dbgs() << ": " << CriticalExits.size() << " critical exits\n");
270 if (!canSplitCriticalExits(Blocks, CriticalExits))
272 // This is a possible split.
276 DEBUG(dbgs() << " getBestSplitLoop found " << Loops.size()
277 << " candidate loops.\n");
282 // Pick the earliest loop.
283 // FIXME: Are there other heuristics to consider?
284 const MachineLoop *Best = 0;
286 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
288 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
289 if (!Best || Idx < BestIdx)
290 Best = *I, BestIdx = Idx;
292 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
296 /// getMultiUseBlocks - if curli has more than one use in a basic block, it
297 /// may be an advantage to split curli for the duration of the block.
298 bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
299 // If curli is local to one block, there is no point to splitting it.
300 if (usingBlocks_.size() <= 1)
302 // Add blocks with multiple uses.
303 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
310 // It doesn't pay to split a 2-instr block if it redefines curli.
311 VNInfo *VN1 = curli_->getVNInfoAt(lis_.getMBBStartIdx(I->first));
313 curli_->getVNInfoAt(lis_.getMBBEndIdx(I->first).getPrevIndex());
314 // live-in and live-out with a different value.
315 if (VN1 && VN2 && VN1 != VN2)
319 Blocks.insert(I->first);
321 return !Blocks.empty();
324 //===----------------------------------------------------------------------===//
326 //===----------------------------------------------------------------------===//
328 // Work around the fact that the std::pair constructors are broken for pointer
329 // pairs in some implementations. makeVV(x, 0) works.
330 static inline std::pair<const VNInfo*, VNInfo*>
331 makeVV(const VNInfo *a, VNInfo *b) {
332 return std::make_pair(a, b);
335 void LiveIntervalMap::reset(LiveInterval *li) {
340 bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
341 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
342 return i != valueMap_.end() && i->second == 0;
345 // defValue - Introduce a li_ def for ParentVNI that could be later than
347 VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
348 assert(li_ && "call reset first");
349 assert(ParentVNI && "Mapping NULL value");
350 assert(Idx.isValid() && "Invalid SlotIndex");
351 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
353 // Create a new value.
354 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
356 // Use insert for lookup, so we can add missing values with a second lookup.
357 std::pair<ValueMap::iterator,bool> InsP =
358 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
360 // This is now a complex def. Mark with a NULL in valueMap.
362 InsP.first->second = 0;
368 // mapValue - Find the mapped value for ParentVNI at Idx.
369 // Potentially create phi-def values.
370 VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
372 assert(li_ && "call reset first");
373 assert(ParentVNI && "Mapping NULL value");
374 assert(Idx.isValid() && "Invalid SlotIndex");
375 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
377 // Use insert for lookup, so we can add missing values with a second lookup.
378 std::pair<ValueMap::iterator,bool> InsP =
379 valueMap_.insert(makeVV(ParentVNI, 0));
381 // This was an unknown value. Create a simple mapping.
383 if (simple) *simple = true;
384 return InsP.first->second = li_->createValueCopy(ParentVNI,
385 lis_.getVNInfoAllocator());
388 // This was a simple mapped value.
389 if (InsP.first->second) {
390 if (simple) *simple = true;
391 return InsP.first->second;
394 // This is a complex mapped value. There may be multiple defs, and we may need
395 // to create phi-defs.
396 if (simple) *simple = false;
397 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
398 assert(IdxMBB && "No MBB at Idx");
400 // Is there a def in the same MBB we can extend?
401 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
404 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
405 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
406 // Perform a depth-first search for predecessor blocks where we know the
407 // dominating VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
409 // Track MBBs where we have created or learned the dominating value.
410 // This may change during the DFS as we create new phi-defs.
411 typedef DenseMap<MachineBasicBlock*, VNInfo*> MBBValueMap;
412 MBBValueMap DomValue;
413 typedef SplitAnalysis::BlockPtrSet BlockPtrSet;
416 // Iterate over IdxMBB predecessors in a depth-first order.
417 // Skip begin() since that is always IdxMBB.
418 for (idf_ext_iterator<MachineBasicBlock*, BlockPtrSet>
419 IDFI = llvm::next(idf_ext_begin(IdxMBB, Visited)),
420 IDFE = idf_ext_end(IdxMBB, Visited); IDFI != IDFE;) {
421 MachineBasicBlock *MBB = *IDFI;
422 SlotIndex End = lis_.getMBBEndIdx(MBB).getPrevSlot();
424 // We are operating on the restricted CFG where ParentVNI is live.
425 if (parentli_.getVNInfoAt(End) != ParentVNI) {
430 // Do we have a dominating value in this block?
431 VNInfo *VNI = extendTo(MBB, End);
437 // Yes, VNI dominates MBB. Make sure we visit MBB again from other paths.
440 // Track the path back to IdxMBB, creating phi-defs
441 // as needed along the way.
442 for (unsigned PI = IDFI.getPathLength()-1; PI != 0; --PI) {
443 // Start from MBB's immediate successor. End at IdxMBB.
444 MachineBasicBlock *Succ = IDFI.getPath(PI-1);
445 std::pair<MBBValueMap::iterator, bool> InsP =
446 DomValue.insert(MBBValueMap::value_type(Succ, VNI));
448 // This is the first time we backtrack to Succ.
452 // We reached Succ again with the same VNI. Nothing is going to change.
453 VNInfo *OVNI = InsP.first->second;
457 // Succ already has a phi-def. No need to continue.
458 SlotIndex Start = lis_.getMBBStartIdx(Succ);
459 if (OVNI->def == Start)
462 // We have a collision between the old and new VNI at Succ. That means
463 // neither dominates and we need a new phi-def.
464 VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
465 VNI->setIsPHIDef(true);
466 InsP.first->second = VNI;
468 // Replace OVNI with VNI in the remaining path.
469 for (; PI > 1 ; --PI) {
470 MBBValueMap::iterator I = DomValue.find(IDFI.getPath(PI-2));
471 if (I == DomValue.end() || I->second != OVNI)
477 // No need to search the children, we found a dominating value.
481 // The search should at least find a dominating value for IdxMBB.
482 assert(!DomValue.empty() && "Couldn't find a reaching definition");
484 // Since we went through the trouble of a full DFS visiting all reaching defs,
485 // the values in DomValue are now accurate. No more phi-defs are needed for
486 // these blocks, so we can color the live ranges.
487 // This makes the next mapValue call much faster.
489 for (MBBValueMap::iterator I = DomValue.begin(), E = DomValue.end(); I != E;
491 MachineBasicBlock *MBB = I->first;
492 VNInfo *VNI = I->second;
493 SlotIndex Start = lis_.getMBBStartIdx(MBB);
495 // Don't add full liveness to IdxMBB, stop at Idx.
497 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
498 // The caller had better add some liveness to IdxVNI, or it leaks.
501 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
504 assert(IdxVNI && "Didn't find value for Idx");
508 // extendTo - Find the last li_ value defined in MBB at or before Idx. The
509 // parentli_ is assumed to be live at Idx. Extend the live range to Idx.
510 // Return the found VNInfo, or NULL.
511 VNInfo *LiveIntervalMap::extendTo(MachineBasicBlock *MBB, SlotIndex Idx) {
512 assert(li_ && "call reset first");
513 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
514 if (I == li_->begin())
517 if (I->end <= lis_.getMBBStartIdx(MBB))
520 I->end = Idx.getNextSlot();
524 // addSimpleRange - Add a simple range from parentli_ to li_.
525 // ParentVNI must be live in the [Start;End) interval.
526 void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
527 const VNInfo *ParentVNI) {
528 assert(li_ && "call reset first");
530 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
531 // A simple mapping is easy.
533 li_->addRange(LiveRange(Start, End, VNI));
537 // ParentVNI is a complex value. We must map per MBB.
538 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
539 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
542 li_->addRange(LiveRange(Start, End, VNI));
547 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
549 // Run sequence of full blocks.
550 for (++MBB; MBB != MBBE; ++MBB) {
551 Start = lis_.getMBBStartIdx(MBB);
552 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
553 mapValue(ParentVNI, Start)));
557 Start = lis_.getMBBStartIdx(MBB);
559 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
562 /// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
563 /// All needed values whose def is not inside [Start;End) must be defined
564 /// beforehand so mapValue will work.
565 void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
566 assert(li_ && "call reset first");
567 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
568 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
570 // Check if --I begins before Start and overlaps.
574 addSimpleRange(Start, std::min(End, I->end), I->valno);
578 // The remaining ranges begin after Start.
579 for (;I != E && I->start < End; ++I)
580 addSimpleRange(I->start, std::min(End, I->end), I->valno);
583 VNInfo *LiveIntervalMap::defByCopyFrom(unsigned Reg,
584 const VNInfo *ParentVNI,
585 MachineBasicBlock &MBB,
586 MachineBasicBlock::iterator I) {
587 const TargetInstrDesc &TID = MBB.getParent()->getTarget().getInstrInfo()->
588 get(TargetOpcode::COPY);
589 MachineInstr *MI = BuildMI(MBB, I, DebugLoc(), TID, li_->reg).addReg(Reg);
590 SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
591 VNInfo *VNI = defValue(ParentVNI, DefIdx);
593 li_->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), VNI));
597 //===----------------------------------------------------------------------===//
599 //===----------------------------------------------------------------------===//
601 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
602 SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
604 : sa_(sa), lis_(lis), vrm_(vrm),
605 mri_(vrm.getMachineFunction().getRegInfo()),
606 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
608 dupli_(lis_, edit.getParent()),
609 openli_(lis_, edit.getParent())
613 bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
614 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
615 if (*I != dupli_.getLI() && (*I)->liveAt(Idx))
620 /// Create a new virtual register and live interval.
621 void SplitEditor::openIntv() {
622 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
625 dupli_.reset(&edit_.create(mri_, lis_, vrm_));
627 openli_.reset(&edit_.create(mri_, lis_, vrm_));
630 /// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
631 /// not live before Idx, a COPY is not inserted.
632 void SplitEditor::enterIntvBefore(SlotIndex Idx) {
633 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
634 DEBUG(dbgs() << " enterIntvBefore " << Idx);
635 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx.getUseIndex());
637 DEBUG(dbgs() << ": not live\n");
640 DEBUG(dbgs() << ": valno " << ParentVNI->id);
641 truncatedValues.insert(ParentVNI);
642 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
643 assert(MI && "enterIntvBefore called with invalid index");
644 VNInfo *VNI = openli_.defByCopyFrom(edit_.getReg(), ParentVNI,
645 *MI->getParent(), MI);
646 openli_.getLI()->addRange(LiveRange(VNI->def, Idx.getDefIndex(), VNI));
647 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
650 /// enterIntvAtEnd - Enter openli at the end of MBB.
651 void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
652 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
653 SlotIndex End = lis_.getMBBEndIdx(&MBB);
654 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End);
655 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(End.getPrevSlot());
657 DEBUG(dbgs() << ": not live\n");
660 DEBUG(dbgs() << ": valno " << ParentVNI->id);
661 truncatedValues.insert(ParentVNI);
662 VNInfo *VNI = openli_.defByCopyFrom(edit_.getReg(), ParentVNI,
663 MBB, MBB.getFirstTerminator());
664 // Make sure openli is live out of MBB.
665 openli_.getLI()->addRange(LiveRange(VNI->def, End, VNI));
666 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
669 /// useIntv - indicate that all instructions in MBB should use openli.
670 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
671 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
674 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
675 assert(openli_.getLI() && "openIntv not called before useIntv");
676 openli_.addRange(Start, End);
677 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
678 << *openli_.getLI() << '\n');
681 /// leaveIntvAfter - Leave openli after the instruction at Idx.
682 void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
683 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
684 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
686 // The interval must be live beyond the instruction at Idx.
687 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx.getBoundaryIndex());
689 DEBUG(dbgs() << ": not live\n");
692 DEBUG(dbgs() << ": valno " << ParentVNI->id);
694 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
695 MachineBasicBlock *MBB = MII->getParent();
696 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI, *MBB,
699 // Finally we must make sure that openli is properly extended from Idx to the
701 openli_.addSimpleRange(Idx.getBoundaryIndex(), VNI->def, ParentVNI);
702 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
705 /// leaveIntvAtTop - Leave the interval at the top of MBB.
706 /// Currently, only one value can leave the interval.
707 void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
708 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
709 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
710 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
712 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Start);
714 DEBUG(dbgs() << ": not live\n");
718 // We are going to insert a back copy, so we must have a dupli_.
719 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI,
722 // Finally we must make sure that openli is properly extended from Start to
724 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
725 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
728 /// closeIntv - Indicate that we are done editing the currently open
729 /// LiveInterval, and ranges can be trimmed.
730 void SplitEditor::closeIntv() {
731 assert(openli_.getLI() && "openIntv not called before closeIntv");
733 DEBUG(dbgs() << " closeIntv cleaning up\n");
734 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
738 /// rewrite - Rewrite all uses of reg to use the new registers.
739 void SplitEditor::rewrite(unsigned reg) {
740 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg),
741 RE = mri_.reg_end(); RI != RE;) {
742 MachineOperand &MO = RI.getOperand();
743 MachineInstr *MI = MO.getParent();
745 if (MI->isDebugValue()) {
746 DEBUG(dbgs() << "Zapping " << *MI);
747 // FIXME: We can do much better with debug values.
751 SlotIndex Idx = lis_.getInstructionIndex(MI);
752 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
753 LiveInterval *LI = 0;
754 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E;
756 LiveInterval *testli = *I;
757 if (testli->liveAt(Idx)) {
762 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'<< Idx);
763 assert(LI && "No register was live at use");
765 DEBUG(dbgs() << '\t' << *MI);
770 SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
771 // Build vector of iterator pairs from the intervals.
772 typedef std::pair<LiveInterval::const_iterator,
773 LiveInterval::const_iterator> IIPair;
774 SmallVector<IIPair, 8> Iters;
775 for (LiveRangeEdit::iterator LI = edit_.begin(), LE = edit_.end(); LI != LE;
777 if (*LI == dupli_.getLI())
779 LiveInterval::const_iterator I = (*LI)->find(Start);
780 LiveInterval::const_iterator E = (*LI)->end();
782 Iters.push_back(std::make_pair(I, E));
785 SlotIndex sidx = Start;
786 // Break [Start;End) into segments that don't overlap any intervals.
788 SlotIndex next = sidx, eidx = End;
789 // Find overlapping intervals.
790 for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) {
791 LiveInterval::const_iterator I = Iters[i].first;
792 // Interval I is overlapping [sidx;eidx). Trim sidx.
793 if (I->start <= sidx) {
795 // Move to the next run, remove iters when all are consumed.
796 I = ++Iters[i].first;
797 if (I == Iters[i].second) {
798 Iters.erase(Iters.begin() + i);
803 // Trim eidx too if needed.
804 if (I->start >= eidx)
809 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
811 dupli_.addSimpleRange(sidx, eidx, VNI);
812 // If the interval end was truncated, we can try again from next.
819 void SplitEditor::computeRemainder() {
820 // First we need to fill in the live ranges in dupli.
821 // If values were redefined, we need a full recoloring with SSA update.
822 // If values were truncated, we only need to truncate the ranges.
823 // If values were partially rematted, we should shrink to uses.
824 // If values were fully rematted, they should be omitted.
825 // FIXME: If a single value is redefined, just move the def and truncate.
826 LiveInterval &parent = edit_.getParent();
828 // Values that are fully contained in the split intervals.
829 SmallPtrSet<const VNInfo*, 8> deadValues;
830 // Map all curli values that should have live defs in dupli.
831 for (LiveInterval::const_vni_iterator I = parent.vni_begin(),
832 E = parent.vni_end(); I != E; ++I) {
833 const VNInfo *VNI = *I;
834 // Original def is contained in the split intervals.
835 if (intervalsLiveAt(VNI->def)) {
836 // Did this value escape?
837 if (dupli_.isMapped(VNI))
838 truncatedValues.insert(VNI);
840 deadValues.insert(VNI);
843 // Add minimal live range at the definition.
844 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
845 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
848 // Add all ranges to dupli.
849 for (LiveInterval::const_iterator I = parent.begin(), E = parent.end();
851 const LiveRange &LR = *I;
852 if (truncatedValues.count(LR.valno)) {
853 // recolor after removing intervals_.
854 addTruncSimpleRange(LR.start, LR.end, LR.valno);
855 } else if (!deadValues.count(LR.valno)) {
856 // recolor without truncation.
857 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
862 void SplitEditor::finish() {
863 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
864 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
866 // Complete dupli liveness.
869 // Get rid of unused values and set phi-kill flags.
870 dupli_.getLI()->RenumberValues(lis_);
872 // Now check if dupli was separated into multiple connected components.
873 ConnectedVNInfoEqClasses ConEQ(lis_);
874 if (unsigned NumComp = ConEQ.Classify(dupli_.getLI())) {
875 DEBUG(dbgs() << " Remainder has " << NumComp << " connected components: "
876 << *dupli_.getLI() << '\n');
877 // Did the remainder break up? Create intervals for all the components.
879 SmallVector<LiveInterval*, 8> dups;
880 dups.push_back(dupli_.getLI());
881 for (unsigned i = 1; i != NumComp; ++i)
882 dups.push_back(&edit_.create(mri_, lis_, vrm_));
883 ConEQ.Distribute(&dups[0]);
884 // Rewrite uses to the new regs.
885 rewrite(dupli_.getLI()->reg);
889 // Rewrite instructions.
890 rewrite(edit_.getReg());
892 // Calculate spill weight and allocation hints for new intervals.
893 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
894 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I){
895 LiveInterval &li = **I;
896 vrai.CalculateRegClass(li.reg);
897 vrai.CalculateWeightAndHint(li);
898 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
899 << ":" << li << '\n');
904 //===----------------------------------------------------------------------===//
906 //===----------------------------------------------------------------------===//
908 void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
909 SplitAnalysis::LoopBlocks Blocks;
910 sa_.getLoopBlocks(Loop, Blocks);
913 dbgs() << " splitAround"; sa_.print(Blocks, dbgs()); dbgs() << '\n';
916 // Break critical edges as needed.
917 SplitAnalysis::BlockPtrSet CriticalExits;
918 sa_.getCriticalExits(Blocks, CriticalExits);
919 assert(CriticalExits.empty() && "Cannot break critical exits yet");
921 // Create new live interval for the loop.
924 // Insert copies in the predecessors.
925 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
926 E = Blocks.Preds.end(); I != E; ++I) {
927 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
931 // Switch all loop blocks.
932 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
933 E = Blocks.Loop.end(); I != E; ++I)
936 // Insert back copies in the exit blocks.
937 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
938 E = Blocks.Exits.end(); I != E; ++I) {
939 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
949 //===----------------------------------------------------------------------===//
950 // Single Block Splitting
951 //===----------------------------------------------------------------------===//
953 /// splitSingleBlocks - Split curli into a separate live interval inside each
954 /// basic block in Blocks.
955 void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
956 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
957 // Determine the first and last instruction using curli in each block.
958 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
959 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
960 IndexPairMap MBBRange;
961 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
962 E = sa_.usingInstrs_.end(); I != E; ++I) {
963 const MachineBasicBlock *MBB = (*I)->getParent();
964 if (!Blocks.count(MBB))
966 SlotIndex Idx = lis_.getInstructionIndex(*I);
967 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
968 IndexPair &IP = MBBRange[MBB];
969 if (!IP.first.isValid() || Idx < IP.first)
971 if (!IP.second.isValid() || Idx > IP.second)
975 // Create a new interval for each block.
976 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
977 E = Blocks.end(); I != E; ++I) {
978 IndexPair &IP = MBBRange[*I];
979 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
980 << IP.first << ';' << IP.second << ")\n");
981 assert(IP.first.isValid() && IP.second.isValid());
984 enterIntvBefore(IP.first);
985 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
986 leaveIntvAfter(IP.second);
993 //===----------------------------------------------------------------------===//
994 // Sub Block Splitting
995 //===----------------------------------------------------------------------===//
997 /// getBlockForInsideSplit - If curli is contained inside a single basic block,
998 /// and it wou pay to subdivide the interval inside that block, return it.
999 /// Otherwise return NULL. The returned block can be passed to
1000 /// SplitEditor::splitInsideBlock.
1001 const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1002 // The interval must be exclusive to one block.
1003 if (usingBlocks_.size() != 1)
1005 // Don't to this for less than 4 instructions. We want to be sure that
1006 // splitting actually reduces the instruction count per interval.
1007 if (usingInstrs_.size() < 4)
1009 return usingBlocks_.begin()->first;
1012 /// splitInsideBlock - Split curli into multiple intervals inside MBB.
1013 void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
1014 SmallVector<SlotIndex, 32> Uses;
1015 Uses.reserve(sa_.usingInstrs_.size());
1016 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1017 E = sa_.usingInstrs_.end(); I != E; ++I)
1018 if ((*I)->getParent() == MBB)
1019 Uses.push_back(lis_.getInstructionIndex(*I));
1020 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1021 << Uses.size() << " instructions.\n");
1022 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1023 array_pod_sort(Uses.begin(), Uses.end());
1025 // Simple algorithm: Find the largest gap between uses as determined by slot
1026 // indices. Create new intervals for instructions before the gap and after the
1028 unsigned bestPos = 0;
1030 DEBUG(dbgs() << " dist (" << Uses[0]);
1031 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1032 int g = Uses[i-1].distance(Uses[i]);
1033 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1035 bestPos = i, bestGap = g;
1037 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1039 // bestPos points to the first use after the best gap.
1040 assert(bestPos > 0 && "Invalid gap");
1042 // FIXME: Don't create intervals for low densities.
1044 // First interval before the gap. Don't create single-instr intervals.
1047 enterIntvBefore(Uses.front());
1048 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1049 leaveIntvAfter(Uses[bestPos-1]);
1053 // Second interval after the gap.
1054 if (bestPos < Uses.size()-1) {
1056 enterIntvBefore(Uses[bestPos]);
1057 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1058 leaveIntvAfter(Uses.back());