SplitKit.cpp revision 2b0f9e73d8623b21fc14335ef6208deab2629cdf
1//===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the SplitAnalysis class as well as mutator functions for
11// live range splitting.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
16#include "SplitKit.h"
17#include "LiveRangeEdit.h"
18#include "VirtRegMap.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/CodeGen/CalcSpillWeights.h"
21#include "llvm/CodeGen/LiveIntervalAnalysis.h"
22#include "llvm/CodeGen/MachineDominators.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetMachine.h"
30
31using namespace llvm;
32
33static cl::opt<bool>
34AllowSplit("spiller-splits-edges",
35           cl::desc("Allow critical edge splitting during spilling"));
36
37STATISTIC(NumFinished, "Number of splits finished");
38STATISTIC(NumSimple,   "Number of splits that were simple");
39
40//===----------------------------------------------------------------------===//
41//                                 Split Analysis
42//===----------------------------------------------------------------------===//
43
44SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm,
45                             const LiveIntervals &lis,
46                             const MachineLoopInfo &mli)
47  : MF(vrm.getMachineFunction()),
48    VRM(vrm),
49    LIS(lis),
50    Loops(mli),
51    TII(*MF.getTarget().getInstrInfo()),
52    CurLI(0) {}
53
54void SplitAnalysis::clear() {
55  UseSlots.clear();
56  UsingInstrs.clear();
57  UsingBlocks.clear();
58  LiveBlocks.clear();
59  CurLI = 0;
60}
61
62bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
63  MachineBasicBlock *T, *F;
64  SmallVector<MachineOperand, 4> Cond;
65  return !TII.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
66}
67
68/// analyzeUses - Count instructions, basic blocks, and loops using CurLI.
69void SplitAnalysis::analyzeUses() {
70  const MachineRegisterInfo &MRI = MF.getRegInfo();
71  for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(CurLI->reg),
72       E = MRI.reg_end(); I != E; ++I) {
73    MachineOperand &MO = I.getOperand();
74    if (MO.isUse() && MO.isUndef())
75      continue;
76    MachineInstr *MI = MO.getParent();
77    if (MI->isDebugValue() || !UsingInstrs.insert(MI))
78      continue;
79    UseSlots.push_back(LIS.getInstructionIndex(MI).getDefIndex());
80    MachineBasicBlock *MBB = MI->getParent();
81    UsingBlocks[MBB]++;
82  }
83  array_pod_sort(UseSlots.begin(), UseSlots.end());
84
85  // Compute per-live block info.
86  if (!calcLiveBlockInfo()) {
87    // FIXME: calcLiveBlockInfo found inconsistencies in the live range.
88    // I am looking at you, SimpleRegisterCoalescing!
89    DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n");
90    const_cast<LiveIntervals&>(LIS)
91      .shrinkToUses(const_cast<LiveInterval*>(CurLI));
92    LiveBlocks.clear();
93    bool fixed = calcLiveBlockInfo();
94    (void)fixed;
95    assert(fixed && "Couldn't fix broken live interval");
96  }
97
98  DEBUG(dbgs() << "  counted "
99               << UsingInstrs.size() << " instrs, "
100               << UsingBlocks.size() << " blocks.\n");
101}
102
103/// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
104/// where CurLI is live.
105bool SplitAnalysis::calcLiveBlockInfo() {
106  if (CurLI->empty())
107    return true;
108
109  LiveInterval::const_iterator LVI = CurLI->begin();
110  LiveInterval::const_iterator LVE = CurLI->end();
111
112  SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE;
113  UseI = UseSlots.begin();
114  UseE = UseSlots.end();
115
116  // Loop over basic blocks where CurLI is live.
117  MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start);
118  for (;;) {
119    BlockInfo BI;
120    BI.MBB = MFI;
121    tie(BI.Start, BI.Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
122
123    // The last split point is the latest possible insertion point that dominates
124    // all successor blocks. If interference reaches LastSplitPoint, it is not
125    // possible to insert a split or reload that makes CurLI live in the
126    // outgoing bundle.
127    MachineBasicBlock::iterator LSP = LIS.getLastSplitPoint(*CurLI, BI.MBB);
128    if (LSP == BI.MBB->end())
129      BI.LastSplitPoint = BI.Stop;
130    else
131      BI.LastSplitPoint = LIS.getInstructionIndex(LSP);
132
133    // LVI is the first live segment overlapping MBB.
134    BI.LiveIn = LVI->start <= BI.Start;
135    if (!BI.LiveIn)
136      BI.Def = LVI->start;
137
138    // Find the first and last uses in the block.
139    BI.Uses = hasUses(MFI);
140    if (BI.Uses && UseI != UseE) {
141      BI.FirstUse = *UseI;
142      assert(BI.FirstUse >= BI.Start);
143      do ++UseI;
144      while (UseI != UseE && *UseI < BI.Stop);
145      BI.LastUse = UseI[-1];
146      assert(BI.LastUse < BI.Stop);
147    }
148
149    // Look for gaps in the live range.
150    bool hasGap = false;
151    BI.LiveOut = true;
152    while (LVI->end < BI.Stop) {
153      SlotIndex LastStop = LVI->end;
154      if (++LVI == LVE || LVI->start >= BI.Stop) {
155        BI.Kill = LastStop;
156        BI.LiveOut = false;
157        break;
158      }
159      if (LastStop < LVI->start) {
160        hasGap = true;
161        BI.Kill = LastStop;
162        BI.Def = LVI->start;
163      }
164    }
165
166    // Don't set LiveThrough when the block has a gap.
167    BI.LiveThrough = !hasGap && BI.LiveIn && BI.LiveOut;
168    LiveBlocks.push_back(BI);
169
170    // FIXME: This should never happen. The live range stops or starts without a
171    // corresponding use. An earlier pass did something wrong.
172    if (!BI.LiveThrough && !BI.Uses)
173      return false;
174
175    // LVI is now at LVE or LVI->end >= Stop.
176    if (LVI == LVE)
177      break;
178
179    // Live segment ends exactly at Stop. Move to the next segment.
180    if (LVI->end == BI.Stop && ++LVI == LVE)
181      break;
182
183    // Pick the next basic block.
184    if (LVI->start < BI.Stop)
185      ++MFI;
186    else
187      MFI = LIS.getMBBFromIndex(LVI->start);
188  }
189  return true;
190}
191
192bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const {
193  unsigned OrigReg = VRM.getOriginal(CurLI->reg);
194  const LiveInterval &Orig = LIS.getInterval(OrigReg);
195  assert(!Orig.empty() && "Splitting empty interval?");
196  LiveInterval::const_iterator I = Orig.find(Idx);
197
198  // Range containing Idx should begin at Idx.
199  if (I != Orig.end() && I->start <= Idx)
200    return I->start == Idx;
201
202  // Range does not contain Idx, previous must end at Idx.
203  return I != Orig.begin() && (--I)->end == Idx;
204}
205
206void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const {
207  for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) {
208    unsigned count = UsingBlocks.lookup(*I);
209    OS << " BB#" << (*I)->getNumber();
210    if (count)
211      OS << '(' << count << ')';
212  }
213}
214
215void SplitAnalysis::analyze(const LiveInterval *li) {
216  clear();
217  CurLI = li;
218  analyzeUses();
219}
220
221
222//===----------------------------------------------------------------------===//
223//                               Split Editor
224//===----------------------------------------------------------------------===//
225
226/// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
227SplitEditor::SplitEditor(SplitAnalysis &sa,
228                         LiveIntervals &lis,
229                         VirtRegMap &vrm,
230                         MachineDominatorTree &mdt)
231  : SA(sa), LIS(lis), VRM(vrm),
232    MRI(vrm.getMachineFunction().getRegInfo()),
233    MDT(mdt),
234    TII(*vrm.getMachineFunction().getTarget().getInstrInfo()),
235    TRI(*vrm.getMachineFunction().getTarget().getRegisterInfo()),
236    Edit(0),
237    OpenIdx(0),
238    RegAssign(Allocator)
239{}
240
241void SplitEditor::reset(LiveRangeEdit &lre) {
242  Edit = &lre;
243  OpenIdx = 0;
244  RegAssign.clear();
245  Values.clear();
246
247  // We don't need to clear LiveOutCache, only LiveOutSeen entries are read.
248  LiveOutSeen.clear();
249
250  // We don't need an AliasAnalysis since we will only be performing
251  // cheap-as-a-copy remats anyway.
252  Edit->anyRematerializable(LIS, TII, 0);
253}
254
255void SplitEditor::dump() const {
256  if (RegAssign.empty()) {
257    dbgs() << " empty\n";
258    return;
259  }
260
261  for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I)
262    dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value();
263  dbgs() << '\n';
264}
265
266VNInfo *SplitEditor::defValue(unsigned RegIdx,
267                              const VNInfo *ParentVNI,
268                              SlotIndex Idx) {
269  assert(ParentVNI && "Mapping  NULL value");
270  assert(Idx.isValid() && "Invalid SlotIndex");
271  assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI");
272  LiveInterval *LI = Edit->get(RegIdx);
273
274  // Create a new value.
275  VNInfo *VNI = LI->getNextValue(Idx, 0, LIS.getVNInfoAllocator());
276
277  // Preserve the PHIDef bit.
278  if (ParentVNI->isPHIDef() && Idx == ParentVNI->def)
279    VNI->setIsPHIDef(true);
280
281  // Use insert for lookup, so we can add missing values with a second lookup.
282  std::pair<ValueMap::iterator, bool> InsP =
283    Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id), VNI));
284
285  // This was the first time (RegIdx, ParentVNI) was mapped.
286  // Keep it as a simple def without any liveness.
287  if (InsP.second)
288    return VNI;
289
290  // If the previous value was a simple mapping, add liveness for it now.
291  if (VNInfo *OldVNI = InsP.first->second) {
292    SlotIndex Def = OldVNI->def;
293    LI->addRange(LiveRange(Def, Def.getNextSlot(), OldVNI));
294    // No longer a simple mapping.
295    InsP.first->second = 0;
296  }
297
298  // This is a complex mapping, add liveness for VNI
299  SlotIndex Def = VNI->def;
300  LI->addRange(LiveRange(Def, Def.getNextSlot(), VNI));
301
302  return VNI;
303}
304
305void SplitEditor::markComplexMapped(unsigned RegIdx, const VNInfo *ParentVNI) {
306  assert(ParentVNI && "Mapping  NULL value");
307  VNInfo *&VNI = Values[std::make_pair(RegIdx, ParentVNI->id)];
308
309  // ParentVNI was either unmapped or already complex mapped. Either way.
310  if (!VNI)
311    return;
312
313  // This was previously a single mapping. Make sure the old def is represented
314  // by a trivial live range.
315  SlotIndex Def = VNI->def;
316  Edit->get(RegIdx)->addRange(LiveRange(Def, Def.getNextSlot(), VNI));
317  VNI = 0;
318}
319
320// extendRange - Extend the live range to reach Idx.
321// Potentially create phi-def values.
322void SplitEditor::extendRange(unsigned RegIdx, SlotIndex Idx) {
323  assert(Idx.isValid() && "Invalid SlotIndex");
324  MachineBasicBlock *IdxMBB = LIS.getMBBFromIndex(Idx);
325  assert(IdxMBB && "No MBB at Idx");
326  LiveInterval *LI = Edit->get(RegIdx);
327
328  // Is there a def in the same MBB we can extend?
329  if (LI->extendInBlock(LIS.getMBBStartIdx(IdxMBB), Idx))
330    return;
331
332  // Now for the fun part. We know that ParentVNI potentially has multiple defs,
333  // and we may need to create even more phi-defs to preserve VNInfo SSA form.
334  // Perform a search for all predecessor blocks where we know the dominating
335  // VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
336
337  // Initialize the live-out cache the first time it is needed.
338  if (LiveOutSeen.empty()) {
339    unsigned N = VRM.getMachineFunction().getNumBlockIDs();
340    LiveOutSeen.resize(N);
341    LiveOutCache.resize(N);
342  }
343
344  // Blocks where LI should be live-in.
345  SmallVector<MachineDomTreeNode*, 16> LiveIn;
346  LiveIn.push_back(MDT[IdxMBB]);
347
348  // Remember if we have seen more than one value.
349  bool UniqueVNI = true;
350  VNInfo *IdxVNI = 0;
351
352  // Using LiveOutCache as a visited set, perform a BFS for all reaching defs.
353  for (unsigned i = 0; i != LiveIn.size(); ++i) {
354    MachineBasicBlock *MBB = LiveIn[i]->getBlock();
355    for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
356           PE = MBB->pred_end(); PI != PE; ++PI) {
357       MachineBasicBlock *Pred = *PI;
358       LiveOutPair &LOP = LiveOutCache[Pred];
359
360       // Is this a known live-out block?
361       if (LiveOutSeen.test(Pred->getNumber())) {
362         if (VNInfo *VNI = LOP.first) {
363           if (IdxVNI && IdxVNI != VNI)
364             UniqueVNI = false;
365           IdxVNI = VNI;
366         }
367         continue;
368       }
369
370       // First time. LOP is garbage and must be cleared below.
371       LiveOutSeen.set(Pred->getNumber());
372
373       // Does Pred provide a live-out value?
374       SlotIndex Start, Last;
375       tie(Start, Last) = LIS.getSlotIndexes()->getMBBRange(Pred);
376       Last = Last.getPrevSlot();
377       VNInfo *VNI = LI->extendInBlock(Start, Last);
378       LOP.first = VNI;
379       if (VNI) {
380         LOP.second = MDT[LIS.getMBBFromIndex(VNI->def)];
381         if (IdxVNI && IdxVNI != VNI)
382           UniqueVNI = false;
383         IdxVNI = VNI;
384         continue;
385       }
386       LOP.second = 0;
387
388       // No, we need a live-in value for Pred as well
389       if (Pred != IdxMBB)
390         LiveIn.push_back(MDT[Pred]);
391       else
392         UniqueVNI = false; // Loopback to IdxMBB, ask updateSSA() for help.
393    }
394  }
395
396  // We may need to add phi-def values to preserve the SSA form.
397  if (UniqueVNI) {
398    LiveOutPair LOP(IdxVNI, MDT[LIS.getMBBFromIndex(IdxVNI->def)]);
399    // Update LiveOutCache, but skip IdxMBB at LiveIn[0].
400    for (unsigned i = 1, e = LiveIn.size(); i != e; ++i)
401      LiveOutCache[LiveIn[i]->getBlock()] = LOP;
402  } else
403    IdxVNI = updateSSA(RegIdx, LiveIn, Idx, IdxMBB);
404
405  // Since we went through the trouble of a full BFS visiting all reaching defs,
406  // the values in LiveIn are now accurate. No more phi-defs are needed
407  // for these blocks, so we can color the live ranges.
408  for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) {
409    MachineBasicBlock *MBB = LiveIn[i]->getBlock();
410    SlotIndex Start = LIS.getMBBStartIdx(MBB);
411    VNInfo *VNI = LiveOutCache[MBB].first;
412
413    // Anything in LiveIn other than IdxMBB is live-through.
414    // In IdxMBB, we should stop at Idx unless the same value is live-out.
415    if (MBB == IdxMBB && IdxVNI != VNI)
416      LI->addRange(LiveRange(Start, Idx.getNextSlot(), IdxVNI));
417    else
418      LI->addRange(LiveRange(Start, LIS.getMBBEndIdx(MBB), VNI));
419  }
420}
421
422VNInfo *SplitEditor::updateSSA(unsigned RegIdx,
423                               SmallVectorImpl<MachineDomTreeNode*> &LiveIn,
424                               SlotIndex Idx,
425                               const MachineBasicBlock *IdxMBB) {
426  // This is essentially the same iterative algorithm that SSAUpdater uses,
427  // except we already have a dominator tree, so we don't have to recompute it.
428  LiveInterval *LI = Edit->get(RegIdx);
429  VNInfo *IdxVNI = 0;
430  unsigned Changes;
431  do {
432    Changes = 0;
433    // Propagate live-out values down the dominator tree, inserting phi-defs
434    // when necessary. Since LiveIn was created by a BFS, going backwards makes
435    // it more likely for us to visit immediate dominators before their
436    // children.
437    for (unsigned i = LiveIn.size(); i; --i) {
438      MachineDomTreeNode *Node = LiveIn[i-1];
439      MachineBasicBlock *MBB = Node->getBlock();
440      MachineDomTreeNode *IDom = Node->getIDom();
441      LiveOutPair IDomValue;
442
443      // We need a live-in value to a block with no immediate dominator?
444      // This is probably an unreachable block that has survived somehow.
445      bool needPHI = !IDom || !LiveOutSeen.test(IDom->getBlock()->getNumber());
446
447      // IDom dominates all of our predecessors, but it may not be the immediate
448      // dominator. Check if any of them have live-out values that are properly
449      // dominated by IDom. If so, we need a phi-def here.
450      if (!needPHI) {
451        IDomValue = LiveOutCache[IDom->getBlock()];
452        for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
453               PE = MBB->pred_end(); PI != PE; ++PI) {
454          LiveOutPair Value = LiveOutCache[*PI];
455          if (!Value.first || Value.first == IDomValue.first)
456            continue;
457          // This predecessor is carrying something other than IDomValue.
458          // It could be because IDomValue hasn't propagated yet, or it could be
459          // because MBB is in the dominance frontier of that value.
460          if (MDT.dominates(IDom, Value.second)) {
461            needPHI = true;
462            break;
463          }
464        }
465      }
466
467      // Create a phi-def if required.
468      if (needPHI) {
469        ++Changes;
470        SlotIndex Start = LIS.getMBBStartIdx(MBB);
471        VNInfo *VNI = LI->getNextValue(Start, 0, LIS.getVNInfoAllocator());
472        VNI->setIsPHIDef(true);
473        // We no longer need LI to be live-in.
474        LiveIn.erase(LiveIn.begin()+(i-1));
475        // Blocks in LiveIn are either IdxMBB, or have a value live-through.
476        if (MBB == IdxMBB)
477          IdxVNI = VNI;
478        // Check if we need to update live-out info.
479        LiveOutPair &LOP = LiveOutCache[MBB];
480        if (LOP.second == Node || !LiveOutSeen.test(MBB->getNumber())) {
481          // We already have a live-out defined in MBB, so this must be IdxMBB.
482          assert(MBB == IdxMBB && "Adding phi-def to known live-out");
483          LI->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
484        } else {
485          // This phi-def is also live-out, so color the whole block.
486          LI->addRange(LiveRange(Start, LIS.getMBBEndIdx(MBB), VNI));
487          LOP = LiveOutPair(VNI, Node);
488        }
489      } else if (IDomValue.first) {
490        // No phi-def here. Remember incoming value for IdxMBB.
491        if (MBB == IdxMBB) {
492          IdxVNI = IDomValue.first;
493          // IdxMBB need not be live-out.
494          if (!LiveOutSeen.test(MBB->getNumber()))
495            continue;
496        }
497        assert(LiveOutSeen.test(MBB->getNumber()) && "Expected live-out block");
498        // Propagate IDomValue if needed:
499        // MBB is live-out and doesn't define its own value.
500        LiveOutPair &LOP = LiveOutCache[MBB];
501        if (LOP.second != Node && LOP.first != IDomValue.first) {
502          ++Changes;
503          LOP = IDomValue;
504        }
505      }
506    }
507  } while (Changes);
508
509  assert(IdxVNI && "Didn't find value for Idx");
510  return IdxVNI;
511}
512
513VNInfo *SplitEditor::defFromParent(unsigned RegIdx,
514                                   VNInfo *ParentVNI,
515                                   SlotIndex UseIdx,
516                                   MachineBasicBlock &MBB,
517                                   MachineBasicBlock::iterator I) {
518  MachineInstr *CopyMI = 0;
519  SlotIndex Def;
520  LiveInterval *LI = Edit->get(RegIdx);
521
522  // Attempt cheap-as-a-copy rematerialization.
523  LiveRangeEdit::Remat RM(ParentVNI);
524  if (Edit->canRematerializeAt(RM, UseIdx, true, LIS)) {
525    Def = Edit->rematerializeAt(MBB, I, LI->reg, RM, LIS, TII, TRI);
526  } else {
527    // Can't remat, just insert a copy from parent.
528    CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg)
529               .addReg(Edit->getReg());
530    Def = LIS.InsertMachineInstrInMaps(CopyMI).getDefIndex();
531  }
532
533  // Define the value in Reg.
534  VNInfo *VNI = defValue(RegIdx, ParentVNI, Def);
535  VNI->setCopy(CopyMI);
536  return VNI;
537}
538
539/// Create a new virtual register and live interval.
540void SplitEditor::openIntv() {
541  assert(!OpenIdx && "Previous LI not closed before openIntv");
542
543  // Create the complement as index 0.
544  if (Edit->empty())
545    Edit->create(MRI, LIS, VRM);
546
547  // Create the open interval.
548  OpenIdx = Edit->size();
549  Edit->create(MRI, LIS, VRM);
550}
551
552SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) {
553  assert(OpenIdx && "openIntv not called before enterIntvBefore");
554  DEBUG(dbgs() << "    enterIntvBefore " << Idx);
555  Idx = Idx.getBaseIndex();
556  VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
557  if (!ParentVNI) {
558    DEBUG(dbgs() << ": not live\n");
559    return Idx;
560  }
561  DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
562  MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
563  assert(MI && "enterIntvBefore called with invalid index");
564
565  VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI);
566  return VNI->def;
567}
568
569SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
570  assert(OpenIdx && "openIntv not called before enterIntvAtEnd");
571  SlotIndex End = LIS.getMBBEndIdx(&MBB);
572  SlotIndex Last = End.getPrevSlot();
573  DEBUG(dbgs() << "    enterIntvAtEnd BB#" << MBB.getNumber() << ", " << Last);
574  VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last);
575  if (!ParentVNI) {
576    DEBUG(dbgs() << ": not live\n");
577    return End;
578  }
579  DEBUG(dbgs() << ": valno " << ParentVNI->id);
580  VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB,
581                              LIS.getLastSplitPoint(Edit->getParent(), &MBB));
582  RegAssign.insert(VNI->def, End, OpenIdx);
583  DEBUG(dump());
584  return VNI->def;
585}
586
587/// useIntv - indicate that all instructions in MBB should use OpenLI.
588void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
589  useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB));
590}
591
592void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
593  assert(OpenIdx && "openIntv not called before useIntv");
594  DEBUG(dbgs() << "    useIntv [" << Start << ';' << End << "):");
595  RegAssign.insert(Start, End, OpenIdx);
596  DEBUG(dump());
597}
598
599SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) {
600  assert(OpenIdx && "openIntv not called before leaveIntvAfter");
601  DEBUG(dbgs() << "    leaveIntvAfter " << Idx);
602
603  // The interval must be live beyond the instruction at Idx.
604  Idx = Idx.getBoundaryIndex();
605  VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
606  if (!ParentVNI) {
607    DEBUG(dbgs() << ": not live\n");
608    return Idx.getNextSlot();
609  }
610  DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
611
612  MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
613  assert(MI && "No instruction at index");
614  VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(),
615                              llvm::next(MachineBasicBlock::iterator(MI)));
616  return VNI->def;
617}
618
619SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) {
620  assert(OpenIdx && "openIntv not called before leaveIntvBefore");
621  DEBUG(dbgs() << "    leaveIntvBefore " << Idx);
622
623  // The interval must be live into the instruction at Idx.
624  Idx = Idx.getBoundaryIndex();
625  VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
626  if (!ParentVNI) {
627    DEBUG(dbgs() << ": not live\n");
628    return Idx.getNextSlot();
629  }
630  DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
631
632  MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
633  assert(MI && "No instruction at index");
634  VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
635  return VNI->def;
636}
637
638SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
639  assert(OpenIdx && "openIntv not called before leaveIntvAtTop");
640  SlotIndex Start = LIS.getMBBStartIdx(&MBB);
641  DEBUG(dbgs() << "    leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
642
643  VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
644  if (!ParentVNI) {
645    DEBUG(dbgs() << ": not live\n");
646    return Start;
647  }
648
649  VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB,
650                              MBB.SkipPHIsAndLabels(MBB.begin()));
651  RegAssign.insert(Start, VNI->def, OpenIdx);
652  DEBUG(dump());
653  return VNI->def;
654}
655
656void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) {
657  assert(OpenIdx && "openIntv not called before overlapIntv");
658  const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
659  assert(ParentVNI == Edit->getParent().getVNInfoAt(End.getPrevSlot()) &&
660         "Parent changes value in extended range");
661  assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) &&
662         "Range cannot span basic blocks");
663
664  // The complement interval will be extended as needed by extendRange().
665  markComplexMapped(0, ParentVNI);
666  DEBUG(dbgs() << "    overlapIntv [" << Start << ';' << End << "):");
667  RegAssign.insert(Start, End, OpenIdx);
668  DEBUG(dump());
669}
670
671/// closeIntv - Indicate that we are done editing the currently open
672/// LiveInterval, and ranges can be trimmed.
673void SplitEditor::closeIntv() {
674  assert(OpenIdx && "openIntv not called before closeIntv");
675  OpenIdx = 0;
676}
677
678/// transferSimpleValues - Transfer all simply defined values to the new live
679/// ranges.
680/// Values that were rematerialized or that have multiple defs are left alone.
681bool SplitEditor::transferSimpleValues() {
682  bool Skipped = false;
683  RegAssignMap::const_iterator AssignI = RegAssign.begin();
684  for (LiveInterval::const_iterator ParentI = Edit->getParent().begin(),
685         ParentE = Edit->getParent().end(); ParentI != ParentE; ++ParentI) {
686    DEBUG(dbgs() << "  blit " << *ParentI << ':');
687    VNInfo *ParentVNI = ParentI->valno;
688    // RegAssign has holes where RegIdx 0 should be used.
689    SlotIndex Start = ParentI->start;
690    AssignI.advanceTo(Start);
691    do {
692      unsigned RegIdx;
693      SlotIndex End = ParentI->end;
694      if (!AssignI.valid()) {
695        RegIdx = 0;
696      } else if (AssignI.start() <= Start) {
697        RegIdx = AssignI.value();
698        if (AssignI.stop() < End) {
699          End = AssignI.stop();
700          ++AssignI;
701        }
702      } else {
703        RegIdx = 0;
704        End = std::min(End, AssignI.start());
705      }
706      DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx);
707      if (VNInfo *VNI = Values.lookup(std::make_pair(RegIdx, ParentVNI->id))) {
708        DEBUG(dbgs() << ':' << VNI->id);
709        Edit->get(RegIdx)->addRange(LiveRange(Start, End, VNI));
710      } else
711        Skipped = true;
712      Start = End;
713    } while (Start != ParentI->end);
714    DEBUG(dbgs() << '\n');
715  }
716  return Skipped;
717}
718
719void SplitEditor::extendPHIKillRanges() {
720    // Extend live ranges to be live-out for successor PHI values.
721  for (LiveInterval::const_vni_iterator I = Edit->getParent().vni_begin(),
722       E = Edit->getParent().vni_end(); I != E; ++I) {
723    const VNInfo *PHIVNI = *I;
724    if (PHIVNI->isUnused() || !PHIVNI->isPHIDef())
725      continue;
726    unsigned RegIdx = RegAssign.lookup(PHIVNI->def);
727    MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def);
728    for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
729         PE = MBB->pred_end(); PI != PE; ++PI) {
730      SlotIndex End = LIS.getMBBEndIdx(*PI).getPrevSlot();
731      // The predecessor may not have a live-out value. That is OK, like an
732      // undef PHI operand.
733      if (Edit->getParent().liveAt(End)) {
734        assert(RegAssign.lookup(End) == RegIdx &&
735               "Different register assignment in phi predecessor");
736        extendRange(RegIdx, End);
737      }
738    }
739  }
740}
741
742/// rewriteAssigned - Rewrite all uses of Edit->getReg().
743void SplitEditor::rewriteAssigned(bool ExtendRanges) {
744  for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()),
745       RE = MRI.reg_end(); RI != RE;) {
746    MachineOperand &MO = RI.getOperand();
747    MachineInstr *MI = MO.getParent();
748    ++RI;
749    // LiveDebugVariables should have handled all DBG_VALUE instructions.
750    if (MI->isDebugValue()) {
751      DEBUG(dbgs() << "Zapping " << *MI);
752      MO.setReg(0);
753      continue;
754    }
755
756    // <undef> operands don't really read the register, so just assign them to
757    // the complement.
758    if (MO.isUse() && MO.isUndef()) {
759      MO.setReg(Edit->get(0)->reg);
760      continue;
761    }
762
763    SlotIndex Idx = LIS.getInstructionIndex(MI);
764    Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
765
766    // Rewrite to the mapped register at Idx.
767    unsigned RegIdx = RegAssign.lookup(Idx);
768    MO.setReg(Edit->get(RegIdx)->reg);
769    DEBUG(dbgs() << "  rewr BB#" << MI->getParent()->getNumber() << '\t'
770                 << Idx << ':' << RegIdx << '\t' << *MI);
771
772    // Extend liveness to Idx.
773    if (ExtendRanges)
774      extendRange(RegIdx, Idx);
775  }
776}
777
778/// rewriteSplit - Rewrite uses of Intvs[0] according to the ConEQ mapping.
779void SplitEditor::rewriteComponents(const SmallVectorImpl<LiveInterval*> &Intvs,
780                                    const ConnectedVNInfoEqClasses &ConEq) {
781  for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Intvs[0]->reg),
782       RE = MRI.reg_end(); RI != RE;) {
783    MachineOperand &MO = RI.getOperand();
784    MachineInstr *MI = MO.getParent();
785    ++RI;
786    if (MO.isUse() && MO.isUndef())
787      continue;
788    // DBG_VALUE instructions should have been eliminated earlier.
789    SlotIndex Idx = LIS.getInstructionIndex(MI);
790    Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
791    DEBUG(dbgs() << "  rewr BB#" << MI->getParent()->getNumber() << '\t'
792                 << Idx << ':');
793    const VNInfo *VNI = Intvs[0]->getVNInfoAt(Idx);
794    assert(VNI && "Interval not live at use.");
795    MO.setReg(Intvs[ConEq.getEqClass(VNI)]->reg);
796    DEBUG(dbgs() << VNI->id << '\t' << *MI);
797  }
798}
799
800void SplitEditor::finish() {
801  assert(OpenIdx == 0 && "Previous LI not closed before rewrite");
802  ++NumFinished;
803
804  // At this point, the live intervals in Edit contain VNInfos corresponding to
805  // the inserted copies.
806
807  // Add the original defs from the parent interval.
808  for (LiveInterval::const_vni_iterator I = Edit->getParent().vni_begin(),
809         E = Edit->getParent().vni_end(); I != E; ++I) {
810    const VNInfo *ParentVNI = *I;
811    if (ParentVNI->isUnused())
812      continue;
813    unsigned RegIdx = RegAssign.lookup(ParentVNI->def);
814    defValue(RegIdx, ParentVNI, ParentVNI->def);
815    // Mark rematted values as complex everywhere to force liveness computation.
816    // The new live ranges may be truncated.
817    if (Edit->didRematerialize(ParentVNI))
818      for (unsigned i = 0, e = Edit->size(); i != e; ++i)
819        markComplexMapped(i, ParentVNI);
820  }
821
822#ifndef NDEBUG
823  // Every new interval must have a def by now, otherwise the split is bogus.
824  for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I)
825    assert((*I)->hasAtLeastOneValue() && "Split interval has no value");
826#endif
827
828  // Transfer the simply mapped values, check if any are complex.
829  bool Complex = transferSimpleValues();
830  if (Complex)
831    extendPHIKillRanges();
832  else
833    ++NumSimple;
834
835  // Rewrite virtual registers, possibly extending ranges.
836  rewriteAssigned(Complex);
837
838  // FIXME: Delete defs that were rematted everywhere.
839
840  // Get rid of unused values and set phi-kill flags.
841  for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I)
842    (*I)->RenumberValues(LIS);
843
844  // Now check if any registers were separated into multiple components.
845  ConnectedVNInfoEqClasses ConEQ(LIS);
846  for (unsigned i = 0, e = Edit->size(); i != e; ++i) {
847    // Don't use iterators, they are invalidated by create() below.
848    LiveInterval *li = Edit->get(i);
849    unsigned NumComp = ConEQ.Classify(li);
850    if (NumComp <= 1)
851      continue;
852    DEBUG(dbgs() << "  " << NumComp << " components: " << *li << '\n');
853    SmallVector<LiveInterval*, 8> dups;
854    dups.push_back(li);
855    for (unsigned i = 1; i != NumComp; ++i)
856      dups.push_back(&Edit->create(MRI, LIS, VRM));
857    rewriteComponents(dups, ConEQ);
858    ConEQ.Distribute(&dups[0]);
859  }
860
861  // Calculate spill weight and allocation hints for new intervals.
862  VirtRegAuxInfo vrai(VRM.getMachineFunction(), LIS, SA.Loops);
863  for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I){
864    LiveInterval &li = **I;
865    vrai.CalculateRegClass(li.reg);
866    vrai.CalculateWeightAndHint(li);
867    DEBUG(dbgs() << "  new interval " << MRI.getRegClass(li.reg)->getName()
868                 << ":" << li << '\n');
869  }
870}
871
872
873//===----------------------------------------------------------------------===//
874//                            Single Block Splitting
875//===----------------------------------------------------------------------===//
876
877/// getMultiUseBlocks - if CurLI has more than one use in a basic block, it
878/// may be an advantage to split CurLI for the duration of the block.
879bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
880  // If CurLI is local to one block, there is no point to splitting it.
881  if (LiveBlocks.size() <= 1)
882    return false;
883  // Add blocks with multiple uses.
884  for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
885    const BlockInfo &BI = LiveBlocks[i];
886    if (!BI.Uses)
887      continue;
888    unsigned Instrs = UsingBlocks.lookup(BI.MBB);
889    if (Instrs <= 1)
890      continue;
891    if (Instrs == 2 && BI.LiveIn && BI.LiveOut && !BI.LiveThrough)
892      continue;
893    Blocks.insert(BI.MBB);
894  }
895  return !Blocks.empty();
896}
897
898/// splitSingleBlocks - Split CurLI into a separate live interval inside each
899/// basic block in Blocks.
900void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
901  DEBUG(dbgs() << "  splitSingleBlocks for " << Blocks.size() << " blocks.\n");
902
903  for (unsigned i = 0, e = SA.LiveBlocks.size(); i != e; ++i) {
904    const SplitAnalysis::BlockInfo &BI = SA.LiveBlocks[i];
905    if (!BI.Uses || !Blocks.count(BI.MBB))
906      continue;
907
908    openIntv();
909    SlotIndex SegStart = enterIntvBefore(BI.FirstUse);
910    if (!BI.LiveOut || BI.LastUse < BI.LastSplitPoint) {
911      useIntv(SegStart, leaveIntvAfter(BI.LastUse));
912    } else {
913      // The last use is after the last valid split point.
914      SlotIndex SegStop = leaveIntvBefore(BI.LastSplitPoint);
915      useIntv(SegStart, SegStop);
916      overlapIntv(SegStop, BI.LastUse);
917    }
918    closeIntv();
919  }
920  finish();
921}
922