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/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() {
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 E = MRI.reg_end(); I != E; ++I) {
68 MachineOperand &MO = I.getOperand();
69 if (MO.isUse() && MO.isUndef())
71 MachineInstr *MI = MO.getParent();
72 if (MI->isDebugValue() || !UsingInstrs.insert(MI))
74 UseSlots.push_back(LIS.getInstructionIndex(MI).getDefIndex());
75 MachineBasicBlock *MBB = MI->getParent();
78 array_pod_sort(UseSlots.begin(), UseSlots.end());
80 DEBUG(dbgs() << " counted "
81 << UsingInstrs.size() << " instrs, "
82 << UsingBlocks.size() << " blocks.\n");
85 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
86 /// where CurLI is live.
87 void SplitAnalysis::calcLiveBlockInfo() {
91 LiveInterval::const_iterator LVI = CurLI->begin();
92 LiveInterval::const_iterator LVE = CurLI->end();
94 SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE;
95 UseI = UseSlots.begin();
96 UseE = UseSlots.end();
98 // Loop over basic blocks where CurLI is live.
99 MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start);
103 SlotIndex Start, Stop;
104 tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
106 // The last split point is the latest possible insertion point that dominates
107 // all successor blocks. If interference reaches LastSplitPoint, it is not
108 // possible to insert a split or reload that makes CurLI live in the
110 MachineBasicBlock::iterator LSP = LIS.getLastSplitPoint(*CurLI, BI.MBB);
111 if (LSP == BI.MBB->end())
112 BI.LastSplitPoint = Stop;
114 BI.LastSplitPoint = LIS.getInstructionIndex(LSP);
116 // LVI is the first live segment overlapping MBB.
117 BI.LiveIn = LVI->start <= Start;
121 // Find the first and last uses in the block.
122 BI.Uses = hasUses(MFI);
123 if (BI.Uses && UseI != UseE) {
125 assert(BI.FirstUse >= Start);
127 while (UseI != UseE && *UseI < Stop);
128 BI.LastUse = UseI[-1];
129 assert(BI.LastUse < Stop);
132 // Look for gaps in the live range.
135 while (LVI->end < Stop) {
136 SlotIndex LastStop = LVI->end;
137 if (++LVI == LVE || LVI->start >= Stop) {
142 if (LastStop < LVI->start) {
149 // Don't set LiveThrough when the block has a gap.
150 BI.LiveThrough = !hasGap && BI.LiveIn && BI.LiveOut;
151 LiveBlocks.push_back(BI);
153 // LVI is now at LVE or LVI->end >= Stop.
157 // Live segment ends exactly at Stop. Move to the next segment.
158 if (LVI->end == Stop && ++LVI == LVE)
161 // Pick the next basic block.
162 if (LVI->start < Stop)
165 MFI = LIS.getMBBFromIndex(LVI->start);
169 void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const {
170 for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) {
171 unsigned count = UsingBlocks.lookup(*I);
172 OS << " BB#" << (*I)->getNumber();
174 OS << '(' << count << ')';
178 void SplitAnalysis::analyze(const LiveInterval *li) {
185 //===----------------------------------------------------------------------===//
187 //===----------------------------------------------------------------------===//
189 // Work around the fact that the std::pair constructors are broken for pointer
190 // pairs in some implementations. makeVV(x, 0) works.
191 static inline std::pair<const VNInfo*, VNInfo*>
192 makeVV(const VNInfo *a, VNInfo *b) {
193 return std::make_pair(a, b);
196 void LiveIntervalMap::reset(LiveInterval *li) {
199 LiveOutCache.clear();
202 bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
203 ValueMap::const_iterator i = Values.find(ParentVNI);
204 return i != Values.end() && i->second == 0;
207 // defValue - Introduce a LI def for ParentVNI that could be later than
209 VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
210 assert(LI && "call reset first");
211 assert(ParentVNI && "Mapping NULL value");
212 assert(Idx.isValid() && "Invalid SlotIndex");
213 assert(ParentLI.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
215 // Create a new value.
216 VNInfo *VNI = LI->getNextValue(Idx, 0, LIS.getVNInfoAllocator());
218 // Preserve the PHIDef bit.
219 if (ParentVNI->isPHIDef() && Idx == ParentVNI->def)
220 VNI->setIsPHIDef(true);
222 // Use insert for lookup, so we can add missing values with a second lookup.
223 std::pair<ValueMap::iterator,bool> InsP =
224 Values.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
226 // This is now a complex def. Mark with a NULL in valueMap.
228 InsP.first->second = 0;
234 // mapValue - Find the mapped value for ParentVNI at Idx.
235 // Potentially create phi-def values.
236 VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
238 assert(LI && "call reset first");
239 assert(ParentVNI && "Mapping NULL value");
240 assert(Idx.isValid() && "Invalid SlotIndex");
241 assert(ParentLI.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
243 // Use insert for lookup, so we can add missing values with a second lookup.
244 std::pair<ValueMap::iterator,bool> InsP =
245 Values.insert(makeVV(ParentVNI, 0));
247 // This was an unknown value. Create a simple mapping.
249 if (simple) *simple = true;
250 return InsP.first->second = LI->createValueCopy(ParentVNI,
251 LIS.getVNInfoAllocator());
254 // This was a simple mapped value.
255 if (InsP.first->second) {
256 if (simple) *simple = true;
257 return InsP.first->second;
260 // This is a complex mapped value. There may be multiple defs, and we may need
261 // to create phi-defs.
262 if (simple) *simple = false;
263 MachineBasicBlock *IdxMBB = LIS.getMBBFromIndex(Idx);
264 assert(IdxMBB && "No MBB at Idx");
266 // Is there a def in the same MBB we can extend?
267 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
270 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
271 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
272 // Perform a search for all predecessor blocks where we know the dominating
273 // VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
274 DEBUG(dbgs() << "\n Reaching defs for BB#" << IdxMBB->getNumber()
275 << " at " << Idx << " in " << *LI << '\n');
277 // Blocks where LI should be live-in.
278 SmallVector<MachineDomTreeNode*, 16> LiveIn;
279 LiveIn.push_back(MDT[IdxMBB]);
281 // Using LiveOutCache as a visited set, perform a BFS for all reaching defs.
282 for (unsigned i = 0; i != LiveIn.size(); ++i) {
283 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
284 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
285 PE = MBB->pred_end(); PI != PE; ++PI) {
286 MachineBasicBlock *Pred = *PI;
287 // Is this a known live-out block?
288 std::pair<LiveOutMap::iterator,bool> LOIP =
289 LiveOutCache.insert(std::make_pair(Pred, LiveOutPair()));
290 // Yes, we have been here before.
292 DEBUG(if (VNInfo *VNI = LOIP.first->second.first)
293 dbgs() << " known valno #" << VNI->id
294 << " at BB#" << Pred->getNumber() << '\n');
298 // Does Pred provide a live-out value?
299 SlotIndex Last = LIS.getMBBEndIdx(Pred).getPrevSlot();
300 if (VNInfo *VNI = extendTo(Pred, Last)) {
301 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(VNI->def);
302 DEBUG(dbgs() << " found valno #" << VNI->id
303 << " from BB#" << DefMBB->getNumber()
304 << " at BB#" << Pred->getNumber() << '\n');
305 LiveOutPair &LOP = LOIP.first->second;
307 LOP.second = MDT[DefMBB];
310 // No, we need a live-in value for Pred as well
312 LiveIn.push_back(MDT[Pred]);
316 // We may need to add phi-def values to preserve the SSA form.
317 // This is essentially the same iterative algorithm that SSAUpdater uses,
318 // except we already have a dominator tree, so we don't have to recompute it.
323 DEBUG(dbgs() << " Iterating over " << LiveIn.size() << " blocks.\n");
324 // Propagate live-out values down the dominator tree, inserting phi-defs when
325 // necessary. Since LiveIn was created by a BFS, going backwards makes it more
326 // likely for us to visit immediate dominators before their children.
327 for (unsigned i = LiveIn.size(); i; --i) {
328 MachineDomTreeNode *Node = LiveIn[i-1];
329 MachineBasicBlock *MBB = Node->getBlock();
330 MachineDomTreeNode *IDom = Node->getIDom();
331 LiveOutPair IDomValue;
332 // We need a live-in value to a block with no immediate dominator?
333 // This is probably an unreachable block that has survived somehow.
334 bool needPHI = !IDom;
336 // Get the IDom live-out value.
338 LiveOutMap::iterator I = LiveOutCache.find(IDom->getBlock());
339 if (I != LiveOutCache.end())
340 IDomValue = I->second;
342 // If IDom is outside our set of live-out blocks, there must be new
343 // defs, and we need a phi-def here.
347 // IDom dominates all of our predecessors, but it may not be the immediate
348 // dominator. Check if any of them have live-out values that are properly
349 // dominated by IDom. If so, we need a phi-def here.
351 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
352 PE = MBB->pred_end(); PI != PE; ++PI) {
353 LiveOutPair Value = LiveOutCache[*PI];
354 if (!Value.first || Value.first == IDomValue.first)
356 // This predecessor is carrying something other than IDomValue.
357 // It could be because IDomValue hasn't propagated yet, or it could be
358 // because MBB is in the dominance frontier of that value.
359 if (MDT.dominates(IDom, Value.second)) {
366 // Create a phi-def if required.
369 SlotIndex Start = LIS.getMBBStartIdx(MBB);
370 VNInfo *VNI = LI->getNextValue(Start, 0, LIS.getVNInfoAllocator());
371 VNI->setIsPHIDef(true);
372 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
373 << " phi-def #" << VNI->id << " at " << Start << '\n');
374 // We no longer need LI to be live-in.
375 LiveIn.erase(LiveIn.begin()+(i-1));
376 // Blocks in LiveIn are either IdxMBB, or have a value live-through.
379 // Check if we need to update live-out info.
380 LiveOutMap::iterator I = LiveOutCache.find(MBB);
381 if (I == LiveOutCache.end() || I->second.second == Node) {
382 // We already have a live-out defined in MBB, so this must be IdxMBB.
383 assert(MBB == IdxMBB && "Adding phi-def to known live-out");
384 LI->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
386 // This phi-def is also live-out, so color the whole block.
387 LI->addRange(LiveRange(Start, LIS.getMBBEndIdx(MBB), VNI));
388 I->second = LiveOutPair(VNI, Node);
390 } else if (IDomValue.first) {
391 // No phi-def here. Remember incoming value for IdxMBB.
393 IdxVNI = IDomValue.first;
394 // Propagate IDomValue if needed:
395 // MBB is live-out and doesn't define its own value.
396 LiveOutMap::iterator I = LiveOutCache.find(MBB);
397 if (I != LiveOutCache.end() && I->second.second != Node &&
398 I->second.first != IDomValue.first) {
400 I->second = IDomValue;
401 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
402 << " idom valno #" << IDomValue.first->id
403 << " from BB#" << IDom->getBlock()->getNumber() << '\n');
407 DEBUG(dbgs() << " - made " << Changes << " changes.\n");
410 assert(IdxVNI && "Didn't find value for Idx");
413 // Check the LiveOutCache invariants.
414 for (LiveOutMap::iterator I = LiveOutCache.begin(), E = LiveOutCache.end();
416 assert(I->first && "Null MBB entry in cache");
417 assert(I->second.first && "Null VNInfo in cache");
418 assert(I->second.second && "Null DomTreeNode in cache");
419 if (I->second.second->getBlock() == I->first)
421 for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(),
422 PE = I->first->pred_end(); PI != PE; ++PI)
423 assert(LiveOutCache.lookup(*PI) == I->second && "Bad invariant");
427 // Since we went through the trouble of a full BFS visiting all reaching defs,
428 // the values in LiveIn are now accurate. No more phi-defs are needed
429 // for these blocks, so we can color the live ranges.
430 // This makes the next mapValue call much faster.
431 for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) {
432 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
433 SlotIndex Start = LIS.getMBBStartIdx(MBB);
434 VNInfo *VNI = LiveOutCache.lookup(MBB).first;
436 // Anything in LiveIn other than IdxMBB is live-through.
437 // In IdxMBB, we should stop at Idx unless the same value is live-out.
438 if (MBB == IdxMBB && IdxVNI != VNI)
439 LI->addRange(LiveRange(Start, Idx.getNextSlot(), IdxVNI));
441 LI->addRange(LiveRange(Start, LIS.getMBBEndIdx(MBB), VNI));
448 void LiveIntervalMap::dumpCache() {
449 for (LiveOutMap::iterator I = LiveOutCache.begin(), E = LiveOutCache.end();
451 assert(I->first && "Null MBB entry in cache");
452 assert(I->second.first && "Null VNInfo in cache");
453 assert(I->second.second && "Null DomTreeNode in cache");
454 dbgs() << " cache: BB#" << I->first->getNumber()
455 << " has valno #" << I->second.first->id << " from BB#"
456 << I->second.second->getBlock()->getNumber() << ", preds";
457 for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(),
458 PE = I->first->pred_end(); PI != PE; ++PI)
459 dbgs() << " BB#" << (*PI)->getNumber();
462 dbgs() << " cache: " << LiveOutCache.size() << " entries.\n";
466 // extendTo - Find the last LI value defined in MBB at or before Idx. The
467 // ParentLI is assumed to be live at Idx. Extend the live range to Idx.
468 // Return the found VNInfo, or NULL.
469 VNInfo *LiveIntervalMap::extendTo(const MachineBasicBlock *MBB, SlotIndex Idx) {
470 assert(LI && "call reset first");
471 LiveInterval::iterator I = std::upper_bound(LI->begin(), LI->end(), Idx);
472 if (I == LI->begin())
475 if (I->end <= LIS.getMBBStartIdx(MBB))
478 I->end = Idx.getNextSlot();
482 // addSimpleRange - Add a simple range from ParentLI to LI.
483 // ParentVNI must be live in the [Start;End) interval.
484 void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
485 const VNInfo *ParentVNI) {
486 assert(LI && "call reset first");
488 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
489 // A simple mapping is easy.
491 LI->addRange(LiveRange(Start, End, VNI));
495 // ParentVNI is a complex value. We must map per MBB.
496 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
497 MachineFunction::iterator MBBE = LIS.getMBBFromIndex(End.getPrevSlot());
500 LI->addRange(LiveRange(Start, End, VNI));
505 LI->addRange(LiveRange(Start, LIS.getMBBEndIdx(MBB), VNI));
507 // Run sequence of full blocks.
508 for (++MBB; MBB != MBBE; ++MBB) {
509 Start = LIS.getMBBStartIdx(MBB);
510 LI->addRange(LiveRange(Start, LIS.getMBBEndIdx(MBB),
511 mapValue(ParentVNI, Start)));
515 Start = LIS.getMBBStartIdx(MBB);
517 LI->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
520 /// addRange - Add live ranges to LI where [Start;End) intersects ParentLI.
521 /// All needed values whose def is not inside [Start;End) must be defined
522 /// beforehand so mapValue will work.
523 void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
524 assert(LI && "call reset first");
525 LiveInterval::const_iterator B = ParentLI.begin(), E = ParentLI.end();
526 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
528 // Check if --I begins before Start and overlaps.
532 addSimpleRange(Start, std::min(End, I->end), I->valno);
536 // The remaining ranges begin after Start.
537 for (;I != E && I->start < End; ++I)
538 addSimpleRange(I->start, std::min(End, I->end), I->valno);
542 //===----------------------------------------------------------------------===//
544 //===----------------------------------------------------------------------===//
546 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
547 SplitEditor::SplitEditor(SplitAnalysis &sa,
550 MachineDominatorTree &mdt,
552 : sa_(sa), LIS(lis), VRM(vrm),
553 MRI(vrm.getMachineFunction().getRegInfo()),
555 TII(*vrm.getMachineFunction().getTarget().getInstrInfo()),
556 TRI(*vrm.getMachineFunction().getTarget().getRegisterInfo()),
561 // We don't need an AliasAnalysis since we will only be performing
562 // cheap-as-a-copy remats anyway.
563 Edit.anyRematerializable(LIS, TII, 0);
566 void SplitEditor::dump() const {
567 if (RegAssign.empty()) {
568 dbgs() << " empty\n";
572 for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I)
573 dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value();
577 VNInfo *SplitEditor::defFromParent(unsigned RegIdx,
580 MachineBasicBlock &MBB,
581 MachineBasicBlock::iterator I) {
582 MachineInstr *CopyMI = 0;
584 LiveInterval *LI = Edit.get(RegIdx);
586 // Attempt cheap-as-a-copy rematerialization.
587 LiveRangeEdit::Remat RM(ParentVNI);
588 if (Edit.canRematerializeAt(RM, UseIdx, true, LIS)) {
589 Def = Edit.rematerializeAt(MBB, I, LI->reg, RM, LIS, TII, TRI);
591 // Can't remat, just insert a copy from parent.
592 CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg)
593 .addReg(Edit.getReg());
594 Def = LIS.InsertMachineInstrInMaps(CopyMI).getDefIndex();
597 // Define the value in Reg.
598 VNInfo *VNI = LIMappers[RegIdx].defValue(ParentVNI, Def);
599 VNI->setCopy(CopyMI);
601 // Add minimal liveness for the new value.
602 Edit.get(RegIdx)->addRange(LiveRange(Def, Def.getNextSlot(), VNI));
606 /// Create a new virtual register and live interval.
607 void SplitEditor::openIntv() {
608 assert(!OpenIdx && "Previous LI not closed before openIntv");
610 // Create the complement as index 0.
612 Edit.create(MRI, LIS, VRM);
613 LIMappers.push_back(LiveIntervalMap(LIS, MDT, Edit.getParent()));
614 LIMappers.back().reset(Edit.get(0));
617 // Create the open interval.
618 OpenIdx = Edit.size();
619 Edit.create(MRI, LIS, VRM);
620 LIMappers.push_back(LiveIntervalMap(LIS, MDT, Edit.getParent()));
621 LIMappers[OpenIdx].reset(Edit.get(OpenIdx));
624 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) {
625 assert(OpenIdx && "openIntv not called before enterIntvBefore");
626 DEBUG(dbgs() << " enterIntvBefore " << Idx);
627 Idx = Idx.getBaseIndex();
628 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Idx);
630 DEBUG(dbgs() << ": not live\n");
633 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
634 MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
635 assert(MI && "enterIntvBefore called with invalid index");
637 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI);
641 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
642 assert(OpenIdx && "openIntv not called before enterIntvAtEnd");
643 SlotIndex End = LIS.getMBBEndIdx(&MBB);
644 SlotIndex Last = End.getPrevSlot();
645 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << Last);
646 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Last);
648 DEBUG(dbgs() << ": not live\n");
651 DEBUG(dbgs() << ": valno " << ParentVNI->id);
652 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB,
653 LIS.getLastSplitPoint(Edit.getParent(), &MBB));
654 RegAssign.insert(VNI->def, End, OpenIdx);
659 /// useIntv - indicate that all instructions in MBB should use OpenLI.
660 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
661 useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB));
664 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
665 assert(OpenIdx && "openIntv not called before useIntv");
666 DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):");
667 RegAssign.insert(Start, End, OpenIdx);
671 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) {
672 assert(OpenIdx && "openIntv not called before leaveIntvAfter");
673 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
675 // The interval must be live beyond the instruction at Idx.
676 Idx = Idx.getBoundaryIndex();
677 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Idx);
679 DEBUG(dbgs() << ": not live\n");
680 return Idx.getNextSlot();
682 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
684 MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
685 assert(MI && "No instruction at index");
686 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(),
687 llvm::next(MachineBasicBlock::iterator(MI)));
691 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) {
692 assert(OpenIdx && "openIntv not called before leaveIntvBefore");
693 DEBUG(dbgs() << " leaveIntvBefore " << Idx);
695 // The interval must be live into the instruction at Idx.
696 Idx = Idx.getBoundaryIndex();
697 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Idx);
699 DEBUG(dbgs() << ": not live\n");
700 return Idx.getNextSlot();
702 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
704 MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
705 assert(MI && "No instruction at index");
706 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
710 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
711 assert(OpenIdx && "openIntv not called before leaveIntvAtTop");
712 SlotIndex Start = LIS.getMBBStartIdx(&MBB);
713 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
715 VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Start);
717 DEBUG(dbgs() << ": not live\n");
721 VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB,
722 MBB.SkipPHIsAndLabels(MBB.begin()));
723 RegAssign.insert(Start, VNI->def, OpenIdx);
728 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) {
729 assert(OpenIdx && "openIntv not called before overlapIntv");
730 assert(Edit.getParent().getVNInfoAt(Start) ==
731 Edit.getParent().getVNInfoAt(End.getPrevSlot()) &&
732 "Parent changes value in extended range");
733 assert(Edit.get(0)->getVNInfoAt(Start) && "Start must come from leaveIntv*");
734 assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) &&
735 "Range cannot span basic blocks");
737 // Treat this as useIntv() for now. The complement interval will be extended
738 // as needed by mapValue().
739 DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):");
740 RegAssign.insert(Start, End, OpenIdx);
744 /// closeIntv - Indicate that we are done editing the currently open
745 /// LiveInterval, and ranges can be trimmed.
746 void SplitEditor::closeIntv() {
747 assert(OpenIdx && "openIntv not called before closeIntv");
751 /// rewriteAssigned - Rewrite all uses of Edit.getReg().
752 void SplitEditor::rewriteAssigned() {
753 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit.getReg()),
754 RE = MRI.reg_end(); RI != RE;) {
755 MachineOperand &MO = RI.getOperand();
756 MachineInstr *MI = MO.getParent();
758 // LiveDebugVariables should have handled all DBG_VALUE instructions.
759 if (MI->isDebugValue()) {
760 DEBUG(dbgs() << "Zapping " << *MI);
765 // <undef> operands don't really read the register, so just assign them to
767 if (MO.isUse() && MO.isUndef()) {
768 MO.setReg(Edit.get(0)->reg);
772 SlotIndex Idx = LIS.getInstructionIndex(MI);
773 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
775 // Rewrite to the mapped register at Idx.
776 unsigned RegIdx = RegAssign.lookup(Idx);
777 MO.setReg(Edit.get(RegIdx)->reg);
778 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'
779 << Idx << ':' << RegIdx << '\t' << *MI);
781 // Extend liveness to Idx.
782 const VNInfo *ParentVNI = Edit.getParent().getVNInfoAt(Idx);
783 LIMappers[RegIdx].mapValue(ParentVNI, Idx);
787 /// rewriteSplit - Rewrite uses of Intvs[0] according to the ConEQ mapping.
788 void SplitEditor::rewriteComponents(const SmallVectorImpl<LiveInterval*> &Intvs,
789 const ConnectedVNInfoEqClasses &ConEq) {
790 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Intvs[0]->reg),
791 RE = MRI.reg_end(); RI != RE;) {
792 MachineOperand &MO = RI.getOperand();
793 MachineInstr *MI = MO.getParent();
795 if (MO.isUse() && MO.isUndef())
797 // DBG_VALUE instructions should have been eliminated earlier.
798 SlotIndex Idx = LIS.getInstructionIndex(MI);
799 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
800 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'
802 const VNInfo *VNI = Intvs[0]->getVNInfoAt(Idx);
803 assert(VNI && "Interval not live at use.");
804 MO.setReg(Intvs[ConEq.getEqClass(VNI)]->reg);
805 DEBUG(dbgs() << VNI->id << '\t' << *MI);
809 void SplitEditor::finish() {
810 assert(OpenIdx == 0 && "Previous LI not closed before rewrite");
812 // At this point, the live intervals in Edit contain VNInfos corresponding to
813 // the inserted copies.
815 // Add the original defs from the parent interval.
816 for (LiveInterval::const_vni_iterator I = Edit.getParent().vni_begin(),
817 E = Edit.getParent().vni_end(); I != E; ++I) {
818 const VNInfo *ParentVNI = *I;
819 if (ParentVNI->isUnused())
821 LiveIntervalMap &LIM = LIMappers[RegAssign.lookup(ParentVNI->def)];
822 VNInfo *VNI = LIM.defValue(ParentVNI, ParentVNI->def);
823 LIM.getLI()->addRange(LiveRange(ParentVNI->def,
824 ParentVNI->def.getNextSlot(), VNI));
825 // Mark all values as complex to force liveness computation.
826 // This should really only be necessary for remat victims, but we are lazy.
827 LIM.markComplexMapped(ParentVNI);
831 // Every new interval must have a def by now, otherwise the split is bogus.
832 for (LiveRangeEdit::iterator I = Edit.begin(), E = Edit.end(); I != E; ++I)
833 assert((*I)->hasAtLeastOneValue() && "Split interval has no value");
836 // FIXME: Don't recompute the liveness of all values, infer it from the
837 // overlaps between the parent live interval and RegAssign.
838 // The mapValue algorithm is only necessary when:
839 // - The parent value maps to multiple defs, and new phis are needed, or
840 // - The value has been rematerialized before some uses, and we want to
841 // minimize the live range so it only reaches the remaining uses.
842 // All other values have simple liveness that can be computed from RegAssign
843 // and the parent live interval.
845 // Extend live ranges to be live-out for successor PHI values.
846 for (LiveInterval::const_vni_iterator I = Edit.getParent().vni_begin(),
847 E = Edit.getParent().vni_end(); I != E; ++I) {
848 const VNInfo *PHIVNI = *I;
849 if (PHIVNI->isUnused() || !PHIVNI->isPHIDef())
851 unsigned RegIdx = RegAssign.lookup(PHIVNI->def);
852 LiveIntervalMap &LIM = LIMappers[RegIdx];
853 MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def);
854 DEBUG(dbgs() << " map phi in BB#" << MBB->getNumber() << '@' << PHIVNI->def
855 << " -> " << RegIdx << '\n');
856 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
857 PE = MBB->pred_end(); PI != PE; ++PI) {
858 SlotIndex End = LIS.getMBBEndIdx(*PI).getPrevSlot();
859 DEBUG(dbgs() << " pred BB#" << (*PI)->getNumber() << '@' << End);
860 // The predecessor may not have a live-out value. That is OK, like an
861 // undef PHI operand.
862 if (VNInfo *VNI = Edit.getParent().getVNInfoAt(End)) {
863 DEBUG(dbgs() << " has parent valno #" << VNI->id << " live out\n");
864 assert(RegAssign.lookup(End) == RegIdx &&
865 "Different register assignment in phi predecessor");
866 LIM.mapValue(VNI, End);
869 DEBUG(dbgs() << " is not live-out\n");
871 DEBUG(dbgs() << " " << *LIM.getLI() << '\n');
874 // Rewrite instructions.
877 // FIXME: Delete defs that were rematted everywhere.
879 // Get rid of unused values and set phi-kill flags.
880 for (LiveRangeEdit::iterator I = Edit.begin(), E = Edit.end(); I != E; ++I)
881 (*I)->RenumberValues(LIS);
883 // Now check if any registers were separated into multiple components.
884 ConnectedVNInfoEqClasses ConEQ(LIS);
885 for (unsigned i = 0, e = Edit.size(); i != e; ++i) {
886 // Don't use iterators, they are invalidated by create() below.
887 LiveInterval *li = Edit.get(i);
888 unsigned NumComp = ConEQ.Classify(li);
891 DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n');
892 SmallVector<LiveInterval*, 8> dups;
894 for (unsigned i = 1; i != NumComp; ++i)
895 dups.push_back(&Edit.create(MRI, LIS, VRM));
896 rewriteComponents(dups, ConEQ);
897 ConEQ.Distribute(&dups[0]);
900 // Calculate spill weight and allocation hints for new intervals.
901 VirtRegAuxInfo vrai(VRM.getMachineFunction(), LIS, sa_.Loops);
902 for (LiveRangeEdit::iterator I = Edit.begin(), E = Edit.end(); I != E; ++I){
903 LiveInterval &li = **I;
904 vrai.CalculateRegClass(li.reg);
905 vrai.CalculateWeightAndHint(li);
906 DEBUG(dbgs() << " new interval " << MRI.getRegClass(li.reg)->getName()
907 << ":" << li << '\n');
912 //===----------------------------------------------------------------------===//
913 // Single Block Splitting
914 //===----------------------------------------------------------------------===//
916 /// getMultiUseBlocks - if CurLI has more than one use in a basic block, it
917 /// may be an advantage to split CurLI for the duration of the block.
918 bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
919 // If CurLI is local to one block, there is no point to splitting it.
920 if (LiveBlocks.size() <= 1)
922 // Add blocks with multiple uses.
923 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
924 const BlockInfo &BI = LiveBlocks[i];
927 unsigned Instrs = UsingBlocks.lookup(BI.MBB);
930 if (Instrs == 2 && BI.LiveIn && BI.LiveOut && !BI.LiveThrough)
932 Blocks.insert(BI.MBB);
934 return !Blocks.empty();
937 /// splitSingleBlocks - Split CurLI into a separate live interval inside each
938 /// basic block in Blocks.
939 void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
940 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
942 for (unsigned i = 0, e = sa_.LiveBlocks.size(); i != e; ++i) {
943 const SplitAnalysis::BlockInfo &BI = sa_.LiveBlocks[i];
944 if (!BI.Uses || !Blocks.count(BI.MBB))
948 SlotIndex SegStart = enterIntvBefore(BI.FirstUse);
949 if (BI.LastUse < BI.LastSplitPoint) {
950 useIntv(SegStart, leaveIntvAfter(BI.LastUse));
952 // THe last use os after tha last valid split point.
953 SlotIndex SegStop = leaveIntvBefore(BI.LastSplitPoint);
954 useIntv(SegStart, SegStop);
955 overlapIntv(SegStop, BI.LastUse);
963 //===----------------------------------------------------------------------===//
964 // Sub Block Splitting
965 //===----------------------------------------------------------------------===//
967 /// getBlockForInsideSplit - If CurLI is contained inside a single basic block,
968 /// and it wou pay to subdivide the interval inside that block, return it.
969 /// Otherwise return NULL. The returned block can be passed to
970 /// SplitEditor::splitInsideBlock.
971 const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
972 // The interval must be exclusive to one block.
973 if (UsingBlocks.size() != 1)
975 // Don't to this for less than 4 instructions. We want to be sure that
976 // splitting actually reduces the instruction count per interval.
977 if (UsingInstrs.size() < 4)
979 return UsingBlocks.begin()->first;
982 /// splitInsideBlock - Split CurLI into multiple intervals inside MBB.
983 void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
984 SmallVector<SlotIndex, 32> Uses;
985 Uses.reserve(sa_.UsingInstrs.size());
986 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.UsingInstrs.begin(),
987 E = sa_.UsingInstrs.end(); I != E; ++I)
988 if ((*I)->getParent() == MBB)
989 Uses.push_back(LIS.getInstructionIndex(*I));
990 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
991 << Uses.size() << " instructions.\n");
992 assert(Uses.size() >= 3 && "Need at least 3 instructions");
993 array_pod_sort(Uses.begin(), Uses.end());
995 // Simple algorithm: Find the largest gap between uses as determined by slot
996 // indices. Create new intervals for instructions before the gap and after the
998 unsigned bestPos = 0;
1000 DEBUG(dbgs() << " dist (" << Uses[0]);
1001 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1002 int g = Uses[i-1].distance(Uses[i]);
1003 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1005 bestPos = i, bestGap = g;
1007 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1009 // bestPos points to the first use after the best gap.
1010 assert(bestPos > 0 && "Invalid gap");
1012 // FIXME: Don't create intervals for low densities.
1014 // First interval before the gap. Don't create single-instr intervals.
1017 useIntv(enterIntvBefore(Uses.front()), leaveIntvAfter(Uses[bestPos-1]));
1021 // Second interval after the gap.
1022 if (bestPos < Uses.size()-1) {
1024 useIntv(enterIntvBefore(Uses[bestPos]), leaveIntvAfter(Uses.back()));