Rename to RegPressure API parameters RegUnits.
[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 class RegisterOperands {
298   const TargetRegisterInfo *TRI;
299   const MachineRegisterInfo *MRI;
300
301 public:
302   SmallVector<unsigned, 8> Uses;
303   SmallVector<unsigned, 8> Defs;
304   SmallVector<unsigned, 8> DeadDefs;
305
306   RegisterOperands(const TargetRegisterInfo *tri,
307                    const MachineRegisterInfo *mri): TRI(tri), MRI(mri) {}
308
309   /// Push this operand's register onto the correct vector.
310   void collect(const MachineOperand &MO) {
311     if (!MO.isReg() || !MO.getReg())
312       return;
313     if (MO.readsReg())
314       pushRegUnits(MO.getReg(), Uses);
315     if (MO.isDef()) {
316       if (MO.isDead())
317         pushRegUnits(MO.getReg(), DeadDefs);
318       else
319         pushRegUnits(MO.getReg(), Defs);
320     }
321   }
322
323 protected:
324   void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) {
325     if (TargetRegisterInfo::isVirtualRegister(Reg)) {
326       if (containsReg(RegUnits, Reg))
327         return;
328       RegUnits.push_back(Reg);
329     }
330     else if (MRI->isAllocatable(Reg)) {
331       for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
332         if (containsReg(RegUnits, *Units))
333           continue;
334         RegUnits.push_back(*Units);
335       }
336     }
337   }
338 };
339
340 /// Collect physical and virtual register operands.
341 static void collectOperands(const MachineInstr *MI,
342                             RegisterOperands &RegOpers) {
343   for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI)
344     RegOpers.collect(*OperI);
345
346   // Remove redundant physreg dead defs.
347   SmallVectorImpl<unsigned>::iterator I =
348     std::remove_if(RegOpers.DeadDefs.begin(), RegOpers.DeadDefs.end(),
349                    std::bind1st(std::ptr_fun(containsReg), RegOpers.Defs));
350   RegOpers.DeadDefs.erase(I, RegOpers.DeadDefs.end());
351 }
352
353 /// Force liveness of registers.
354 void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) {
355   for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
356     if (LiveRegs.insert(Regs[i]))
357       increaseRegPressure(Regs[i]);
358   }
359 }
360
361 /// Add Reg to the live in set and increase max pressure.
362 void RegPressureTracker::discoverLiveIn(unsigned Reg) {
363   assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
364   if (containsReg(P.LiveInRegs, Reg))
365     return;
366
367   // At live in discovery, unconditionally increase the high water mark.
368   P.LiveInRegs.push_back(Reg);
369   increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
370 }
371
372 /// Add Reg to the live out set and increase max pressure.
373 void RegPressureTracker::discoverLiveOut(unsigned Reg) {
374   assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
375   if (containsReg(P.LiveOutRegs, Reg))
376     return;
377
378   // At live out discovery, unconditionally increase the high water mark.
379   P.LiveOutRegs.push_back(Reg);
380   increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
381 }
382
383 /// Recede across the previous instruction.
384 bool RegPressureTracker::recede() {
385   // Check for the top of the analyzable region.
386   if (CurrPos == MBB->begin()) {
387     closeRegion();
388     return false;
389   }
390   if (!isBottomClosed())
391     closeBottom();
392
393   // Open the top of the region using block iterators.
394   if (!RequireIntervals && isTopClosed())
395     static_cast<RegionPressure&>(P).openTop(CurrPos);
396
397   // Find the previous instruction.
398   do
399     --CurrPos;
400   while (CurrPos != MBB->begin() && CurrPos->isDebugValue());
401
402   if (CurrPos->isDebugValue()) {
403     closeRegion();
404     return false;
405   }
406   SlotIndex SlotIdx;
407   if (RequireIntervals)
408     SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
409
410   // Open the top of the region using slot indexes.
411   if (RequireIntervals && isTopClosed())
412     static_cast<IntervalPressure&>(P).openTop(SlotIdx);
413
414   RegisterOperands RegOpers(TRI, MRI);
415   collectOperands(CurrPos, RegOpers);
416
417   // Boost pressure for all dead defs together.
418   increaseRegPressure(RegOpers.DeadDefs);
419   decreaseRegPressure(RegOpers.DeadDefs);
420
421   // Kill liveness at live defs.
422   // TODO: consider earlyclobbers?
423   for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
424     unsigned Reg = RegOpers.Defs[i];
425     if (LiveRegs.erase(Reg))
426       decreaseRegPressure(Reg);
427     else
428       discoverLiveOut(Reg);
429   }
430
431   // Generate liveness for uses.
432   for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
433     unsigned Reg = RegOpers.Uses[i];
434     if (!LiveRegs.contains(Reg)) {
435       // Adjust liveouts if LiveIntervals are available.
436       if (RequireIntervals) {
437         const LiveInterval *LI = getInterval(Reg);
438         if (LI && !LI->killedAt(SlotIdx))
439           discoverLiveOut(Reg);
440       }
441       increaseRegPressure(Reg);
442       LiveRegs.insert(Reg);
443     }
444   }
445   if (TrackUntiedDefs) {
446     for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
447       unsigned Reg = RegOpers.Defs[i];
448       if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg))
449         UntiedDefs.insert(Reg);
450     }
451   }
452   return true;
453 }
454
455 /// Advance across the current instruction.
456 bool RegPressureTracker::advance() {
457   assert(!TrackUntiedDefs && "unsupported mode");
458
459   // Check for the bottom of the analyzable region.
460   if (CurrPos == MBB->end()) {
461     closeRegion();
462     return false;
463   }
464   if (!isTopClosed())
465     closeTop();
466
467   SlotIndex SlotIdx;
468   if (RequireIntervals)
469     SlotIdx = getCurrSlot();
470
471   // Open the bottom of the region using slot indexes.
472   if (isBottomClosed()) {
473     if (RequireIntervals)
474       static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
475     else
476       static_cast<RegionPressure&>(P).openBottom(CurrPos);
477   }
478
479   RegisterOperands RegOpers(TRI, MRI);
480   collectOperands(CurrPos, RegOpers);
481
482   for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
483     unsigned Reg = RegOpers.Uses[i];
484     // Discover live-ins.
485     bool isLive = LiveRegs.contains(Reg);
486     if (!isLive)
487       discoverLiveIn(Reg);
488     // Kill liveness at last uses.
489     bool lastUse = false;
490     if (RequireIntervals) {
491       const LiveInterval *LI = getInterval(Reg);
492       lastUse = LI && LI->killedAt(SlotIdx);
493     }
494     else {
495       // Allocatable physregs are always single-use before register rewriting.
496       lastUse = !TargetRegisterInfo::isVirtualRegister(Reg);
497     }
498     if (lastUse && isLive) {
499       LiveRegs.erase(Reg);
500       decreaseRegPressure(Reg);
501     }
502     else if (!lastUse && !isLive)
503       increaseRegPressure(Reg);
504   }
505
506   // Generate liveness for defs.
507   for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
508     unsigned Reg = RegOpers.Defs[i];
509     if (LiveRegs.insert(Reg))
510       increaseRegPressure(Reg);
511   }
512
513   // Boost pressure for all dead defs together.
514   increaseRegPressure(RegOpers.DeadDefs);
515   decreaseRegPressure(RegOpers.DeadDefs);
516
517   // Find the next instruction.
518   do
519     ++CurrPos;
520   while (CurrPos != MBB->end() && CurrPos->isDebugValue());
521   return true;
522 }
523
524 /// Find the max change in excess pressure across all sets.
525 static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec,
526                                        ArrayRef<unsigned> NewPressureVec,
527                                        RegPressureDelta &Delta,
528                                        const RegisterClassInfo *RCI,
529                                        ArrayRef<unsigned> LiveThruPressureVec) {
530   int ExcessUnits = 0;
531   unsigned PSetID = ~0U;
532   for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) {
533     unsigned POld = OldPressureVec[i];
534     unsigned PNew = NewPressureVec[i];
535     int PDiff = (int)PNew - (int)POld;
536     if (!PDiff) // No change in this set in the common case.
537       continue;
538     // Only consider change beyond the limit.
539     unsigned Limit = RCI->getRegPressureSetLimit(i);
540     if (!LiveThruPressureVec.empty())
541       Limit += LiveThruPressureVec[i];
542
543     if (Limit > POld) {
544       if (Limit > PNew)
545         PDiff = 0;            // Under the limit
546       else
547         PDiff = PNew - Limit; // Just exceeded limit.
548     }
549     else if (Limit > PNew)
550       PDiff = Limit - POld;   // Just obeyed limit.
551
552     if (PDiff) {
553       ExcessUnits = PDiff;
554       PSetID = i;
555       break;
556     }
557   }
558   Delta.Excess.PSetID = PSetID;
559   Delta.Excess.UnitIncrease = ExcessUnits;
560 }
561
562 /// Find the max change in max pressure that either surpasses a critical PSet
563 /// limit or exceeds the current MaxPressureLimit.
564 ///
565 /// FIXME: comparing each element of the old and new MaxPressure vectors here is
566 /// silly. It's done now to demonstrate the concept but will go away with a
567 /// RegPressureTracker API change to work with pressure differences.
568 static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec,
569                                     ArrayRef<unsigned> NewMaxPressureVec,
570                                     ArrayRef<PressureElement> CriticalPSets,
571                                     ArrayRef<unsigned> MaxPressureLimit,
572                                     RegPressureDelta &Delta) {
573   Delta.CriticalMax = PressureElement();
574   Delta.CurrentMax = PressureElement();
575
576   unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
577   for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) {
578     unsigned POld = OldMaxPressureVec[i];
579     unsigned PNew = NewMaxPressureVec[i];
580     if (PNew == POld) // No change in this set in the common case.
581       continue;
582
583     if (!Delta.CriticalMax.isValid()) {
584       while (CritIdx != CritEnd && CriticalPSets[CritIdx].PSetID < i)
585         ++CritIdx;
586
587       if (CritIdx != CritEnd && CriticalPSets[CritIdx].PSetID == i) {
588         int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].UnitIncrease;
589         if (PDiff > 0) {
590           Delta.CriticalMax.PSetID = i;
591           Delta.CriticalMax.UnitIncrease = PDiff;
592         }
593       }
594     }
595     // Find the first increase above MaxPressureLimit.
596     // (Ignores negative MDiff).
597     if (!Delta.CurrentMax.isValid()) {
598       int MDiff = (int)PNew - (int)MaxPressureLimit[i];
599       if (MDiff > 0) {
600         Delta.CurrentMax.PSetID = i;
601         Delta.CurrentMax.UnitIncrease = MDiff;
602         if (CritIdx == CritEnd || Delta.CriticalMax.isValid())
603           break;
604       }
605     }
606   }
607 }
608
609 /// Record the upward impact of a single instruction on current register
610 /// pressure. Unlike the advance/recede pressure tracking interface, this does
611 /// not discover live in/outs.
612 ///
613 /// This is intended for speculative queries. It leaves pressure inconsistent
614 /// with the current position, so must be restored by the caller.
615 void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) {
616   assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
617
618   // Account for register pressure similar to RegPressureTracker::recede().
619   RegisterOperands RegOpers(TRI, MRI);
620   collectOperands(MI, RegOpers);
621
622   // Boost max pressure for all dead defs together.
623   // Since CurrSetPressure and MaxSetPressure
624   increaseRegPressure(RegOpers.DeadDefs);
625   decreaseRegPressure(RegOpers.DeadDefs);
626
627   // Kill liveness at live defs.
628   for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
629     unsigned Reg = RegOpers.Defs[i];
630     if (!containsReg(RegOpers.Uses, Reg))
631       decreaseRegPressure(Reg);
632   }
633   // Generate liveness for uses.
634   for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
635     unsigned Reg = RegOpers.Uses[i];
636     if (!LiveRegs.contains(Reg))
637       increaseRegPressure(Reg);
638   }
639 }
640
641 /// Consider the pressure increase caused by traversing this instruction
642 /// bottom-up. Find the pressure set with the most change beyond its pressure
643 /// limit based on the tracker's current pressure, and return the change in
644 /// number of register units of that pressure set introduced by this
645 /// instruction.
646 ///
647 /// This assumes that the current LiveOut set is sufficient.
648 ///
649 /// FIXME: This is expensive for an on-the-fly query. We need to cache the
650 /// result per-SUnit with enough information to adjust for the current
651 /// scheduling position. But this works as a proof of concept.
652 void RegPressureTracker::
653 getMaxUpwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
654                           ArrayRef<PressureElement> CriticalPSets,
655                           ArrayRef<unsigned> MaxPressureLimit) {
656   // Snapshot Pressure.
657   // FIXME: The snapshot heap space should persist. But I'm planning to
658   // summarize the pressure effect so we don't need to snapshot at all.
659   std::vector<unsigned> SavedPressure = CurrSetPressure;
660   std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
661
662   bumpUpwardPressure(MI);
663
664   computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
665                              LiveThruPressure);
666   computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
667                           MaxPressureLimit, Delta);
668   assert(Delta.CriticalMax.UnitIncrease >= 0 &&
669          Delta.CurrentMax.UnitIncrease >= 0 && "cannot decrease max pressure");
670
671   // Restore the tracker's state.
672   P.MaxSetPressure.swap(SavedMaxPressure);
673   CurrSetPressure.swap(SavedPressure);
674 }
675
676 /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
677 static bool findUseBetween(unsigned Reg,
678                            SlotIndex PriorUseIdx, SlotIndex NextUseIdx,
679                            const MachineRegisterInfo *MRI,
680                            const LiveIntervals *LIS) {
681   for (MachineRegisterInfo::use_nodbg_iterator
682          UI = MRI->use_nodbg_begin(Reg), UE = MRI->use_nodbg_end();
683          UI != UE; UI.skipInstruction()) {
684       const MachineInstr* MI = &*UI;
685       if (MI->isDebugValue())
686         continue;
687       SlotIndex InstSlot = LIS->getInstructionIndex(MI).getRegSlot();
688       if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx)
689         return true;
690   }
691   return false;
692 }
693
694 /// Record the downward impact of a single instruction on current register
695 /// pressure. Unlike the advance/recede pressure tracking interface, this does
696 /// not discover live in/outs.
697 ///
698 /// This is intended for speculative queries. It leaves pressure inconsistent
699 /// with the current position, so must be restored by the caller.
700 void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) {
701   assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
702
703   // Account for register pressure similar to RegPressureTracker::recede().
704   RegisterOperands RegOpers(TRI, MRI);
705   collectOperands(MI, RegOpers);
706
707   // Kill liveness at last uses. Assume allocatable physregs are single-use
708   // rather than checking LiveIntervals.
709   SlotIndex SlotIdx;
710   if (RequireIntervals)
711     SlotIdx = LIS->getInstructionIndex(MI).getRegSlot();
712
713   for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
714     unsigned Reg = RegOpers.Uses[i];
715     if (RequireIntervals) {
716       // FIXME: allow the caller to pass in the list of vreg uses that remain
717       // to be bottom-scheduled to avoid searching uses at each query.
718       SlotIndex CurrIdx = getCurrSlot();
719       const LiveInterval *LI = getInterval(Reg);
720       if (LI && LI->killedAt(SlotIdx)
721           && !findUseBetween(Reg, CurrIdx, SlotIdx, MRI, LIS)) {
722         decreaseRegPressure(Reg);
723       }
724     }
725     else if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
726       // Allocatable physregs are always single-use before register rewriting.
727       decreaseRegPressure(Reg);
728     }
729   }
730
731   // Generate liveness for defs.
732   increaseRegPressure(RegOpers.Defs);
733
734   // Boost pressure for all dead defs together.
735   increaseRegPressure(RegOpers.DeadDefs);
736   decreaseRegPressure(RegOpers.DeadDefs);
737 }
738
739 /// Consider the pressure increase caused by traversing this instruction
740 /// top-down. Find the register class with the most change in its pressure limit
741 /// based on the tracker's current pressure, and return the number of excess
742 /// register units of that pressure set introduced by this instruction.
743 ///
744 /// This assumes that the current LiveIn set is sufficient.
745 void RegPressureTracker::
746 getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
747                             ArrayRef<PressureElement> CriticalPSets,
748                             ArrayRef<unsigned> MaxPressureLimit) {
749   // Snapshot Pressure.
750   std::vector<unsigned> SavedPressure = CurrSetPressure;
751   std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
752
753   bumpDownwardPressure(MI);
754
755   computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
756                              LiveThruPressure);
757   computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
758                           MaxPressureLimit, Delta);
759   assert(Delta.CriticalMax.UnitIncrease >= 0 &&
760          Delta.CurrentMax.UnitIncrease >= 0 && "cannot decrease max pressure");
761
762   // Restore the tracker's state.
763   P.MaxSetPressure.swap(SavedMaxPressure);
764   CurrSetPressure.swap(SavedPressure);
765 }
766
767 /// Get the pressure of each PSet after traversing this instruction bottom-up.
768 void RegPressureTracker::
769 getUpwardPressure(const MachineInstr *MI,
770                   std::vector<unsigned> &PressureResult,
771                   std::vector<unsigned> &MaxPressureResult) {
772   // Snapshot pressure.
773   PressureResult = CurrSetPressure;
774   MaxPressureResult = P.MaxSetPressure;
775
776   bumpUpwardPressure(MI);
777
778   // Current pressure becomes the result. Restore current pressure.
779   P.MaxSetPressure.swap(MaxPressureResult);
780   CurrSetPressure.swap(PressureResult);
781 }
782
783 /// Get the pressure of each PSet after traversing this instruction top-down.
784 void RegPressureTracker::
785 getDownwardPressure(const MachineInstr *MI,
786                     std::vector<unsigned> &PressureResult,
787                     std::vector<unsigned> &MaxPressureResult) {
788   // Snapshot pressure.
789   PressureResult = CurrSetPressure;
790   MaxPressureResult = P.MaxSetPressure;
791
792   bumpDownwardPressure(MI);
793
794   // Current pressure becomes the result. Restore current pressure.
795   P.MaxSetPressure.swap(MaxPressureResult);
796   CurrSetPressure.swap(PressureResult);
797 }