Fix typo, make helper static.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGRRList.cpp
1 //===----- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler --===//
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 implements bottom-up and top-down register pressure reduction list
11 // schedulers, using standard algorithms.  The basic approach uses a priority
12 // queue of available nodes to schedule.  One at a time, nodes are taken from
13 // the priority queue (thus in priority order), checked for legality to
14 // schedule, and emitted if legal.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "pre-RA-sched"
19 #include "ScheduleDAGSDNodes.h"
20 #include "llvm/InlineAsm.h"
21 #include "llvm/CodeGen/SchedulerRegistry.h"
22 #include "llvm/CodeGen/SelectionDAGISel.h"
23 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <climits>
36 using namespace llvm;
37
38 STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
39 STATISTIC(NumUnfolds,    "Number of nodes unfolded");
40 STATISTIC(NumDups,       "Number of duplicated nodes");
41 STATISTIC(NumPRCopies,   "Number of physical register copies");
42
43 static RegisterScheduler
44   burrListDAGScheduler("list-burr",
45                        "Bottom-up register reduction list scheduling",
46                        createBURRListDAGScheduler);
47 static RegisterScheduler
48   tdrListrDAGScheduler("list-tdrr",
49                        "Top-down register reduction list scheduling",
50                        createTDRRListDAGScheduler);
51 static RegisterScheduler
52   sourceListDAGScheduler("source",
53                          "Similar to list-burr but schedules in source "
54                          "order when possible",
55                          createSourceListDAGScheduler);
56
57 static RegisterScheduler
58   hybridListDAGScheduler("list-hybrid",
59                          "Bottom-up register pressure aware list scheduling "
60                          "which tries to balance latency and register pressure",
61                          createHybridListDAGScheduler);
62
63 static RegisterScheduler
64   ILPListDAGScheduler("list-ilp",
65                       "Bottom-up register pressure aware list scheduling "
66                       "which tries to balance ILP and register pressure",
67                       createILPListDAGScheduler);
68
69 static cl::opt<bool> DisableSchedCycles(
70   "disable-sched-cycles", cl::Hidden, cl::init(false),
71   cl::desc("Disable cycle-level precision during preRA scheduling"));
72
73 // Temporary sched=list-ilp flags until the heuristics are robust.
74 static cl::opt<bool> DisableSchedRegPressure(
75   "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
76   cl::desc("Disable regpressure priority in sched=list-ilp"));
77 static cl::opt<bool> DisableSchedLiveUses(
78   "disable-sched-live-uses", cl::Hidden, cl::init(true),
79   cl::desc("Disable live use priority in sched=list-ilp"));
80 static cl::opt<bool> DisableSchedStalls(
81   "disable-sched-stalls", cl::Hidden, cl::init(true),
82   cl::desc("Disable no-stall priority in sched=list-ilp"));
83 static cl::opt<bool> DisableSchedCriticalPath(
84   "disable-sched-critical-path", cl::Hidden, cl::init(false),
85   cl::desc("Disable critical path priority in sched=list-ilp"));
86 static cl::opt<bool> DisableSchedHeight(
87   "disable-sched-height", cl::Hidden, cl::init(false),
88   cl::desc("Disable scheduled-height priority in sched=list-ilp"));
89
90 static cl::opt<int> MaxReorderWindow(
91   "max-sched-reorder", cl::Hidden, cl::init(6),
92   cl::desc("Number of instructions to allow ahead of the critical path "
93            "in sched=list-ilp"));
94
95 static cl::opt<unsigned> AvgIPC(
96   "sched-avg-ipc", cl::Hidden, cl::init(1),
97   cl::desc("Average inst/cycle whan no target itinerary exists."));
98
99 #ifndef NDEBUG
100 namespace {
101   // For sched=list-ilp, Count the number of times each factor comes into play.
102   enum { FactPressureDiff, FactRegUses, FactHeight, FactDepth, FactStatic,
103          FactOther, NumFactors };
104 }
105 static const char *FactorName[NumFactors] =
106 {"PressureDiff", "RegUses", "Height", "Depth","Static", "Other"};
107 static int FactorCount[NumFactors];
108 #endif //!NDEBUG
109
110 namespace {
111 //===----------------------------------------------------------------------===//
112 /// ScheduleDAGRRList - The actual register reduction list scheduler
113 /// implementation.  This supports both top-down and bottom-up scheduling.
114 ///
115 class ScheduleDAGRRList : public ScheduleDAGSDNodes {
116 private:
117   /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
118   /// it is top-down.
119   bool isBottomUp;
120
121   /// NeedLatency - True if the scheduler will make use of latency information.
122   ///
123   bool NeedLatency;
124
125   /// AvailableQueue - The priority queue to use for the available SUnits.
126   SchedulingPriorityQueue *AvailableQueue;
127
128   /// PendingQueue - This contains all of the instructions whose operands have
129   /// been issued, but their results are not ready yet (due to the latency of
130   /// the operation).  Once the operands becomes available, the instruction is
131   /// added to the AvailableQueue.
132   std::vector<SUnit*> PendingQueue;
133
134   /// HazardRec - The hazard recognizer to use.
135   ScheduleHazardRecognizer *HazardRec;
136
137   /// CurCycle - The current scheduler state corresponds to this cycle.
138   unsigned CurCycle;
139
140   /// MinAvailableCycle - Cycle of the soonest available instruction.
141   unsigned MinAvailableCycle;
142
143   /// IssueCount - Count instructions issued in this cycle
144   /// Currently valid only for bottom-up scheduling.
145   unsigned IssueCount;
146
147   /// LiveRegDefs - A set of physical registers and their definition
148   /// that are "live". These nodes must be scheduled before any other nodes that
149   /// modifies the registers can be scheduled.
150   unsigned NumLiveRegs;
151   std::vector<SUnit*> LiveRegDefs;
152   std::vector<SUnit*> LiveRegGens;
153
154   /// Topo - A topological ordering for SUnits which permits fast IsReachable
155   /// and similar queries.
156   ScheduleDAGTopologicalSort Topo;
157
158 public:
159   ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
160                     SchedulingPriorityQueue *availqueue,
161                     CodeGenOpt::Level OptLevel)
162     : ScheduleDAGSDNodes(mf), isBottomUp(availqueue->isBottomUp()),
163       NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
164       Topo(SUnits) {
165
166     const TargetMachine &tm = mf.getTarget();
167     if (DisableSchedCycles || !NeedLatency)
168       HazardRec = new ScheduleHazardRecognizer();
169     else
170       HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
171   }
172
173   ~ScheduleDAGRRList() {
174     delete HazardRec;
175     delete AvailableQueue;
176   }
177
178   void Schedule();
179
180   ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
181
182   /// IsReachable - Checks if SU is reachable from TargetSU.
183   bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
184     return Topo.IsReachable(SU, TargetSU);
185   }
186
187   /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
188   /// create a cycle.
189   bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
190     return Topo.WillCreateCycle(SU, TargetSU);
191   }
192
193   /// AddPred - adds a predecessor edge to SUnit SU.
194   /// This returns true if this is a new predecessor.
195   /// Updates the topological ordering if required.
196   void AddPred(SUnit *SU, const SDep &D) {
197     Topo.AddPred(SU, D.getSUnit());
198     SU->addPred(D);
199   }
200
201   /// RemovePred - removes a predecessor edge from SUnit SU.
202   /// This returns true if an edge was removed.
203   /// Updates the topological ordering if required.
204   void RemovePred(SUnit *SU, const SDep &D) {
205     Topo.RemovePred(SU, D.getSUnit());
206     SU->removePred(D);
207   }
208
209 private:
210   bool isReady(SUnit *SU) {
211     return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
212       AvailableQueue->isReady(SU);
213   }
214
215   void ReleasePred(SUnit *SU, const SDep *PredEdge);
216   void ReleasePredecessors(SUnit *SU);
217   void ReleaseSucc(SUnit *SU, const SDep *SuccEdge);
218   void ReleaseSuccessors(SUnit *SU);
219   void ReleasePending();
220   void AdvanceToCycle(unsigned NextCycle);
221   void AdvancePastStalls(SUnit *SU);
222   void EmitNode(SUnit *SU);
223   void ScheduleNodeBottomUp(SUnit*);
224   void CapturePred(SDep *PredEdge);
225   void UnscheduleNodeBottomUp(SUnit*);
226   void RestoreHazardCheckerBottomUp();
227   void BacktrackBottomUp(SUnit*, SUnit*);
228   SUnit *CopyAndMoveSuccessors(SUnit*);
229   void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
230                                 const TargetRegisterClass*,
231                                 const TargetRegisterClass*,
232                                 SmallVector<SUnit*, 2>&);
233   bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
234
235   SUnit *PickNodeToScheduleBottomUp();
236   void ListScheduleBottomUp();
237
238   void ScheduleNodeTopDown(SUnit*);
239   void ListScheduleTopDown();
240
241
242   /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
243   /// Updates the topological ordering if required.
244   SUnit *CreateNewSUnit(SDNode *N) {
245     unsigned NumSUnits = SUnits.size();
246     SUnit *NewNode = NewSUnit(N);
247     // Update the topological ordering.
248     if (NewNode->NodeNum >= NumSUnits)
249       Topo.InitDAGTopologicalSorting();
250     return NewNode;
251   }
252
253   /// CreateClone - Creates a new SUnit from an existing one.
254   /// Updates the topological ordering if required.
255   SUnit *CreateClone(SUnit *N) {
256     unsigned NumSUnits = SUnits.size();
257     SUnit *NewNode = Clone(N);
258     // Update the topological ordering.
259     if (NewNode->NodeNum >= NumSUnits)
260       Topo.InitDAGTopologicalSorting();
261     return NewNode;
262   }
263
264   /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
265   /// need actual latency information but the hybrid scheduler does.
266   bool ForceUnitLatencies() const {
267     return !NeedLatency;
268   }
269 };
270 }  // end anonymous namespace
271
272
273 /// Schedule - Schedule the DAG using list scheduling.
274 void ScheduleDAGRRList::Schedule() {
275   DEBUG(dbgs()
276         << "********** List Scheduling BB#" << BB->getNumber()
277         << " '" << BB->getName() << "' **********\n");
278 #ifndef NDEBUG
279   for (int i = 0; i < NumFactors; ++i) {
280     FactorCount[i] = 0;
281   }
282 #endif //!NDEBUG
283
284   CurCycle = 0;
285   IssueCount = 0;
286   MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
287   NumLiveRegs = 0;
288   LiveRegDefs.resize(TRI->getNumRegs(), NULL);
289   LiveRegGens.resize(TRI->getNumRegs(), NULL);
290
291   // Build the scheduling graph.
292   BuildSchedGraph(NULL);
293
294   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
295           SUnits[su].dumpAll(this));
296   Topo.InitDAGTopologicalSorting();
297
298   AvailableQueue->initNodes(SUnits);
299
300   HazardRec->Reset();
301
302   // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
303   if (isBottomUp)
304     ListScheduleBottomUp();
305   else
306     ListScheduleTopDown();
307
308 #ifndef NDEBUG
309   for (int i = 0; i < NumFactors; ++i) {
310     DEBUG(dbgs() << FactorName[i] << "\t" << FactorCount[i] << "\n");
311   }
312 #endif // !NDEBUG
313   AvailableQueue->releaseState();
314 }
315
316 //===----------------------------------------------------------------------===//
317 //  Bottom-Up Scheduling
318 //===----------------------------------------------------------------------===//
319
320 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
321 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
322 void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
323   SUnit *PredSU = PredEdge->getSUnit();
324
325 #ifndef NDEBUG
326   if (PredSU->NumSuccsLeft == 0) {
327     dbgs() << "*** Scheduling failed! ***\n";
328     PredSU->dump(this);
329     dbgs() << " has been released too many times!\n";
330     llvm_unreachable(0);
331   }
332 #endif
333   --PredSU->NumSuccsLeft;
334
335   if (!ForceUnitLatencies()) {
336     // Updating predecessor's height. This is now the cycle when the
337     // predecessor can be scheduled without causing a pipeline stall.
338     PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
339   }
340
341   // If all the node's successors are scheduled, this node is ready
342   // to be scheduled. Ignore the special EntrySU node.
343   if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
344     PredSU->isAvailable = true;
345
346     unsigned Height = PredSU->getHeight();
347     if (Height < MinAvailableCycle)
348       MinAvailableCycle = Height;
349
350     if (isReady(PredSU)) {
351       AvailableQueue->push(PredSU);
352     }
353     // CapturePred and others may have left the node in the pending queue, avoid
354     // adding it twice.
355     else if (!PredSU->isPending) {
356       PredSU->isPending = true;
357       PendingQueue.push_back(PredSU);
358     }
359   }
360 }
361
362 /// Call ReleasePred for each predecessor, then update register live def/gen.
363 /// Always update LiveRegDefs for a register dependence even if the current SU
364 /// also defines the register. This effectively create one large live range
365 /// across a sequence of two-address node. This is important because the
366 /// entire chain must be scheduled together. Example:
367 ///
368 /// flags = (3) add
369 /// flags = (2) addc flags
370 /// flags = (1) addc flags
371 ///
372 /// results in
373 ///
374 /// LiveRegDefs[flags] = 3
375 /// LiveRegGens[flags] = 1
376 ///
377 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
378 /// interference on flags.
379 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
380   // Bottom up: release predecessors
381   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
382        I != E; ++I) {
383     ReleasePred(SU, &*I);
384     if (I->isAssignedRegDep()) {
385       // This is a physical register dependency and it's impossible or
386       // expensive to copy the register. Make sure nothing that can
387       // clobber the register is scheduled between the predecessor and
388       // this node.
389       SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
390       assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
391              "interference on register dependence");
392       LiveRegDefs[I->getReg()] = I->getSUnit();
393       if (!LiveRegGens[I->getReg()]) {
394         ++NumLiveRegs;
395         LiveRegGens[I->getReg()] = SU;
396       }
397     }
398   }
399 }
400
401 /// Check to see if any of the pending instructions are ready to issue.  If
402 /// so, add them to the available queue.
403 void ScheduleDAGRRList::ReleasePending() {
404   if (DisableSchedCycles) {
405     assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
406     return;
407   }
408
409   // If the available queue is empty, it is safe to reset MinAvailableCycle.
410   if (AvailableQueue->empty())
411     MinAvailableCycle = UINT_MAX;
412
413   // Check to see if any of the pending instructions are ready to issue.  If
414   // so, add them to the available queue.
415   for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
416     unsigned ReadyCycle =
417       isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDepth();
418     if (ReadyCycle < MinAvailableCycle)
419       MinAvailableCycle = ReadyCycle;
420
421     if (PendingQueue[i]->isAvailable) {
422       if (!isReady(PendingQueue[i]))
423           continue;
424       AvailableQueue->push(PendingQueue[i]);
425     }
426     PendingQueue[i]->isPending = false;
427     PendingQueue[i] = PendingQueue.back();
428     PendingQueue.pop_back();
429     --i; --e;
430   }
431 }
432
433 /// Move the scheduler state forward by the specified number of Cycles.
434 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
435   if (NextCycle <= CurCycle)
436     return;
437
438   IssueCount = 0;
439   AvailableQueue->setCurCycle(NextCycle);
440   if (!HazardRec->isEnabled()) {
441     // Bypass lots of virtual calls in case of long latency.
442     CurCycle = NextCycle;
443   }
444   else {
445     for (; CurCycle != NextCycle; ++CurCycle) {
446       if (isBottomUp)
447         HazardRec->RecedeCycle();
448       else
449         HazardRec->AdvanceCycle();
450     }
451   }
452   // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
453   // available Q to release pending nodes at least once before popping.
454   ReleasePending();
455 }
456
457 /// Move the scheduler state forward until the specified node's dependents are
458 /// ready and can be scheduled with no resource conflicts.
459 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
460   if (DisableSchedCycles)
461     return;
462
463   unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
464
465   // Bump CurCycle to account for latency. We assume the latency of other
466   // available instructions may be hidden by the stall (not a full pipe stall).
467   // This updates the hazard recognizer's cycle before reserving resources for
468   // this instruction.
469   AdvanceToCycle(ReadyCycle);
470
471   // Calls are scheduled in their preceding cycle, so don't conflict with
472   // hazards from instructions after the call. EmitNode will reset the
473   // scoreboard state before emitting the call.
474   if (isBottomUp && SU->isCall)
475     return;
476
477   // FIXME: For resource conflicts in very long non-pipelined stages, we
478   // should probably skip ahead here to avoid useless scoreboard checks.
479   int Stalls = 0;
480   while (true) {
481     ScheduleHazardRecognizer::HazardType HT =
482       HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
483
484     if (HT == ScheduleHazardRecognizer::NoHazard)
485       break;
486
487     ++Stalls;
488   }
489   AdvanceToCycle(CurCycle + Stalls);
490 }
491
492 /// Record this SUnit in the HazardRecognizer.
493 /// Does not update CurCycle.
494 void ScheduleDAGRRList::EmitNode(SUnit *SU) {
495   if (!HazardRec->isEnabled())
496     return;
497
498   // Check for phys reg copy.
499   if (!SU->getNode())
500     return;
501
502   switch (SU->getNode()->getOpcode()) {
503   default:
504     assert(SU->getNode()->isMachineOpcode() &&
505            "This target-independent node should not be scheduled.");
506     break;
507   case ISD::MERGE_VALUES:
508   case ISD::TokenFactor:
509   case ISD::CopyToReg:
510   case ISD::CopyFromReg:
511   case ISD::EH_LABEL:
512     // Noops don't affect the scoreboard state. Copies are likely to be
513     // removed.
514     return;
515   case ISD::INLINEASM:
516     // For inline asm, clear the pipeline state.
517     HazardRec->Reset();
518     return;
519   }
520   if (isBottomUp && SU->isCall) {
521     // Calls are scheduled with their preceding instructions. For bottom-up
522     // scheduling, clear the pipeline state before emitting.
523     HazardRec->Reset();
524   }
525
526   HazardRec->EmitInstruction(SU);
527
528   if (!isBottomUp && SU->isCall) {
529     HazardRec->Reset();
530   }
531 }
532
533 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
534 /// count of its predecessors. If a predecessor pending count is zero, add it to
535 /// the Available queue.
536 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
537   DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
538   DEBUG(SU->dump(this));
539
540 #ifndef NDEBUG
541   if (CurCycle < SU->getHeight())
542     DEBUG(dbgs() << "   Height [" << SU->getHeight() << "] pipeline stall!\n");
543 #endif
544
545   // FIXME: Do not modify node height. It may interfere with
546   // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
547   // node it's ready cycle can aid heuristics, and after scheduling it can
548   // indicate the scheduled cycle.
549   SU->setHeightToAtLeast(CurCycle);
550
551   // Reserve resources for the scheduled intruction.
552   EmitNode(SU);
553
554   Sequence.push_back(SU);
555
556   AvailableQueue->ScheduledNode(SU);
557
558   // If HazardRec is disabled, and each inst counts as one cycle, then
559   // advance CurCycle before ReleasePredecessors to avoid useles pushed to
560   // PendingQueue for schedulers that implement HasReadyFilter.
561   if (!HazardRec->isEnabled() && AvgIPC < 2)
562     AdvanceToCycle(CurCycle + 1);
563
564   // Update liveness of predecessors before successors to avoid treating a
565   // two-address node as a live range def.
566   ReleasePredecessors(SU);
567
568   // Release all the implicit physical register defs that are live.
569   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
570        I != E; ++I) {
571     // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
572     if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
573       assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
574       --NumLiveRegs;
575       LiveRegDefs[I->getReg()] = NULL;
576       LiveRegGens[I->getReg()] = NULL;
577     }
578   }
579
580   SU->isScheduled = true;
581
582   // Conditions under which the scheduler should eagerly advance the cycle:
583   // (1) No available instructions
584   // (2) All pipelines full, so available instructions must have hazards.
585   //
586   // If HazardRec is disabled, the cycle was advanced earlier.
587   //
588   // Check AvailableQueue after ReleasePredecessors in case of zero latency.
589   ++IssueCount;
590   if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
591       || (!HazardRec->isEnabled() && AvgIPC > 1 && IssueCount == AvgIPC)
592       || AvailableQueue->empty())
593     AdvanceToCycle(CurCycle + 1);
594 }
595
596 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
597 /// unscheduled, incrcease the succ left count of its predecessors. Remove
598 /// them from AvailableQueue if necessary.
599 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
600   SUnit *PredSU = PredEdge->getSUnit();
601   if (PredSU->isAvailable) {
602     PredSU->isAvailable = false;
603     if (!PredSU->isPending)
604       AvailableQueue->remove(PredSU);
605   }
606
607   assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
608   ++PredSU->NumSuccsLeft;
609 }
610
611 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
612 /// its predecessor states to reflect the change.
613 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
614   DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
615   DEBUG(SU->dump(this));
616
617   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
618        I != E; ++I) {
619     CapturePred(&*I);
620     if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
621       assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
622       assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
623              "Physical register dependency violated?");
624       --NumLiveRegs;
625       LiveRegDefs[I->getReg()] = NULL;
626       LiveRegGens[I->getReg()] = NULL;
627     }
628   }
629
630   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
631        I != E; ++I) {
632     if (I->isAssignedRegDep()) {
633       // This becomes the nearest def. Note that an earlier def may still be
634       // pending if this is a two-address node.
635       LiveRegDefs[I->getReg()] = SU;
636       if (!LiveRegDefs[I->getReg()]) {
637         ++NumLiveRegs;
638       }
639       if (LiveRegGens[I->getReg()] == NULL ||
640           I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
641         LiveRegGens[I->getReg()] = I->getSUnit();
642     }
643   }
644   if (SU->getHeight() < MinAvailableCycle)
645     MinAvailableCycle = SU->getHeight();
646
647   SU->setHeightDirty();
648   SU->isScheduled = false;
649   SU->isAvailable = true;
650   if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
651     // Don't make available until backtracking is complete.
652     SU->isPending = true;
653     PendingQueue.push_back(SU);
654   }
655   else {
656     AvailableQueue->push(SU);
657   }
658   AvailableQueue->UnscheduledNode(SU);
659 }
660
661 /// After backtracking, the hazard checker needs to be restored to a state
662 /// corresponding the the current cycle.
663 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
664   HazardRec->Reset();
665
666   unsigned LookAhead = std::min((unsigned)Sequence.size(),
667                                 HazardRec->getMaxLookAhead());
668   if (LookAhead == 0)
669     return;
670
671   std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
672   unsigned HazardCycle = (*I)->getHeight();
673   for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
674     SUnit *SU = *I;
675     for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
676       HazardRec->RecedeCycle();
677     }
678     EmitNode(SU);
679   }
680 }
681
682 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
683 /// BTCycle in order to schedule a specific node.
684 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
685   SUnit *OldSU = Sequence.back();
686   while (true) {
687     Sequence.pop_back();
688     if (SU->isSucc(OldSU))
689       // Don't try to remove SU from AvailableQueue.
690       SU->isAvailable = false;
691     // FIXME: use ready cycle instead of height
692     CurCycle = OldSU->getHeight();
693     UnscheduleNodeBottomUp(OldSU);
694     AvailableQueue->setCurCycle(CurCycle);
695     if (OldSU == BtSU)
696       break;
697     OldSU = Sequence.back();
698   }
699
700   assert(!SU->isSucc(OldSU) && "Something is wrong!");
701
702   RestoreHazardCheckerBottomUp();
703
704   ReleasePending();
705
706   ++NumBacktracks;
707 }
708
709 static bool isOperandOf(const SUnit *SU, SDNode *N) {
710   for (const SDNode *SUNode = SU->getNode(); SUNode;
711        SUNode = SUNode->getGluedNode()) {
712     if (SUNode->isOperandOf(N))
713       return true;
714   }
715   return false;
716 }
717
718 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
719 /// successors to the newly created node.
720 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
721   SDNode *N = SU->getNode();
722   if (!N)
723     return NULL;
724
725   if (SU->getNode()->getGluedNode())
726     return NULL;
727
728   SUnit *NewSU;
729   bool TryUnfold = false;
730   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
731     EVT VT = N->getValueType(i);
732     if (VT == MVT::Glue)
733       return NULL;
734     else if (VT == MVT::Other)
735       TryUnfold = true;
736   }
737   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
738     const SDValue &Op = N->getOperand(i);
739     EVT VT = Op.getNode()->getValueType(Op.getResNo());
740     if (VT == MVT::Glue)
741       return NULL;
742   }
743
744   if (TryUnfold) {
745     SmallVector<SDNode*, 2> NewNodes;
746     if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
747       return NULL;
748
749     DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
750     assert(NewNodes.size() == 2 && "Expected a load folding node!");
751
752     N = NewNodes[1];
753     SDNode *LoadNode = NewNodes[0];
754     unsigned NumVals = N->getNumValues();
755     unsigned OldNumVals = SU->getNode()->getNumValues();
756     for (unsigned i = 0; i != NumVals; ++i)
757       DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
758     DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
759                                    SDValue(LoadNode, 1));
760
761     // LoadNode may already exist. This can happen when there is another
762     // load from the same location and producing the same type of value
763     // but it has different alignment or volatileness.
764     bool isNewLoad = true;
765     SUnit *LoadSU;
766     if (LoadNode->getNodeId() != -1) {
767       LoadSU = &SUnits[LoadNode->getNodeId()];
768       isNewLoad = false;
769     } else {
770       LoadSU = CreateNewSUnit(LoadNode);
771       LoadNode->setNodeId(LoadSU->NodeNum);
772
773       InitNumRegDefsLeft(LoadSU);
774       ComputeLatency(LoadSU);
775     }
776
777     SUnit *NewSU = CreateNewSUnit(N);
778     assert(N->getNodeId() == -1 && "Node already inserted!");
779     N->setNodeId(NewSU->NodeNum);
780
781     const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
782     for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
783       if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
784         NewSU->isTwoAddress = true;
785         break;
786       }
787     }
788     if (TID.isCommutable())
789       NewSU->isCommutable = true;
790
791     InitNumRegDefsLeft(NewSU);
792     ComputeLatency(NewSU);
793
794     // Record all the edges to and from the old SU, by category.
795     SmallVector<SDep, 4> ChainPreds;
796     SmallVector<SDep, 4> ChainSuccs;
797     SmallVector<SDep, 4> LoadPreds;
798     SmallVector<SDep, 4> NodePreds;
799     SmallVector<SDep, 4> NodeSuccs;
800     for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
801          I != E; ++I) {
802       if (I->isCtrl())
803         ChainPreds.push_back(*I);
804       else if (isOperandOf(I->getSUnit(), LoadNode))
805         LoadPreds.push_back(*I);
806       else
807         NodePreds.push_back(*I);
808     }
809     for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
810          I != E; ++I) {
811       if (I->isCtrl())
812         ChainSuccs.push_back(*I);
813       else
814         NodeSuccs.push_back(*I);
815     }
816
817     // Now assign edges to the newly-created nodes.
818     for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
819       const SDep &Pred = ChainPreds[i];
820       RemovePred(SU, Pred);
821       if (isNewLoad)
822         AddPred(LoadSU, Pred);
823     }
824     for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
825       const SDep &Pred = LoadPreds[i];
826       RemovePred(SU, Pred);
827       if (isNewLoad)
828         AddPred(LoadSU, Pred);
829     }
830     for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
831       const SDep &Pred = NodePreds[i];
832       RemovePred(SU, Pred);
833       AddPred(NewSU, Pred);
834     }
835     for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
836       SDep D = NodeSuccs[i];
837       SUnit *SuccDep = D.getSUnit();
838       D.setSUnit(SU);
839       RemovePred(SuccDep, D);
840       D.setSUnit(NewSU);
841       AddPred(SuccDep, D);
842       // Balance register pressure.
843       if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
844           && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
845         --NewSU->NumRegDefsLeft;
846     }
847     for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
848       SDep D = ChainSuccs[i];
849       SUnit *SuccDep = D.getSUnit();
850       D.setSUnit(SU);
851       RemovePred(SuccDep, D);
852       if (isNewLoad) {
853         D.setSUnit(LoadSU);
854         AddPred(SuccDep, D);
855       }
856     }
857
858     // Add a data dependency to reflect that NewSU reads the value defined
859     // by LoadSU.
860     AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
861
862     if (isNewLoad)
863       AvailableQueue->addNode(LoadSU);
864     AvailableQueue->addNode(NewSU);
865
866     ++NumUnfolds;
867
868     if (NewSU->NumSuccsLeft == 0) {
869       NewSU->isAvailable = true;
870       return NewSU;
871     }
872     SU = NewSU;
873   }
874
875   DEBUG(dbgs() << "    Duplicating SU #" << SU->NodeNum << "\n");
876   NewSU = CreateClone(SU);
877
878   // New SUnit has the exact same predecessors.
879   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
880        I != E; ++I)
881     if (!I->isArtificial())
882       AddPred(NewSU, *I);
883
884   // Only copy scheduled successors. Cut them from old node's successor
885   // list and move them over.
886   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
887   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
888        I != E; ++I) {
889     if (I->isArtificial())
890       continue;
891     SUnit *SuccSU = I->getSUnit();
892     if (SuccSU->isScheduled) {
893       SDep D = *I;
894       D.setSUnit(NewSU);
895       AddPred(SuccSU, D);
896       D.setSUnit(SU);
897       DelDeps.push_back(std::make_pair(SuccSU, D));
898     }
899   }
900   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
901     RemovePred(DelDeps[i].first, DelDeps[i].second);
902
903   AvailableQueue->updateNode(SU);
904   AvailableQueue->addNode(NewSU);
905
906   ++NumDups;
907   return NewSU;
908 }
909
910 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
911 /// scheduled successors of the given SUnit to the last copy.
912 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
913                                                const TargetRegisterClass *DestRC,
914                                                const TargetRegisterClass *SrcRC,
915                                                SmallVector<SUnit*, 2> &Copies) {
916   SUnit *CopyFromSU = CreateNewSUnit(NULL);
917   CopyFromSU->CopySrcRC = SrcRC;
918   CopyFromSU->CopyDstRC = DestRC;
919
920   SUnit *CopyToSU = CreateNewSUnit(NULL);
921   CopyToSU->CopySrcRC = DestRC;
922   CopyToSU->CopyDstRC = SrcRC;
923
924   // Only copy scheduled successors. Cut them from old node's successor
925   // list and move them over.
926   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
927   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
928        I != E; ++I) {
929     if (I->isArtificial())
930       continue;
931     SUnit *SuccSU = I->getSUnit();
932     if (SuccSU->isScheduled) {
933       SDep D = *I;
934       D.setSUnit(CopyToSU);
935       AddPred(SuccSU, D);
936       DelDeps.push_back(std::make_pair(SuccSU, *I));
937     }
938   }
939   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
940     RemovePred(DelDeps[i].first, DelDeps[i].second);
941
942   AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
943   AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
944
945   AvailableQueue->updateNode(SU);
946   AvailableQueue->addNode(CopyFromSU);
947   AvailableQueue->addNode(CopyToSU);
948   Copies.push_back(CopyFromSU);
949   Copies.push_back(CopyToSU);
950
951   ++NumPRCopies;
952 }
953
954 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
955 /// definition of the specified node.
956 /// FIXME: Move to SelectionDAG?
957 static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
958                                  const TargetInstrInfo *TII) {
959   const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
960   assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
961   unsigned NumRes = TID.getNumDefs();
962   for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
963     if (Reg == *ImpDef)
964       break;
965     ++NumRes;
966   }
967   return N->getValueType(NumRes);
968 }
969
970 /// CheckForLiveRegDef - Return true and update live register vector if the
971 /// specified register def of the specified SUnit clobbers any "live" registers.
972 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
973                                std::vector<SUnit*> &LiveRegDefs,
974                                SmallSet<unsigned, 4> &RegAdded,
975                                SmallVector<unsigned, 4> &LRegs,
976                                const TargetRegisterInfo *TRI) {
977   for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
978
979     // Check if Ref is live.
980     if (!LiveRegDefs[Reg]) continue;
981
982     // Allow multiple uses of the same def.
983     if (LiveRegDefs[Reg] == SU) continue;
984
985     // Add Reg to the set of interfering live regs.
986     if (RegAdded.insert(Reg))
987       LRegs.push_back(Reg);
988   }
989 }
990
991 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
992 /// scheduling of the given node to satisfy live physical register dependencies.
993 /// If the specific node is the last one that's available to schedule, do
994 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
995 bool ScheduleDAGRRList::
996 DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
997   if (NumLiveRegs == 0)
998     return false;
999
1000   SmallSet<unsigned, 4> RegAdded;
1001   // If this node would clobber any "live" register, then it's not ready.
1002   //
1003   // If SU is the currently live definition of the same register that it uses,
1004   // then we are free to schedule it.
1005   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1006        I != E; ++I) {
1007     if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
1008       CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
1009                          RegAdded, LRegs, TRI);
1010   }
1011
1012   for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
1013     if (Node->getOpcode() == ISD::INLINEASM) {
1014       // Inline asm can clobber physical defs.
1015       unsigned NumOps = Node->getNumOperands();
1016       if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
1017         --NumOps;  // Ignore the glue operand.
1018
1019       for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
1020         unsigned Flags =
1021           cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
1022         unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
1023
1024         ++i; // Skip the ID value.
1025         if (InlineAsm::isRegDefKind(Flags) ||
1026             InlineAsm::isRegDefEarlyClobberKind(Flags)) {
1027           // Check for def of register or earlyclobber register.
1028           for (; NumVals; --NumVals, ++i) {
1029             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1030             if (TargetRegisterInfo::isPhysicalRegister(Reg))
1031               CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1032           }
1033         } else
1034           i += NumVals;
1035       }
1036       continue;
1037     }
1038
1039     if (!Node->isMachineOpcode())
1040       continue;
1041     const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
1042     if (!TID.ImplicitDefs)
1043       continue;
1044     for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
1045       CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1046   }
1047
1048   return !LRegs.empty();
1049 }
1050
1051 /// Return a node that can be scheduled in this cycle. Requirements:
1052 /// (1) Ready: latency has been satisfied
1053 /// (2) No Hazards: resources are available
1054 /// (3) No Interferences: may unschedule to break register interferences.
1055 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1056   SmallVector<SUnit*, 4> Interferences;
1057   DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1058
1059   SUnit *CurSU = AvailableQueue->pop();
1060   while (CurSU) {
1061     SmallVector<unsigned, 4> LRegs;
1062     if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1063       break;
1064     LRegsMap.insert(std::make_pair(CurSU, LRegs));
1065
1066     CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
1067     Interferences.push_back(CurSU);
1068     CurSU = AvailableQueue->pop();
1069   }
1070   if (CurSU) {
1071     // Add the nodes that aren't ready back onto the available list.
1072     for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1073       Interferences[i]->isPending = false;
1074       assert(Interferences[i]->isAvailable && "must still be available");
1075       AvailableQueue->push(Interferences[i]);
1076     }
1077     return CurSU;
1078   }
1079
1080   // All candidates are delayed due to live physical reg dependencies.
1081   // Try backtracking, code duplication, or inserting cross class copies
1082   // to resolve it.
1083   for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1084     SUnit *TrySU = Interferences[i];
1085     SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1086
1087     // Try unscheduling up to the point where it's safe to schedule
1088     // this node.
1089     SUnit *BtSU = NULL;
1090     unsigned LiveCycle = UINT_MAX;
1091     for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1092       unsigned Reg = LRegs[j];
1093       if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1094         BtSU = LiveRegGens[Reg];
1095         LiveCycle = BtSU->getHeight();
1096       }
1097     }
1098     if (!WillCreateCycle(TrySU, BtSU))  {
1099       BacktrackBottomUp(TrySU, BtSU);
1100
1101       // Force the current node to be scheduled before the node that
1102       // requires the physical reg dep.
1103       if (BtSU->isAvailable) {
1104         BtSU->isAvailable = false;
1105         if (!BtSU->isPending)
1106           AvailableQueue->remove(BtSU);
1107       }
1108       AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
1109                           /*Reg=*/0, /*isNormalMemory=*/false,
1110                           /*isMustAlias=*/false, /*isArtificial=*/true));
1111
1112       // If one or more successors has been unscheduled, then the current
1113       // node is no longer avaialable. Schedule a successor that's now
1114       // available instead.
1115       if (!TrySU->isAvailable) {
1116         CurSU = AvailableQueue->pop();
1117       }
1118       else {
1119         CurSU = TrySU;
1120         TrySU->isPending = false;
1121         Interferences.erase(Interferences.begin()+i);
1122       }
1123       break;
1124     }
1125   }
1126
1127   if (!CurSU) {
1128     // Can't backtrack. If it's too expensive to copy the value, then try
1129     // duplicate the nodes that produces these "too expensive to copy"
1130     // values to break the dependency. In case even that doesn't work,
1131     // insert cross class copies.
1132     // If it's not too expensive, i.e. cost != -1, issue copies.
1133     SUnit *TrySU = Interferences[0];
1134     SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1135     assert(LRegs.size() == 1 && "Can't handle this yet!");
1136     unsigned Reg = LRegs[0];
1137     SUnit *LRDef = LiveRegDefs[Reg];
1138     EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1139     const TargetRegisterClass *RC =
1140       TRI->getMinimalPhysRegClass(Reg, VT);
1141     const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1142
1143     // If cross copy register class is null, then it must be possible copy
1144     // the value directly. Do not try duplicate the def.
1145     SUnit *NewDef = 0;
1146     if (DestRC)
1147       NewDef = CopyAndMoveSuccessors(LRDef);
1148     else
1149       DestRC = RC;
1150     if (!NewDef) {
1151       // Issue copies, these can be expensive cross register class copies.
1152       SmallVector<SUnit*, 2> Copies;
1153       InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1154       DEBUG(dbgs() << "    Adding an edge from SU #" << TrySU->NodeNum
1155             << " to SU #" << Copies.front()->NodeNum << "\n");
1156       AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1157                           /*Reg=*/0, /*isNormalMemory=*/false,
1158                           /*isMustAlias=*/false,
1159                           /*isArtificial=*/true));
1160       NewDef = Copies.back();
1161     }
1162
1163     DEBUG(dbgs() << "    Adding an edge from SU #" << NewDef->NodeNum
1164           << " to SU #" << TrySU->NodeNum << "\n");
1165     LiveRegDefs[Reg] = NewDef;
1166     AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1167                          /*Reg=*/0, /*isNormalMemory=*/false,
1168                          /*isMustAlias=*/false,
1169                          /*isArtificial=*/true));
1170     TrySU->isAvailable = false;
1171     CurSU = NewDef;
1172   }
1173
1174   assert(CurSU && "Unable to resolve live physical register dependencies!");
1175
1176   // Add the nodes that aren't ready back onto the available list.
1177   for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1178     Interferences[i]->isPending = false;
1179     // May no longer be available due to backtracking.
1180     if (Interferences[i]->isAvailable) {
1181       AvailableQueue->push(Interferences[i]);
1182     }
1183   }
1184   return CurSU;
1185 }
1186
1187 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1188 /// schedulers.
1189 void ScheduleDAGRRList::ListScheduleBottomUp() {
1190   // Release any predecessors of the special Exit node.
1191   ReleasePredecessors(&ExitSU);
1192
1193   // Add root to Available queue.
1194   if (!SUnits.empty()) {
1195     SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
1196     assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1197     RootSU->isAvailable = true;
1198     AvailableQueue->push(RootSU);
1199   }
1200
1201   // While Available queue is not empty, grab the node with the highest
1202   // priority. If it is not ready put it back.  Schedule the node.
1203   Sequence.reserve(SUnits.size());
1204   while (!AvailableQueue->empty()) {
1205     DEBUG(dbgs() << "\n*** Examining Available\n";
1206           AvailableQueue->dump(this));
1207
1208     // Pick the best node to schedule taking all constraints into
1209     // consideration.
1210     SUnit *SU = PickNodeToScheduleBottomUp();
1211
1212     AdvancePastStalls(SU);
1213
1214     ScheduleNodeBottomUp(SU);
1215
1216     while (AvailableQueue->empty() && !PendingQueue.empty()) {
1217       // Advance the cycle to free resources. Skip ahead to the next ready SU.
1218       assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1219       AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1220     }
1221   }
1222
1223   // Reverse the order if it is bottom up.
1224   std::reverse(Sequence.begin(), Sequence.end());
1225
1226 #ifndef NDEBUG
1227   VerifySchedule(isBottomUp);
1228 #endif
1229 }
1230
1231 //===----------------------------------------------------------------------===//
1232 //  Top-Down Scheduling
1233 //===----------------------------------------------------------------------===//
1234
1235 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1236 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1237 void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
1238   SUnit *SuccSU = SuccEdge->getSUnit();
1239
1240 #ifndef NDEBUG
1241   if (SuccSU->NumPredsLeft == 0) {
1242     dbgs() << "*** Scheduling failed! ***\n";
1243     SuccSU->dump(this);
1244     dbgs() << " has been released too many times!\n";
1245     llvm_unreachable(0);
1246   }
1247 #endif
1248   --SuccSU->NumPredsLeft;
1249
1250   // If all the node's predecessors are scheduled, this node is ready
1251   // to be scheduled. Ignore the special ExitSU node.
1252   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
1253     SuccSU->isAvailable = true;
1254     AvailableQueue->push(SuccSU);
1255   }
1256 }
1257
1258 void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1259   // Top down: release successors
1260   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1261        I != E; ++I) {
1262     assert(!I->isAssignedRegDep() &&
1263            "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1264
1265     ReleaseSucc(SU, &*I);
1266   }
1267 }
1268
1269 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1270 /// count of its successors. If a successor pending count is zero, add it to
1271 /// the Available queue.
1272 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
1273   DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
1274   DEBUG(SU->dump(this));
1275
1276   assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1277   SU->setDepthToAtLeast(CurCycle);
1278   Sequence.push_back(SU);
1279
1280   ReleaseSuccessors(SU);
1281   SU->isScheduled = true;
1282   AvailableQueue->ScheduledNode(SU);
1283 }
1284
1285 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1286 /// schedulers.
1287 void ScheduleDAGRRList::ListScheduleTopDown() {
1288   AvailableQueue->setCurCycle(CurCycle);
1289
1290   // Release any successors of the special Entry node.
1291   ReleaseSuccessors(&EntrySU);
1292
1293   // All leaves to Available queue.
1294   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1295     // It is available if it has no predecessors.
1296     if (SUnits[i].Preds.empty()) {
1297       AvailableQueue->push(&SUnits[i]);
1298       SUnits[i].isAvailable = true;
1299     }
1300   }
1301
1302   // While Available queue is not empty, grab the node with the highest
1303   // priority. If it is not ready put it back.  Schedule the node.
1304   Sequence.reserve(SUnits.size());
1305   while (!AvailableQueue->empty()) {
1306     SUnit *CurSU = AvailableQueue->pop();
1307
1308     if (CurSU)
1309       ScheduleNodeTopDown(CurSU);
1310     ++CurCycle;
1311     AvailableQueue->setCurCycle(CurCycle);
1312   }
1313
1314 #ifndef NDEBUG
1315   VerifySchedule(isBottomUp);
1316 #endif
1317 }
1318
1319
1320 //===----------------------------------------------------------------------===//
1321 //                RegReductionPriorityQueue Definition
1322 //===----------------------------------------------------------------------===//
1323 //
1324 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1325 // to reduce register pressure.
1326 //
1327 namespace {
1328 class RegReductionPQBase;
1329
1330 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1331   bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1332 };
1333
1334 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1335 // reduction scheduler.
1336 struct bu_ls_rr_sort : public queue_sort {
1337   enum {
1338     IsBottomUp = true,
1339     HasReadyFilter = false
1340   };
1341
1342   RegReductionPQBase *SPQ;
1343   bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1344   bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1345
1346   bool operator()(SUnit* left, SUnit* right) const;
1347 };
1348
1349 // td_ls_rr_sort - Priority function for top down register pressure reduction
1350 // scheduler.
1351 struct td_ls_rr_sort : public queue_sort {
1352   enum {
1353     IsBottomUp = false,
1354     HasReadyFilter = false
1355   };
1356
1357   RegReductionPQBase *SPQ;
1358   td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1359   td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1360
1361   bool operator()(const SUnit* left, const SUnit* right) const;
1362 };
1363
1364 // src_ls_rr_sort - Priority function for source order scheduler.
1365 struct src_ls_rr_sort : public queue_sort {
1366   enum {
1367     IsBottomUp = true,
1368     HasReadyFilter = false
1369   };
1370
1371   RegReductionPQBase *SPQ;
1372   src_ls_rr_sort(RegReductionPQBase *spq)
1373     : SPQ(spq) {}
1374   src_ls_rr_sort(const src_ls_rr_sort &RHS)
1375     : SPQ(RHS.SPQ) {}
1376
1377   bool operator()(SUnit* left, SUnit* right) const;
1378 };
1379
1380 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1381 struct hybrid_ls_rr_sort : public queue_sort {
1382   enum {
1383     IsBottomUp = true,
1384     HasReadyFilter = false
1385   };
1386
1387   RegReductionPQBase *SPQ;
1388   hybrid_ls_rr_sort(RegReductionPQBase *spq)
1389     : SPQ(spq) {}
1390   hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1391     : SPQ(RHS.SPQ) {}
1392
1393   bool isReady(SUnit *SU, unsigned CurCycle) const;
1394
1395   bool operator()(SUnit* left, SUnit* right) const;
1396 };
1397
1398 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1399 // scheduler.
1400 struct ilp_ls_rr_sort : public queue_sort {
1401   enum {
1402     IsBottomUp = true,
1403     HasReadyFilter = false
1404   };
1405
1406   RegReductionPQBase *SPQ;
1407   ilp_ls_rr_sort(RegReductionPQBase *spq)
1408     : SPQ(spq) {}
1409   ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1410     : SPQ(RHS.SPQ) {}
1411
1412   bool isReady(SUnit *SU, unsigned CurCycle) const;
1413
1414   bool operator()(SUnit* left, SUnit* right) const;
1415 };
1416
1417 class RegReductionPQBase : public SchedulingPriorityQueue {
1418 protected:
1419   std::vector<SUnit*> Queue;
1420   unsigned CurQueueId;
1421   bool TracksRegPressure;
1422
1423   // SUnits - The SUnits for the current graph.
1424   std::vector<SUnit> *SUnits;
1425
1426   MachineFunction &MF;
1427   const TargetInstrInfo *TII;
1428   const TargetRegisterInfo *TRI;
1429   const TargetLowering *TLI;
1430   ScheduleDAGRRList *scheduleDAG;
1431
1432   // SethiUllmanNumbers - The SethiUllman number for each node.
1433   std::vector<unsigned> SethiUllmanNumbers;
1434
1435   /// RegPressure - Tracking current reg pressure per register class.
1436   ///
1437   std::vector<unsigned> RegPressure;
1438
1439   /// RegLimit - Tracking the number of allocatable registers per register
1440   /// class.
1441   std::vector<unsigned> RegLimit;
1442
1443 public:
1444   RegReductionPQBase(MachineFunction &mf,
1445                      bool hasReadyFilter,
1446                      bool tracksrp,
1447                      const TargetInstrInfo *tii,
1448                      const TargetRegisterInfo *tri,
1449                      const TargetLowering *tli)
1450     : SchedulingPriorityQueue(hasReadyFilter),
1451       CurQueueId(0), TracksRegPressure(tracksrp),
1452       MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1453     if (TracksRegPressure) {
1454       unsigned NumRC = TRI->getNumRegClasses();
1455       RegLimit.resize(NumRC);
1456       RegPressure.resize(NumRC);
1457       std::fill(RegLimit.begin(), RegLimit.end(), 0);
1458       std::fill(RegPressure.begin(), RegPressure.end(), 0);
1459       for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1460              E = TRI->regclass_end(); I != E; ++I)
1461         RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
1462     }
1463   }
1464
1465   void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1466     scheduleDAG = scheduleDag;
1467   }
1468
1469   ScheduleHazardRecognizer* getHazardRec() {
1470     return scheduleDAG->getHazardRec();
1471   }
1472
1473   void initNodes(std::vector<SUnit> &sunits);
1474
1475   void addNode(const SUnit *SU);
1476
1477   void updateNode(const SUnit *SU);
1478
1479   void releaseState() {
1480     SUnits = 0;
1481     SethiUllmanNumbers.clear();
1482     std::fill(RegPressure.begin(), RegPressure.end(), 0);
1483   }
1484
1485   unsigned getNodePriority(const SUnit *SU) const;
1486
1487   unsigned getNodeOrdering(const SUnit *SU) const {
1488     return scheduleDAG->DAG->GetOrdering(SU->getNode());
1489   }
1490
1491   bool empty() const { return Queue.empty(); }
1492
1493   void push(SUnit *U) {
1494     assert(!U->NodeQueueId && "Node in the queue already");
1495     U->NodeQueueId = ++CurQueueId;
1496     Queue.push_back(U);
1497   }
1498
1499   void remove(SUnit *SU) {
1500     assert(!Queue.empty() && "Queue is empty!");
1501     assert(SU->NodeQueueId != 0 && "Not in queue!");
1502     std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1503                                                  SU);
1504     if (I != prior(Queue.end()))
1505       std::swap(*I, Queue.back());
1506     Queue.pop_back();
1507     SU->NodeQueueId = 0;
1508   }
1509
1510   bool tracksRegPressure() const { return TracksRegPressure; }
1511
1512   void dumpRegPressure() const;
1513
1514   bool HighRegPressure(const SUnit *SU) const;
1515
1516   bool MayReduceRegPressure(SUnit *SU) const;
1517
1518   int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
1519
1520   void ScheduledNode(SUnit *SU);
1521
1522   void UnscheduledNode(SUnit *SU);
1523
1524 protected:
1525   bool canClobber(const SUnit *SU, const SUnit *Op);
1526   void AddPseudoTwoAddrDeps();
1527   void PrescheduleNodesWithMultipleUses();
1528   void CalculateSethiUllmanNumbers();
1529 };
1530
1531 template<class SF>
1532 class RegReductionPriorityQueue : public RegReductionPQBase {
1533   static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1534     std::vector<SUnit *>::iterator Best = Q.begin();
1535     for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1536            E = Q.end(); I != E; ++I)
1537       if (Picker(*Best, *I))
1538         Best = I;
1539     SUnit *V = *Best;
1540     if (Best != prior(Q.end()))
1541       std::swap(*Best, Q.back());
1542     Q.pop_back();
1543     return V;
1544   }
1545
1546   SF Picker;
1547
1548 public:
1549   RegReductionPriorityQueue(MachineFunction &mf,
1550                             bool tracksrp,
1551                             const TargetInstrInfo *tii,
1552                             const TargetRegisterInfo *tri,
1553                             const TargetLowering *tli)
1554     : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1555       Picker(this) {}
1556
1557   bool isBottomUp() const { return SF::IsBottomUp; }
1558
1559   bool isReady(SUnit *U) const {
1560     return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1561   }
1562
1563   SUnit *pop() {
1564     if (Queue.empty()) return NULL;
1565
1566     SUnit *V = popFromQueue(Queue, Picker);
1567     V->NodeQueueId = 0;
1568     return V;
1569   }
1570
1571   void dump(ScheduleDAG *DAG) const {
1572     // Emulate pop() without clobbering NodeQueueIds.
1573     std::vector<SUnit*> DumpQueue = Queue;
1574     SF DumpPicker = Picker;
1575     while (!DumpQueue.empty()) {
1576       SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1577       if (isBottomUp())
1578         dbgs() << "Height " << SU->getHeight() << ": ";
1579       else
1580         dbgs() << "Depth " << SU->getDepth() << ": ";
1581       SU->dump(DAG);
1582     }
1583   }
1584 };
1585
1586 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1587 BURegReductionPriorityQueue;
1588
1589 typedef RegReductionPriorityQueue<td_ls_rr_sort>
1590 TDRegReductionPriorityQueue;
1591
1592 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1593 SrcRegReductionPriorityQueue;
1594
1595 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1596 HybridBURRPriorityQueue;
1597
1598 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1599 ILPBURRPriorityQueue;
1600 } // end anonymous namespace
1601
1602 //===----------------------------------------------------------------------===//
1603 //           Static Node Priority for Register Pressure Reduction
1604 //===----------------------------------------------------------------------===//
1605
1606 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1607 /// Smaller number is the higher priority.
1608 static unsigned
1609 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1610   unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1611   if (SethiUllmanNumber != 0)
1612     return SethiUllmanNumber;
1613
1614   unsigned Extra = 0;
1615   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1616        I != E; ++I) {
1617     if (I->isCtrl()) continue;  // ignore chain preds
1618     SUnit *PredSU = I->getSUnit();
1619     unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1620     if (PredSethiUllman > SethiUllmanNumber) {
1621       SethiUllmanNumber = PredSethiUllman;
1622       Extra = 0;
1623     } else if (PredSethiUllman == SethiUllmanNumber)
1624       ++Extra;
1625   }
1626
1627   SethiUllmanNumber += Extra;
1628
1629   if (SethiUllmanNumber == 0)
1630     SethiUllmanNumber = 1;
1631
1632   return SethiUllmanNumber;
1633 }
1634
1635 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1636 /// scheduling units.
1637 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1638   SethiUllmanNumbers.assign(SUnits->size(), 0);
1639
1640   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1641     CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1642 }
1643
1644 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
1645   SUnits = &sunits;
1646   // Add pseudo dependency edges for two-address nodes.
1647   AddPseudoTwoAddrDeps();
1648   // Reroute edges to nodes with multiple uses.
1649   if (!TracksRegPressure)
1650     PrescheduleNodesWithMultipleUses();
1651   // Calculate node priorities.
1652   CalculateSethiUllmanNumbers();
1653 }
1654
1655 void RegReductionPQBase::addNode(const SUnit *SU) {
1656   unsigned SUSize = SethiUllmanNumbers.size();
1657   if (SUnits->size() > SUSize)
1658     SethiUllmanNumbers.resize(SUSize*2, 0);
1659   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1660 }
1661
1662 void RegReductionPQBase::updateNode(const SUnit *SU) {
1663   SethiUllmanNumbers[SU->NodeNum] = 0;
1664   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1665 }
1666
1667 // Lower priority means schedule further down. For bottom-up scheduling, lower
1668 // priority SUs are scheduled before higher priority SUs.
1669 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1670   assert(SU->NodeNum < SethiUllmanNumbers.size());
1671   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1672   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1673     // CopyToReg should be close to its uses to facilitate coalescing and
1674     // avoid spilling.
1675     return 0;
1676   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1677       Opc == TargetOpcode::SUBREG_TO_REG ||
1678       Opc == TargetOpcode::INSERT_SUBREG)
1679     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1680     // close to their uses to facilitate coalescing.
1681     return 0;
1682   if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1683     // If SU does not have a register use, i.e. it doesn't produce a value
1684     // that would be consumed (e.g. store), then it terminates a chain of
1685     // computation.  Give it a large SethiUllman number so it will be
1686     // scheduled right before its predecessors that it doesn't lengthen
1687     // their live ranges.
1688     return 0xffff;
1689   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1690     // If SU does not have a register def, schedule it close to its uses
1691     // because it does not lengthen any live ranges.
1692     return 0;
1693   return SethiUllmanNumbers[SU->NodeNum];
1694 }
1695
1696 //===----------------------------------------------------------------------===//
1697 //                     Register Pressure Tracking
1698 //===----------------------------------------------------------------------===//
1699
1700 void RegReductionPQBase::dumpRegPressure() const {
1701   for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1702          E = TRI->regclass_end(); I != E; ++I) {
1703     const TargetRegisterClass *RC = *I;
1704     unsigned Id = RC->getID();
1705     unsigned RP = RegPressure[Id];
1706     if (!RP) continue;
1707     DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1708           << '\n');
1709   }
1710 }
1711
1712 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1713   if (!TLI)
1714     return false;
1715
1716   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1717        I != E; ++I) {
1718     if (I->isCtrl())
1719       continue;
1720     SUnit *PredSU = I->getSUnit();
1721     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1722     // to cover the number of registers defined (they are all live).
1723     if (PredSU->NumRegDefsLeft == 0) {
1724       continue;
1725     }
1726     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1727          RegDefPos.IsValid(); RegDefPos.Advance()) {
1728       EVT VT = RegDefPos.GetValue();
1729       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1730       unsigned Cost = TLI->getRepRegClassCostFor(VT);
1731       if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1732         return true;
1733     }
1734   }
1735   return false;
1736 }
1737
1738 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
1739   const SDNode *N = SU->getNode();
1740
1741   if (!N->isMachineOpcode() || !SU->NumSuccs)
1742     return false;
1743
1744   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1745   for (unsigned i = 0; i != NumDefs; ++i) {
1746     EVT VT = N->getValueType(i);
1747     if (!N->hasAnyUseOfValue(i))
1748       continue;
1749     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1750     if (RegPressure[RCId] >= RegLimit[RCId])
1751       return true;
1752   }
1753   return false;
1754 }
1755
1756 // Compute the register pressure contribution by this instruction by count up
1757 // for uses that are not live and down for defs. Only count register classes
1758 // that are already under high pressure. As a side effect, compute the number of
1759 // uses of registers that are already live.
1760 //
1761 // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1762 // so could probably be factored.
1763 int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1764   LiveUses = 0;
1765   int PDiff = 0;
1766   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1767        I != E; ++I) {
1768     if (I->isCtrl())
1769       continue;
1770     SUnit *PredSU = I->getSUnit();
1771     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1772     // to cover the number of registers defined (they are all live).
1773     if (PredSU->NumRegDefsLeft == 0) {
1774       if (PredSU->getNode()->isMachineOpcode())
1775         ++LiveUses;
1776       continue;
1777     }
1778     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1779          RegDefPos.IsValid(); RegDefPos.Advance()) {
1780       EVT VT = RegDefPos.GetValue();
1781       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1782       if (RegPressure[RCId] >= RegLimit[RCId])
1783         ++PDiff;
1784     }
1785   }
1786   const SDNode *N = SU->getNode();
1787
1788   if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
1789     return PDiff;
1790
1791   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1792   for (unsigned i = 0; i != NumDefs; ++i) {
1793     EVT VT = N->getValueType(i);
1794     if (!N->hasAnyUseOfValue(i))
1795       continue;
1796     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1797     if (RegPressure[RCId] >= RegLimit[RCId])
1798       --PDiff;
1799   }
1800   return PDiff;
1801 }
1802
1803 void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1804   if (!TracksRegPressure)
1805     return;
1806
1807   if (!SU->getNode())
1808     return;
1809   
1810   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1811        I != E; ++I) {
1812     if (I->isCtrl())
1813       continue;
1814     SUnit *PredSU = I->getSUnit();
1815     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1816     // to cover the number of registers defined (they are all live).
1817     if (PredSU->NumRegDefsLeft == 0) {
1818       continue;
1819     }
1820     // FIXME: The ScheduleDAG currently loses information about which of a
1821     // node's values is consumed by each dependence. Consequently, if the node
1822     // defines multiple register classes, we don't know which to pressurize
1823     // here. Instead the following loop consumes the register defs in an
1824     // arbitrary order. At least it handles the common case of clustered loads
1825     // to the same class. For precise liveness, each SDep needs to indicate the
1826     // result number. But that tightly couples the ScheduleDAG with the
1827     // SelectionDAG making updates tricky. A simpler hack would be to attach a
1828     // value type or register class to SDep.
1829     //
1830     // The most important aspect of register tracking is balancing the increase
1831     // here with the reduction further below. Note that this SU may use multiple
1832     // defs in PredSU. The can't be determined here, but we've already
1833     // compensated by reducing NumRegDefsLeft in PredSU during
1834     // ScheduleDAGSDNodes::AddSchedEdges.
1835     --PredSU->NumRegDefsLeft;
1836     unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
1837     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1838          RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1839       if (SkipRegDefs)
1840         continue;
1841       EVT VT = RegDefPos.GetValue();
1842       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1843       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1844       break;
1845     }
1846   }
1847
1848   // We should have this assert, but there may be dead SDNodes that never
1849   // materialize as SUnits, so they don't appear to generate liveness.
1850   //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
1851   int SkipRegDefs = (int)SU->NumRegDefsLeft;
1852   for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
1853        RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1854     if (SkipRegDefs > 0)
1855       continue;
1856     EVT VT = RegDefPos.GetValue();
1857     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1858     if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT)) {
1859       // Register pressure tracking is imprecise. This can happen. But we try
1860       // hard not to let it happen because it likely results in poor scheduling.
1861       DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") has too many regdefs\n");
1862       RegPressure[RCId] = 0;
1863     }
1864     else {
1865       RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1866     }
1867   }
1868   dumpRegPressure();
1869 }
1870
1871 void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
1872   if (!TracksRegPressure)
1873     return;
1874
1875   const SDNode *N = SU->getNode();
1876   if (!N) return;
1877   
1878   if (!N->isMachineOpcode()) {
1879     if (N->getOpcode() != ISD::CopyToReg)
1880       return;
1881   } else {
1882     unsigned Opc = N->getMachineOpcode();
1883     if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1884         Opc == TargetOpcode::INSERT_SUBREG ||
1885         Opc == TargetOpcode::SUBREG_TO_REG ||
1886         Opc == TargetOpcode::REG_SEQUENCE ||
1887         Opc == TargetOpcode::IMPLICIT_DEF)
1888       return;
1889   }
1890
1891   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1892        I != E; ++I) {
1893     if (I->isCtrl())
1894       continue;
1895     SUnit *PredSU = I->getSUnit();
1896     // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1897     // counts data deps.
1898     if (PredSU->NumSuccsLeft != PredSU->Succs.size())
1899       continue;
1900     const SDNode *PN = PredSU->getNode();
1901     if (!PN->isMachineOpcode()) {
1902       if (PN->getOpcode() == ISD::CopyFromReg) {
1903         EVT VT = PN->getValueType(0);
1904         unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1905         RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1906       }
1907       continue;
1908     }
1909     unsigned POpc = PN->getMachineOpcode();
1910     if (POpc == TargetOpcode::IMPLICIT_DEF)
1911       continue;
1912     if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1913       EVT VT = PN->getOperand(0).getValueType();
1914       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1915       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1916       continue;
1917     } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1918                POpc == TargetOpcode::SUBREG_TO_REG) {
1919       EVT VT = PN->getValueType(0);
1920       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1921       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1922       continue;
1923     }
1924     unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1925     for (unsigned i = 0; i != NumDefs; ++i) {
1926       EVT VT = PN->getValueType(i);
1927       if (!PN->hasAnyUseOfValue(i))
1928         continue;
1929       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1930       if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1931         // Register pressure tracking is imprecise. This can happen.
1932         RegPressure[RCId] = 0;
1933       else
1934         RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1935     }
1936   }
1937
1938   // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1939   // may transfer data dependencies to CopyToReg.
1940   if (SU->NumSuccs && N->isMachineOpcode()) {
1941     unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1942     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1943       EVT VT = N->getValueType(i);
1944       if (VT == MVT::Glue || VT == MVT::Other)
1945         continue;
1946       if (!N->hasAnyUseOfValue(i))
1947         continue;
1948       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1949       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1950     }
1951   }
1952
1953   dumpRegPressure();
1954 }
1955
1956 //===----------------------------------------------------------------------===//
1957 //           Dynamic Node Priority for Register Pressure Reduction
1958 //===----------------------------------------------------------------------===//
1959
1960 /// closestSucc - Returns the scheduled cycle of the successor which is
1961 /// closest to the current cycle.
1962 static unsigned closestSucc(const SUnit *SU) {
1963   unsigned MaxHeight = 0;
1964   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1965        I != E; ++I) {
1966     if (I->isCtrl()) continue;  // ignore chain succs
1967     unsigned Height = I->getSUnit()->getHeight();
1968     // If there are bunch of CopyToRegs stacked up, they should be considered
1969     // to be at the same position.
1970     if (I->getSUnit()->getNode() &&
1971         I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
1972       Height = closestSucc(I->getSUnit())+1;
1973     if (Height > MaxHeight)
1974       MaxHeight = Height;
1975   }
1976   return MaxHeight;
1977 }
1978
1979 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1980 /// for scratch registers, i.e. number of data dependencies.
1981 static unsigned calcMaxScratches(const SUnit *SU) {
1982   unsigned Scratches = 0;
1983   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1984        I != E; ++I) {
1985     if (I->isCtrl()) continue;  // ignore chain preds
1986     Scratches++;
1987   }
1988   return Scratches;
1989 }
1990
1991 /// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
1992 /// CopyToReg to a virtual register. This SU def is probably a liveout and
1993 /// it has no other use. It should be scheduled closer to the terminator.
1994 static bool hasOnlyLiveOutUses(const SUnit *SU) {
1995   bool RetVal = false;
1996   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1997        I != E; ++I) {
1998     if (I->isCtrl()) continue;
1999     const SUnit *SuccSU = I->getSUnit();
2000     if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2001       unsigned Reg =
2002         cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2003       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2004         RetVal = true;
2005         continue;
2006       }
2007     }
2008     return false;
2009   }
2010   return RetVal;
2011 }
2012
2013 /// UnitsSharePred - Return true if the two scheduling units share a common
2014 /// data predecessor.
2015 static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
2016   SmallSet<const SUnit*, 4> Preds;
2017   for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
2018        I != E; ++I) {
2019     if (I->isCtrl()) continue;  // ignore chain preds
2020     Preds.insert(I->getSUnit());
2021   }
2022   for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
2023        I != E; ++I) {
2024     if (I->isCtrl()) continue;  // ignore chain preds
2025     if (Preds.count(I->getSUnit()))
2026       return true;
2027   }
2028   return false;
2029 }
2030
2031 // Check for either a dependence (latency) or resource (hazard) stall.
2032 //
2033 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2034 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2035   if ((int)SPQ->getCurCycle() < Height) return true;
2036   if (SPQ->getHazardRec()->getHazardType(SU, 0)
2037       != ScheduleHazardRecognizer::NoHazard)
2038     return true;
2039   return false;
2040 }
2041
2042 // Return -1 if left has higher priority, 1 if right has higher priority.
2043 // Return 0 if latency-based priority is equivalent.
2044 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2045                             RegReductionPQBase *SPQ) {
2046   // If the two nodes share an operand and one of them has a single
2047   // use that is a live out copy, favor the one that is live out. Otherwise
2048   // it will be difficult to eliminate the copy if the instruction is a
2049   // loop induction variable update. e.g.
2050   // BB:
2051   // sub r1, r3, #1
2052   // str r0, [r2, r3]
2053   // mov r3, r1
2054   // cmp
2055   // bne BB
2056   bool SharePred = UnitsSharePred(left, right);
2057   // FIXME: Only adjust if BB is a loop back edge.
2058   // FIXME: What's the cost of a copy?
2059   int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
2060   int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
2061   int LHeight = (int)left->getHeight() - LBonus;
2062   int RHeight = (int)right->getHeight() - RBonus;
2063
2064   bool LStall = (!checkPref || left->SchedulingPref == Sched::Latency) &&
2065     BUHasStall(left, LHeight, SPQ);
2066   bool RStall = (!checkPref || right->SchedulingPref == Sched::Latency) &&
2067     BUHasStall(right, RHeight, SPQ);
2068
2069   // If scheduling one of the node will cause a pipeline stall, delay it.
2070   // If scheduling either one of the node will cause a pipeline stall, sort
2071   // them according to their height.
2072   if (LStall) {
2073     if (!RStall)
2074       return 1;
2075     if (LHeight != RHeight)
2076       return LHeight > RHeight ? 1 : -1;
2077   } else if (RStall)
2078     return -1;
2079
2080   // If either node is scheduling for latency, sort them by height/depth
2081   // and latency.
2082   if (!checkPref || (left->SchedulingPref == Sched::Latency ||
2083                      right->SchedulingPref == Sched::Latency)) {
2084     if (DisableSchedCycles) {
2085       if (LHeight != RHeight)
2086         return LHeight > RHeight ? 1 : -1;
2087     }
2088     else {
2089       // If neither instruction stalls (!LStall && !RStall) then
2090       // its height is already covered so only its depth matters. We also reach
2091       // this if both stall but have the same height.
2092       unsigned LDepth = left->getDepth();
2093       unsigned RDepth = right->getDepth();
2094       if (LDepth != RDepth) {
2095         DEBUG(dbgs() << "  Comparing latency of SU (" << left->NodeNum
2096               << ") depth " << LDepth << " vs SU (" << right->NodeNum
2097               << ") depth " << RDepth << "\n");
2098         return LDepth < RDepth ? 1 : -1;
2099       }
2100     }
2101     if (left->Latency != right->Latency)
2102       return left->Latency > right->Latency ? 1 : -1;
2103   }
2104   return 0;
2105 }
2106
2107 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
2108   unsigned LPriority = SPQ->getNodePriority(left);
2109   unsigned RPriority = SPQ->getNodePriority(right);
2110   if (LPriority != RPriority) {
2111     DEBUG(++FactorCount[FactStatic]);
2112     return LPriority > RPriority;
2113   }
2114   DEBUG(++FactorCount[FactOther]);
2115
2116   // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2117   // e.g.
2118   // t1 = op t2, c1
2119   // t3 = op t4, c2
2120   //
2121   // and the following instructions are both ready.
2122   // t2 = op c3
2123   // t4 = op c4
2124   //
2125   // Then schedule t2 = op first.
2126   // i.e.
2127   // t4 = op c4
2128   // t2 = op c3
2129   // t1 = op t2, c1
2130   // t3 = op t4, c2
2131   //
2132   // This creates more short live intervals.
2133   unsigned LDist = closestSucc(left);
2134   unsigned RDist = closestSucc(right);
2135   if (LDist != RDist)
2136     return LDist < RDist;
2137
2138   // How many registers becomes live when the node is scheduled.
2139   unsigned LScratch = calcMaxScratches(left);
2140   unsigned RScratch = calcMaxScratches(right);
2141   if (LScratch != RScratch)
2142     return LScratch > RScratch;
2143
2144   if (!DisableSchedCycles) {
2145     int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2146     if (result != 0)
2147       return result > 0;
2148   }
2149   else {
2150     if (left->getHeight() != right->getHeight())
2151       return left->getHeight() > right->getHeight();
2152
2153     if (left->getDepth() != right->getDepth())
2154       return left->getDepth() < right->getDepth();
2155   }
2156
2157   assert(left->NodeQueueId && right->NodeQueueId &&
2158          "NodeQueueId cannot be zero");
2159   return (left->NodeQueueId > right->NodeQueueId);
2160 }
2161
2162 // Bottom up
2163 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2164   return BURRSort(left, right, SPQ);
2165 }
2166
2167 // Source order, otherwise bottom up.
2168 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2169   unsigned LOrder = SPQ->getNodeOrdering(left);
2170   unsigned ROrder = SPQ->getNodeOrdering(right);
2171
2172   // Prefer an ordering where the lower the non-zero order number, the higher
2173   // the preference.
2174   if ((LOrder || ROrder) && LOrder != ROrder)
2175     return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2176
2177   return BURRSort(left, right, SPQ);
2178 }
2179
2180 // If the time between now and when the instruction will be ready can cover
2181 // the spill code, then avoid adding it to the ready queue. This gives long
2182 // stalls highest priority and allows hoisting across calls. It should also
2183 // speed up processing the available queue.
2184 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2185   static const unsigned ReadyDelay = 3;
2186
2187   if (SPQ->MayReduceRegPressure(SU)) return true;
2188
2189   if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2190
2191   if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2192       != ScheduleHazardRecognizer::NoHazard)
2193     return false;
2194
2195   return true;
2196 }
2197
2198 // Return true if right should be scheduled with higher priority than left.
2199 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2200   if (left->isCall || right->isCall)
2201     // No way to compute latency of calls.
2202     return BURRSort(left, right, SPQ);
2203
2204   bool LHigh = SPQ->HighRegPressure(left);
2205   bool RHigh = SPQ->HighRegPressure(right);
2206   // Avoid causing spills. If register pressure is high, schedule for
2207   // register pressure reduction.
2208   if (LHigh && !RHigh) {
2209     DEBUG(dbgs() << "  pressure SU(" << left->NodeNum << ") > SU("
2210           << right->NodeNum << ")\n");
2211     return true;
2212   }
2213   else if (!LHigh && RHigh) {
2214     DEBUG(dbgs() << "  pressure SU(" << right->NodeNum << ") > SU("
2215           << left->NodeNum << ")\n");
2216     return false;
2217   }
2218   else if (!LHigh && !RHigh) {
2219     int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2220     if (result != 0)
2221       return result > 0;
2222   }
2223   return BURRSort(left, right, SPQ);
2224 }
2225
2226 // Schedule as many instructions in each cycle as possible. So don't make an
2227 // instruction available unless it is ready in the current cycle.
2228 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2229   if (SU->getHeight() > CurCycle) return false;
2230
2231   if (SPQ->getHazardRec()->getHazardType(SU, 0)
2232       != ScheduleHazardRecognizer::NoHazard)
2233     return false;
2234
2235   return true;
2236 }
2237
2238 static bool canEnableCoalescing(SUnit *SU) {
2239   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2240   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2241     // CopyToReg should be close to its uses to facilitate coalescing and
2242     // avoid spilling.
2243     return true;
2244
2245   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2246       Opc == TargetOpcode::SUBREG_TO_REG ||
2247       Opc == TargetOpcode::INSERT_SUBREG)
2248     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2249     // close to their uses to facilitate coalescing.
2250     return true;
2251
2252   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2253     // If SU does not have a register def, schedule it close to its uses
2254     // because it does not lengthen any live ranges.
2255     return true;
2256
2257   return false;
2258 }
2259
2260 // list-ilp is currently an experimental scheduler that allows various
2261 // heuristics to be enabled prior to the normal register reduction logic.
2262 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2263   if (left->isCall || right->isCall)
2264     // No way to compute latency of calls.
2265     return BURRSort(left, right, SPQ);
2266
2267   unsigned LLiveUses = 0, RLiveUses = 0;
2268   int LPDiff = 0, RPDiff = 0;
2269   if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2270     LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2271     RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2272   }
2273   if (!DisableSchedRegPressure && LPDiff != RPDiff) {
2274     DEBUG(++FactorCount[FactPressureDiff]);
2275     DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2276           << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
2277     return LPDiff > RPDiff;
2278   }
2279
2280   if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
2281     bool LReduce = canEnableCoalescing(left);
2282     bool RReduce = canEnableCoalescing(right);
2283     DEBUG(if (LReduce != RReduce) ++FactorCount[FactPressureDiff]);
2284     if (LReduce && !RReduce) return false;
2285     if (RReduce && !LReduce) return true;
2286   }
2287
2288   if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2289     DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2290           << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
2291     DEBUG(++FactorCount[FactRegUses]);
2292     return LLiveUses < RLiveUses;
2293   }
2294
2295   if (!DisableSchedStalls) {
2296     bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2297     bool RStall = BUHasStall(right, right->getHeight(), SPQ);
2298     if (LStall != RStall) {
2299       DEBUG(++FactorCount[FactHeight]);
2300       return left->getHeight() > right->getHeight();
2301     }
2302   }
2303
2304   if (!DisableSchedCriticalPath) {
2305     int spread = (int)left->getDepth() - (int)right->getDepth();
2306     if (std::abs(spread) > MaxReorderWindow) {
2307       DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2308             << left->getDepth() << " != SU(" << right->NodeNum << "): "
2309             << right->getDepth() << "\n");
2310       DEBUG(++FactorCount[FactDepth]);
2311       return left->getDepth() < right->getDepth();
2312     }
2313   }
2314
2315   if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
2316     int spread = (int)left->getHeight() - (int)right->getHeight();
2317     if (std::abs(spread) > MaxReorderWindow) {
2318       DEBUG(++FactorCount[FactHeight]);
2319       return left->getHeight() > right->getHeight();
2320     }
2321   }
2322
2323   return BURRSort(left, right, SPQ);
2324 }
2325
2326 //===----------------------------------------------------------------------===//
2327 //                    Preschedule for Register Pressure
2328 //===----------------------------------------------------------------------===//
2329
2330 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
2331   if (SU->isTwoAddress) {
2332     unsigned Opc = SU->getNode()->getMachineOpcode();
2333     const TargetInstrDesc &TID = TII->get(Opc);
2334     unsigned NumRes = TID.getNumDefs();
2335     unsigned NumOps = TID.getNumOperands() - NumRes;
2336     for (unsigned i = 0; i != NumOps; ++i) {
2337       if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
2338         SDNode *DU = SU->getNode()->getOperand(i).getNode();
2339         if (DU->getNodeId() != -1 &&
2340             Op->OrigNode == &(*SUnits)[DU->getNodeId()])
2341           return true;
2342       }
2343     }
2344   }
2345   return false;
2346 }
2347
2348 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
2349 /// physical register defs.
2350 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
2351                                   const TargetInstrInfo *TII,
2352                                   const TargetRegisterInfo *TRI) {
2353   SDNode *N = SuccSU->getNode();
2354   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2355   const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
2356   assert(ImpDefs && "Caller should check hasPhysRegDefs");
2357   for (const SDNode *SUNode = SU->getNode(); SUNode;
2358        SUNode = SUNode->getGluedNode()) {
2359     if (!SUNode->isMachineOpcode())
2360       continue;
2361     const unsigned *SUImpDefs =
2362       TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2363     if (!SUImpDefs)
2364       return false;
2365     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2366       EVT VT = N->getValueType(i);
2367       if (VT == MVT::Glue || VT == MVT::Other)
2368         continue;
2369       if (!N->hasAnyUseOfValue(i))
2370         continue;
2371       unsigned Reg = ImpDefs[i - NumDefs];
2372       for (;*SUImpDefs; ++SUImpDefs) {
2373         unsigned SUReg = *SUImpDefs;
2374         if (TRI->regsOverlap(Reg, SUReg))
2375           return true;
2376       }
2377     }
2378   }
2379   return false;
2380 }
2381
2382 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2383 /// are not handled well by the general register pressure reduction
2384 /// heuristics. When presented with code like this:
2385 ///
2386 ///      N
2387 ///    / |
2388 ///   /  |
2389 ///  U  store
2390 ///  |
2391 /// ...
2392 ///
2393 /// the heuristics tend to push the store up, but since the
2394 /// operand of the store has another use (U), this would increase
2395 /// the length of that other use (the U->N edge).
2396 ///
2397 /// This function transforms code like the above to route U's
2398 /// dependence through the store when possible, like this:
2399 ///
2400 ///      N
2401 ///      ||
2402 ///      ||
2403 ///     store
2404 ///       |
2405 ///       U
2406 ///       |
2407 ///      ...
2408 ///
2409 /// This results in the store being scheduled immediately
2410 /// after N, which shortens the U->N live range, reducing
2411 /// register pressure.
2412 ///
2413 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
2414   // Visit all the nodes in topological order, working top-down.
2415   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2416     SUnit *SU = &(*SUnits)[i];
2417     // For now, only look at nodes with no data successors, such as stores.
2418     // These are especially important, due to the heuristics in
2419     // getNodePriority for nodes with no data successors.
2420     if (SU->NumSuccs != 0)
2421       continue;
2422     // For now, only look at nodes with exactly one data predecessor.
2423     if (SU->NumPreds != 1)
2424       continue;
2425     // Avoid prescheduling copies to virtual registers, which don't behave
2426     // like other nodes from the perspective of scheduling heuristics.
2427     if (SDNode *N = SU->getNode())
2428       if (N->getOpcode() == ISD::CopyToReg &&
2429           TargetRegisterInfo::isVirtualRegister
2430             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2431         continue;
2432
2433     // Locate the single data predecessor.
2434     SUnit *PredSU = 0;
2435     for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2436          EE = SU->Preds.end(); II != EE; ++II)
2437       if (!II->isCtrl()) {
2438         PredSU = II->getSUnit();
2439         break;
2440       }
2441     assert(PredSU);
2442
2443     // Don't rewrite edges that carry physregs, because that requires additional
2444     // support infrastructure.
2445     if (PredSU->hasPhysRegDefs)
2446       continue;
2447     // Short-circuit the case where SU is PredSU's only data successor.
2448     if (PredSU->NumSuccs == 1)
2449       continue;
2450     // Avoid prescheduling to copies from virtual registers, which don't behave
2451     // like other nodes from the perspective of scheduling heuristics.
2452     if (SDNode *N = SU->getNode())
2453       if (N->getOpcode() == ISD::CopyFromReg &&
2454           TargetRegisterInfo::isVirtualRegister
2455             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2456         continue;
2457
2458     // Perform checks on the successors of PredSU.
2459     for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2460          EE = PredSU->Succs.end(); II != EE; ++II) {
2461       SUnit *PredSuccSU = II->getSUnit();
2462       if (PredSuccSU == SU) continue;
2463       // If PredSU has another successor with no data successors, for
2464       // now don't attempt to choose either over the other.
2465       if (PredSuccSU->NumSuccs == 0)
2466         goto outer_loop_continue;
2467       // Don't break physical register dependencies.
2468       if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2469         if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2470           goto outer_loop_continue;
2471       // Don't introduce graph cycles.
2472       if (scheduleDAG->IsReachable(SU, PredSuccSU))
2473         goto outer_loop_continue;
2474     }
2475
2476     // Ok, the transformation is safe and the heuristics suggest it is
2477     // profitable. Update the graph.
2478     DEBUG(dbgs() << "    Prescheduling SU #" << SU->NodeNum
2479                  << " next to PredSU #" << PredSU->NodeNum
2480                  << " to guide scheduling in the presence of multiple uses\n");
2481     for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2482       SDep Edge = PredSU->Succs[i];
2483       assert(!Edge.isAssignedRegDep());
2484       SUnit *SuccSU = Edge.getSUnit();
2485       if (SuccSU != SU) {
2486         Edge.setSUnit(PredSU);
2487         scheduleDAG->RemovePred(SuccSU, Edge);
2488         scheduleDAG->AddPred(SU, Edge);
2489         Edge.setSUnit(SU);
2490         scheduleDAG->AddPred(SuccSU, Edge);
2491         --i;
2492       }
2493     }
2494   outer_loop_continue:;
2495   }
2496 }
2497
2498 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2499 /// it as a def&use operand. Add a pseudo control edge from it to the other
2500 /// node (if it won't create a cycle) so the two-address one will be scheduled
2501 /// first (lower in the schedule). If both nodes are two-address, favor the
2502 /// one that has a CopyToReg use (more likely to be a loop induction update).
2503 /// If both are two-address, but one is commutable while the other is not
2504 /// commutable, favor the one that's not commutable.
2505 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
2506   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2507     SUnit *SU = &(*SUnits)[i];
2508     if (!SU->isTwoAddress)
2509       continue;
2510
2511     SDNode *Node = SU->getNode();
2512     if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
2513       continue;
2514
2515     bool isLiveOut = hasOnlyLiveOutUses(SU);
2516     unsigned Opc = Node->getMachineOpcode();
2517     const TargetInstrDesc &TID = TII->get(Opc);
2518     unsigned NumRes = TID.getNumDefs();
2519     unsigned NumOps = TID.getNumOperands() - NumRes;
2520     for (unsigned j = 0; j != NumOps; ++j) {
2521       if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2522         continue;
2523       SDNode *DU = SU->getNode()->getOperand(j).getNode();
2524       if (DU->getNodeId() == -1)
2525         continue;
2526       const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2527       if (!DUSU) continue;
2528       for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2529            E = DUSU->Succs.end(); I != E; ++I) {
2530         if (I->isCtrl()) continue;
2531         SUnit *SuccSU = I->getSUnit();
2532         if (SuccSU == SU)
2533           continue;
2534         // Be conservative. Ignore if nodes aren't at roughly the same
2535         // depth and height.
2536         if (SuccSU->getHeight() < SU->getHeight() &&
2537             (SU->getHeight() - SuccSU->getHeight()) > 1)
2538           continue;
2539         // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2540         // constrains whatever is using the copy, instead of the copy
2541         // itself. In the case that the copy is coalesced, this
2542         // preserves the intent of the pseudo two-address heurietics.
2543         while (SuccSU->Succs.size() == 1 &&
2544                SuccSU->getNode()->isMachineOpcode() &&
2545                SuccSU->getNode()->getMachineOpcode() ==
2546                  TargetOpcode::COPY_TO_REGCLASS)
2547           SuccSU = SuccSU->Succs.front().getSUnit();
2548         // Don't constrain non-instruction nodes.
2549         if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2550           continue;
2551         // Don't constrain nodes with physical register defs if the
2552         // predecessor can clobber them.
2553         if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
2554           if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
2555             continue;
2556         }
2557         // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2558         // these may be coalesced away. We want them close to their uses.
2559         unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
2560         if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2561             SuccOpc == TargetOpcode::INSERT_SUBREG ||
2562             SuccOpc == TargetOpcode::SUBREG_TO_REG)
2563           continue;
2564         if ((!canClobber(SuccSU, DUSU) ||
2565              (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
2566              (!SU->isCommutable && SuccSU->isCommutable)) &&
2567             !scheduleDAG->IsReachable(SuccSU, SU)) {
2568           DEBUG(dbgs() << "    Adding a pseudo-two-addr edge from SU #"
2569                        << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
2570           scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
2571                                         /*Reg=*/0, /*isNormalMemory=*/false,
2572                                         /*isMustAlias=*/false,
2573                                         /*isArtificial=*/true));
2574         }
2575       }
2576     }
2577   }
2578 }
2579
2580 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
2581 /// predecessors of the successors of the SUnit SU. Stop when the provided
2582 /// limit is exceeded.
2583 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
2584                                                     unsigned Limit) {
2585   unsigned Sum = 0;
2586   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2587        I != E; ++I) {
2588     const SUnit *SuccSU = I->getSUnit();
2589     for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2590          EE = SuccSU->Preds.end(); II != EE; ++II) {
2591       SUnit *PredSU = II->getSUnit();
2592       if (!PredSU->isScheduled)
2593         if (++Sum > Limit)
2594           return Sum;
2595     }
2596   }
2597   return Sum;
2598 }
2599
2600
2601 // Top down
2602 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
2603   unsigned LPriority = SPQ->getNodePriority(left);
2604   unsigned RPriority = SPQ->getNodePriority(right);
2605   bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2606   bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
2607   bool LIsFloater = LIsTarget && left->NumPreds == 0;
2608   bool RIsFloater = RIsTarget && right->NumPreds == 0;
2609   unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2610   unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
2611
2612   if (left->NumSuccs == 0 && right->NumSuccs != 0)
2613     return false;
2614   else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2615     return true;
2616
2617   if (LIsFloater)
2618     LBonus -= 2;
2619   if (RIsFloater)
2620     RBonus -= 2;
2621   if (left->NumSuccs == 1)
2622     LBonus += 2;
2623   if (right->NumSuccs == 1)
2624     RBonus += 2;
2625
2626   if (LPriority+LBonus != RPriority+RBonus)
2627     return LPriority+LBonus < RPriority+RBonus;
2628
2629   if (left->getDepth() != right->getDepth())
2630     return left->getDepth() < right->getDepth();
2631
2632   if (left->NumSuccsLeft != right->NumSuccsLeft)
2633     return left->NumSuccsLeft > right->NumSuccsLeft;
2634
2635   assert(left->NodeQueueId && right->NodeQueueId &&
2636          "NodeQueueId cannot be zero");
2637   return (left->NodeQueueId > right->NodeQueueId);
2638 }
2639
2640 //===----------------------------------------------------------------------===//
2641 //                         Public Constructor Functions
2642 //===----------------------------------------------------------------------===//
2643
2644 llvm::ScheduleDAGSDNodes *
2645 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2646                                  CodeGenOpt::Level OptLevel) {
2647   const TargetMachine &TM = IS->TM;
2648   const TargetInstrInfo *TII = TM.getInstrInfo();
2649   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2650
2651   BURegReductionPriorityQueue *PQ =
2652     new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2653   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2654   PQ->setScheduleDAG(SD);
2655   return SD;
2656 }
2657
2658 llvm::ScheduleDAGSDNodes *
2659 llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2660                                  CodeGenOpt::Level OptLevel) {
2661   const TargetMachine &TM = IS->TM;
2662   const TargetInstrInfo *TII = TM.getInstrInfo();
2663   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2664
2665   TDRegReductionPriorityQueue *PQ =
2666     new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2667   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2668   PQ->setScheduleDAG(SD);
2669   return SD;
2670 }
2671
2672 llvm::ScheduleDAGSDNodes *
2673 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2674                                    CodeGenOpt::Level OptLevel) {
2675   const TargetMachine &TM = IS->TM;
2676   const TargetInstrInfo *TII = TM.getInstrInfo();
2677   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2678
2679   SrcRegReductionPriorityQueue *PQ =
2680     new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
2681   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
2682   PQ->setScheduleDAG(SD);
2683   return SD;
2684 }
2685
2686 llvm::ScheduleDAGSDNodes *
2687 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2688                                    CodeGenOpt::Level OptLevel) {
2689   const TargetMachine &TM = IS->TM;
2690   const TargetInstrInfo *TII = TM.getInstrInfo();
2691   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2692   const TargetLowering *TLI = &IS->getTargetLowering();
2693
2694   HybridBURRPriorityQueue *PQ =
2695     new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2696
2697   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2698   PQ->setScheduleDAG(SD);
2699   return SD;
2700 }
2701
2702 llvm::ScheduleDAGSDNodes *
2703 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2704                                 CodeGenOpt::Level OptLevel) {
2705   const TargetMachine &TM = IS->TM;
2706   const TargetInstrInfo *TII = TM.getInstrInfo();
2707   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2708   const TargetLowering *TLI = &IS->getTargetLowering();
2709
2710   ILPBURRPriorityQueue *PQ =
2711     new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
2712   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
2713   PQ->setScheduleDAG(SD);
2714   return SD;
2715 }