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 "splitter"
16 #include "SplitKit.h"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/CalcSpillWeights.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineLoopInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 
29 using namespace llvm;
30 
31 static cl::opt<bool>
32 AllowSplit("spiller-splits-edges",
33            cl::desc("Allow critical edge splitting during spilling"));
34 
35 //===----------------------------------------------------------------------===//
36 //                                 Split Analysis
37 //===----------------------------------------------------------------------===//
38 
39 SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
40                              const LiveIntervals &lis,
41                              const MachineLoopInfo &mli)
42   : mf_(mf),
43     lis_(lis),
44     loops_(mli),
45     tii_(*mf.getTarget().getInstrInfo()),
46     curli_(0) {}
47 
48 void SplitAnalysis::clear() {
49   usingInstrs_.clear();
50   usingBlocks_.clear();
51   usingLoops_.clear();
52   curli_ = 0;
53 }
54 
55 bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
56   MachineBasicBlock *T, *F;
57   SmallVector<MachineOperand, 4> Cond;
58   return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
59 }
60 
61 /// analyzeUses - Count instructions, basic blocks, and loops using curli.
62 void SplitAnalysis::analyzeUses() {
63   const MachineRegisterInfo &MRI = mf_.getRegInfo();
64   for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
65        MachineInstr *MI = I.skipInstruction();) {
66     if (MI->isDebugValue() || !usingInstrs_.insert(MI))
67       continue;
68     MachineBasicBlock *MBB = MI->getParent();
69     if (usingBlocks_[MBB]++)
70       continue;
71     if (MachineLoop *Loop = loops_.getLoopFor(MBB))
72       usingLoops_[Loop]++;
73   }
74   DEBUG(dbgs() << "  counted "
75                << usingInstrs_.size() << " instrs, "
76                << usingBlocks_.size() << " blocks, "
77                << usingLoops_.size()  << " loops.\n");
78 }
79 
80 /// removeUse - Update statistics by noting that MI no longer uses curli.
81 void SplitAnalysis::removeUse(const MachineInstr *MI) {
82   if (!usingInstrs_.erase(MI))
83     return;
84 
85   // Decrement MBB count.
86   const MachineBasicBlock *MBB = MI->getParent();
87   BlockCountMap::iterator bi = usingBlocks_.find(MBB);
88   assert(bi != usingBlocks_.end() && "MBB missing");
89   assert(bi->second && "0 count in map");
90   if (--bi->second)
91     return;
92   // No more uses in MBB.
93   usingBlocks_.erase(bi);
94 
95   // Decrement loop count.
96   MachineLoop *Loop = loops_.getLoopFor(MBB);
97   if (!Loop)
98     return;
99   LoopCountMap::iterator li = usingLoops_.find(Loop);
100   assert(li != usingLoops_.end() && "Loop missing");
101   assert(li->second && "0 count in map");
102   if (--li->second)
103     return;
104   // No more blocks in Loop.
105   usingLoops_.erase(li);
106 }
107 
108 // Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
109 // predecessor blocks, and exit blocks.
110 void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
111   Blocks.clear();
112 
113   // Blocks in the loop.
114   Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
115 
116   // Predecessor blocks.
117   const MachineBasicBlock *Header = Loop->getHeader();
118   for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
119        E = Header->pred_end(); I != E; ++I)
120     if (!Blocks.Loop.count(*I))
121       Blocks.Preds.insert(*I);
122 
123   // Exit blocks.
124   for (MachineLoop::block_iterator I = Loop->block_begin(),
125        E = Loop->block_end(); I != E; ++I) {
126     const MachineBasicBlock *MBB = *I;
127     for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
128        SE = MBB->succ_end(); SI != SE; ++SI)
129       if (!Blocks.Loop.count(*SI))
130         Blocks.Exits.insert(*SI);
131   }
132 }
133 
134 /// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
135 /// and around the Loop.
136 SplitAnalysis::LoopPeripheralUse SplitAnalysis::
137 analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
138   LoopPeripheralUse use = ContainedInLoop;
139   for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
140        I != E; ++I) {
141     const MachineBasicBlock *MBB = I->first;
142     // Is this a peripheral block?
143     if (use < MultiPeripheral &&
144         (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
145       if (I->second > 1) use = MultiPeripheral;
146       else               use = SinglePeripheral;
147       continue;
148     }
149     // Is it a loop block?
150     if (Blocks.Loop.count(MBB))
151       continue;
152     // It must be an unrelated block.
153     return OutsideLoop;
154   }
155   return use;
156 }
157 
158 /// getCriticalExits - It may be necessary to partially break critical edges
159 /// leaving the loop if an exit block has phi uses of curli. Collect the exit
160 /// blocks that need special treatment into CriticalExits.
161 void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
162                                      BlockPtrSet &CriticalExits) {
163   CriticalExits.clear();
164 
165   // A critical exit block contains a phi def of curli, and has a predecessor
166   // that is not in the loop nor a loop predecessor.
167   // For such an exit block, the edges carrying the new variable must be moved
168   // to a new pre-exit block.
169   for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
170        I != E; ++I) {
171     const MachineBasicBlock *Succ = *I;
172     SlotIndex SuccIdx = lis_.getMBBStartIdx(Succ);
173     VNInfo *SuccVNI = curli_->getVNInfoAt(SuccIdx);
174     // This exit may not have curli live in at all. No need to split.
175     if (!SuccVNI)
176       continue;
177     // If this is not a PHI def, it is either using a value from before the
178     // loop, or a value defined inside the loop. Both are safe.
179     if (!SuccVNI->isPHIDef() || SuccVNI->def.getBaseIndex() != SuccIdx)
180       continue;
181     // This exit block does have a PHI. Does it also have a predecessor that is
182     // not a loop block or loop predecessor?
183     for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
184          PE = Succ->pred_end(); PI != PE; ++PI) {
185       const MachineBasicBlock *Pred = *PI;
186       if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
187         continue;
188       // This is a critical exit block, and we need to split the exit edge.
189       CriticalExits.insert(Succ);
190       break;
191     }
192   }
193 }
194 
195 /// canSplitCriticalExits - Return true if it is possible to insert new exit
196 /// blocks before the blocks in CriticalExits.
197 bool
198 SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
199                                      BlockPtrSet &CriticalExits) {
200   // If we don't allow critical edge splitting, require no critical exits.
201   if (!AllowSplit)
202     return CriticalExits.empty();
203 
204   for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
205        I != E; ++I) {
206     const MachineBasicBlock *Succ = *I;
207     // We want to insert a new pre-exit MBB before Succ, and change all the
208     // in-loop blocks to branch to the pre-exit instead of Succ.
209     // Check that all the in-loop predecessors can be changed.
210     for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
211          PE = Succ->pred_end(); PI != PE; ++PI) {
212       const MachineBasicBlock *Pred = *PI;
213       // The external predecessors won't be altered.
214       if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
215         continue;
216       if (!canAnalyzeBranch(Pred))
217         return false;
218     }
219 
220     // If Succ's layout predecessor falls through, that too must be analyzable.
221     // We need to insert the pre-exit block in the gap.
222     MachineFunction::const_iterator MFI = Succ;
223     if (MFI == mf_.begin())
224       continue;
225     if (!canAnalyzeBranch(--MFI))
226       return false;
227   }
228   // No problems found.
229   return true;
230 }
231 
232 void SplitAnalysis::analyze(const LiveInterval *li) {
233   clear();
234   curli_ = li;
235   analyzeUses();
236 }
237 
238 const MachineLoop *SplitAnalysis::getBestSplitLoop() {
239   assert(curli_ && "Call analyze() before getBestSplitLoop");
240   if (usingLoops_.empty())
241     return 0;
242 
243   LoopPtrSet Loops, SecondLoops;
244   LoopBlocks Blocks;
245   BlockPtrSet CriticalExits;
246 
247   // Find first-class and second class candidate loops.
248   // We prefer to split around loops where curli is used outside the periphery.
249   for (LoopCountMap::const_iterator I = usingLoops_.begin(),
250        E = usingLoops_.end(); I != E; ++I) {
251     const MachineLoop *Loop = I->first;
252     getLoopBlocks(Loop, Blocks);
253 
254     LoopPtrSet *LPS = 0;
255     switch(analyzeLoopPeripheralUse(Blocks)) {
256     case OutsideLoop:
257       LPS = &Loops;
258       break;
259     case MultiPeripheral:
260       LPS = &SecondLoops;
261       break;
262     case ContainedInLoop:
263       DEBUG(dbgs() << "  contained in " << *Loop);
264       continue;
265     case SinglePeripheral:
266       DEBUG(dbgs() << "  single peripheral use in " << *Loop);
267       continue;
268     }
269     // Will it be possible to split around this loop?
270     getCriticalExits(Blocks, CriticalExits);
271     DEBUG(dbgs() << "  " << CriticalExits.size() << " critical exits from "
272                  << *Loop);
273     if (!canSplitCriticalExits(Blocks, CriticalExits))
274       continue;
275     // This is a possible split.
276     assert(LPS);
277     LPS->insert(Loop);
278   }
279 
280   DEBUG(dbgs() << "  getBestSplitLoop found " << Loops.size() << " + "
281                << SecondLoops.size() << " candidate loops.\n");
282 
283   // If there are no first class loops available, look at second class loops.
284   if (Loops.empty())
285     Loops = SecondLoops;
286 
287   if (Loops.empty())
288     return 0;
289 
290   // Pick the earliest loop.
291   // FIXME: Are there other heuristics to consider?
292   const MachineLoop *Best = 0;
293   SlotIndex BestIdx;
294   for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
295        ++I) {
296     SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
297     if (!Best || Idx < BestIdx)
298       Best = *I, BestIdx = Idx;
299   }
300   DEBUG(dbgs() << "  getBestSplitLoop found " << *Best);
301   return Best;
302 }
303 
304 /// getMultiUseBlocks - if curli has more than one use in a basic block, it
305 /// may be an advantage to split curli for the duration of the block.
306 bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
307   // If curli is local to one block, there is no point to splitting it.
308   if (usingBlocks_.size() <= 1)
309     return false;
310   // Add blocks with multiple uses.
311   for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
312        I != E; ++I)
313     switch (I->second) {
314     case 0:
315     case 1:
316       continue;
317     case 2: {
318       // It doesn't pay to split a 2-instr block if it redefines curli.
319       VNInfo *VN1 = curli_->getVNInfoAt(lis_.getMBBStartIdx(I->first));
320       VNInfo *VN2 =
321         curli_->getVNInfoAt(lis_.getMBBEndIdx(I->first).getPrevIndex());
322       // live-in and live-out with a different value.
323       if (VN1 && VN2 && VN1 != VN2)
324         continue;
325     } // Fall through.
326     default:
327       Blocks.insert(I->first);
328     }
329   return !Blocks.empty();
330 }
331 
332 //===----------------------------------------------------------------------===//
333 //                               LiveIntervalMap
334 //===----------------------------------------------------------------------===//
335 
336 // Work around the fact that the std::pair constructors are broken for pointer
337 // pairs in some implementations. makeVV(x, 0) works.
338 static inline std::pair<const VNInfo*, VNInfo*>
339 makeVV(const VNInfo *a, VNInfo *b) {
340   return std::make_pair(a, b);
341 }
342 
343 void LiveIntervalMap::reset(LiveInterval *li) {
344   li_ = li;
345   valueMap_.clear();
346 }
347 
348 bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
349   ValueMap::const_iterator i = valueMap_.find(ParentVNI);
350   return i != valueMap_.end() && i->second == 0;
351 }
352 
353 // defValue - Introduce a li_ def for ParentVNI that could be later than
354 // ParentVNI->def.
355 VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
356   assert(li_ && "call reset first");
357   assert(ParentVNI && "Mapping  NULL value");
358   assert(Idx.isValid() && "Invalid SlotIndex");
359   assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
360 
361   // Create a new value.
362   VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
363 
364   // Use insert for lookup, so we can add missing values with a second lookup.
365   std::pair<ValueMap::iterator,bool> InsP =
366     valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
367 
368   // This is now a complex def. Mark with a NULL in valueMap.
369   if (!InsP.second)
370     InsP.first->second = 0;
371 
372   return VNI;
373 }
374 
375 
376 // mapValue - Find the mapped value for ParentVNI at Idx.
377 // Potentially create phi-def values.
378 VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
379                                   bool *simple) {
380   assert(li_ && "call reset first");
381   assert(ParentVNI && "Mapping  NULL value");
382   assert(Idx.isValid() && "Invalid SlotIndex");
383   assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
384 
385   // Use insert for lookup, so we can add missing values with a second lookup.
386   std::pair<ValueMap::iterator,bool> InsP =
387     valueMap_.insert(makeVV(ParentVNI, 0));
388 
389   // This was an unknown value. Create a simple mapping.
390   if (InsP.second) {
391     if (simple) *simple = true;
392     return InsP.first->second = li_->createValueCopy(ParentVNI,
393                                                      lis_.getVNInfoAllocator());
394   }
395 
396   // This was a simple mapped value.
397   if (InsP.first->second) {
398     if (simple) *simple = true;
399     return InsP.first->second;
400   }
401 
402   // This is a complex mapped value. There may be multiple defs, and we may need
403   // to create phi-defs.
404   if (simple) *simple = false;
405   MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
406   assert(IdxMBB && "No MBB at Idx");
407 
408   // Is there a def in the same MBB we can extend?
409   if (VNInfo *VNI = extendTo(IdxMBB, Idx))
410     return VNI;
411 
412   // Now for the fun part. We know that ParentVNI potentially has multiple defs,
413   // and we may need to create even more phi-defs to preserve VNInfo SSA form.
414   // Perform a depth-first search for predecessor blocks where we know the
415   // dominating VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
416 
417   // Track MBBs where we have created or learned the dominating value.
418   // This may change during the DFS as we create new phi-defs.
419   typedef DenseMap<MachineBasicBlock*, VNInfo*> MBBValueMap;
420   MBBValueMap DomValue;
421   typedef SplitAnalysis::BlockPtrSet BlockPtrSet;
422   BlockPtrSet Visited;
423 
424   // Iterate over IdxMBB predecessors in a depth-first order.
425   // Skip begin() since that is always IdxMBB.
426   for (idf_ext_iterator<MachineBasicBlock*, BlockPtrSet>
427          IDFI = llvm::next(idf_ext_begin(IdxMBB, Visited)),
428          IDFE = idf_ext_end(IdxMBB, Visited); IDFI != IDFE;) {
429     MachineBasicBlock *MBB = *IDFI;
430     SlotIndex End = lis_.getMBBEndIdx(MBB).getPrevSlot();
431 
432     // We are operating on the restricted CFG where ParentVNI is live.
433     if (parentli_.getVNInfoAt(End) != ParentVNI) {
434       IDFI.skipChildren();
435       continue;
436     }
437 
438     // Do we have a dominating value in this block?
439     VNInfo *VNI = extendTo(MBB, End);
440     if (!VNI) {
441       ++IDFI;
442       continue;
443     }
444 
445     // Yes, VNI dominates MBB. Make sure we visit MBB again from other paths.
446     Visited.erase(MBB);
447 
448     // Track the path back to IdxMBB, creating phi-defs
449     // as needed along the way.
450     for (unsigned PI = IDFI.getPathLength()-1; PI != 0; --PI) {
451       // Start from MBB's immediate successor. End at IdxMBB.
452       MachineBasicBlock *Succ = IDFI.getPath(PI-1);
453       std::pair<MBBValueMap::iterator, bool> InsP =
454         DomValue.insert(MBBValueMap::value_type(Succ, VNI));
455 
456       // This is the first time we backtrack to Succ.
457       if (InsP.second)
458         continue;
459 
460       // We reached Succ again with the same VNI. Nothing is going to change.
461       VNInfo *OVNI = InsP.first->second;
462       if (OVNI == VNI)
463         break;
464 
465       // Succ already has a phi-def. No need to continue.
466       SlotIndex Start = lis_.getMBBStartIdx(Succ);
467       if (OVNI->def == Start)
468         break;
469 
470       // We have a collision between the old and new VNI at Succ. That means
471       // neither dominates and we need a new phi-def.
472       VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
473       VNI->setIsPHIDef(true);
474       InsP.first->second = VNI;
475 
476       // Replace OVNI with VNI in the remaining path.
477       for (; PI > 1 ; --PI) {
478         MBBValueMap::iterator I = DomValue.find(IDFI.getPath(PI-2));
479         if (I == DomValue.end() || I->second != OVNI)
480           break;
481         I->second = VNI;
482       }
483     }
484 
485     // No need to search the children, we found a dominating value.
486     IDFI.skipChildren();
487   }
488 
489   // The search should at least find a dominating value for IdxMBB.
490   assert(!DomValue.empty() && "Couldn't find a reaching definition");
491 
492   // Since we went through the trouble of a full DFS visiting all reaching defs,
493   // the values in DomValue are now accurate. No more phi-defs are needed for
494   // these blocks, so we can color the live ranges.
495   // This makes the next mapValue call much faster.
496   VNInfo *IdxVNI = 0;
497   for (MBBValueMap::iterator I = DomValue.begin(), E = DomValue.end(); I != E;
498        ++I) {
499      MachineBasicBlock *MBB = I->first;
500      VNInfo *VNI = I->second;
501      SlotIndex Start = lis_.getMBBStartIdx(MBB);
502      if (MBB == IdxMBB) {
503        // Don't add full liveness to IdxMBB, stop at Idx.
504        if (Start != Idx)
505          li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
506        // The caller had better add some liveness to IdxVNI, or it leaks.
507        IdxVNI = VNI;
508      } else
509       li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
510   }
511 
512   assert(IdxVNI && "Didn't find value for Idx");
513   return IdxVNI;
514 }
515 
516 // extendTo - Find the last li_ value defined in MBB at or before Idx. The
517 // parentli_ is assumed to be live at Idx. Extend the live range to Idx.
518 // Return the found VNInfo, or NULL.
519 VNInfo *LiveIntervalMap::extendTo(MachineBasicBlock *MBB, SlotIndex Idx) {
520   assert(li_ && "call reset first");
521   LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
522   if (I == li_->begin())
523     return 0;
524   --I;
525   if (I->end <= lis_.getMBBStartIdx(MBB))
526     return 0;
527   if (I->end <= Idx)
528     I->end = Idx.getNextSlot();
529   return I->valno;
530 }
531 
532 // addSimpleRange - Add a simple range from parentli_ to li_.
533 // ParentVNI must be live in the [Start;End) interval.
534 void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
535                                      const VNInfo *ParentVNI) {
536   assert(li_ && "call reset first");
537   bool simple;
538   VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
539   // A simple mapping is easy.
540   if (simple) {
541     li_->addRange(LiveRange(Start, End, VNI));
542     return;
543   }
544 
545   // ParentVNI is a complex value. We must map per MBB.
546   MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
547   MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
548 
549   if (MBB == MBBE) {
550     li_->addRange(LiveRange(Start, End, VNI));
551     return;
552   }
553 
554   // First block.
555   li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
556 
557   // Run sequence of full blocks.
558   for (++MBB; MBB != MBBE; ++MBB) {
559     Start = lis_.getMBBStartIdx(MBB);
560     li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
561                             mapValue(ParentVNI, Start)));
562   }
563 
564   // Final block.
565   Start = lis_.getMBBStartIdx(MBB);
566   if (Start != End)
567     li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
568 }
569 
570 /// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
571 /// All needed values whose def is not inside [Start;End) must be defined
572 /// beforehand so mapValue will work.
573 void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
574   assert(li_ && "call reset first");
575   LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
576   LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
577 
578   // Check if --I begins before Start and overlaps.
579   if (I != B) {
580     --I;
581     if (I->end > Start)
582       addSimpleRange(Start, std::min(End, I->end), I->valno);
583     ++I;
584   }
585 
586   // The remaining ranges begin after Start.
587   for (;I != E && I->start < End; ++I)
588     addSimpleRange(I->start, std::min(End, I->end), I->valno);
589 }
590 
591 VNInfo *LiveIntervalMap::defByCopyFrom(unsigned Reg,
592                                        const VNInfo *ParentVNI,
593                                        MachineBasicBlock &MBB,
594                                        MachineBasicBlock::iterator I) {
595   const TargetInstrDesc &TID = MBB.getParent()->getTarget().getInstrInfo()->
596     get(TargetOpcode::COPY);
597   MachineInstr *MI = BuildMI(MBB, I, DebugLoc(), TID, li_->reg).addReg(Reg);
598   SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
599   VNInfo *VNI = defValue(ParentVNI, DefIdx);
600   VNI->setCopy(MI);
601   li_->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), VNI));
602   return VNI;
603 }
604 
605 //===----------------------------------------------------------------------===//
606 //                               Split Editor
607 //===----------------------------------------------------------------------===//
608 
609 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
610 SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
611                          SmallVectorImpl<LiveInterval*> &intervals)
612   : sa_(sa), lis_(lis), vrm_(vrm),
613     mri_(vrm.getMachineFunction().getRegInfo()),
614     tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
615     curli_(sa_.getCurLI()),
616     dupli_(lis_, *curli_),
617     openli_(lis_, *curli_),
618     intervals_(intervals),
619     firstInterval(intervals_.size())
620 {
621   assert(curli_ && "SplitEditor created from empty SplitAnalysis");
622 
623   // Make sure curli_ is assigned a stack slot, so all our intervals get the
624   // same slot as curli_.
625   if (vrm_.getStackSlot(curli_->reg) == VirtRegMap::NO_STACK_SLOT)
626     vrm_.assignVirt2StackSlot(curli_->reg);
627 
628 }
629 
630 LiveInterval *SplitEditor::createInterval() {
631   unsigned Reg = mri_.createVirtualRegister(mri_.getRegClass(curli_->reg));
632   LiveInterval &Intv = lis_.getOrCreateInterval(Reg);
633   vrm_.grow();
634   vrm_.assignVirt2StackSlot(Reg, vrm_.getStackSlot(curli_->reg));
635   return &Intv;
636 }
637 
638 bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
639   for (int i = firstInterval, e = intervals_.size(); i != e; ++i)
640     if (intervals_[i]->liveAt(Idx))
641       return true;
642   return false;
643 }
644 
645 /// Create a new virtual register and live interval.
646 void SplitEditor::openIntv() {
647   assert(!openli_.getLI() && "Previous LI not closed before openIntv");
648 
649   if (!dupli_.getLI())
650     dupli_.reset(createInterval());
651 
652   openli_.reset(createInterval());
653   intervals_.push_back(openli_.getLI());
654 }
655 
656 /// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
657 /// not live before Idx, a COPY is not inserted.
658 void SplitEditor::enterIntvBefore(SlotIndex Idx) {
659   assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
660   VNInfo *ParentVNI = curli_->getVNInfoAt(Idx.getUseIndex());
661   if (!ParentVNI) {
662     DEBUG(dbgs() << "    enterIntvBefore " << Idx << ": not live\n");
663     return;
664   }
665   truncatedValues.insert(ParentVNI);
666   MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
667   assert(MI && "enterIntvBefore called with invalid index");
668   openli_.defByCopyFrom(curli_->reg, ParentVNI, *MI->getParent(), MI);
669   DEBUG(dbgs() << "    enterIntvBefore " << Idx << ": " << *openli_.getLI()
670                << '\n');
671 }
672 
673 /// enterIntvAtEnd - Enter openli at the end of MBB.
674 void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
675   assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
676   SlotIndex End = lis_.getMBBEndIdx(&MBB);
677   VNInfo *ParentVNI = curli_->getVNInfoAt(End.getPrevSlot());
678   if (!ParentVNI) {
679     DEBUG(dbgs() << "    enterIntvAtEnd " << End << ": not live\n");
680     return;
681   }
682   truncatedValues.insert(ParentVNI);
683   VNInfo *VNI = openli_.defByCopyFrom(curli_->reg, ParentVNI,
684                                       MBB, MBB.getFirstTerminator());
685   // Make sure openli is live out of MBB.
686   openli_.getLI()->addRange(LiveRange(VNI->def, End, VNI));
687   DEBUG(dbgs() << "    enterIntvAtEnd: " << *openli_.getLI() << '\n');
688 }
689 
690 /// useIntv - indicate that all instructions in MBB should use openli.
691 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
692   useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
693 }
694 
695 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
696   assert(openli_.getLI() && "openIntv not called before useIntv");
697   openli_.addRange(Start, End);
698   DEBUG(dbgs() << "    use [" << Start << ';' << End << "): "
699                << *openli_.getLI() << '\n');
700 }
701 
702 /// leaveIntvAfter - Leave openli after the instruction at Idx.
703 void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
704   assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
705 
706   // The interval must be live beyond the instruction at Idx.
707   VNInfo *ParentVNI = curli_->getVNInfoAt(Idx.getBoundaryIndex());
708   if (!ParentVNI) {
709     DEBUG(dbgs() << "    leaveIntvAfter " << Idx << ": not live\n");
710     return;
711   }
712 
713   MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
714   MachineBasicBlock *MBB = MII->getParent();
715   VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI, *MBB,
716                                      llvm::next(MII));
717 
718   // Finally we must make sure that openli is properly extended from Idx to the
719   // new copy.
720   openli_.addSimpleRange(Idx.getBoundaryIndex(), VNI->def, ParentVNI);
721   DEBUG(dbgs() << "    leaveIntvAfter " << Idx << ": " << *openli_.getLI()
722                << '\n');
723 }
724 
725 /// leaveIntvAtTop - Leave the interval at the top of MBB.
726 /// Currently, only one value can leave the interval.
727 void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
728   assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
729 
730   SlotIndex Start = lis_.getMBBStartIdx(&MBB);
731   VNInfo *ParentVNI = curli_->getVNInfoAt(Start);
732 
733   // Is curli even live-in to MBB?
734   if (!ParentVNI) {
735     DEBUG(dbgs() << "    leaveIntvAtTop at " << Start << ": not live\n");
736     return;
737   }
738 
739   // We are going to insert a back copy, so we must have a dupli_.
740   VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI,
741                                      MBB, MBB.begin());
742 
743   // Finally we must make sure that openli is properly extended from Start to
744   // the new copy.
745   openli_.addSimpleRange(Start, VNI->def, ParentVNI);
746   DEBUG(dbgs() << "    leaveIntvAtTop at " << Start << ": " << *openli_.getLI()
747                << '\n');
748 }
749 
750 /// closeIntv - Indicate that we are done editing the currently open
751 /// LiveInterval, and ranges can be trimmed.
752 void SplitEditor::closeIntv() {
753   assert(openli_.getLI() && "openIntv not called before closeIntv");
754 
755   DEBUG(dbgs() << "    closeIntv cleaning up\n");
756   DEBUG(dbgs() << "    open " << *openli_.getLI() << '\n');
757   openli_.reset(0);
758 }
759 
760 void
761 SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
762   SlotIndex sidx = Start;
763 
764   // Break [Start;End) into segments that don't overlap any intervals.
765   for (;;) {
766     SlotIndex next = sidx, eidx = End;
767     // Find overlapping intervals.
768     for (int i = firstInterval, e = intervals_.size(); i != e && sidx < eidx;
769          ++i) {
770       LiveInterval::const_iterator I = intervals_[i]->find(sidx);
771       LiveInterval::const_iterator E = intervals_[i]->end();
772       if (I == E)
773         continue;
774       // Interval I is overlapping [sidx;eidx). Trim sidx.
775       if (I->start <= sidx) {
776         sidx = I->end;
777         if (++I == E)
778           continue;
779       }
780       // Trim eidx too if needed.
781       if (I->start >= eidx)
782         continue;
783       eidx = I->start;
784       if (I->end > next)
785         next = I->end;
786     }
787     // Now, [sidx;eidx) doesn't overlap anything in intervals_.
788     if (sidx < eidx)
789       dupli_.addSimpleRange(sidx, eidx, VNI);
790     // If the interval end was truncated, we can try again from next.
791     if (next <= sidx)
792       break;
793     sidx = next;
794   }
795 }
796 
797 /// rewrite - after all the new live ranges have been created, rewrite
798 /// instructions using curli to use the new intervals.
799 void SplitEditor::rewrite() {
800   assert(!openli_.getLI() && "Previous LI not closed before rewrite");
801   assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
802 
803   // First we need to fill in the live ranges in dupli.
804   // If values were redefined, we need a full recoloring with SSA update.
805   // If values were truncated, we only need to truncate the ranges.
806   // If values were partially rematted, we should shrink to uses.
807   // If values were fully rematted, they should be omitted.
808   // FIXME: If a single value is redefined, just move the def and truncate.
809 
810   // Values that are fully contained in the split intervals.
811   SmallPtrSet<const VNInfo*, 8> deadValues;
812 
813   // Map all curli values that should have live defs in dupli.
814   for (LiveInterval::const_vni_iterator I = curli_->vni_begin(),
815        E = curli_->vni_end(); I != E; ++I) {
816     const VNInfo *VNI = *I;
817     // Original def is contained in the split intervals.
818     if (intervalsLiveAt(VNI->def)) {
819       // Did this value escape?
820       if (dupli_.isMapped(VNI))
821         truncatedValues.insert(VNI);
822       else
823         deadValues.insert(VNI);
824       continue;
825     }
826     // Add minimal live range at the definition.
827     VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
828     dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
829   }
830 
831   // Add all ranges to dupli.
832   for (LiveInterval::const_iterator I = curli_->begin(), E = curli_->end();
833        I != E; ++I) {
834     const LiveRange &LR = *I;
835     if (truncatedValues.count(LR.valno)) {
836       // recolor after removing intervals_.
837       addTruncSimpleRange(LR.start, LR.end, LR.valno);
838     } else if (!deadValues.count(LR.valno)) {
839       // recolor without truncation.
840       dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
841     }
842   }
843 
844 
845   const LiveInterval *curli = sa_.getCurLI();
846   for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(curli->reg),
847        RE = mri_.reg_end(); RI != RE;) {
848     MachineOperand &MO = RI.getOperand();
849     MachineInstr *MI = MO.getParent();
850     ++RI;
851     if (MI->isDebugValue()) {
852       DEBUG(dbgs() << "Zapping " << *MI);
853       // FIXME: We can do much better with debug values.
854       MO.setReg(0);
855       continue;
856     }
857     SlotIndex Idx = lis_.getInstructionIndex(MI);
858     Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
859     LiveInterval *LI = dupli_.getLI();
860     for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
861       LiveInterval *testli = intervals_[i];
862       if (testli->liveAt(Idx)) {
863         LI = testli;
864         break;
865       }
866     }
867     MO.setReg(LI->reg);
868     sa_.removeUse(MI);
869     DEBUG(dbgs() << "  rewrite " << Idx << '\t' << *MI);
870   }
871 
872   // dupli_ goes in last, after rewriting.
873   if (dupli_.getLI()->empty()) {
874     DEBUG(dbgs() << "  dupli became empty?\n");
875     lis_.removeInterval(dupli_.getLI()->reg);
876     dupli_.reset(0);
877   } else {
878     dupli_.getLI()->RenumberValues(lis_);
879     intervals_.push_back(dupli_.getLI());
880   }
881 
882   // Calculate spill weight and allocation hints for new intervals.
883   VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
884   for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
885     LiveInterval &li = *intervals_[i];
886     vrai.CalculateRegClass(li.reg);
887     vrai.CalculateWeightAndHint(li);
888     DEBUG(dbgs() << "  new interval " << mri_.getRegClass(li.reg)->getName()
889                  << ":" << li << '\n');
890   }
891 }
892 
893 
894 //===----------------------------------------------------------------------===//
895 //                               Loop Splitting
896 //===----------------------------------------------------------------------===//
897 
898 void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
899   SplitAnalysis::LoopBlocks Blocks;
900   sa_.getLoopBlocks(Loop, Blocks);
901 
902   // Break critical edges as needed.
903   SplitAnalysis::BlockPtrSet CriticalExits;
904   sa_.getCriticalExits(Blocks, CriticalExits);
905   assert(CriticalExits.empty() && "Cannot break critical exits yet");
906 
907   // Create new live interval for the loop.
908   openIntv();
909 
910   // Insert copies in the predecessors.
911   for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
912        E = Blocks.Preds.end(); I != E; ++I) {
913     MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
914     enterIntvAtEnd(MBB);
915   }
916 
917   // Switch all loop blocks.
918   for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
919        E = Blocks.Loop.end(); I != E; ++I)
920      useIntv(**I);
921 
922   // Insert back copies in the exit blocks.
923   for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
924        E = Blocks.Exits.end(); I != E; ++I) {
925     MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
926     leaveIntvAtTop(MBB);
927   }
928 
929   // Done.
930   closeIntv();
931   rewrite();
932 }
933 
934 
935 //===----------------------------------------------------------------------===//
936 //                            Single Block Splitting
937 //===----------------------------------------------------------------------===//
938 
939 /// splitSingleBlocks - Split curli into a separate live interval inside each
940 /// basic block in Blocks.
941 void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
942   DEBUG(dbgs() << "  splitSingleBlocks for " << Blocks.size() << " blocks.\n");
943   // Determine the first and last instruction using curli in each block.
944   typedef std::pair<SlotIndex,SlotIndex> IndexPair;
945   typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
946   IndexPairMap MBBRange;
947   for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
948        E = sa_.usingInstrs_.end(); I != E; ++I) {
949     const MachineBasicBlock *MBB = (*I)->getParent();
950     if (!Blocks.count(MBB))
951       continue;
952     SlotIndex Idx = lis_.getInstructionIndex(*I);
953     DEBUG(dbgs() << "  BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
954     IndexPair &IP = MBBRange[MBB];
955     if (!IP.first.isValid() || Idx < IP.first)
956       IP.first = Idx;
957     if (!IP.second.isValid() || Idx > IP.second)
958       IP.second = Idx;
959   }
960 
961   // Create a new interval for each block.
962   for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
963        E = Blocks.end(); I != E; ++I) {
964     IndexPair &IP = MBBRange[*I];
965     DEBUG(dbgs() << "  splitting for BB#" << (*I)->getNumber() << ": ["
966                  << IP.first << ';' << IP.second << ")\n");
967     assert(IP.first.isValid() && IP.second.isValid());
968 
969     openIntv();
970     enterIntvBefore(IP.first);
971     useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
972     leaveIntvAfter(IP.second);
973     closeIntv();
974   }
975   rewrite();
976 }
977 
978 
979 //===----------------------------------------------------------------------===//
980 //                            Sub Block Splitting
981 //===----------------------------------------------------------------------===//
982 
983 /// getBlockForInsideSplit - If curli is contained inside a single basic block,
984 /// and it wou pay to subdivide the interval inside that block, return it.
985 /// Otherwise return NULL. The returned block can be passed to
986 /// SplitEditor::splitInsideBlock.
987 const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
988   // The interval must be exclusive to one block.
989   if (usingBlocks_.size() != 1)
990     return 0;
991   // Don't to this for less than 4 instructions. We want to be sure that
992   // splitting actually reduces the instruction count per interval.
993   if (usingInstrs_.size() < 4)
994     return 0;
995   return usingBlocks_.begin()->first;
996 }
997 
998 /// splitInsideBlock - Split curli into multiple intervals inside MBB.
999 void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
1000   SmallVector<SlotIndex, 32> Uses;
1001   Uses.reserve(sa_.usingInstrs_.size());
1002   for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1003        E = sa_.usingInstrs_.end(); I != E; ++I)
1004     if ((*I)->getParent() == MBB)
1005       Uses.push_back(lis_.getInstructionIndex(*I));
1006   DEBUG(dbgs() << "  splitInsideBlock BB#" << MBB->getNumber() << " for "
1007                << Uses.size() << " instructions.\n");
1008   assert(Uses.size() >= 3 && "Need at least 3 instructions");
1009   array_pod_sort(Uses.begin(), Uses.end());
1010 
1011   // Simple algorithm: Find the largest gap between uses as determined by slot
1012   // indices. Create new intervals for instructions before the gap and after the
1013   // gap.
1014   unsigned bestPos = 0;
1015   int bestGap = 0;
1016   DEBUG(dbgs() << "    dist (" << Uses[0]);
1017   for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1018     int g = Uses[i-1].distance(Uses[i]);
1019     DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1020     if (g > bestGap)
1021       bestPos = i, bestGap = g;
1022   }
1023   DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1024 
1025   // bestPos points to the first use after the best gap.
1026   assert(bestPos > 0 && "Invalid gap");
1027 
1028   // FIXME: Don't create intervals for low densities.
1029 
1030   // First interval before the gap. Don't create single-instr intervals.
1031   if (bestPos > 1) {
1032     openIntv();
1033     enterIntvBefore(Uses.front());
1034     useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1035     leaveIntvAfter(Uses[bestPos-1]);
1036     closeIntv();
1037   }
1038 
1039   // Second interval after the gap.
1040   if (bestPos < Uses.size()-1) {
1041     openIntv();
1042     enterIntvBefore(Uses[bestPos]);
1043     useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1044     leaveIntvAfter(Uses.back());
1045     closeIntv();
1046   }
1047 
1048   rewrite();
1049 }
1050