mi-sched: update PressureDiffs on-the-fly for liveness.
[oota-llvm.git] / lib / CodeGen / RegisterPressure.cpp
1 //===-- RegisterPressure.cpp - Dynamic Register Pressure ------------------===//
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 implements the RegisterPressure class which can be used to track
11 // MachineInstr level register pressure.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/RegisterPressure.h"
16 #include "llvm/CodeGen/LiveInterval.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/CodeGen/RegisterClassInfo.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetMachine.h"
23
24 using namespace llvm;
25
26 /// Increase pressure for each pressure set provided by TargetRegisterInfo.
27 static void increaseSetPressure(std::vector<unsigned> &CurrSetPressure,
28                                 PSetIterator PSetI) {
29   unsigned Weight = PSetI.getWeight();
30   for (; PSetI.isValid(); ++PSetI)
31     CurrSetPressure[*PSetI] += Weight;
32 }
33
34 /// Decrease pressure for each pressure set provided by TargetRegisterInfo.
35 static void decreaseSetPressure(std::vector<unsigned> &CurrSetPressure,
36                                 PSetIterator PSetI) {
37   unsigned Weight = PSetI.getWeight();
38   for (; PSetI.isValid(); ++PSetI) {
39     assert(CurrSetPressure[*PSetI] >= Weight && "register pressure underflow");
40     CurrSetPressure[*PSetI] -= Weight;
41   }
42 }
43
44 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
45 void llvm::dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
46                               const TargetRegisterInfo *TRI) {
47   bool Empty = true;
48   for (unsigned i = 0, e = SetPressure.size(); i < e; ++i) {
49     if (SetPressure[i] != 0) {
50       dbgs() << TRI->getRegPressureSetName(i) << "=" << SetPressure[i] << '\n';
51       Empty = false;
52     }
53   }
54   if (Empty)
55     dbgs() << "\n";
56 }
57
58 void RegisterPressure::dump(const TargetRegisterInfo *TRI) const {
59   dbgs() << "Max Pressure: ";
60   dumpRegSetPressure(MaxSetPressure, TRI);
61   dbgs() << "Live In: ";
62   for (unsigned i = 0, e = LiveInRegs.size(); i < e; ++i)
63     dbgs() << PrintReg(LiveInRegs[i], TRI) << " ";
64   dbgs() << '\n';
65   dbgs() << "Live Out: ";
66   for (unsigned i = 0, e = LiveOutRegs.size(); i < e; ++i)
67     dbgs() << PrintReg(LiveOutRegs[i], TRI) << " ";
68   dbgs() << '\n';
69 }
70
71 void RegPressureTracker::dump() const {
72   if (!isTopClosed() || !isBottomClosed()) {
73     dbgs() << "Curr Pressure: ";
74     dumpRegSetPressure(CurrSetPressure, TRI);
75   }
76   P.dump(TRI);
77 }
78 #endif
79
80 /// Increase the current pressure as impacted by these registers and bump
81 /// the high water mark if needed.
82 void RegPressureTracker::increaseRegPressure(ArrayRef<unsigned> RegUnits) {
83   for (unsigned i = 0, e = RegUnits.size(); i != e; ++i) {
84     PSetIterator PSetI = MRI->getPressureSets(RegUnits[i]);
85     unsigned Weight = PSetI.getWeight();
86     for (; PSetI.isValid(); ++PSetI) {
87       CurrSetPressure[*PSetI] += Weight;
88       if (CurrSetPressure[*PSetI] > P.MaxSetPressure[*PSetI]) {
89         P.MaxSetPressure[*PSetI] = CurrSetPressure[*PSetI];
90       }
91     }
92   }
93 }
94
95 /// Simply decrease the current pressure as impacted by these registers.
96 void RegPressureTracker::decreaseRegPressure(ArrayRef<unsigned> RegUnits) {
97   for (unsigned I = 0, E = RegUnits.size(); I != E; ++I)
98     decreaseSetPressure(CurrSetPressure, MRI->getPressureSets(RegUnits[I]));
99 }
100
101 /// Clear the result so it can be used for another round of pressure tracking.
102 void IntervalPressure::reset() {
103   TopIdx = BottomIdx = SlotIndex();
104   MaxSetPressure.clear();
105   LiveInRegs.clear();
106   LiveOutRegs.clear();
107 }
108
109 /// Clear the result so it can be used for another round of pressure tracking.
110 void RegionPressure::reset() {
111   TopPos = BottomPos = MachineBasicBlock::const_iterator();
112   MaxSetPressure.clear();
113   LiveInRegs.clear();
114   LiveOutRegs.clear();
115 }
116
117 /// If the current top is not less than or equal to the next index, open it.
118 /// We happen to need the SlotIndex for the next top for pressure update.
119 void IntervalPressure::openTop(SlotIndex NextTop) {
120   if (TopIdx <= NextTop)
121     return;
122   TopIdx = SlotIndex();
123   LiveInRegs.clear();
124 }
125
126 /// If the current top is the previous instruction (before receding), open it.
127 void RegionPressure::openTop(MachineBasicBlock::const_iterator PrevTop) {
128   if (TopPos != PrevTop)
129     return;
130   TopPos = MachineBasicBlock::const_iterator();
131   LiveInRegs.clear();
132 }
133
134 /// If the current bottom is not greater than the previous index, open it.
135 void IntervalPressure::openBottom(SlotIndex PrevBottom) {
136   if (BottomIdx > PrevBottom)
137     return;
138   BottomIdx = SlotIndex();
139   LiveInRegs.clear();
140 }
141
142 /// If the current bottom is the previous instr (before advancing), open it.
143 void RegionPressure::openBottom(MachineBasicBlock::const_iterator PrevBottom) {
144   if (BottomPos != PrevBottom)
145     return;
146   BottomPos = MachineBasicBlock::const_iterator();
147   LiveInRegs.clear();
148 }
149
150 const LiveInterval *RegPressureTracker::getInterval(unsigned Reg) const {
151   if (TargetRegisterInfo::isVirtualRegister(Reg))
152     return &LIS->getInterval(Reg);
153   return LIS->getCachedRegUnit(Reg);
154 }
155
156 /// Setup the RegPressureTracker.
157 ///
158 /// TODO: Add support for pressure without LiveIntervals.
159 void RegPressureTracker::init(const MachineFunction *mf,
160                               const RegisterClassInfo *rci,
161                               const LiveIntervals *lis,
162                               const MachineBasicBlock *mbb,
163                               MachineBasicBlock::const_iterator pos,
164                               bool ShouldTrackUntiedDefs)
165 {
166   MF = mf;
167   TRI = MF->getTarget().getRegisterInfo();
168   RCI = rci;
169   MRI = &MF->getRegInfo();
170   MBB = mbb;
171   TrackUntiedDefs = ShouldTrackUntiedDefs;
172
173   if (RequireIntervals) {
174     assert(lis && "IntervalPressure requires LiveIntervals");
175     LIS = lis;
176   }
177
178   CurrPos = pos;
179   CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0);
180   LiveThruPressure.clear();
181
182   if (RequireIntervals)
183     static_cast<IntervalPressure&>(P).reset();
184   else
185     static_cast<RegionPressure&>(P).reset();
186   P.MaxSetPressure = CurrSetPressure;
187
188   LiveRegs.PhysRegs.clear();
189   LiveRegs.PhysRegs.setUniverse(TRI->getNumRegs());
190   LiveRegs.VirtRegs.clear();
191   LiveRegs.VirtRegs.setUniverse(MRI->getNumVirtRegs());
192   UntiedDefs.clear();
193   if (TrackUntiedDefs)
194     UntiedDefs.setUniverse(MRI->getNumVirtRegs());
195 }
196
197 /// Does this pressure result have a valid top position and live ins.
198 bool RegPressureTracker::isTopClosed() const {
199   if (RequireIntervals)
200     return static_cast<IntervalPressure&>(P).TopIdx.isValid();
201   return (static_cast<RegionPressure&>(P).TopPos ==
202           MachineBasicBlock::const_iterator());
203 }
204
205 /// Does this pressure result have a valid bottom position and live outs.
206 bool RegPressureTracker::isBottomClosed() const {
207   if (RequireIntervals)
208     return static_cast<IntervalPressure&>(P).BottomIdx.isValid();
209   return (static_cast<RegionPressure&>(P).BottomPos ==
210           MachineBasicBlock::const_iterator());
211 }
212
213
214 SlotIndex RegPressureTracker::getCurrSlot() const {
215   MachineBasicBlock::const_iterator IdxPos = CurrPos;
216   while (IdxPos != MBB->end() && IdxPos->isDebugValue())
217     ++IdxPos;
218   if (IdxPos == MBB->end())
219     return LIS->getMBBEndIdx(MBB);
220   return LIS->getInstructionIndex(IdxPos).getRegSlot();
221 }
222
223 /// Set the boundary for the top of the region and summarize live ins.
224 void RegPressureTracker::closeTop() {
225   if (RequireIntervals)
226     static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot();
227   else
228     static_cast<RegionPressure&>(P).TopPos = CurrPos;
229
230   assert(P.LiveInRegs.empty() && "inconsistent max pressure result");
231   P.LiveInRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size());
232   P.LiveInRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end());
233   for (SparseSet<unsigned>::const_iterator I =
234          LiveRegs.VirtRegs.begin(), E = LiveRegs.VirtRegs.end(); I != E; ++I)
235     P.LiveInRegs.push_back(*I);
236   std::sort(P.LiveInRegs.begin(), P.LiveInRegs.end());
237   P.LiveInRegs.erase(std::unique(P.LiveInRegs.begin(), P.LiveInRegs.end()),
238                      P.LiveInRegs.end());
239 }
240
241 /// Set the boundary for the bottom of the region and summarize live outs.
242 void RegPressureTracker::closeBottom() {
243   if (RequireIntervals)
244     static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot();
245   else
246     static_cast<RegionPressure&>(P).BottomPos = CurrPos;
247
248   assert(P.LiveOutRegs.empty() && "inconsistent max pressure result");
249   P.LiveOutRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size());
250   P.LiveOutRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end());
251   for (SparseSet<unsigned>::const_iterator I =
252          LiveRegs.VirtRegs.begin(), E = LiveRegs.VirtRegs.end(); I != E; ++I)
253     P.LiveOutRegs.push_back(*I);
254   std::sort(P.LiveOutRegs.begin(), P.LiveOutRegs.end());
255   P.LiveOutRegs.erase(std::unique(P.LiveOutRegs.begin(), P.LiveOutRegs.end()),
256                       P.LiveOutRegs.end());
257 }
258
259 /// Finalize the region boundaries and record live ins and live outs.
260 void RegPressureTracker::closeRegion() {
261   if (!isTopClosed() && !isBottomClosed()) {
262     assert(LiveRegs.PhysRegs.empty() && LiveRegs.VirtRegs.empty() &&
263            "no region boundary");
264     return;
265   }
266   if (!isBottomClosed())
267     closeBottom();
268   else if (!isTopClosed())
269     closeTop();
270   // If both top and bottom are closed, do nothing.
271 }
272
273 /// The register tracker is unaware of global liveness so ignores normal
274 /// live-thru ranges. However, two-address or coalesced chains can also lead
275 /// to live ranges with no holes. Count these to inform heuristics that we
276 /// can never drop below this pressure.
277 void RegPressureTracker::initLiveThru(const RegPressureTracker &RPTracker) {
278   LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0);
279   assert(isBottomClosed() && "need bottom-up tracking to intialize.");
280   for (unsigned i = 0, e = P.LiveOutRegs.size(); i < e; ++i) {
281     unsigned Reg = P.LiveOutRegs[i];
282     if (TargetRegisterInfo::isVirtualRegister(Reg)
283         && !RPTracker.hasUntiedDef(Reg)) {
284       increaseSetPressure(LiveThruPressure, MRI->getPressureSets(Reg));
285     }
286   }
287 }
288
289 /// \brief Convenient wrapper for checking membership in RegisterOperands.
290 /// (std::count() doesn't have an early exit).
291 static bool containsReg(ArrayRef<unsigned> RegUnits, unsigned RegUnit) {
292   return std::find(RegUnits.begin(), RegUnits.end(), RegUnit) != RegUnits.end();
293 }
294
295 /// Collect this instruction's unique uses and defs into SmallVectors for
296 /// processing defs and uses in order.
297 ///
298 /// FIXME: always ignore tied opers
299 class RegisterOperands {
300   const TargetRegisterInfo *TRI;
301   const MachineRegisterInfo *MRI;
302   bool IgnoreDead;
303
304 public:
305   SmallVector<unsigned, 8> Uses;
306   SmallVector<unsigned, 8> Defs;
307   SmallVector<unsigned, 8> DeadDefs;
308
309   RegisterOperands(const TargetRegisterInfo *tri,
310                    const MachineRegisterInfo *mri, bool ID = false):
311     TRI(tri), MRI(mri), IgnoreDead(ID) {}
312
313   /// Push this operand's register onto the correct vector.
314   void collect(const MachineOperand &MO) {
315     if (!MO.isReg() || !MO.getReg())
316       return;
317     if (MO.readsReg())
318       pushRegUnits(MO.getReg(), Uses);
319     if (MO.isDef()) {
320       if (MO.isDead()) {
321         if (!IgnoreDead)
322           pushRegUnits(MO.getReg(), DeadDefs);
323       }
324       else
325         pushRegUnits(MO.getReg(), Defs);
326     }
327   }
328
329 protected:
330   void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) {
331     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
332       if (containsReg(RegUnits, Reg))
333         return;
334       RegUnits.push_back(Reg);
335     }
336     else if (MRI->isAllocatable(Reg)) {
337       for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
338         if (containsReg(RegUnits, *Units))
339           continue;
340         RegUnits.push_back(*Units);
341       }
342     }
343   }
344 };
345
346 /// Collect physical and virtual register operands.
347 static void collectOperands(const MachineInstr *MI,
348                             RegisterOperands &RegOpers) {
349   for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI)
350     RegOpers.collect(*OperI);
351
352   // Remove redundant physreg dead defs.
353   SmallVectorImpl<unsigned>::iterator I =
354     std::remove_if(RegOpers.DeadDefs.begin(), RegOpers.DeadDefs.end(),
355                    std::bind1st(std::ptr_fun(containsReg), RegOpers.Defs));
356   RegOpers.DeadDefs.erase(I, RegOpers.DeadDefs.end());
357 }
358
359 /// Initialize an array of N PressureDiffs.
360 void PressureDiffs::init(unsigned N) {
361   Size = N;
362   if (N <= Max) {
363     memset(PDiffArray, 0, N * sizeof(PressureDiff));
364     return;
365   }
366   Max = Size;
367   free(PDiffArray);
368   PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff)));
369 }
370
371 /// Add a change in pressure to the pressure diff of a given instruction.
372 void PressureDiff::addPressureChange(unsigned RegUnit, bool IsDec,
373                                      const MachineRegisterInfo *MRI) {
374   PSetIterator PSetI = MRI->getPressureSets(RegUnit);
375   int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight();
376   for (; PSetI.isValid(); ++PSetI) {
377     // Find an existing entry in the pressure diff for this PSet.
378     PressureDiff::iterator I = begin(), E = end();
379     for (; I != E && I->isValid(); ++I) {
380       if (I->getPSet() >= *PSetI)
381         break;
382     }
383     // If all pressure sets are more constrained, skip the remaining PSets.
384     if (I == E)
385       break;
386     // Insert this PressureChange.
387     if (!I->isValid() || I->getPSet() != *PSetI) {
388       PressureChange PTmp = PressureChange(*PSetI);
389       for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J)
390         std::swap(*J,PTmp);
391     }
392     // Update the units for this pressure set.
393     I->setUnitInc(I->getUnitInc() + Weight);
394   }
395 }
396
397 /// Record the pressure difference induced by the given operand list.
398 static void collectPDiff(PressureDiff &PDiff, RegisterOperands &RegOpers,
399                          const MachineRegisterInfo *MRI) {
400   assert(!PDiff.begin()->isValid() && "stale PDiff");
401
402   for (unsigned i = 0, e = RegOpers.Defs.size(); i != e; ++i)
403     PDiff.addPressureChange(RegOpers.Defs[i], true, MRI);
404
405   for (unsigned i = 0, e = RegOpers.Uses.size(); i != e; ++i)
406     PDiff.addPressureChange(RegOpers.Uses[i], false, MRI);
407 }
408
409 /// Force liveness of registers.
410 void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) {
411   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
412     if (LiveRegs.insert(Regs[i]))
413       increaseRegPressure(Regs[i]);
414   }
415 }
416
417 /// Add Reg to the live in set and increase max pressure.
418 void RegPressureTracker::discoverLiveIn(unsigned Reg) {
419   assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
420   if (containsReg(P.LiveInRegs, Reg))
421     return;
422
423   // At live in discovery, unconditionally increase the high water mark.
424   P.LiveInRegs.push_back(Reg);
425   increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
426 }
427
428 /// Add Reg to the live out set and increase max pressure.
429 void RegPressureTracker::discoverLiveOut(unsigned Reg) {
430   assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
431   if (containsReg(P.LiveOutRegs, Reg))
432     return;
433
434   // At live out discovery, unconditionally increase the high water mark.
435   P.LiveOutRegs.push_back(Reg);
436   increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
437 }
438
439 /// Recede across the previous instruction. If LiveUses is provided, record any
440 /// RegUnits that are made live by the current instruction's uses. This includes
441 /// registers that are both defined and used by the instruction.  If a pressure
442 /// difference pointer is provided record the changes is pressure caused by this
443 /// instruction independent of liveness.
444 bool RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses,
445                                 PressureDiff *PDiff) {
446   // Check for the top of the analyzable region.
447   if (CurrPos == MBB->begin()) {
448     closeRegion();
449     return false;
450   }
451   if (!isBottomClosed())
452     closeBottom();
453
454   // Open the top of the region using block iterators.
455   if (!RequireIntervals && isTopClosed())
456     static_cast<RegionPressure&>(P).openTop(CurrPos);
457
458   // Find the previous instruction.
459   do
460     --CurrPos;
461   while (CurrPos != MBB->begin() && CurrPos->isDebugValue());
462
463   if (CurrPos->isDebugValue()) {
464     closeRegion();
465     return false;
466   }
467   SlotIndex SlotIdx;
468   if (RequireIntervals)
469     SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
470
471   // Open the top of the region using slot indexes.
472   if (RequireIntervals && isTopClosed())
473     static_cast<IntervalPressure&>(P).openTop(SlotIdx);
474
475   RegisterOperands RegOpers(TRI, MRI);
476   collectOperands(CurrPos, RegOpers);
477
478   if (PDiff)
479     collectPDiff(*PDiff, RegOpers, MRI);
480
481   // Boost pressure for all dead defs together.
482   increaseRegPressure(RegOpers.DeadDefs);
483   decreaseRegPressure(RegOpers.DeadDefs);
484
485   // Kill liveness at live defs.
486   // TODO: consider earlyclobbers?
487   for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
488     unsigned Reg = RegOpers.Defs[i];
489     if (LiveRegs.erase(Reg))
490       decreaseRegPressure(Reg);
491     else
492       discoverLiveOut(Reg);
493   }
494
495   // Generate liveness for uses.
496   for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
497     unsigned Reg = RegOpers.Uses[i];
498     if (!LiveRegs.contains(Reg)) {
499       // Adjust liveouts if LiveIntervals are available.
500       if (RequireIntervals) {
501         const LiveInterval *LI = getInterval(Reg);
502         // Check if this LR is killed and not redefined here.
503         if (LI && !LI->isKilledAtInstr(SlotIdx)
504             && !LI->isDefinedByInstr(SlotIdx)) {
505             discoverLiveOut(Reg);
506         }
507       }
508       increaseRegPressure(Reg);
509       LiveRegs.insert(Reg);
510       if (LiveUses && !containsReg(*LiveUses, Reg))
511         LiveUses->push_back(Reg);
512     }
513   }
514   if (TrackUntiedDefs) {
515     for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
516       unsigned Reg = RegOpers.Defs[i];
517       if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg))
518         UntiedDefs.insert(Reg);
519     }
520   }
521   return true;
522 }
523
524 /// Advance across the current instruction.
525 bool RegPressureTracker::advance() {
526   assert(!TrackUntiedDefs && "unsupported mode");
527
528   // Check for the bottom of the analyzable region.
529   if (CurrPos == MBB->end()) {
530     closeRegion();
531     return false;
532   }
533   if (!isTopClosed())
534     closeTop();
535
536   SlotIndex SlotIdx;
537   if (RequireIntervals)
538     SlotIdx = getCurrSlot();
539
540   // Open the bottom of the region using slot indexes.
541   if (isBottomClosed()) {
542     if (RequireIntervals)
543       static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
544     else
545       static_cast<RegionPressure&>(P).openBottom(CurrPos);
546   }
547
548   RegisterOperands RegOpers(TRI, MRI);
549   collectOperands(CurrPos, RegOpers);
550
551   for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
552     unsigned Reg = RegOpers.Uses[i];
553     // Discover live-ins.
554     bool isLive = LiveRegs.contains(Reg);
555     if (!isLive)
556       discoverLiveIn(Reg);
557     // Kill liveness at last uses.
558     bool lastUse = false;
559     if (RequireIntervals) {
560       const LiveInterval *LI = getInterval(Reg);
561       lastUse = LI && LI->isKilledAtInstr(SlotIdx);
562     }
563     else {
564       // Allocatable physregs are always single-use before register rewriting.
565       lastUse = !TargetRegisterInfo::isVirtualRegister(Reg);
566     }
567     if (lastUse && isLive) {
568       LiveRegs.erase(Reg);
569       decreaseRegPressure(Reg);
570     }
571     else if (!lastUse && !isLive)
572       increaseRegPressure(Reg);
573   }
574
575   // Generate liveness for defs.
576   for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
577     unsigned Reg = RegOpers.Defs[i];
578     if (LiveRegs.insert(Reg))
579       increaseRegPressure(Reg);
580   }
581
582   // Boost pressure for all dead defs together.
583   increaseRegPressure(RegOpers.DeadDefs);
584   decreaseRegPressure(RegOpers.DeadDefs);
585
586   // Find the next instruction.
587   do
588     ++CurrPos;
589   while (CurrPos != MBB->end() && CurrPos->isDebugValue());
590   return true;
591 }
592
593 /// Find the max change in excess pressure across all sets.
594 static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec,
595                                        ArrayRef<unsigned> NewPressureVec,
596                                        RegPressureDelta &Delta,
597                                        const RegisterClassInfo *RCI,
598                                        ArrayRef<unsigned> LiveThruPressureVec) {
599   Delta.Excess = PressureChange();
600   for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) {
601     unsigned POld = OldPressureVec[i];
602     unsigned PNew = NewPressureVec[i];
603     int PDiff = (int)PNew - (int)POld;
604     if (!PDiff) // No change in this set in the common case.
605       continue;
606     // Only consider change beyond the limit.
607     unsigned Limit = RCI->getRegPressureSetLimit(i);
608     if (!LiveThruPressureVec.empty())
609       Limit += LiveThruPressureVec[i];
610
611     if (Limit > POld) {
612       if (Limit > PNew)
613         PDiff = 0;            // Under the limit
614       else
615         PDiff = PNew - Limit; // Just exceeded limit.
616     }
617     else if (Limit > PNew)
618       PDiff = Limit - POld;   // Just obeyed limit.
619
620     if (PDiff) {
621       Delta.Excess = PressureChange(i);
622       Delta.Excess.setUnitInc(PDiff);
623       break;
624     }
625   }
626 }
627
628 /// Find the max change in max pressure that either surpasses a critical PSet
629 /// limit or exceeds the current MaxPressureLimit.
630 ///
631 /// FIXME: comparing each element of the old and new MaxPressure vectors here is
632 /// silly. It's done now to demonstrate the concept but will go away with a
633 /// RegPressureTracker API change to work with pressure differences.
634 static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec,
635                                     ArrayRef<unsigned> NewMaxPressureVec,
636                                     ArrayRef<PressureChange> CriticalPSets,
637                                     ArrayRef<unsigned> MaxPressureLimit,
638                                     RegPressureDelta &Delta) {
639   Delta.CriticalMax = PressureChange();
640   Delta.CurrentMax = PressureChange();
641
642   unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
643   for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) {
644     unsigned POld = OldMaxPressureVec[i];
645     unsigned PNew = NewMaxPressureVec[i];
646     if (PNew == POld) // No change in this set in the common case.
647       continue;
648
649     if (!Delta.CriticalMax.isValid()) {
650       while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i)
651         ++CritIdx;
652
653       if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) {
654         int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc();
655         if (PDiff > 0) {
656           Delta.CriticalMax = PressureChange(i);
657           Delta.CriticalMax.setUnitInc(PDiff);
658         }
659       }
660     }
661     // Find the first increase above MaxPressureLimit.
662     // (Ignores negative MDiff).
663     if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) {
664       Delta.CurrentMax = PressureChange(i);
665       Delta.CurrentMax.setUnitInc(PNew - POld);
666       if (CritIdx == CritEnd || Delta.CriticalMax.isValid())
667         break;
668     }
669   }
670 }
671
672 /// Record the upward impact of a single instruction on current register
673 /// pressure. Unlike the advance/recede pressure tracking interface, this does
674 /// not discover live in/outs.
675 ///
676 /// This is intended for speculative queries. It leaves pressure inconsistent
677 /// with the current position, so must be restored by the caller.
678 void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) {
679   assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
680
681   // Account for register pressure similar to RegPressureTracker::recede().
682   RegisterOperands RegOpers(TRI, MRI, /*IgnoreDead=*/true);
683   collectOperands(MI, RegOpers);
684
685   // Boost max pressure for all dead defs together.
686   // Since CurrSetPressure and MaxSetPressure
687   increaseRegPressure(RegOpers.DeadDefs);
688   decreaseRegPressure(RegOpers.DeadDefs);
689
690   // Kill liveness at live defs.
691   for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
692     unsigned Reg = RegOpers.Defs[i];
693     if (!containsReg(RegOpers.Uses, Reg))
694       decreaseRegPressure(Reg);
695   }
696   // Generate liveness for uses.
697   for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
698     unsigned Reg = RegOpers.Uses[i];
699     if (!LiveRegs.contains(Reg))
700       increaseRegPressure(Reg);
701   }
702 }
703
704 /// Consider the pressure increase caused by traversing this instruction
705 /// bottom-up. Find the pressure set with the most change beyond its pressure
706 /// limit based on the tracker's current pressure, and return the change in
707 /// number of register units of that pressure set introduced by this
708 /// instruction.
709 ///
710 /// This assumes that the current LiveOut set is sufficient.
711 ///
712 /// FIXME: This is expensive for an on-the-fly query. We need to cache the
713 /// result per-SUnit with enough information to adjust for the current
714 /// scheduling position. But this works as a proof of concept.
715 void RegPressureTracker::
716 getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff,
717                           RegPressureDelta &Delta,
718                           ArrayRef<PressureChange> CriticalPSets,
719                           ArrayRef<unsigned> MaxPressureLimit) {
720   // Snapshot Pressure.
721   // FIXME: The snapshot heap space should persist. But I'm planning to
722   // summarize the pressure effect so we don't need to snapshot at all.
723   std::vector<unsigned> SavedPressure = CurrSetPressure;
724   std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
725
726   bumpUpwardPressure(MI);
727
728   computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
729                              LiveThruPressure);
730   computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
731                           MaxPressureLimit, Delta);
732   assert(Delta.CriticalMax.getUnitInc() >= 0 &&
733          Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
734
735   // Restore the tracker's state.
736   P.MaxSetPressure.swap(SavedMaxPressure);
737   CurrSetPressure.swap(SavedPressure);
738
739 #ifndef NDEBUG
740   if (!PDiff)
741     return;
742
743   // Check if the alternate algorithm yields the same result.
744   RegPressureDelta Delta2;
745   getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit);
746   if (Delta != Delta2) {
747     dbgs() << "DELTA: " << *MI;
748     if (Delta.Excess.isValid())
749       dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet())
750              << " " << Delta.Excess.getUnitInc() << "\n";
751     if (Delta.CriticalMax.isValid())
752       dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet())
753              << " " << Delta.CriticalMax.getUnitInc() << "\n";
754     if (Delta.CurrentMax.isValid())
755       dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet())
756              << " " << Delta.CurrentMax.getUnitInc() << "\n";
757     if (Delta2.Excess.isValid())
758       dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet())
759              << " " << Delta2.Excess.getUnitInc() << "\n";
760     if (Delta2.CriticalMax.isValid())
761       dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet())
762              << " " << Delta2.CriticalMax.getUnitInc() << "\n";
763     if (Delta2.CurrentMax.isValid())
764       dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet())
765              << " " << Delta2.CurrentMax.getUnitInc() << "\n";
766     llvm_unreachable("RegP Delta Mismatch");
767   }
768 #endif
769 }
770
771 /// This is a prototype of the fast version of querying register pressure that
772 /// does not directly depend on current liveness. It's still slow because we
773 /// recompute pressure change on-the-fly. This implementation only exists to
774 /// prove correctness.
775 ///
776 /// @param Delta captures information needed for heuristics.
777 ///
778 /// @param CriticalPSets Are the pressure sets that are known to exceed some
779 /// limit within the region, not necessarily at the current position.
780 ///
781 /// @param MaxPressureLimit Is the max pressure within the region, not
782 /// necessarily at the current position.
783 void RegPressureTracker::
784 getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff,
785                        RegPressureDelta &Delta,
786                        ArrayRef<PressureChange> CriticalPSets,
787                        ArrayRef<unsigned> MaxPressureLimit) const {
788   unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
789   for (PressureDiff::const_iterator
790          PDiffI = PDiff.begin(), PDiffE = PDiff.end();
791        PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) {
792
793     unsigned PSetID = PDiffI->getPSet();
794     unsigned Limit = RCI->getRegPressureSetLimit(PSetID);
795     if (!LiveThruPressure.empty())
796       Limit += LiveThruPressure[PSetID];
797
798     unsigned POld = CurrSetPressure[PSetID];
799     unsigned MOld = P.MaxSetPressure[PSetID];
800     unsigned MNew = MOld;
801     // Ignore DeadDefs here because they aren't captured by PressureChange.
802     unsigned PNew = POld + PDiffI->getUnitInc();
803     assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld) && "PSet overflow");
804     if (PNew > MOld)
805       MNew = PNew;
806     // Check if current pressure has exceeded the limit.
807     if (!Delta.Excess.isValid()) {
808       unsigned ExcessInc = 0;
809       if (PNew > Limit)
810         ExcessInc = POld > Limit ? PNew - POld : PNew - Limit;
811       else if (POld > Limit)
812         ExcessInc = Limit - POld;
813       if (ExcessInc) {
814         Delta.Excess = PressureChange(PSetID);
815         Delta.Excess.setUnitInc(ExcessInc);
816       }
817     }
818     // Check if max pressure has exceeded a critical pressure set max.
819     if (MNew == MOld)
820       continue;
821     if (!Delta.CriticalMax.isValid()) {
822       while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID)
823         ++CritIdx;
824
825       if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) {
826         int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc();
827         if (CritInc > 0 && CritInc <= INT16_MAX) {
828           Delta.CriticalMax = PressureChange(PSetID);
829           Delta.CriticalMax.setUnitInc(CritInc);
830         }
831       }
832     }
833     // Check if max pressure has exceeded the current max.
834     if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) {
835       Delta.CurrentMax = PressureChange(PSetID);
836       Delta.CurrentMax.setUnitInc(MNew - MOld);
837     }
838   }
839 }
840
841 /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
842 static bool findUseBetween(unsigned Reg,
843                            SlotIndex PriorUseIdx, SlotIndex NextUseIdx,
844                            const MachineRegisterInfo *MRI,
845                            const LiveIntervals *LIS) {
846   for (MachineRegisterInfo::use_nodbg_iterator
847          UI = MRI->use_nodbg_begin(Reg), UE = MRI->use_nodbg_end();
848          UI != UE; UI.skipInstruction()) {
849       const MachineInstr* MI = &*UI;
850       if (MI->isDebugValue())
851         continue;
852       SlotIndex InstSlot = LIS->getInstructionIndex(MI).getRegSlot();
853       if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx)
854         return true;
855   }
856   return false;
857 }
858
859 /// Record the downward impact of a single instruction on current register
860 /// pressure. Unlike the advance/recede pressure tracking interface, this does
861 /// not discover live in/outs.
862 ///
863 /// This is intended for speculative queries. It leaves pressure inconsistent
864 /// with the current position, so must be restored by the caller.
865 void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) {
866   assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
867
868   // Account for register pressure similar to RegPressureTracker::recede().
869   RegisterOperands RegOpers(TRI, MRI);
870   collectOperands(MI, RegOpers);
871
872   // Kill liveness at last uses. Assume allocatable physregs are single-use
873   // rather than checking LiveIntervals.
874   SlotIndex SlotIdx;
875   if (RequireIntervals)
876     SlotIdx = LIS->getInstructionIndex(MI).getRegSlot();
877
878   for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
879     unsigned Reg = RegOpers.Uses[i];
880     if (RequireIntervals) {
881       // FIXME: allow the caller to pass in the list of vreg uses that remain
882       // to be bottom-scheduled to avoid searching uses at each query.
883       SlotIndex CurrIdx = getCurrSlot();
884       const LiveInterval *LI = getInterval(Reg);
885       if (LI && LI->isKilledAtInstr(SlotIdx)
886           && !findUseBetween(Reg, CurrIdx, SlotIdx, MRI, LIS)) {
887         decreaseRegPressure(Reg);
888       }
889     }
890     else if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
891       // Allocatable physregs are always single-use before register rewriting.
892       decreaseRegPressure(Reg);
893     }
894   }
895
896   // Generate liveness for defs.
897   increaseRegPressure(RegOpers.Defs);
898
899   // Boost pressure for all dead defs together.
900   increaseRegPressure(RegOpers.DeadDefs);
901   decreaseRegPressure(RegOpers.DeadDefs);
902 }
903
904 /// Consider the pressure increase caused by traversing this instruction
905 /// top-down. Find the register class with the most change in its pressure limit
906 /// based on the tracker's current pressure, and return the number of excess
907 /// register units of that pressure set introduced by this instruction.
908 ///
909 /// This assumes that the current LiveIn set is sufficient.
910 void RegPressureTracker::
911 getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
912                             ArrayRef<PressureChange> CriticalPSets,
913                             ArrayRef<unsigned> MaxPressureLimit) {
914   // Snapshot Pressure.
915   std::vector<unsigned> SavedPressure = CurrSetPressure;
916   std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
917
918   bumpDownwardPressure(MI);
919
920   computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
921                              LiveThruPressure);
922   computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
923                           MaxPressureLimit, Delta);
924   assert(Delta.CriticalMax.getUnitInc() >= 0 &&
925          Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
926
927   // Restore the tracker's state.
928   P.MaxSetPressure.swap(SavedMaxPressure);
929   CurrSetPressure.swap(SavedPressure);
930 }
931
932 /// Get the pressure of each PSet after traversing this instruction bottom-up.
933 void RegPressureTracker::
934 getUpwardPressure(const MachineInstr *MI,
935                   std::vector<unsigned> &PressureResult,
936                   std::vector<unsigned> &MaxPressureResult) {
937   // Snapshot pressure.
938   PressureResult = CurrSetPressure;
939   MaxPressureResult = P.MaxSetPressure;
940
941   bumpUpwardPressure(MI);
942
943   // Current pressure becomes the result. Restore current pressure.
944   P.MaxSetPressure.swap(MaxPressureResult);
945   CurrSetPressure.swap(PressureResult);
946 }
947
948 /// Get the pressure of each PSet after traversing this instruction top-down.
949 void RegPressureTracker::
950 getDownwardPressure(const MachineInstr *MI,
951                     std::vector<unsigned> &PressureResult,
952                     std::vector<unsigned> &MaxPressureResult) {
953   // Snapshot pressure.
954   PressureResult = CurrSetPressure;
955   MaxPressureResult = P.MaxSetPressure;
956
957   bumpDownwardPressure(MI);
958
959   // Current pressure becomes the result. Restore current pressure.
960   P.MaxSetPressure.swap(MaxPressureResult);
961   CurrSetPressure.swap(PressureResult);
962 }