Use the value mapping provided by LiveIntervalMap. This simplifies the code a
[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 "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     // FIXME: We need an SSA updater to properly handle multiple exit blocks.
255     if (Blocks.Exits.size() > 1) {
256       DEBUG(dbgs() << "  multiple exits from " << *Loop);
257       continue;
258     }
259
260     LoopPtrSet *LPS = 0;
261     switch(analyzeLoopPeripheralUse(Blocks)) {
262     case OutsideLoop:
263       LPS = &Loops;
264       break;
265     case MultiPeripheral:
266       LPS = &SecondLoops;
267       break;
268     case ContainedInLoop:
269       DEBUG(dbgs() << "  contained in " << *Loop);
270       continue;
271     case SinglePeripheral:
272       DEBUG(dbgs() << "  single peripheral use in " << *Loop);
273       continue;
274     }
275     // Will it be possible to split around this loop?
276     getCriticalExits(Blocks, CriticalExits);
277     DEBUG(dbgs() << "  " << CriticalExits.size() << " critical exits from "
278                  << *Loop);
279     if (!canSplitCriticalExits(Blocks, CriticalExits))
280       continue;
281     // This is a possible split.
282     assert(LPS);
283     LPS->insert(Loop);
284   }
285
286   DEBUG(dbgs() << "  getBestSplitLoop found " << Loops.size() << " + "
287                << SecondLoops.size() << " candidate loops.\n");
288
289   // If there are no first class loops available, look at second class loops.
290   if (Loops.empty())
291     Loops = SecondLoops;
292
293   if (Loops.empty())
294     return 0;
295
296   // Pick the earliest loop.
297   // FIXME: Are there other heuristics to consider?
298   const MachineLoop *Best = 0;
299   SlotIndex BestIdx;
300   for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
301        ++I) {
302     SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
303     if (!Best || Idx < BestIdx)
304       Best = *I, BestIdx = Idx;
305   }
306   DEBUG(dbgs() << "  getBestSplitLoop found " << *Best);
307   return Best;
308 }
309
310 /// getMultiUseBlocks - if curli has more than one use in a basic block, it
311 /// may be an advantage to split curli for the duration of the block.
312 bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
313   // If curli is local to one block, there is no point to splitting it.
314   if (usingBlocks_.size() <= 1)
315     return false;
316   // Add blocks with multiple uses.
317   for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
318        I != E; ++I)
319     switch (I->second) {
320     case 0:
321     case 1:
322       continue;
323     case 2: {
324       // It doesn't pay to split a 2-instr block if it redefines curli.
325       VNInfo *VN1 = curli_->getVNInfoAt(lis_.getMBBStartIdx(I->first));
326       VNInfo *VN2 =
327         curli_->getVNInfoAt(lis_.getMBBEndIdx(I->first).getPrevIndex());
328       // live-in and live-out with a different value.
329       if (VN1 && VN2 && VN1 != VN2)
330         continue;
331     } // Fall through.
332     default:
333       Blocks.insert(I->first);
334     }
335   return !Blocks.empty();
336 }
337
338 //===----------------------------------------------------------------------===//
339 //                               LiveIntervalMap
340 //===----------------------------------------------------------------------===//
341
342 // Work around the fact that the std::pair constructors are broken for pointer
343 // pairs in some implementations. makeVV(x, 0) works.
344 static inline std::pair<const VNInfo*, VNInfo*>
345 makeVV(const VNInfo *a, VNInfo *b) {
346   return std::make_pair(a, b);
347 }
348
349 void LiveIntervalMap::reset(LiveInterval *li) {
350   li_ = li;
351   valueMap_.clear();
352 }
353
354 // defValue - Introduce a li_ def for ParentVNI that could be later than
355 // ParentVNI->def.
356 VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
357   assert(li_ && "call reset first");
358   assert(ParentVNI && "Mapping  NULL value");
359   assert(Idx.isValid() && "Invalid SlotIndex");
360   assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
361
362   // Is this a simple 1-1 mapping? Not likely.
363   if (Idx == ParentVNI->def)
364     return mapValue(ParentVNI, Idx);
365
366   // This is now a complex def. Mark with a NULL in valueMap.
367   valueMap_[ParentVNI] = 0;
368
369   // Should we insert a minimal snippet of VNI LiveRange, or can we count on
370   // callers to do that? We need it for lookups of complex values.
371   VNInfo *VNI = li_->getNextValue(Idx, 0, true, lis_.getVNInfoAllocator());
372   return VNI;
373 }
374
375 // mapValue - Find the mapped value for ParentVNI at Idx.
376 // Potentially create phi-def values.
377 VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx) {
378   assert(li_ && "call reset first");
379   assert(ParentVNI && "Mapping  NULL value");
380   assert(Idx.isValid() && "Invalid SlotIndex");
381   assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
382
383   // Use insert for lookup, so we can add missing values with a second lookup.
384   std::pair<ValueMap::iterator,bool> InsP =
385     valueMap_.insert(makeVV(ParentVNI, 0));
386
387   // This was an unknown value. Create a simple mapping.
388   if (InsP.second)
389     return InsP.first->second = li_->createValueCopy(ParentVNI,
390                                                      lis_.getVNInfoAllocator());
391   // This was a simple mapped value.
392   if (InsP.first->second)
393     return InsP.first->second;
394
395   // This is a complex mapped value. There may be multiple defs, and we may need
396   // to create phi-defs.
397   MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
398   assert(IdxMBB && "No MBB at Idx");
399
400   // Is there a def in the same MBB we can extend?
401   if (VNInfo *VNI = extendTo(IdxMBB, Idx))
402     return VNI;
403
404   // Now for the fun part. We know that ParentVNI potentially has multiple defs,
405   // and we may need to create even more phi-defs to preserve VNInfo SSA form.
406   // Perform a depth-first search for predecessor blocks where we know the
407   // dominating VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
408
409   // Track MBBs where we have created or learned the dominating value.
410   // This may change during the DFS as we create new phi-defs.
411   typedef DenseMap<MachineBasicBlock*, VNInfo*> MBBValueMap;
412   MBBValueMap DomValue;
413
414   for (idf_iterator<MachineBasicBlock*>
415          IDFI = idf_begin(IdxMBB),
416          IDFE = idf_end(IdxMBB); IDFI != IDFE;) {
417     MachineBasicBlock *MBB = *IDFI;
418     SlotIndex End = lis_.getMBBEndIdx(MBB).getPrevSlot();
419
420     // We are operating on the restricted CFG where ParentVNI is live.
421     if (parentli_.getVNInfoAt(End) != ParentVNI) {
422       IDFI.skipChildren();
423       continue;
424     }
425
426     // Do we have a dominating value in this block?
427     VNInfo *VNI = extendTo(MBB, End);
428     if (!VNI) {
429       ++IDFI;
430       continue;
431     }
432
433     // Yes, VNI dominates MBB. Track the path back to IdxMBB, creating phi-defs
434     // as needed along the way.
435     for (unsigned PI = IDFI.getPathLength()-1; PI != 0; --PI) {
436       // Start from MBB's immediate successor. End at IdxMBB.
437       MachineBasicBlock *Succ = IDFI.getPath(PI-1);
438       std::pair<MBBValueMap::iterator, bool> InsP =
439         DomValue.insert(MBBValueMap::value_type(Succ, VNI));
440
441       // This is the first time we backtrack to Succ.
442       if (InsP.second)
443         continue;
444
445       // We reached Succ again with the same VNI. Nothing is going to change.
446       VNInfo *OVNI = InsP.first->second;
447       if (OVNI == VNI)
448         break;
449
450       // Succ already has a phi-def. No need to continue.
451       SlotIndex Start = lis_.getMBBStartIdx(Succ);
452       if (OVNI->def == Start)
453         break;
454
455       // We have a collision between the old and new VNI at Succ. That means
456       // neither dominates and we need a new phi-def.
457       VNI = li_->getNextValue(Start, 0, true, lis_.getVNInfoAllocator());
458       VNI->setIsPHIDef(true);
459       InsP.first->second = VNI;
460
461       // Replace OVNI with VNI in the remaining path.
462       for (; PI > 1 ; --PI) {
463         MBBValueMap::iterator I = DomValue.find(IDFI.getPath(PI-2));
464         if (I == DomValue.end() || I->second != OVNI)
465           break;
466         I->second = VNI;
467       }
468     }
469
470     // No need to search the children, we found a dominating value.
471     IDFI.skipChildren();
472   }
473
474   // The search should at least find a dominating value for IdxMBB.
475   assert(!DomValue.empty() && "Couldn't find a reaching definition");
476
477   // Since we went through the trouble of a full DFS visiting all reaching defs,
478   // the values in DomValue are now accurate. No more phi-defs are needed for
479   // these blocks, so we can color the live ranges.
480   // This makes the next mapValue call much faster.
481   VNInfo *IdxVNI = 0;
482   for (MBBValueMap::iterator I = DomValue.begin(), E = DomValue.end(); I != E;
483        ++I) {
484      MachineBasicBlock *MBB = I->first;
485      VNInfo *VNI = I->second;
486      SlotIndex Start = lis_.getMBBStartIdx(MBB);
487      if (MBB == IdxMBB) {
488        // Don't add full liveness to IdxMBB, stop at Idx.
489        if (Start != Idx)
490          li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
491        // The caller had better add some liveness to IdxVNI, or it leaks.
492        IdxVNI = VNI;
493      } else
494       li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
495   }
496
497   assert(IdxVNI && "Didn't find value for Idx");
498   return IdxVNI;
499 }
500
501 // extendTo - Find the last li_ value defined in MBB at or before Idx. The
502 // parentli_ is assumed to be live at Idx. Extend the live range to Idx.
503 // Return the found VNInfo, or NULL.
504 VNInfo *LiveIntervalMap::extendTo(MachineBasicBlock *MBB, SlotIndex Idx) {
505   assert(li_ && "call reset first");
506   LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
507   if (I == li_->begin())
508     return 0;
509   --I;
510   if (I->start < lis_.getMBBStartIdx(MBB))
511     return 0;
512   if (I->end <= Idx)
513     I->end = Idx.getNextSlot();
514   return I->valno;
515 }
516
517 // addSimpleRange - Add a simple range from parentli_ to li_.
518 // ParentVNI must be live in the [Start;End) interval.
519 void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
520                                      const VNInfo *ParentVNI) {
521   assert(li_ && "call reset first");
522   VNInfo *VNI = mapValue(ParentVNI, Start);
523   // A simple mappoing is easy.
524   if (VNI->def == ParentVNI->def) {
525     li_->addRange(LiveRange(Start, End, VNI));
526     return;
527   }
528
529   // ParentVNI is a complex value. We must map per MBB.
530   MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
531   MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End);
532
533   if (MBB == MBBE) {
534     li_->addRange(LiveRange(Start, End, VNI));
535     return;
536   }
537
538   // First block.
539   li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
540
541   // Run sequence of full blocks.
542   for (++MBB; MBB != MBBE; ++MBB) {
543     Start = lis_.getMBBStartIdx(MBB);
544     li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
545                             mapValue(ParentVNI, Start)));
546   }
547
548   // Final block.
549   Start = lis_.getMBBStartIdx(MBB);
550   if (Start != End)
551     li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
552 }
553
554 /// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
555 /// All needed values whose def is not inside [Start;End) must be defined
556 /// beforehand so mapValue will work.
557 void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
558   assert(li_ && "call reset first");
559   LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
560   LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
561
562   // Check if --I begins before Start and overlaps.
563   if (I != B) {
564     --I;
565     if (I->end > Start)
566       addSimpleRange(Start, std::min(End, I->end), I->valno);
567     ++I;
568   }
569
570   // The remaining ranges begin after Start.
571   for (;I != E && I->start < End; ++I)
572     addSimpleRange(I->start, std::min(End, I->end), I->valno);
573 }
574
575 VNInfo *LiveIntervalMap::defByCopyFrom(unsigned Reg,
576                                        const VNInfo *ParentVNI,
577                                        MachineBasicBlock &MBB,
578                                        MachineBasicBlock::iterator I) {
579   const TargetInstrDesc &TID = MBB.getParent()->getTarget().getInstrInfo()->
580     get(TargetOpcode::COPY);
581   MachineInstr *MI = BuildMI(MBB, I, DebugLoc(), TID, li_->reg).addReg(Reg);
582   SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
583   VNInfo *VNI = defValue(ParentVNI, DefIdx);
584   VNI->setCopy(MI);
585   li_->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), VNI));
586   return VNI;
587 }
588
589 //===----------------------------------------------------------------------===//
590 //                               Split Editor
591 //===----------------------------------------------------------------------===//
592
593 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
594 SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
595                          SmallVectorImpl<LiveInterval*> &intervals)
596   : sa_(sa), lis_(lis), vrm_(vrm),
597     mri_(vrm.getMachineFunction().getRegInfo()),
598     tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
599     curli_(sa_.getCurLI()),
600     dupli_(lis_, *curli_),
601     openli_(lis_, *curli_),
602     intervals_(intervals),
603     firstInterval(intervals_.size())
604 {
605   assert(curli_ && "SplitEditor created from empty SplitAnalysis");
606
607   // Make sure curli_ is assigned a stack slot, so all our intervals get the
608   // same slot as curli_.
609   if (vrm_.getStackSlot(curli_->reg) == VirtRegMap::NO_STACK_SLOT)
610     vrm_.assignVirt2StackSlot(curli_->reg);
611
612 }
613
614 LiveInterval *SplitEditor::createInterval() {
615   unsigned Reg = mri_.createVirtualRegister(mri_.getRegClass(curli_->reg));
616   LiveInterval &Intv = lis_.getOrCreateInterval(Reg);
617   vrm_.grow();
618   vrm_.assignVirt2StackSlot(Reg, vrm_.getStackSlot(curli_->reg));
619   return &Intv;
620 }
621
622 /// Create a new virtual register and live interval.
623 void SplitEditor::openIntv() {
624   assert(!openli_.getLI() && "Previous LI not closed before openIntv");
625
626   if (!dupli_.getLI()) {
627     // Create an interval for dupli that is a copy of curli.
628     dupli_.reset(createInterval());
629     dupli_.getLI()->Copy(*curli_, &mri_, lis_.getVNInfoAllocator());
630   }
631
632   openli_.reset(createInterval());
633   intervals_.push_back(openli_.getLI());
634 }
635
636 /// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
637 /// not live before Idx, a COPY is not inserted.
638 void SplitEditor::enterIntvBefore(SlotIndex Idx) {
639   assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
640   VNInfo *ParentVNI = curli_->getVNInfoAt(Idx.getUseIndex());
641   if (!ParentVNI) {
642     DEBUG(dbgs() << "    enterIntvBefore " << Idx << ": not live\n");
643     return;
644   }
645   MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
646   assert(MI && "enterIntvBefore called with invalid index");
647   openli_.defByCopyFrom(curli_->reg, ParentVNI, *MI->getParent(), MI);
648   DEBUG(dbgs() << "    enterIntvBefore " << Idx << ": " << *openli_.getLI()
649                << '\n');
650 }
651
652 /// enterIntvAtEnd - Enter openli at the end of MBB.
653 void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
654   assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
655   SlotIndex End = lis_.getMBBEndIdx(&MBB);
656   VNInfo *ParentVNI = curli_->getVNInfoAt(End.getPrevSlot());
657   if (!ParentVNI) {
658     DEBUG(dbgs() << "    enterIntvAtEnd " << End << ": not live\n");
659     return;
660   }
661   VNInfo *VNI = openli_.defByCopyFrom(curli_->reg, ParentVNI,
662                                       MBB, MBB.getFirstTerminator());
663   // Make sure openli is live out of MBB.
664   openli_.getLI()->addRange(LiveRange(VNI->def, End, VNI));
665   DEBUG(dbgs() << "    enterIntvAtEnd: " << *openli_.getLI() << '\n');
666 }
667
668 /// useIntv - indicate that all instructions in MBB should use openli.
669 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
670   useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
671 }
672
673 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
674   assert(openli_.getLI() && "openIntv not called before useIntv");
675   openli_.addRange(Start, End);
676   DEBUG(dbgs() << "    use [" << Start << ';' << End << "): "
677                << *openli_.getLI() << '\n');
678 }
679
680 /// leaveIntvAfter - Leave openli after the instruction at Idx.
681 void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
682   assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
683
684   // The interval must be live beyond the instruction at Idx.
685   SlotIndex EndIdx = Idx.getNextIndex().getBaseIndex();
686   VNInfo *ParentVNI = curli_->getVNInfoAt(EndIdx);
687   if (!ParentVNI) {
688     DEBUG(dbgs() << "    leaveIntvAfter " << Idx << ": not live\n");
689     return;
690   }
691
692   MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
693   assert(MI && "leaveIntvAfter called with invalid index");
694
695   VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI,
696                                   *MI->getParent(), MI);
697
698   // Finally we must make sure that openli is properly extended from Idx to the
699   // new copy.
700   openli_.mapValue(ParentVNI, VNI->def.getUseIndex());
701
702   DEBUG(dbgs() << "    leaveIntvAfter " << Idx << ": " << *openli_.getLI()
703                << '\n');
704 }
705
706 /// leaveIntvAtTop - Leave the interval at the top of MBB.
707 /// Currently, only one value can leave the interval.
708 void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
709   assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
710
711   SlotIndex Start = lis_.getMBBStartIdx(&MBB);
712   VNInfo *ParentVNI = curli_->getVNInfoAt(Start);
713
714   // Is curli even live-in to MBB?
715   if (!ParentVNI) {
716     DEBUG(dbgs() << "    leaveIntvAtTop at " << Start << ": not live\n");
717     return;
718   }
719
720   // We are going to insert a back copy, so we must have a dupli_.
721   VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI,
722                                      MBB, MBB.begin());
723
724   // Finally we must make sure that openli is properly extended from Start to
725   // the new copy.
726   openli_.mapValue(ParentVNI, VNI->def.getUseIndex());
727
728   DEBUG(dbgs() << "    leaveIntvAtTop at " << Start << ": " << *openli_.getLI()
729                << '\n');
730 }
731
732 /// closeIntv - Indicate that we are done editing the currently open
733 /// LiveInterval, and ranges can be trimmed.
734 void SplitEditor::closeIntv() {
735   assert(openli_.getLI() && "openIntv not called before closeIntv");
736
737   DEBUG(dbgs() << "    closeIntv cleaning up\n");
738   DEBUG(dbgs() << "    open " << *openli_.getLI() << '\n');
739
740   for (LiveInterval::iterator I = openli_.getLI()->begin(),
741        E = openli_.getLI()->end(); I != E; ++I) {
742     dupli_.getLI()->removeRange(I->start, I->end);
743   }
744   // FIXME: A block branching to the entry block may also branch elsewhere
745   // curli is live. We need both openli and curli to be live in that case.
746   DEBUG(dbgs() << "    dup2 " << *dupli_.getLI() << '\n');
747   openli_.reset(0);
748 }
749
750 /// rewrite - after all the new live ranges have been created, rewrite
751 /// instructions using curli to use the new intervals.
752 bool SplitEditor::rewrite() {
753   assert(!openli_.getLI() && "Previous LI not closed before rewrite");
754   const LiveInterval *curli = sa_.getCurLI();
755   for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(curli->reg),
756        RE = mri_.reg_end(); RI != RE;) {
757     MachineOperand &MO = RI.getOperand();
758     MachineInstr *MI = MO.getParent();
759     ++RI;
760     if (MI->isDebugValue()) {
761       DEBUG(dbgs() << "Zapping " << *MI);
762       // FIXME: We can do much better with debug values.
763       MO.setReg(0);
764       continue;
765     }
766     SlotIndex Idx = lis_.getInstructionIndex(MI);
767     Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
768     LiveInterval *LI = dupli_.getLI();
769     for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
770       LiveInterval *testli = intervals_[i];
771       if (testli->liveAt(Idx)) {
772         LI = testli;
773         break;
774       }
775     }
776     if (LI) {
777       MO.setReg(LI->reg);
778       sa_.removeUse(MI);
779       DEBUG(dbgs() << "  rewrite " << Idx << '\t' << *MI);
780     }
781   }
782
783   // dupli_ goes in last, after rewriting.
784   if (dupli_.getLI()) {
785     if (dupli_.getLI()->empty()) {
786       DEBUG(dbgs() << "  dupli became empty?\n");
787       lis_.removeInterval(dupli_.getLI()->reg);
788       dupli_.reset(0);
789     } else {
790       dupli_.getLI()->RenumberValues(lis_);
791       intervals_.push_back(dupli_.getLI());
792     }
793   }
794
795   // Calculate spill weight and allocation hints for new intervals.
796   VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
797   for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
798     LiveInterval &li = *intervals_[i];
799     vrai.CalculateRegClass(li.reg);
800     vrai.CalculateWeightAndHint(li);
801     DEBUG(dbgs() << "  new interval " << mri_.getRegClass(li.reg)->getName()
802                  << ":" << li << '\n');
803   }
804   return dupli_.getLI();
805 }
806
807
808 //===----------------------------------------------------------------------===//
809 //                               Loop Splitting
810 //===----------------------------------------------------------------------===//
811
812 bool SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
813   SplitAnalysis::LoopBlocks Blocks;
814   sa_.getLoopBlocks(Loop, Blocks);
815
816   // Break critical edges as needed.
817   SplitAnalysis::BlockPtrSet CriticalExits;
818   sa_.getCriticalExits(Blocks, CriticalExits);
819   assert(CriticalExits.empty() && "Cannot break critical exits yet");
820
821   // Create new live interval for the loop.
822   openIntv();
823
824   // Insert copies in the predecessors.
825   for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
826        E = Blocks.Preds.end(); I != E; ++I) {
827     MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
828     enterIntvAtEnd(MBB);
829   }
830
831   // Switch all loop blocks.
832   for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
833        E = Blocks.Loop.end(); I != E; ++I)
834      useIntv(**I);
835
836   // Insert back copies in the exit blocks.
837   for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
838        E = Blocks.Exits.end(); I != E; ++I) {
839     MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
840     leaveIntvAtTop(MBB);
841   }
842
843   // Done.
844   closeIntv();
845   return rewrite();
846 }
847
848
849 //===----------------------------------------------------------------------===//
850 //                            Single Block Splitting
851 //===----------------------------------------------------------------------===//
852
853 /// splitSingleBlocks - Split curli into a separate live interval inside each
854 /// basic block in Blocks. Return true if curli has been completely replaced,
855 /// false if curli is still intact, and needs to be spilled or split further.
856 bool SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
857   DEBUG(dbgs() << "  splitSingleBlocks for " << Blocks.size() << " blocks.\n");
858   // Determine the first and last instruction using curli in each block.
859   typedef std::pair<SlotIndex,SlotIndex> IndexPair;
860   typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
861   IndexPairMap MBBRange;
862   for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
863        E = sa_.usingInstrs_.end(); I != E; ++I) {
864     const MachineBasicBlock *MBB = (*I)->getParent();
865     if (!Blocks.count(MBB))
866       continue;
867     SlotIndex Idx = lis_.getInstructionIndex(*I);
868     DEBUG(dbgs() << "  BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
869     IndexPair &IP = MBBRange[MBB];
870     if (!IP.first.isValid() || Idx < IP.first)
871       IP.first = Idx;
872     if (!IP.second.isValid() || Idx > IP.second)
873       IP.second = Idx;
874   }
875
876   // Create a new interval for each block.
877   for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
878        E = Blocks.end(); I != E; ++I) {
879     IndexPair &IP = MBBRange[*I];
880     DEBUG(dbgs() << "  splitting for BB#" << (*I)->getNumber() << ": ["
881                  << IP.first << ';' << IP.second << ")\n");
882     assert(IP.first.isValid() && IP.second.isValid());
883
884     openIntv();
885     enterIntvBefore(IP.first);
886     useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
887     leaveIntvAfter(IP.second);
888     closeIntv();
889   }
890   return rewrite();
891 }
892
893
894 //===----------------------------------------------------------------------===//
895 //                            Sub Block Splitting
896 //===----------------------------------------------------------------------===//
897
898 /// getBlockForInsideSplit - If curli is contained inside a single basic block,
899 /// and it wou pay to subdivide the interval inside that block, return it.
900 /// Otherwise return NULL. The returned block can be passed to
901 /// SplitEditor::splitInsideBlock.
902 const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
903   // The interval must be exclusive to one block.
904   if (usingBlocks_.size() != 1)
905     return 0;
906   // Don't to this for less than 4 instructions. We want to be sure that
907   // splitting actually reduces the instruction count per interval.
908   if (usingInstrs_.size() < 4)
909     return 0;
910   return usingBlocks_.begin()->first;
911 }
912
913 /// splitInsideBlock - Split curli into multiple intervals inside MBB. Return
914 /// true if curli has been completely replaced, false if curli is still
915 /// intact, and needs to be spilled or split further.
916 bool SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
917   SmallVector<SlotIndex, 32> Uses;
918   Uses.reserve(sa_.usingInstrs_.size());
919   for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
920        E = sa_.usingInstrs_.end(); I != E; ++I)
921     if ((*I)->getParent() == MBB)
922       Uses.push_back(lis_.getInstructionIndex(*I));
923   DEBUG(dbgs() << "  splitInsideBlock BB#" << MBB->getNumber() << " for "
924                << Uses.size() << " instructions.\n");
925   assert(Uses.size() >= 3 && "Need at least 3 instructions");
926   array_pod_sort(Uses.begin(), Uses.end());
927
928   // Simple algorithm: Find the largest gap between uses as determined by slot
929   // indices. Create new intervals for instructions before the gap and after the
930   // gap.
931   unsigned bestPos = 0;
932   int bestGap = 0;
933   DEBUG(dbgs() << "    dist (" << Uses[0]);
934   for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
935     int g = Uses[i-1].distance(Uses[i]);
936     DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
937     if (g > bestGap)
938       bestPos = i, bestGap = g;
939   }
940   DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
941
942   // bestPos points to the first use after the best gap.
943   assert(bestPos > 0 && "Invalid gap");
944
945   // FIXME: Don't create intervals for low densities.
946
947   // First interval before the gap. Don't create single-instr intervals.
948   if (bestPos > 1) {
949     openIntv();
950     enterIntvBefore(Uses.front());
951     useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
952     leaveIntvAfter(Uses[bestPos-1]);
953     closeIntv();
954   }
955
956   // Second interval after the gap.
957   if (bestPos < Uses.size()-1) {
958     openIntv();
959     enterIntvBefore(Uses[bestPos]);
960     useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
961     leaveIntvAfter(Uses.back());
962     closeIntv();
963   }
964
965   return rewrite();
966 }