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