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