SplitKit.cpp revision c64379da075a59bd5178c62c970c8d2b84457ab2
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/MachineLoopInfo.h"
24#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/GraphWriter.h"
28#include "llvm/Support/raw_ostream.h"
29#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetMachine.h"
31
32using namespace llvm;
33
34static cl::opt<bool>
35AllowSplit("spiller-splits-edges",
36           cl::desc("Allow critical edge splitting during spilling"));
37
38//===----------------------------------------------------------------------===//
39//                                 Edge Bundles
40//===----------------------------------------------------------------------===//
41
42/// compute - Compute the edge bundles for MF. Bundles depend only on the CFG.
43void EdgeBundles::compute(const MachineFunction *mf) {
44  MF = mf;
45  EC.clear();
46  EC.grow(2 * MF->size());
47
48  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
49       ++I) {
50    const MachineBasicBlock &MBB = *I;
51    unsigned OutE = 2 * MBB.getNumber() + 1;
52    // Join the outgoing bundle with the ingoing bundles of all successors.
53    for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
54           SE = MBB.succ_end(); SI != SE; ++SI)
55      EC.join(OutE, 2 * (*SI)->getNumber());
56  }
57  EC.compress();
58}
59
60/// view - Visualize the annotated bipartite CFG with Graphviz.
61void EdgeBundles::view() const {
62  ViewGraph(*this, "EdgeBundles");
63}
64
65/// Specialize WriteGraph, the standard implementation won't work.
66raw_ostream &llvm::WriteGraph(raw_ostream &O, const EdgeBundles &G,
67                              bool ShortNames,
68                              const std::string &Title) {
69  const MachineFunction *MF = G.getMachineFunction();
70
71  O << "digraph {\n";
72  for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
73       I != E; ++I) {
74    unsigned BB = I->getNumber();
75    O << "\t\"BB#" << BB << "\" [ shape=box ]\n"
76      << '\t' << G.getBundle(BB, false) << " -> \"BB#" << BB << "\"\n"
77      << "\t\"BB#" << BB << "\" -> " << G.getBundle(BB, true) << '\n';
78    for (MachineBasicBlock::const_succ_iterator SI = I->succ_begin(),
79           SE = I->succ_end(); SI != SE; ++SI)
80      O << "\t\"BB#" << BB << "\" -> \"BB#" << (*SI)->getNumber()
81        << "\" [ color=lightgray ]\n";
82  }
83  O << "}\n";
84  return O;
85}
86
87
88//===----------------------------------------------------------------------===//
89//                                 Split Analysis
90//===----------------------------------------------------------------------===//
91
92SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
93                             const LiveIntervals &lis,
94                             const MachineLoopInfo &mli)
95  : mf_(mf),
96    lis_(lis),
97    loops_(mli),
98    tii_(*mf.getTarget().getInstrInfo()),
99    curli_(0) {}
100
101void SplitAnalysis::clear() {
102  usingInstrs_.clear();
103  usingBlocks_.clear();
104  usingLoops_.clear();
105  curli_ = 0;
106}
107
108bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
109  MachineBasicBlock *T, *F;
110  SmallVector<MachineOperand, 4> Cond;
111  return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
112}
113
114/// analyzeUses - Count instructions, basic blocks, and loops using curli.
115void SplitAnalysis::analyzeUses() {
116  const MachineRegisterInfo &MRI = mf_.getRegInfo();
117  for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
118       MachineInstr *MI = I.skipInstruction();) {
119    if (MI->isDebugValue() || !usingInstrs_.insert(MI))
120      continue;
121    MachineBasicBlock *MBB = MI->getParent();
122    if (usingBlocks_[MBB]++)
123      continue;
124    for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop;
125         Loop = Loop->getParentLoop())
126      usingLoops_[Loop]++;
127  }
128  DEBUG(dbgs() << "  counted "
129               << usingInstrs_.size() << " instrs, "
130               << usingBlocks_.size() << " blocks, "
131               << usingLoops_.size()  << " loops.\n");
132}
133
134void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const {
135  for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) {
136    unsigned count = usingBlocks_.lookup(*I);
137    OS << " BB#" << (*I)->getNumber();
138    if (count)
139      OS << '(' << count << ')';
140  }
141}
142
143// Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
144// predecessor blocks, and exit blocks.
145void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
146  Blocks.clear();
147
148  // Blocks in the loop.
149  Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
150
151  // Predecessor blocks.
152  const MachineBasicBlock *Header = Loop->getHeader();
153  for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
154       E = Header->pred_end(); I != E; ++I)
155    if (!Blocks.Loop.count(*I))
156      Blocks.Preds.insert(*I);
157
158  // Exit blocks.
159  for (MachineLoop::block_iterator I = Loop->block_begin(),
160       E = Loop->block_end(); I != E; ++I) {
161    const MachineBasicBlock *MBB = *I;
162    for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
163       SE = MBB->succ_end(); SI != SE; ++SI)
164      if (!Blocks.Loop.count(*SI))
165        Blocks.Exits.insert(*SI);
166  }
167}
168
169void SplitAnalysis::print(const LoopBlocks &B, raw_ostream &OS) const {
170  OS << "Loop:";
171  print(B.Loop, OS);
172  OS << ", preds:";
173  print(B.Preds, OS);
174  OS << ", exits:";
175  print(B.Exits, OS);
176}
177
178/// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
179/// and around the Loop.
180SplitAnalysis::LoopPeripheralUse SplitAnalysis::
181analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
182  LoopPeripheralUse use = ContainedInLoop;
183  for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
184       I != E; ++I) {
185    const MachineBasicBlock *MBB = I->first;
186    // Is this a peripheral block?
187    if (use < MultiPeripheral &&
188        (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
189      if (I->second > 1) use = MultiPeripheral;
190      else               use = SinglePeripheral;
191      continue;
192    }
193    // Is it a loop block?
194    if (Blocks.Loop.count(MBB))
195      continue;
196    // It must be an unrelated block.
197    DEBUG(dbgs() << ", outside: BB#" << MBB->getNumber());
198    return OutsideLoop;
199  }
200  return use;
201}
202
203/// getCriticalExits - It may be necessary to partially break critical edges
204/// leaving the loop if an exit block has predecessors from outside the loop
205/// periphery.
206void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
207                                     BlockPtrSet &CriticalExits) {
208  CriticalExits.clear();
209
210  // A critical exit block has curli live-in, and has a predecessor that is not
211  // in the loop nor a loop predecessor. For such an exit block, the edges
212  // carrying the new variable must be moved to a new pre-exit block.
213  for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
214       I != E; ++I) {
215    const MachineBasicBlock *Exit = *I;
216    // A single-predecessor exit block is definitely not a critical edge.
217    if (Exit->pred_size() == 1)
218      continue;
219    // This exit may not have curli live in at all. No need to split.
220    if (!lis_.isLiveInToMBB(*curli_, Exit))
221      continue;
222    // Does this exit block have a predecessor that is not a loop block or loop
223    // predecessor?
224    for (MachineBasicBlock::const_pred_iterator PI = Exit->pred_begin(),
225         PE = Exit->pred_end(); PI != PE; ++PI) {
226      const MachineBasicBlock *Pred = *PI;
227      if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
228        continue;
229      // This is a critical exit block, and we need to split the exit edge.
230      CriticalExits.insert(Exit);
231      break;
232    }
233  }
234}
235
236void SplitAnalysis::getCriticalPreds(const SplitAnalysis::LoopBlocks &Blocks,
237                                     BlockPtrSet &CriticalPreds) {
238  CriticalPreds.clear();
239
240  // A critical predecessor block has curli live-out, and has a successor that
241  // has curli live-in and is not in the loop nor a loop exit block. For such a
242  // predecessor block, we must carry the value in both the 'inside' and
243  // 'outside' registers.
244  for (BlockPtrSet::iterator I = Blocks.Preds.begin(), E = Blocks.Preds.end();
245       I != E; ++I) {
246    const MachineBasicBlock *Pred = *I;
247    // Definitely not a critical edge.
248    if (Pred->succ_size() == 1)
249      continue;
250    // This block may not have curli live out at all if there is a PHI.
251    if (!lis_.isLiveOutOfMBB(*curli_, Pred))
252      continue;
253    // Does this block have a successor outside the loop?
254    for (MachineBasicBlock::const_pred_iterator SI = Pred->succ_begin(),
255         SE = Pred->succ_end(); SI != SE; ++SI) {
256      const MachineBasicBlock *Succ = *SI;
257      if (Blocks.Loop.count(Succ) || Blocks.Exits.count(Succ))
258        continue;
259      if (!lis_.isLiveInToMBB(*curli_, Succ))
260        continue;
261      // This is a critical predecessor block.
262      CriticalPreds.insert(Pred);
263      break;
264    }
265  }
266}
267
268/// canSplitCriticalExits - Return true if it is possible to insert new exit
269/// blocks before the blocks in CriticalExits.
270bool
271SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
272                                     BlockPtrSet &CriticalExits) {
273  // If we don't allow critical edge splitting, require no critical exits.
274  if (!AllowSplit)
275    return CriticalExits.empty();
276
277  for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
278       I != E; ++I) {
279    const MachineBasicBlock *Succ = *I;
280    // We want to insert a new pre-exit MBB before Succ, and change all the
281    // in-loop blocks to branch to the pre-exit instead of Succ.
282    // Check that all the in-loop predecessors can be changed.
283    for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
284         PE = Succ->pred_end(); PI != PE; ++PI) {
285      const MachineBasicBlock *Pred = *PI;
286      // The external predecessors won't be altered.
287      if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
288        continue;
289      if (!canAnalyzeBranch(Pred))
290        return false;
291    }
292
293    // If Succ's layout predecessor falls through, that too must be analyzable.
294    // We need to insert the pre-exit block in the gap.
295    MachineFunction::const_iterator MFI = Succ;
296    if (MFI == mf_.begin())
297      continue;
298    if (!canAnalyzeBranch(--MFI))
299      return false;
300  }
301  // No problems found.
302  return true;
303}
304
305void SplitAnalysis::analyze(const LiveInterval *li) {
306  clear();
307  curli_ = li;
308  analyzeUses();
309}
310
311void SplitAnalysis::getSplitLoops(LoopPtrSet &Loops) {
312  assert(curli_ && "Call analyze() before getSplitLoops");
313  if (usingLoops_.empty())
314    return;
315
316  LoopBlocks Blocks;
317  BlockPtrSet CriticalExits;
318
319  // We split around loops where curli is used outside the periphery.
320  for (LoopCountMap::const_iterator I = usingLoops_.begin(),
321       E = usingLoops_.end(); I != E; ++I) {
322    const MachineLoop *Loop = I->first;
323    getLoopBlocks(Loop, Blocks);
324    DEBUG({ dbgs() << "  "; print(Blocks, dbgs()); });
325
326    switch(analyzeLoopPeripheralUse(Blocks)) {
327    case OutsideLoop:
328      break;
329    case MultiPeripheral:
330      // FIXME: We could split a live range with multiple uses in a peripheral
331      // block and still make progress. However, it is possible that splitting
332      // another live range will insert copies into a peripheral block, and
333      // there is a small chance we can enter an infinite loop, inserting copies
334      // forever.
335      // For safety, stick to splitting live ranges with uses outside the
336      // periphery.
337      DEBUG(dbgs() << ": multiple peripheral uses");
338      break;
339    case ContainedInLoop:
340      DEBUG(dbgs() << ": fully contained\n");
341      continue;
342    case SinglePeripheral:
343      DEBUG(dbgs() << ": single peripheral use\n");
344      continue;
345    }
346    // Will it be possible to split around this loop?
347    getCriticalExits(Blocks, CriticalExits);
348    DEBUG(dbgs() << ": " << CriticalExits.size() << " critical exits\n");
349    if (!canSplitCriticalExits(Blocks, CriticalExits))
350      continue;
351    // This is a possible split.
352    Loops.insert(Loop);
353  }
354
355  DEBUG(dbgs() << "  getSplitLoops found " << Loops.size()
356               << " candidate loops.\n");
357}
358
359const MachineLoop *SplitAnalysis::getBestSplitLoop() {
360  LoopPtrSet Loops;
361  getSplitLoops(Loops);
362  if (Loops.empty())
363    return 0;
364
365  // Pick the earliest loop.
366  // FIXME: Are there other heuristics to consider?
367  const MachineLoop *Best = 0;
368  SlotIndex BestIdx;
369  for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
370       ++I) {
371    SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
372    if (!Best || Idx < BestIdx)
373      Best = *I, BestIdx = Idx;
374  }
375  DEBUG(dbgs() << "  getBestSplitLoop found " << *Best);
376  return Best;
377}
378
379/// isBypassLoop - Return true if curli is live through Loop and has no uses
380/// inside the loop. Bypass loops are candidates for splitting because it can
381/// prevent interference inside the loop.
382bool SplitAnalysis::isBypassLoop(const MachineLoop *Loop) {
383  // If curli is live into the loop header and there are no uses in the loop, it
384  // must be live in the entire loop and live on at least one exiting edge.
385  return !usingLoops_.count(Loop) &&
386         lis_.isLiveInToMBB(*curli_, Loop->getHeader());
387}
388
389/// getBypassLoops - Get all the maximal bypass loops. These are the bypass
390/// loops whose parent is not a bypass loop.
391void SplitAnalysis::getBypassLoops(LoopPtrSet &BypassLoops) {
392  SmallVector<MachineLoop*, 8> Todo(loops_.begin(), loops_.end());
393  while (!Todo.empty()) {
394    MachineLoop *Loop = Todo.pop_back_val();
395    if (!usingLoops_.count(Loop)) {
396      // This is either a bypass loop or completely irrelevant.
397      if (lis_.isLiveInToMBB(*curli_, Loop->getHeader()))
398        BypassLoops.insert(Loop);
399      // Either way, skip the child loops.
400      continue;
401    }
402
403    // The child loops may be bypass loops.
404    Todo.append(Loop->begin(), Loop->end());
405  }
406}
407
408
409//===----------------------------------------------------------------------===//
410//                               LiveIntervalMap
411//===----------------------------------------------------------------------===//
412
413// Work around the fact that the std::pair constructors are broken for pointer
414// pairs in some implementations. makeVV(x, 0) works.
415static inline std::pair<const VNInfo*, VNInfo*>
416makeVV(const VNInfo *a, VNInfo *b) {
417  return std::make_pair(a, b);
418}
419
420void LiveIntervalMap::reset(LiveInterval *li) {
421  li_ = li;
422  valueMap_.clear();
423  liveOutCache_.clear();
424}
425
426bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
427  ValueMap::const_iterator i = valueMap_.find(ParentVNI);
428  return i != valueMap_.end() && i->second == 0;
429}
430
431// defValue - Introduce a li_ def for ParentVNI that could be later than
432// ParentVNI->def.
433VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
434  assert(li_ && "call reset first");
435  assert(ParentVNI && "Mapping  NULL value");
436  assert(Idx.isValid() && "Invalid SlotIndex");
437  assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
438
439  // Create a new value.
440  VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
441
442  // Preserve the PHIDef bit.
443  if (ParentVNI->isPHIDef() && Idx == ParentVNI->def)
444    VNI->setIsPHIDef(true);
445
446  // Use insert for lookup, so we can add missing values with a second lookup.
447  std::pair<ValueMap::iterator,bool> InsP =
448    valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
449
450  // This is now a complex def. Mark with a NULL in valueMap.
451  if (!InsP.second)
452    InsP.first->second = 0;
453
454  return VNI;
455}
456
457
458// mapValue - Find the mapped value for ParentVNI at Idx.
459// Potentially create phi-def values.
460VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
461                                  bool *simple) {
462  assert(li_ && "call reset first");
463  assert(ParentVNI && "Mapping  NULL value");
464  assert(Idx.isValid() && "Invalid SlotIndex");
465  assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
466
467  // Use insert for lookup, so we can add missing values with a second lookup.
468  std::pair<ValueMap::iterator,bool> InsP =
469    valueMap_.insert(makeVV(ParentVNI, 0));
470
471  // This was an unknown value. Create a simple mapping.
472  if (InsP.second) {
473    if (simple) *simple = true;
474    return InsP.first->second = li_->createValueCopy(ParentVNI,
475                                                     lis_.getVNInfoAllocator());
476  }
477
478  // This was a simple mapped value.
479  if (InsP.first->second) {
480    if (simple) *simple = true;
481    return InsP.first->second;
482  }
483
484  // This is a complex mapped value. There may be multiple defs, and we may need
485  // to create phi-defs.
486  if (simple) *simple = false;
487  MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
488  assert(IdxMBB && "No MBB at Idx");
489
490  // Is there a def in the same MBB we can extend?
491  if (VNInfo *VNI = extendTo(IdxMBB, Idx))
492    return VNI;
493
494  // Now for the fun part. We know that ParentVNI potentially has multiple defs,
495  // and we may need to create even more phi-defs to preserve VNInfo SSA form.
496  // Perform a search for all predecessor blocks where we know the dominating
497  // VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
498  DEBUG(dbgs() << "\n  Reaching defs for BB#" << IdxMBB->getNumber()
499               << " at " << Idx << " in " << *li_ << '\n');
500
501  // Blocks where li_ should be live-in.
502  SmallVector<MachineDomTreeNode*, 16> LiveIn;
503  LiveIn.push_back(mdt_[IdxMBB]);
504
505  // Using liveOutCache_ as a visited set, perform a BFS for all reaching defs.
506  for (unsigned i = 0; i != LiveIn.size(); ++i) {
507    MachineBasicBlock *MBB = LiveIn[i]->getBlock();
508    for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
509           PE = MBB->pred_end(); PI != PE; ++PI) {
510       MachineBasicBlock *Pred = *PI;
511       // Is this a known live-out block?
512       std::pair<LiveOutMap::iterator,bool> LOIP =
513         liveOutCache_.insert(std::make_pair(Pred, LiveOutPair()));
514       // Yes, we have been here before.
515       if (!LOIP.second) {
516         DEBUG(if (VNInfo *VNI = LOIP.first->second.first)
517                 dbgs() << "    known valno #" << VNI->id
518                        << " at BB#" << Pred->getNumber() << '\n');
519         continue;
520       }
521
522       // Does Pred provide a live-out value?
523       SlotIndex Last = lis_.getMBBEndIdx(Pred).getPrevSlot();
524       if (VNInfo *VNI = extendTo(Pred, Last)) {
525         MachineBasicBlock *DefMBB = lis_.getMBBFromIndex(VNI->def);
526         DEBUG(dbgs() << "    found valno #" << VNI->id
527                      << " from BB#" << DefMBB->getNumber()
528                      << " at BB#" << Pred->getNumber() << '\n');
529         LiveOutPair &LOP = LOIP.first->second;
530         LOP.first = VNI;
531         LOP.second = mdt_[DefMBB];
532         continue;
533       }
534       // No, we need a live-in value for Pred as well
535       if (Pred != IdxMBB)
536         LiveIn.push_back(mdt_[Pred]);
537    }
538  }
539
540  // We may need to add phi-def values to preserve the SSA form.
541  // This is essentially the same iterative algorithm that SSAUpdater uses,
542  // except we already have a dominator tree, so we don't have to recompute it.
543  VNInfo *IdxVNI = 0;
544  unsigned Changes;
545  do {
546    Changes = 0;
547    DEBUG(dbgs() << "  Iterating over " << LiveIn.size() << " blocks.\n");
548    // Propagate live-out values down the dominator tree, inserting phi-defs when
549    // necessary. Since LiveIn was created by a BFS, going backwards makes it more
550    // likely for us to visit immediate dominators before their children.
551    for (unsigned i = LiveIn.size(); i; --i) {
552      MachineDomTreeNode *Node = LiveIn[i-1];
553      MachineBasicBlock *MBB = Node->getBlock();
554      MachineDomTreeNode *IDom = Node->getIDom();
555      LiveOutPair IDomValue;
556      // We need a live-in value to a block with no immediate dominator?
557      // This is probably an unreachable block that has survived somehow.
558      bool needPHI = !IDom;
559
560      // Get the IDom live-out value.
561      if (!needPHI) {
562        LiveOutMap::iterator I = liveOutCache_.find(IDom->getBlock());
563        if (I != liveOutCache_.end())
564          IDomValue = I->second;
565        else
566          // If IDom is outside our set of live-out blocks, there must be new
567          // defs, and we need a phi-def here.
568          needPHI = true;
569      }
570
571      // IDom dominates all of our predecessors, but it may not be the immediate
572      // dominator. Check if any of them have live-out values that are properly
573      // dominated by IDom. If so, we need a phi-def here.
574      if (!needPHI) {
575        for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
576               PE = MBB->pred_end(); PI != PE; ++PI) {
577          LiveOutPair Value = liveOutCache_[*PI];
578          if (!Value.first || Value.first == IDomValue.first)
579            continue;
580          // This predecessor is carrying something other than IDomValue.
581          // It could be because IDomValue hasn't propagated yet, or it could be
582          // because MBB is in the dominance frontier of that value.
583          if (mdt_.dominates(IDom, Value.second)) {
584            needPHI = true;
585            break;
586          }
587        }
588      }
589
590      // Create a phi-def if required.
591      if (needPHI) {
592        ++Changes;
593        SlotIndex Start = lis_.getMBBStartIdx(MBB);
594        VNInfo *VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
595        VNI->setIsPHIDef(true);
596        DEBUG(dbgs() << "    - BB#" << MBB->getNumber()
597                     << " phi-def #" << VNI->id << " at " << Start << '\n');
598        // We no longer need li_ to be live-in.
599        LiveIn.erase(LiveIn.begin()+(i-1));
600        // Blocks in LiveIn are either IdxMBB, or have a value live-through.
601        if (MBB == IdxMBB)
602          IdxVNI = VNI;
603        // Check if we need to update live-out info.
604        LiveOutMap::iterator I = liveOutCache_.find(MBB);
605        if (I == liveOutCache_.end() || I->second.second == Node) {
606          // We already have a live-out defined in MBB, so this must be IdxMBB.
607          assert(MBB == IdxMBB && "Adding phi-def to known live-out");
608          li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
609        } else {
610          // This phi-def is also live-out, so color the whole block.
611          li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
612          I->second = LiveOutPair(VNI, Node);
613        }
614      } else if (IDomValue.first) {
615        // No phi-def here. Remember incoming value for IdxMBB.
616        if (MBB == IdxMBB)
617          IdxVNI = IDomValue.first;
618        // Propagate IDomValue if needed:
619        // MBB is live-out and doesn't define its own value.
620        LiveOutMap::iterator I = liveOutCache_.find(MBB);
621        if (I != liveOutCache_.end() && I->second.second != Node &&
622            I->second.first != IDomValue.first) {
623          ++Changes;
624          I->second = IDomValue;
625          DEBUG(dbgs() << "    - BB#" << MBB->getNumber()
626                       << " idom valno #" << IDomValue.first->id
627                       << " from BB#" << IDom->getBlock()->getNumber() << '\n');
628        }
629      }
630    }
631    DEBUG(dbgs() << "  - made " << Changes << " changes.\n");
632  } while (Changes);
633
634  assert(IdxVNI && "Didn't find value for Idx");
635
636#ifndef NDEBUG
637  // Check the liveOutCache_ invariants.
638  for (LiveOutMap::iterator I = liveOutCache_.begin(), E = liveOutCache_.end();
639         I != E; ++I) {
640    assert(I->first && "Null MBB entry in cache");
641    assert(I->second.first && "Null VNInfo in cache");
642    assert(I->second.second && "Null DomTreeNode in cache");
643    if (I->second.second->getBlock() == I->first)
644      continue;
645    for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(),
646           PE = I->first->pred_end(); PI != PE; ++PI)
647      assert(liveOutCache_.lookup(*PI) == I->second && "Bad invariant");
648  }
649#endif
650
651  // Since we went through the trouble of a full BFS visiting all reaching defs,
652  // the values in LiveIn are now accurate. No more phi-defs are needed
653  // for these blocks, so we can color the live ranges.
654  // This makes the next mapValue call much faster.
655  for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) {
656    MachineBasicBlock *MBB = LiveIn[i]->getBlock();
657    SlotIndex Start = lis_.getMBBStartIdx(MBB);
658    if (MBB == IdxMBB) {
659      li_->addRange(LiveRange(Start, Idx.getNextSlot(), IdxVNI));
660      continue;
661    }
662    // Anything in LiveIn other than IdxMBB is live-through.
663    VNInfo *VNI = liveOutCache_.lookup(MBB).first;
664    assert(VNI && "Missing block value");
665    li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
666  }
667
668  return IdxVNI;
669}
670
671// extendTo - Find the last li_ value defined in MBB at or before Idx. The
672// parentli_ is assumed to be live at Idx. Extend the live range to Idx.
673// Return the found VNInfo, or NULL.
674VNInfo *LiveIntervalMap::extendTo(const MachineBasicBlock *MBB, SlotIndex Idx) {
675  assert(li_ && "call reset first");
676  LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
677  if (I == li_->begin())
678    return 0;
679  --I;
680  if (I->end <= lis_.getMBBStartIdx(MBB))
681    return 0;
682  if (I->end <= Idx)
683    I->end = Idx.getNextSlot();
684  return I->valno;
685}
686
687// addSimpleRange - Add a simple range from parentli_ to li_.
688// ParentVNI must be live in the [Start;End) interval.
689void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
690                                     const VNInfo *ParentVNI) {
691  assert(li_ && "call reset first");
692  bool simple;
693  VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
694  // A simple mapping is easy.
695  if (simple) {
696    li_->addRange(LiveRange(Start, End, VNI));
697    return;
698  }
699
700  // ParentVNI is a complex value. We must map per MBB.
701  MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
702  MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
703
704  if (MBB == MBBE) {
705    li_->addRange(LiveRange(Start, End, VNI));
706    return;
707  }
708
709  // First block.
710  li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
711
712  // Run sequence of full blocks.
713  for (++MBB; MBB != MBBE; ++MBB) {
714    Start = lis_.getMBBStartIdx(MBB);
715    li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
716                            mapValue(ParentVNI, Start)));
717  }
718
719  // Final block.
720  Start = lis_.getMBBStartIdx(MBB);
721  if (Start != End)
722    li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
723}
724
725/// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
726/// All needed values whose def is not inside [Start;End) must be defined
727/// beforehand so mapValue will work.
728void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
729  assert(li_ && "call reset first");
730  LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
731  LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
732
733  // Check if --I begins before Start and overlaps.
734  if (I != B) {
735    --I;
736    if (I->end > Start)
737      addSimpleRange(Start, std::min(End, I->end), I->valno);
738    ++I;
739  }
740
741  // The remaining ranges begin after Start.
742  for (;I != E && I->start < End; ++I)
743    addSimpleRange(I->start, std::min(End, I->end), I->valno);
744}
745
746
747//===----------------------------------------------------------------------===//
748//                               Split Editor
749//===----------------------------------------------------------------------===//
750
751/// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
752SplitEditor::SplitEditor(SplitAnalysis &sa,
753                         LiveIntervals &lis,
754                         VirtRegMap &vrm,
755                         MachineDominatorTree &mdt,
756                         LiveRangeEdit &edit)
757  : sa_(sa), lis_(lis), vrm_(vrm),
758    mri_(vrm.getMachineFunction().getRegInfo()),
759    tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
760    tri_(*vrm.getMachineFunction().getTarget().getRegisterInfo()),
761    edit_(edit),
762    dupli_(lis_, mdt, edit.getParent()),
763    openli_(lis_, mdt, edit.getParent())
764{
765  // We don't need an AliasAnalysis since we will only be performing
766  // cheap-as-a-copy remats anyway.
767  edit_.anyRematerializable(lis_, tii_, 0);
768}
769
770bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
771  for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
772    if (*I != dupli_.getLI() && (*I)->liveAt(Idx))
773      return true;
774  return false;
775}
776
777VNInfo *SplitEditor::defFromParent(LiveIntervalMap &Reg,
778                                   VNInfo *ParentVNI,
779                                   SlotIndex UseIdx,
780                                   MachineBasicBlock &MBB,
781                                   MachineBasicBlock::iterator I) {
782  VNInfo *VNI = 0;
783  MachineInstr *CopyMI = 0;
784  SlotIndex Def;
785
786  // Attempt cheap-as-a-copy rematerialization.
787  LiveRangeEdit::Remat RM(ParentVNI);
788  if (edit_.canRematerializeAt(RM, UseIdx, true, lis_)) {
789    Def = edit_.rematerializeAt(MBB, I, Reg.getLI()->reg, RM,
790                                          lis_, tii_, tri_);
791  } else {
792    // Can't remat, just insert a copy from parent.
793    CopyMI = BuildMI(MBB, I, DebugLoc(), tii_.get(TargetOpcode::COPY),
794                     Reg.getLI()->reg).addReg(edit_.getReg());
795    Def = lis_.InsertMachineInstrInMaps(CopyMI).getDefIndex();
796  }
797
798  // Define the value in Reg.
799  VNI = Reg.defValue(ParentVNI, Def);
800  VNI->setCopy(CopyMI);
801
802  // Add minimal liveness for the new value.
803  if (UseIdx < Def)
804    UseIdx = Def;
805  Reg.getLI()->addRange(LiveRange(Def, UseIdx.getNextSlot(), VNI));
806  return VNI;
807}
808
809/// Create a new virtual register and live interval.
810void SplitEditor::openIntv() {
811  assert(!openli_.getLI() && "Previous LI not closed before openIntv");
812  if (!dupli_.getLI())
813    dupli_.reset(&edit_.create(mri_, lis_, vrm_));
814
815  openli_.reset(&edit_.create(mri_, lis_, vrm_));
816}
817
818/// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
819/// not live before Idx, a COPY is not inserted.
820void SplitEditor::enterIntvBefore(SlotIndex Idx) {
821  assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
822  Idx = Idx.getUseIndex();
823  DEBUG(dbgs() << "    enterIntvBefore " << Idx);
824  VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
825  if (!ParentVNI) {
826    DEBUG(dbgs() << ": not live\n");
827    return;
828  }
829  DEBUG(dbgs() << ": valno " << ParentVNI->id);
830  truncatedValues.insert(ParentVNI);
831  MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
832  assert(MI && "enterIntvBefore called with invalid index");
833
834  defFromParent(openli_, ParentVNI, Idx, *MI->getParent(), MI);
835
836  DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
837}
838
839/// enterIntvAtEnd - Enter openli at the end of MBB.
840void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
841  assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
842  SlotIndex End = lis_.getMBBEndIdx(&MBB).getPrevSlot();
843  DEBUG(dbgs() << "    enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End);
844  VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(End);
845  if (!ParentVNI) {
846    DEBUG(dbgs() << ": not live\n");
847    return;
848  }
849  DEBUG(dbgs() << ": valno " << ParentVNI->id);
850  truncatedValues.insert(ParentVNI);
851  defFromParent(openli_, ParentVNI, End, MBB, MBB.getFirstTerminator());
852  DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
853}
854
855/// useIntv - indicate that all instructions in MBB should use openli.
856void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
857  useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
858}
859
860void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
861  assert(openli_.getLI() && "openIntv not called before useIntv");
862  openli_.addRange(Start, End);
863  DEBUG(dbgs() << "    use [" << Start << ';' << End << "): "
864               << *openli_.getLI() << '\n');
865}
866
867/// leaveIntvAfter - Leave openli after the instruction at Idx.
868void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
869  assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
870  DEBUG(dbgs() << "    leaveIntvAfter " << Idx);
871
872  // The interval must be live beyond the instruction at Idx.
873  Idx = Idx.getBoundaryIndex();
874  VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
875  if (!ParentVNI) {
876    DEBUG(dbgs() << ": not live\n");
877    return;
878  }
879  DEBUG(dbgs() << ": valno " << ParentVNI->id);
880
881  MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
882  VNInfo *VNI = defFromParent(dupli_, ParentVNI, Idx,
883                              *MII->getParent(), llvm::next(MII));
884
885  // Make sure that openli is properly extended from Idx to the new copy.
886  // FIXME: This shouldn't be necessary for remats.
887  openli_.addSimpleRange(Idx, VNI->def, ParentVNI);
888
889  DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
890}
891
892/// leaveIntvAtTop - Leave the interval at the top of MBB.
893/// Currently, only one value can leave the interval.
894void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
895  assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
896  SlotIndex Start = lis_.getMBBStartIdx(&MBB);
897  DEBUG(dbgs() << "    leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
898
899  VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Start);
900  if (!ParentVNI) {
901    DEBUG(dbgs() << ": not live\n");
902    return;
903  }
904
905  VNInfo *VNI = defFromParent(dupli_, ParentVNI, Start, MBB,
906                              MBB.SkipPHIsAndLabels(MBB.begin()));
907
908  // Finally we must make sure that openli is properly extended from Start to
909  // the new copy.
910  openli_.addSimpleRange(Start, VNI->def, ParentVNI);
911  DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
912}
913
914/// closeIntv - Indicate that we are done editing the currently open
915/// LiveInterval, and ranges can be trimmed.
916void SplitEditor::closeIntv() {
917  assert(openli_.getLI() && "openIntv not called before closeIntv");
918
919  DEBUG(dbgs() << "    closeIntv cleaning up\n");
920  DEBUG(dbgs() << "    open " << *openli_.getLI() << '\n');
921  openli_.reset(0);
922}
923
924/// rewrite - Rewrite all uses of reg to use the new registers.
925void SplitEditor::rewrite(unsigned reg) {
926  for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg),
927       RE = mri_.reg_end(); RI != RE;) {
928    MachineOperand &MO = RI.getOperand();
929    unsigned OpNum = RI.getOperandNo();
930    MachineInstr *MI = MO.getParent();
931    ++RI;
932    if (MI->isDebugValue()) {
933      DEBUG(dbgs() << "Zapping " << *MI);
934      // FIXME: We can do much better with debug values.
935      MO.setReg(0);
936      continue;
937    }
938    SlotIndex Idx = lis_.getInstructionIndex(MI);
939    Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
940    LiveInterval *LI = 0;
941    for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E;
942         ++I) {
943      LiveInterval *testli = *I;
944      if (testli->liveAt(Idx)) {
945        LI = testli;
946        break;
947      }
948    }
949    DEBUG(dbgs() << "  rewr BB#" << MI->getParent()->getNumber() << '\t'<< Idx);
950    assert(LI && "No register was live at use");
951    MO.setReg(LI->reg);
952    if (MO.isUse() && !MI->isRegTiedToDefOperand(OpNum))
953      MO.setIsKill(LI->killedAt(Idx.getDefIndex()));
954    DEBUG(dbgs() << '\t' << *MI);
955  }
956}
957
958void
959SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
960  // Build vector of iterator pairs from the intervals.
961  typedef std::pair<LiveInterval::const_iterator,
962                    LiveInterval::const_iterator> IIPair;
963  SmallVector<IIPair, 8> Iters;
964  for (LiveRangeEdit::iterator LI = edit_.begin(), LE = edit_.end(); LI != LE;
965       ++LI) {
966    if (*LI == dupli_.getLI())
967      continue;
968    LiveInterval::const_iterator I = (*LI)->find(Start);
969    LiveInterval::const_iterator E = (*LI)->end();
970    if (I != E)
971      Iters.push_back(std::make_pair(I, E));
972  }
973
974  SlotIndex sidx = Start;
975  // Break [Start;End) into segments that don't overlap any intervals.
976  for (;;) {
977    SlotIndex next = sidx, eidx = End;
978    // Find overlapping intervals.
979    for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) {
980      LiveInterval::const_iterator I = Iters[i].first;
981      // Interval I is overlapping [sidx;eidx). Trim sidx.
982      if (I->start <= sidx) {
983        sidx = I->end;
984        // Move to the next run, remove iters when all are consumed.
985        I = ++Iters[i].first;
986        if (I == Iters[i].second) {
987          Iters.erase(Iters.begin() + i);
988          --i;
989          continue;
990        }
991      }
992      // Trim eidx too if needed.
993      if (I->start >= eidx)
994        continue;
995      eidx = I->start;
996      next = I->end;
997    }
998    // Now, [sidx;eidx) doesn't overlap anything in intervals_.
999    if (sidx < eidx)
1000      dupli_.addSimpleRange(sidx, eidx, VNI);
1001    // If the interval end was truncated, we can try again from next.
1002    if (next <= sidx)
1003      break;
1004    sidx = next;
1005  }
1006}
1007
1008void SplitEditor::computeRemainder() {
1009  // First we need to fill in the live ranges in dupli.
1010  // If values were redefined, we need a full recoloring with SSA update.
1011  // If values were truncated, we only need to truncate the ranges.
1012  // If values were partially rematted, we should shrink to uses.
1013  // If values were fully rematted, they should be omitted.
1014  // FIXME: If a single value is redefined, just move the def and truncate.
1015  LiveInterval &parent = edit_.getParent();
1016
1017  // Values that are fully contained in the split intervals.
1018  SmallPtrSet<const VNInfo*, 8> deadValues;
1019  // Map all curli values that should have live defs in dupli.
1020  for (LiveInterval::const_vni_iterator I = parent.vni_begin(),
1021       E = parent.vni_end(); I != E; ++I) {
1022    const VNInfo *VNI = *I;
1023    // Don't transfer unused values to the new intervals.
1024    if (VNI->isUnused())
1025      continue;
1026    // Original def is contained in the split intervals.
1027    if (intervalsLiveAt(VNI->def)) {
1028      // Did this value escape?
1029      if (dupli_.isMapped(VNI))
1030        truncatedValues.insert(VNI);
1031      else
1032        deadValues.insert(VNI);
1033      continue;
1034    }
1035    // Add minimal live range at the definition.
1036    VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
1037    dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
1038  }
1039
1040  // Add all ranges to dupli.
1041  for (LiveInterval::const_iterator I = parent.begin(), E = parent.end();
1042       I != E; ++I) {
1043    const LiveRange &LR = *I;
1044    if (truncatedValues.count(LR.valno)) {
1045      // recolor after removing intervals_.
1046      addTruncSimpleRange(LR.start, LR.end, LR.valno);
1047    } else if (!deadValues.count(LR.valno)) {
1048      // recolor without truncation.
1049      dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
1050    }
1051  }
1052
1053  // Extend dupli_ to be live out of any critical loop predecessors.
1054  // This means we have multiple registers live out of those blocks.
1055  // The alternative would be to split the critical edges.
1056  if (criticalPreds_.empty())
1057    return;
1058  for (SplitAnalysis::BlockPtrSet::iterator I = criticalPreds_.begin(),
1059       E = criticalPreds_.end(); I != E; ++I)
1060     dupli_.extendTo(*I, lis_.getMBBEndIdx(*I).getPrevSlot());
1061   criticalPreds_.clear();
1062}
1063
1064void SplitEditor::finish() {
1065  assert(!openli_.getLI() && "Previous LI not closed before rewrite");
1066  assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
1067
1068  // Complete dupli liveness.
1069  computeRemainder();
1070
1071  // Get rid of unused values and set phi-kill flags.
1072  for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
1073    (*I)->RenumberValues(lis_);
1074
1075  // Rewrite instructions.
1076  rewrite(edit_.getReg());
1077
1078  // Now check if any registers were separated into multiple components.
1079  ConnectedVNInfoEqClasses ConEQ(lis_);
1080  for (unsigned i = 0, e = edit_.size(); i != e; ++i) {
1081    // Don't use iterators, they are invalidated by create() below.
1082    LiveInterval *li = edit_.get(i);
1083    unsigned NumComp = ConEQ.Classify(li);
1084    if (NumComp <= 1)
1085      continue;
1086    DEBUG(dbgs() << "  " << NumComp << " components: " << *li << '\n');
1087    SmallVector<LiveInterval*, 8> dups;
1088    dups.push_back(li);
1089    for (unsigned i = 1; i != NumComp; ++i)
1090      dups.push_back(&edit_.create(mri_, lis_, vrm_));
1091    ConEQ.Distribute(&dups[0]);
1092    // Rewrite uses to the new regs.
1093    rewrite(li->reg);
1094  }
1095
1096  // Calculate spill weight and allocation hints for new intervals.
1097  VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
1098  for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I){
1099    LiveInterval &li = **I;
1100    vrai.CalculateRegClass(li.reg);
1101    vrai.CalculateWeightAndHint(li);
1102    DEBUG(dbgs() << "  new interval " << mri_.getRegClass(li.reg)->getName()
1103                 << ":" << li << '\n');
1104  }
1105}
1106
1107
1108//===----------------------------------------------------------------------===//
1109//                               Loop Splitting
1110//===----------------------------------------------------------------------===//
1111
1112void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
1113  SplitAnalysis::LoopBlocks Blocks;
1114  sa_.getLoopBlocks(Loop, Blocks);
1115
1116  DEBUG({
1117    dbgs() << "  splitAround"; sa_.print(Blocks, dbgs()); dbgs() << '\n';
1118  });
1119
1120  // Break critical edges as needed.
1121  SplitAnalysis::BlockPtrSet CriticalExits;
1122  sa_.getCriticalExits(Blocks, CriticalExits);
1123  assert(CriticalExits.empty() && "Cannot break critical exits yet");
1124
1125  // Get critical predecessors so computeRemainder can deal with them.
1126  sa_.getCriticalPreds(Blocks, criticalPreds_);
1127
1128  // Create new live interval for the loop.
1129  openIntv();
1130
1131  // Insert copies in the predecessors if live-in to the header.
1132  if (lis_.isLiveInToMBB(edit_.getParent(), Loop->getHeader())) {
1133    for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
1134           E = Blocks.Preds.end(); I != E; ++I) {
1135      MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
1136      enterIntvAtEnd(MBB);
1137    }
1138  }
1139
1140  // Switch all loop blocks.
1141  for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
1142       E = Blocks.Loop.end(); I != E; ++I)
1143     useIntv(**I);
1144
1145  // Insert back copies in the exit blocks.
1146  for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
1147       E = Blocks.Exits.end(); I != E; ++I) {
1148    MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
1149    leaveIntvAtTop(MBB);
1150  }
1151
1152  // Done.
1153  closeIntv();
1154  finish();
1155}
1156
1157
1158//===----------------------------------------------------------------------===//
1159//                            Single Block Splitting
1160//===----------------------------------------------------------------------===//
1161
1162/// getMultiUseBlocks - if curli has more than one use in a basic block, it
1163/// may be an advantage to split curli for the duration of the block.
1164bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
1165  // If curli is local to one block, there is no point to splitting it.
1166  if (usingBlocks_.size() <= 1)
1167    return false;
1168  // Add blocks with multiple uses.
1169  for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
1170       I != E; ++I)
1171    switch (I->second) {
1172    case 0:
1173    case 1:
1174      continue;
1175    case 2: {
1176      // When there are only two uses and curli is both live in and live out,
1177      // we don't really win anything by isolating the block since we would be
1178      // inserting two copies.
1179      // The remaing register would still have two uses in the block. (Unless it
1180      // separates into disconnected components).
1181      if (lis_.isLiveInToMBB(*curli_, I->first) &&
1182          lis_.isLiveOutOfMBB(*curli_, I->first))
1183        continue;
1184    } // Fall through.
1185    default:
1186      Blocks.insert(I->first);
1187    }
1188  return !Blocks.empty();
1189}
1190
1191/// splitSingleBlocks - Split curli into a separate live interval inside each
1192/// basic block in Blocks.
1193void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
1194  DEBUG(dbgs() << "  splitSingleBlocks for " << Blocks.size() << " blocks.\n");
1195  // Determine the first and last instruction using curli in each block.
1196  typedef std::pair<SlotIndex,SlotIndex> IndexPair;
1197  typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
1198  IndexPairMap MBBRange;
1199  for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1200       E = sa_.usingInstrs_.end(); I != E; ++I) {
1201    const MachineBasicBlock *MBB = (*I)->getParent();
1202    if (!Blocks.count(MBB))
1203      continue;
1204    SlotIndex Idx = lis_.getInstructionIndex(*I);
1205    DEBUG(dbgs() << "  BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
1206    IndexPair &IP = MBBRange[MBB];
1207    if (!IP.first.isValid() || Idx < IP.first)
1208      IP.first = Idx;
1209    if (!IP.second.isValid() || Idx > IP.second)
1210      IP.second = Idx;
1211  }
1212
1213  // Create a new interval for each block.
1214  for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
1215       E = Blocks.end(); I != E; ++I) {
1216    IndexPair &IP = MBBRange[*I];
1217    DEBUG(dbgs() << "  splitting for BB#" << (*I)->getNumber() << ": ["
1218                 << IP.first << ';' << IP.second << ")\n");
1219    assert(IP.first.isValid() && IP.second.isValid());
1220
1221    openIntv();
1222    enterIntvBefore(IP.first);
1223    useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
1224    leaveIntvAfter(IP.second);
1225    closeIntv();
1226  }
1227  finish();
1228}
1229
1230
1231//===----------------------------------------------------------------------===//
1232//                            Sub Block Splitting
1233//===----------------------------------------------------------------------===//
1234
1235/// getBlockForInsideSplit - If curli is contained inside a single basic block,
1236/// and it wou pay to subdivide the interval inside that block, return it.
1237/// Otherwise return NULL. The returned block can be passed to
1238/// SplitEditor::splitInsideBlock.
1239const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1240  // The interval must be exclusive to one block.
1241  if (usingBlocks_.size() != 1)
1242    return 0;
1243  // Don't to this for less than 4 instructions. We want to be sure that
1244  // splitting actually reduces the instruction count per interval.
1245  if (usingInstrs_.size() < 4)
1246    return 0;
1247  return usingBlocks_.begin()->first;
1248}
1249
1250/// splitInsideBlock - Split curli into multiple intervals inside MBB.
1251void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
1252  SmallVector<SlotIndex, 32> Uses;
1253  Uses.reserve(sa_.usingInstrs_.size());
1254  for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1255       E = sa_.usingInstrs_.end(); I != E; ++I)
1256    if ((*I)->getParent() == MBB)
1257      Uses.push_back(lis_.getInstructionIndex(*I));
1258  DEBUG(dbgs() << "  splitInsideBlock BB#" << MBB->getNumber() << " for "
1259               << Uses.size() << " instructions.\n");
1260  assert(Uses.size() >= 3 && "Need at least 3 instructions");
1261  array_pod_sort(Uses.begin(), Uses.end());
1262
1263  // Simple algorithm: Find the largest gap between uses as determined by slot
1264  // indices. Create new intervals for instructions before the gap and after the
1265  // gap.
1266  unsigned bestPos = 0;
1267  int bestGap = 0;
1268  DEBUG(dbgs() << "    dist (" << Uses[0]);
1269  for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1270    int g = Uses[i-1].distance(Uses[i]);
1271    DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1272    if (g > bestGap)
1273      bestPos = i, bestGap = g;
1274  }
1275  DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1276
1277  // bestPos points to the first use after the best gap.
1278  assert(bestPos > 0 && "Invalid gap");
1279
1280  // FIXME: Don't create intervals for low densities.
1281
1282  // First interval before the gap. Don't create single-instr intervals.
1283  if (bestPos > 1) {
1284    openIntv();
1285    enterIntvBefore(Uses.front());
1286    useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1287    leaveIntvAfter(Uses[bestPos-1]);
1288    closeIntv();
1289  }
1290
1291  // Second interval after the gap.
1292  if (bestPos < Uses.size()-1) {
1293    openIntv();
1294    enterIntvBefore(Uses[bestPos]);
1295    useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1296    leaveIntvAfter(Uses.back());
1297    closeIntv();
1298  }
1299
1300  finish();
1301}
1302