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