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