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