LLVM API Documentation

ScheduleDAGRRList.cpp
Go to the documentation of this file.
00001 //===----- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler --===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements bottom-up and top-down register pressure reduction list
00011 // schedulers, using standard algorithms.  The basic approach uses a priority
00012 // queue of available nodes to schedule.  One at a time, nodes are taken from
00013 // the priority queue (thus in priority order), checked for legality to
00014 // schedule, and emitted if legal.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #include "llvm/CodeGen/SchedulerRegistry.h"
00019 #include "ScheduleDAGSDNodes.h"
00020 #include "llvm/ADT/STLExtras.h"
00021 #include "llvm/ADT/SmallSet.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/CodeGen/MachineRegisterInfo.h"
00024 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
00025 #include "llvm/CodeGen/SelectionDAGISel.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/IR/InlineAsm.h"
00028 #include "llvm/Support/Debug.h"
00029 #include "llvm/Support/ErrorHandling.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 #include "llvm/Target/TargetInstrInfo.h"
00032 #include "llvm/Target/TargetLowering.h"
00033 #include "llvm/Target/TargetRegisterInfo.h"
00034 #include "llvm/Target/TargetSubtargetInfo.h"
00035 #include <climits>
00036 using namespace llvm;
00037 
00038 #define DEBUG_TYPE "pre-RA-sched"
00039 
00040 STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
00041 STATISTIC(NumUnfolds,    "Number of nodes unfolded");
00042 STATISTIC(NumDups,       "Number of duplicated nodes");
00043 STATISTIC(NumPRCopies,   "Number of physical register copies");
00044 
00045 static RegisterScheduler
00046   burrListDAGScheduler("list-burr",
00047                        "Bottom-up register reduction list scheduling",
00048                        createBURRListDAGScheduler);
00049 static RegisterScheduler
00050   sourceListDAGScheduler("source",
00051                          "Similar to list-burr but schedules in source "
00052                          "order when possible",
00053                          createSourceListDAGScheduler);
00054 
00055 static RegisterScheduler
00056   hybridListDAGScheduler("list-hybrid",
00057                          "Bottom-up register pressure aware list scheduling "
00058                          "which tries to balance latency and register pressure",
00059                          createHybridListDAGScheduler);
00060 
00061 static RegisterScheduler
00062   ILPListDAGScheduler("list-ilp",
00063                       "Bottom-up register pressure aware list scheduling "
00064                       "which tries to balance ILP and register pressure",
00065                       createILPListDAGScheduler);
00066 
00067 static cl::opt<bool> DisableSchedCycles(
00068   "disable-sched-cycles", cl::Hidden, cl::init(false),
00069   cl::desc("Disable cycle-level precision during preRA scheduling"));
00070 
00071 // Temporary sched=list-ilp flags until the heuristics are robust.
00072 // Some options are also available under sched=list-hybrid.
00073 static cl::opt<bool> DisableSchedRegPressure(
00074   "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
00075   cl::desc("Disable regpressure priority in sched=list-ilp"));
00076 static cl::opt<bool> DisableSchedLiveUses(
00077   "disable-sched-live-uses", cl::Hidden, cl::init(true),
00078   cl::desc("Disable live use priority in sched=list-ilp"));
00079 static cl::opt<bool> DisableSchedVRegCycle(
00080   "disable-sched-vrcycle", cl::Hidden, cl::init(false),
00081   cl::desc("Disable virtual register cycle interference checks"));
00082 static cl::opt<bool> DisableSchedPhysRegJoin(
00083   "disable-sched-physreg-join", cl::Hidden, cl::init(false),
00084   cl::desc("Disable physreg def-use affinity"));
00085 static cl::opt<bool> DisableSchedStalls(
00086   "disable-sched-stalls", cl::Hidden, cl::init(true),
00087   cl::desc("Disable no-stall priority in sched=list-ilp"));
00088 static cl::opt<bool> DisableSchedCriticalPath(
00089   "disable-sched-critical-path", cl::Hidden, cl::init(false),
00090   cl::desc("Disable critical path priority in sched=list-ilp"));
00091 static cl::opt<bool> DisableSchedHeight(
00092   "disable-sched-height", cl::Hidden, cl::init(false),
00093   cl::desc("Disable scheduled-height priority in sched=list-ilp"));
00094 static cl::opt<bool> Disable2AddrHack(
00095   "disable-2addr-hack", cl::Hidden, cl::init(true),
00096   cl::desc("Disable scheduler's two-address hack"));
00097 
00098 static cl::opt<int> MaxReorderWindow(
00099   "max-sched-reorder", cl::Hidden, cl::init(6),
00100   cl::desc("Number of instructions to allow ahead of the critical path "
00101            "in sched=list-ilp"));
00102 
00103 static cl::opt<unsigned> AvgIPC(
00104   "sched-avg-ipc", cl::Hidden, cl::init(1),
00105   cl::desc("Average inst/cycle whan no target itinerary exists."));
00106 
00107 namespace {
00108 //===----------------------------------------------------------------------===//
00109 /// ScheduleDAGRRList - The actual register reduction list scheduler
00110 /// implementation.  This supports both top-down and bottom-up scheduling.
00111 ///
00112 class ScheduleDAGRRList : public ScheduleDAGSDNodes {
00113 private:
00114   /// NeedLatency - True if the scheduler will make use of latency information.
00115   ///
00116   bool NeedLatency;
00117 
00118   /// AvailableQueue - The priority queue to use for the available SUnits.
00119   SchedulingPriorityQueue *AvailableQueue;
00120 
00121   /// PendingQueue - This contains all of the instructions whose operands have
00122   /// been issued, but their results are not ready yet (due to the latency of
00123   /// the operation).  Once the operands becomes available, the instruction is
00124   /// added to the AvailableQueue.
00125   std::vector<SUnit*> PendingQueue;
00126 
00127   /// HazardRec - The hazard recognizer to use.
00128   ScheduleHazardRecognizer *HazardRec;
00129 
00130   /// CurCycle - The current scheduler state corresponds to this cycle.
00131   unsigned CurCycle;
00132 
00133   /// MinAvailableCycle - Cycle of the soonest available instruction.
00134   unsigned MinAvailableCycle;
00135 
00136   /// IssueCount - Count instructions issued in this cycle
00137   /// Currently valid only for bottom-up scheduling.
00138   unsigned IssueCount;
00139 
00140   /// LiveRegDefs - A set of physical registers and their definition
00141   /// that are "live". These nodes must be scheduled before any other nodes that
00142   /// modifies the registers can be scheduled.
00143   unsigned NumLiveRegs;
00144   std::vector<SUnit*> LiveRegDefs;
00145   std::vector<SUnit*> LiveRegGens;
00146 
00147   // Collect interferences between physical register use/defs.
00148   // Each interference is an SUnit and set of physical registers.
00149   SmallVector<SUnit*, 4> Interferences;
00150   typedef DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMapT;
00151   LRegsMapT LRegsMap;
00152 
00153   /// Topo - A topological ordering for SUnits which permits fast IsReachable
00154   /// and similar queries.
00155   ScheduleDAGTopologicalSort Topo;
00156 
00157   // Hack to keep track of the inverse of FindCallSeqStart without more crazy
00158   // DAG crawling.
00159   DenseMap<SUnit*, SUnit*> CallSeqEndForStart;
00160 
00161 public:
00162   ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
00163                     SchedulingPriorityQueue *availqueue,
00164                     CodeGenOpt::Level OptLevel)
00165     : ScheduleDAGSDNodes(mf),
00166       NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
00167       Topo(SUnits, nullptr) {
00168 
00169     const TargetSubtargetInfo &STI = mf.getSubtarget();
00170     if (DisableSchedCycles || !NeedLatency)
00171       HazardRec = new ScheduleHazardRecognizer();
00172     else
00173       HazardRec = STI.getInstrInfo()->CreateTargetHazardRecognizer(&STI, this);
00174   }
00175 
00176   ~ScheduleDAGRRList() {
00177     delete HazardRec;
00178     delete AvailableQueue;
00179   }
00180 
00181   void Schedule() override;
00182 
00183   ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
00184 
00185   /// IsReachable - Checks if SU is reachable from TargetSU.
00186   bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
00187     return Topo.IsReachable(SU, TargetSU);
00188   }
00189 
00190   /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
00191   /// create a cycle.
00192   bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
00193     return Topo.WillCreateCycle(SU, TargetSU);
00194   }
00195 
00196   /// AddPred - adds a predecessor edge to SUnit SU.
00197   /// This returns true if this is a new predecessor.
00198   /// Updates the topological ordering if required.
00199   void AddPred(SUnit *SU, const SDep &D) {
00200     Topo.AddPred(SU, D.getSUnit());
00201     SU->addPred(D);
00202   }
00203 
00204   /// RemovePred - removes a predecessor edge from SUnit SU.
00205   /// This returns true if an edge was removed.
00206   /// Updates the topological ordering if required.
00207   void RemovePred(SUnit *SU, const SDep &D) {
00208     Topo.RemovePred(SU, D.getSUnit());
00209     SU->removePred(D);
00210   }
00211 
00212 private:
00213   bool isReady(SUnit *SU) {
00214     return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
00215       AvailableQueue->isReady(SU);
00216   }
00217 
00218   void ReleasePred(SUnit *SU, const SDep *PredEdge);
00219   void ReleasePredecessors(SUnit *SU);
00220   void ReleasePending();
00221   void AdvanceToCycle(unsigned NextCycle);
00222   void AdvancePastStalls(SUnit *SU);
00223   void EmitNode(SUnit *SU);
00224   void ScheduleNodeBottomUp(SUnit*);
00225   void CapturePred(SDep *PredEdge);
00226   void UnscheduleNodeBottomUp(SUnit*);
00227   void RestoreHazardCheckerBottomUp();
00228   void BacktrackBottomUp(SUnit*, SUnit*);
00229   SUnit *CopyAndMoveSuccessors(SUnit*);
00230   void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
00231                                 const TargetRegisterClass*,
00232                                 const TargetRegisterClass*,
00233                                 SmallVectorImpl<SUnit*>&);
00234   bool DelayForLiveRegsBottomUp(SUnit*, SmallVectorImpl<unsigned>&);
00235 
00236   void releaseInterferences(unsigned Reg = 0);
00237 
00238   SUnit *PickNodeToScheduleBottomUp();
00239   void ListScheduleBottomUp();
00240 
00241   /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
00242   /// Updates the topological ordering if required.
00243   SUnit *CreateNewSUnit(SDNode *N) {
00244     unsigned NumSUnits = SUnits.size();
00245     SUnit *NewNode = newSUnit(N);
00246     // Update the topological ordering.
00247     if (NewNode->NodeNum >= NumSUnits)
00248       Topo.InitDAGTopologicalSorting();
00249     return NewNode;
00250   }
00251 
00252   /// CreateClone - Creates a new SUnit from an existing one.
00253   /// Updates the topological ordering if required.
00254   SUnit *CreateClone(SUnit *N) {
00255     unsigned NumSUnits = SUnits.size();
00256     SUnit *NewNode = Clone(N);
00257     // Update the topological ordering.
00258     if (NewNode->NodeNum >= NumSUnits)
00259       Topo.InitDAGTopologicalSorting();
00260     return NewNode;
00261   }
00262 
00263   /// forceUnitLatencies - Register-pressure-reducing scheduling doesn't
00264   /// need actual latency information but the hybrid scheduler does.
00265   bool forceUnitLatencies() const override {
00266     return !NeedLatency;
00267   }
00268 };
00269 }  // end anonymous namespace
00270 
00271 /// GetCostForDef - Looks up the register class and cost for a given definition.
00272 /// Typically this just means looking up the representative register class,
00273 /// but for untyped values (MVT::Untyped) it means inspecting the node's
00274 /// opcode to determine what register class is being generated.
00275 static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos,
00276                           const TargetLowering *TLI,
00277                           const TargetInstrInfo *TII,
00278                           const TargetRegisterInfo *TRI,
00279                           unsigned &RegClass, unsigned &Cost,
00280                           const MachineFunction &MF) {
00281   MVT VT = RegDefPos.GetValue();
00282 
00283   // Special handling for untyped values.  These values can only come from
00284   // the expansion of custom DAG-to-DAG patterns.
00285   if (VT == MVT::Untyped) {
00286     const SDNode *Node = RegDefPos.GetNode();
00287 
00288     // Special handling for CopyFromReg of untyped values.
00289     if (!Node->isMachineOpcode() && Node->getOpcode() == ISD::CopyFromReg) {
00290       unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
00291       const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(Reg);
00292       RegClass = RC->getID();
00293       Cost = 1;
00294       return;
00295     }
00296 
00297     unsigned Opcode = Node->getMachineOpcode();
00298     if (Opcode == TargetOpcode::REG_SEQUENCE) {
00299       unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
00300       const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
00301       RegClass = RC->getID();
00302       Cost = 1;
00303       return;
00304     }
00305 
00306     unsigned Idx = RegDefPos.GetIdx();
00307     const MCInstrDesc Desc = TII->get(Opcode);
00308     const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx, TRI, MF);
00309     RegClass = RC->getID();
00310     // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
00311     // better way to determine it.
00312     Cost = 1;
00313   } else {
00314     RegClass = TLI->getRepRegClassFor(VT)->getID();
00315     Cost = TLI->getRepRegClassCostFor(VT);
00316   }
00317 }
00318 
00319 /// Schedule - Schedule the DAG using list scheduling.
00320 void ScheduleDAGRRList::Schedule() {
00321   DEBUG(dbgs()
00322         << "********** List Scheduling BB#" << BB->getNumber()
00323         << " '" << BB->getName() << "' **********\n");
00324 
00325   CurCycle = 0;
00326   IssueCount = 0;
00327   MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
00328   NumLiveRegs = 0;
00329   // Allocate slots for each physical register, plus one for a special register
00330   // to track the virtual resource of a calling sequence.
00331   LiveRegDefs.resize(TRI->getNumRegs() + 1, nullptr);
00332   LiveRegGens.resize(TRI->getNumRegs() + 1, nullptr);
00333   CallSeqEndForStart.clear();
00334   assert(Interferences.empty() && LRegsMap.empty() && "stale Interferences");
00335 
00336   // Build the scheduling graph.
00337   BuildSchedGraph(nullptr);
00338 
00339   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
00340           SUnits[su].dumpAll(this));
00341   Topo.InitDAGTopologicalSorting();
00342 
00343   AvailableQueue->initNodes(SUnits);
00344 
00345   HazardRec->Reset();
00346 
00347   // Execute the actual scheduling loop.
00348   ListScheduleBottomUp();
00349 
00350   AvailableQueue->releaseState();
00351 
00352   DEBUG({
00353       dbgs() << "*** Final schedule ***\n";
00354       dumpSchedule();
00355       dbgs() << '\n';
00356     });
00357 }
00358 
00359 //===----------------------------------------------------------------------===//
00360 //  Bottom-Up Scheduling
00361 //===----------------------------------------------------------------------===//
00362 
00363 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
00364 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
00365 void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
00366   SUnit *PredSU = PredEdge->getSUnit();
00367 
00368 #ifndef NDEBUG
00369   if (PredSU->NumSuccsLeft == 0) {
00370     dbgs() << "*** Scheduling failed! ***\n";
00371     PredSU->dump(this);
00372     dbgs() << " has been released too many times!\n";
00373     llvm_unreachable(nullptr);
00374   }
00375 #endif
00376   --PredSU->NumSuccsLeft;
00377 
00378   if (!forceUnitLatencies()) {
00379     // Updating predecessor's height. This is now the cycle when the
00380     // predecessor can be scheduled without causing a pipeline stall.
00381     PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
00382   }
00383 
00384   // If all the node's successors are scheduled, this node is ready
00385   // to be scheduled. Ignore the special EntrySU node.
00386   if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
00387     PredSU->isAvailable = true;
00388 
00389     unsigned Height = PredSU->getHeight();
00390     if (Height < MinAvailableCycle)
00391       MinAvailableCycle = Height;
00392 
00393     if (isReady(PredSU)) {
00394       AvailableQueue->push(PredSU);
00395     }
00396     // CapturePred and others may have left the node in the pending queue, avoid
00397     // adding it twice.
00398     else if (!PredSU->isPending) {
00399       PredSU->isPending = true;
00400       PendingQueue.push_back(PredSU);
00401     }
00402   }
00403 }
00404 
00405 /// IsChainDependent - Test if Outer is reachable from Inner through
00406 /// chain dependencies.
00407 static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
00408                              unsigned NestLevel,
00409                              const TargetInstrInfo *TII) {
00410   SDNode *N = Outer;
00411   for (;;) {
00412     if (N == Inner)
00413       return true;
00414     // For a TokenFactor, examine each operand. There may be multiple ways
00415     // to get to the CALLSEQ_BEGIN, but we need to find the path with the
00416     // most nesting in order to ensure that we find the corresponding match.
00417     if (N->getOpcode() == ISD::TokenFactor) {
00418       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00419         if (IsChainDependent(N->getOperand(i).getNode(), Inner, NestLevel, TII))
00420           return true;
00421       return false;
00422     }
00423     // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
00424     if (N->isMachineOpcode()) {
00425       if (N->getMachineOpcode() ==
00426           (unsigned)TII->getCallFrameDestroyOpcode()) {
00427         ++NestLevel;
00428       } else if (N->getMachineOpcode() ==
00429                  (unsigned)TII->getCallFrameSetupOpcode()) {
00430         if (NestLevel == 0)
00431           return false;
00432         --NestLevel;
00433       }
00434     }
00435     // Otherwise, find the chain and continue climbing.
00436     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00437       if (N->getOperand(i).getValueType() == MVT::Other) {
00438         N = N->getOperand(i).getNode();
00439         goto found_chain_operand;
00440       }
00441     return false;
00442   found_chain_operand:;
00443     if (N->getOpcode() == ISD::EntryToken)
00444       return false;
00445   }
00446 }
00447 
00448 /// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
00449 /// the corresponding (lowered) CALLSEQ_BEGIN node.
00450 ///
00451 /// NestLevel and MaxNested are used in recursion to indcate the current level
00452 /// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
00453 /// level seen so far.
00454 ///
00455 /// TODO: It would be better to give CALLSEQ_END an explicit operand to point
00456 /// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
00457 static SDNode *
00458 FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
00459                  const TargetInstrInfo *TII) {
00460   for (;;) {
00461     // For a TokenFactor, examine each operand. There may be multiple ways
00462     // to get to the CALLSEQ_BEGIN, but we need to find the path with the
00463     // most nesting in order to ensure that we find the corresponding match.
00464     if (N->getOpcode() == ISD::TokenFactor) {
00465       SDNode *Best = nullptr;
00466       unsigned BestMaxNest = MaxNest;
00467       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00468         unsigned MyNestLevel = NestLevel;
00469         unsigned MyMaxNest = MaxNest;
00470         if (SDNode *New = FindCallSeqStart(N->getOperand(i).getNode(),
00471                                            MyNestLevel, MyMaxNest, TII))
00472           if (!Best || (MyMaxNest > BestMaxNest)) {
00473             Best = New;
00474             BestMaxNest = MyMaxNest;
00475           }
00476       }
00477       assert(Best);
00478       MaxNest = BestMaxNest;
00479       return Best;
00480     }
00481     // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
00482     if (N->isMachineOpcode()) {
00483       if (N->getMachineOpcode() ==
00484           (unsigned)TII->getCallFrameDestroyOpcode()) {
00485         ++NestLevel;
00486         MaxNest = std::max(MaxNest, NestLevel);
00487       } else if (N->getMachineOpcode() ==
00488                  (unsigned)TII->getCallFrameSetupOpcode()) {
00489         assert(NestLevel != 0);
00490         --NestLevel;
00491         if (NestLevel == 0)
00492           return N;
00493       }
00494     }
00495     // Otherwise, find the chain and continue climbing.
00496     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00497       if (N->getOperand(i).getValueType() == MVT::Other) {
00498         N = N->getOperand(i).getNode();
00499         goto found_chain_operand;
00500       }
00501     return nullptr;
00502   found_chain_operand:;
00503     if (N->getOpcode() == ISD::EntryToken)
00504       return nullptr;
00505   }
00506 }
00507 
00508 /// Call ReleasePred for each predecessor, then update register live def/gen.
00509 /// Always update LiveRegDefs for a register dependence even if the current SU
00510 /// also defines the register. This effectively create one large live range
00511 /// across a sequence of two-address node. This is important because the
00512 /// entire chain must be scheduled together. Example:
00513 ///
00514 /// flags = (3) add
00515 /// flags = (2) addc flags
00516 /// flags = (1) addc flags
00517 ///
00518 /// results in
00519 ///
00520 /// LiveRegDefs[flags] = 3
00521 /// LiveRegGens[flags] = 1
00522 ///
00523 /// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
00524 /// interference on flags.
00525 void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
00526   // Bottom up: release predecessors
00527   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
00528        I != E; ++I) {
00529     ReleasePred(SU, &*I);
00530     if (I->isAssignedRegDep()) {
00531       // This is a physical register dependency and it's impossible or
00532       // expensive to copy the register. Make sure nothing that can
00533       // clobber the register is scheduled between the predecessor and
00534       // this node.
00535       SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
00536       assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
00537              "interference on register dependence");
00538       LiveRegDefs[I->getReg()] = I->getSUnit();
00539       if (!LiveRegGens[I->getReg()]) {
00540         ++NumLiveRegs;
00541         LiveRegGens[I->getReg()] = SU;
00542       }
00543     }
00544   }
00545 
00546   // If we're scheduling a lowered CALLSEQ_END, find the corresponding
00547   // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
00548   // these nodes, to prevent other calls from being interscheduled with them.
00549   unsigned CallResource = TRI->getNumRegs();
00550   if (!LiveRegDefs[CallResource])
00551     for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
00552       if (Node->isMachineOpcode() &&
00553           Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
00554         unsigned NestLevel = 0;
00555         unsigned MaxNest = 0;
00556         SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
00557 
00558         SUnit *Def = &SUnits[N->getNodeId()];
00559         CallSeqEndForStart[Def] = SU;
00560 
00561         ++NumLiveRegs;
00562         LiveRegDefs[CallResource] = Def;
00563         LiveRegGens[CallResource] = SU;
00564         break;
00565       }
00566 }
00567 
00568 /// Check to see if any of the pending instructions are ready to issue.  If
00569 /// so, add them to the available queue.
00570 void ScheduleDAGRRList::ReleasePending() {
00571   if (DisableSchedCycles) {
00572     assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
00573     return;
00574   }
00575 
00576   // If the available queue is empty, it is safe to reset MinAvailableCycle.
00577   if (AvailableQueue->empty())
00578     MinAvailableCycle = UINT_MAX;
00579 
00580   // Check to see if any of the pending instructions are ready to issue.  If
00581   // so, add them to the available queue.
00582   for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
00583     unsigned ReadyCycle = PendingQueue[i]->getHeight();
00584     if (ReadyCycle < MinAvailableCycle)
00585       MinAvailableCycle = ReadyCycle;
00586 
00587     if (PendingQueue[i]->isAvailable) {
00588       if (!isReady(PendingQueue[i]))
00589           continue;
00590       AvailableQueue->push(PendingQueue[i]);
00591     }
00592     PendingQueue[i]->isPending = false;
00593     PendingQueue[i] = PendingQueue.back();
00594     PendingQueue.pop_back();
00595     --i; --e;
00596   }
00597 }
00598 
00599 /// Move the scheduler state forward by the specified number of Cycles.
00600 void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
00601   if (NextCycle <= CurCycle)
00602     return;
00603 
00604   IssueCount = 0;
00605   AvailableQueue->setCurCycle(NextCycle);
00606   if (!HazardRec->isEnabled()) {
00607     // Bypass lots of virtual calls in case of long latency.
00608     CurCycle = NextCycle;
00609   }
00610   else {
00611     for (; CurCycle != NextCycle; ++CurCycle) {
00612       HazardRec->RecedeCycle();
00613     }
00614   }
00615   // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
00616   // available Q to release pending nodes at least once before popping.
00617   ReleasePending();
00618 }
00619 
00620 /// Move the scheduler state forward until the specified node's dependents are
00621 /// ready and can be scheduled with no resource conflicts.
00622 void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
00623   if (DisableSchedCycles)
00624     return;
00625 
00626   // FIXME: Nodes such as CopyFromReg probably should not advance the current
00627   // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
00628   // has predecessors the cycle will be advanced when they are scheduled.
00629   // But given the crude nature of modeling latency though such nodes, we
00630   // currently need to treat these nodes like real instructions.
00631   // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
00632 
00633   unsigned ReadyCycle = SU->getHeight();
00634 
00635   // Bump CurCycle to account for latency. We assume the latency of other
00636   // available instructions may be hidden by the stall (not a full pipe stall).
00637   // This updates the hazard recognizer's cycle before reserving resources for
00638   // this instruction.
00639   AdvanceToCycle(ReadyCycle);
00640 
00641   // Calls are scheduled in their preceding cycle, so don't conflict with
00642   // hazards from instructions after the call. EmitNode will reset the
00643   // scoreboard state before emitting the call.
00644   if (SU->isCall)
00645     return;
00646 
00647   // FIXME: For resource conflicts in very long non-pipelined stages, we
00648   // should probably skip ahead here to avoid useless scoreboard checks.
00649   int Stalls = 0;
00650   while (true) {
00651     ScheduleHazardRecognizer::HazardType HT =
00652       HazardRec->getHazardType(SU, -Stalls);
00653 
00654     if (HT == ScheduleHazardRecognizer::NoHazard)
00655       break;
00656 
00657     ++Stalls;
00658   }
00659   AdvanceToCycle(CurCycle + Stalls);
00660 }
00661 
00662 /// Record this SUnit in the HazardRecognizer.
00663 /// Does not update CurCycle.
00664 void ScheduleDAGRRList::EmitNode(SUnit *SU) {
00665   if (!HazardRec->isEnabled())
00666     return;
00667 
00668   // Check for phys reg copy.
00669   if (!SU->getNode())
00670     return;
00671 
00672   switch (SU->getNode()->getOpcode()) {
00673   default:
00674     assert(SU->getNode()->isMachineOpcode() &&
00675            "This target-independent node should not be scheduled.");
00676     break;
00677   case ISD::MERGE_VALUES:
00678   case ISD::TokenFactor:
00679   case ISD::LIFETIME_START:
00680   case ISD::LIFETIME_END:
00681   case ISD::CopyToReg:
00682   case ISD::CopyFromReg:
00683   case ISD::EH_LABEL:
00684     // Noops don't affect the scoreboard state. Copies are likely to be
00685     // removed.
00686     return;
00687   case ISD::INLINEASM:
00688     // For inline asm, clear the pipeline state.
00689     HazardRec->Reset();
00690     return;
00691   }
00692   if (SU->isCall) {
00693     // Calls are scheduled with their preceding instructions. For bottom-up
00694     // scheduling, clear the pipeline state before emitting.
00695     HazardRec->Reset();
00696   }
00697 
00698   HazardRec->EmitInstruction(SU);
00699 }
00700 
00701 static void resetVRegCycle(SUnit *SU);
00702 
00703 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
00704 /// count of its predecessors. If a predecessor pending count is zero, add it to
00705 /// the Available queue.
00706 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
00707   DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
00708   DEBUG(SU->dump(this));
00709 
00710 #ifndef NDEBUG
00711   if (CurCycle < SU->getHeight())
00712     DEBUG(dbgs() << "   Height [" << SU->getHeight()
00713           << "] pipeline stall!\n");
00714 #endif
00715 
00716   // FIXME: Do not modify node height. It may interfere with
00717   // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
00718   // node its ready cycle can aid heuristics, and after scheduling it can
00719   // indicate the scheduled cycle.
00720   SU->setHeightToAtLeast(CurCycle);
00721 
00722   // Reserve resources for the scheduled instruction.
00723   EmitNode(SU);
00724 
00725   Sequence.push_back(SU);
00726 
00727   AvailableQueue->scheduledNode(SU);
00728 
00729   // If HazardRec is disabled, and each inst counts as one cycle, then
00730   // advance CurCycle before ReleasePredecessors to avoid useless pushes to
00731   // PendingQueue for schedulers that implement HasReadyFilter.
00732   if (!HazardRec->isEnabled() && AvgIPC < 2)
00733     AdvanceToCycle(CurCycle + 1);
00734 
00735   // Update liveness of predecessors before successors to avoid treating a
00736   // two-address node as a live range def.
00737   ReleasePredecessors(SU);
00738 
00739   // Release all the implicit physical register defs that are live.
00740   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
00741        I != E; ++I) {
00742     // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
00743     if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
00744       assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
00745       --NumLiveRegs;
00746       LiveRegDefs[I->getReg()] = nullptr;
00747       LiveRegGens[I->getReg()] = nullptr;
00748       releaseInterferences(I->getReg());
00749     }
00750   }
00751   // Release the special call resource dependence, if this is the beginning
00752   // of a call.
00753   unsigned CallResource = TRI->getNumRegs();
00754   if (LiveRegDefs[CallResource] == SU)
00755     for (const SDNode *SUNode = SU->getNode(); SUNode;
00756          SUNode = SUNode->getGluedNode()) {
00757       if (SUNode->isMachineOpcode() &&
00758           SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
00759         assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
00760         --NumLiveRegs;
00761         LiveRegDefs[CallResource] = nullptr;
00762         LiveRegGens[CallResource] = nullptr;
00763         releaseInterferences(CallResource);
00764       }
00765     }
00766 
00767   resetVRegCycle(SU);
00768 
00769   SU->isScheduled = true;
00770 
00771   // Conditions under which the scheduler should eagerly advance the cycle:
00772   // (1) No available instructions
00773   // (2) All pipelines full, so available instructions must have hazards.
00774   //
00775   // If HazardRec is disabled, the cycle was pre-advanced before calling
00776   // ReleasePredecessors. In that case, IssueCount should remain 0.
00777   //
00778   // Check AvailableQueue after ReleasePredecessors in case of zero latency.
00779   if (HazardRec->isEnabled() || AvgIPC > 1) {
00780     if (SU->getNode() && SU->getNode()->isMachineOpcode())
00781       ++IssueCount;
00782     if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
00783         || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
00784       AdvanceToCycle(CurCycle + 1);
00785   }
00786 }
00787 
00788 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
00789 /// unscheduled, incrcease the succ left count of its predecessors. Remove
00790 /// them from AvailableQueue if necessary.
00791 void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
00792   SUnit *PredSU = PredEdge->getSUnit();
00793   if (PredSU->isAvailable) {
00794     PredSU->isAvailable = false;
00795     if (!PredSU->isPending)
00796       AvailableQueue->remove(PredSU);
00797   }
00798 
00799   assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
00800   ++PredSU->NumSuccsLeft;
00801 }
00802 
00803 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
00804 /// its predecessor states to reflect the change.
00805 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
00806   DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
00807   DEBUG(SU->dump(this));
00808 
00809   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
00810        I != E; ++I) {
00811     CapturePred(&*I);
00812     if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
00813       assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
00814       assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
00815              "Physical register dependency violated?");
00816       --NumLiveRegs;
00817       LiveRegDefs[I->getReg()] = nullptr;
00818       LiveRegGens[I->getReg()] = nullptr;
00819       releaseInterferences(I->getReg());
00820     }
00821   }
00822 
00823   // Reclaim the special call resource dependence, if this is the beginning
00824   // of a call.
00825   unsigned CallResource = TRI->getNumRegs();
00826   for (const SDNode *SUNode = SU->getNode(); SUNode;
00827        SUNode = SUNode->getGluedNode()) {
00828     if (SUNode->isMachineOpcode() &&
00829         SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
00830       ++NumLiveRegs;
00831       LiveRegDefs[CallResource] = SU;
00832       LiveRegGens[CallResource] = CallSeqEndForStart[SU];
00833     }
00834   }
00835 
00836   // Release the special call resource dependence, if this is the end
00837   // of a call.
00838   if (LiveRegGens[CallResource] == SU)
00839     for (const SDNode *SUNode = SU->getNode(); SUNode;
00840          SUNode = SUNode->getGluedNode()) {
00841       if (SUNode->isMachineOpcode() &&
00842           SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
00843         assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
00844         --NumLiveRegs;
00845         LiveRegDefs[CallResource] = nullptr;
00846         LiveRegGens[CallResource] = nullptr;
00847         releaseInterferences(CallResource);
00848       }
00849     }
00850 
00851   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
00852        I != E; ++I) {
00853     if (I->isAssignedRegDep()) {
00854       if (!LiveRegDefs[I->getReg()])
00855         ++NumLiveRegs;
00856       // This becomes the nearest def. Note that an earlier def may still be
00857       // pending if this is a two-address node.
00858       LiveRegDefs[I->getReg()] = SU;
00859       if (LiveRegGens[I->getReg()] == nullptr ||
00860           I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
00861         LiveRegGens[I->getReg()] = I->getSUnit();
00862     }
00863   }
00864   if (SU->getHeight() < MinAvailableCycle)
00865     MinAvailableCycle = SU->getHeight();
00866 
00867   SU->setHeightDirty();
00868   SU->isScheduled = false;
00869   SU->isAvailable = true;
00870   if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
00871     // Don't make available until backtracking is complete.
00872     SU->isPending = true;
00873     PendingQueue.push_back(SU);
00874   }
00875   else {
00876     AvailableQueue->push(SU);
00877   }
00878   AvailableQueue->unscheduledNode(SU);
00879 }
00880 
00881 /// After backtracking, the hazard checker needs to be restored to a state
00882 /// corresponding the current cycle.
00883 void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
00884   HazardRec->Reset();
00885 
00886   unsigned LookAhead = std::min((unsigned)Sequence.size(),
00887                                 HazardRec->getMaxLookAhead());
00888   if (LookAhead == 0)
00889     return;
00890 
00891   std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
00892   unsigned HazardCycle = (*I)->getHeight();
00893   for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
00894     SUnit *SU = *I;
00895     for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
00896       HazardRec->RecedeCycle();
00897     }
00898     EmitNode(SU);
00899   }
00900 }
00901 
00902 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
00903 /// BTCycle in order to schedule a specific node.
00904 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
00905   SUnit *OldSU = Sequence.back();
00906   while (true) {
00907     Sequence.pop_back();
00908     // FIXME: use ready cycle instead of height
00909     CurCycle = OldSU->getHeight();
00910     UnscheduleNodeBottomUp(OldSU);
00911     AvailableQueue->setCurCycle(CurCycle);
00912     if (OldSU == BtSU)
00913       break;
00914     OldSU = Sequence.back();
00915   }
00916 
00917   assert(!SU->isSucc(OldSU) && "Something is wrong!");
00918 
00919   RestoreHazardCheckerBottomUp();
00920 
00921   ReleasePending();
00922 
00923   ++NumBacktracks;
00924 }
00925 
00926 static bool isOperandOf(const SUnit *SU, SDNode *N) {
00927   for (const SDNode *SUNode = SU->getNode(); SUNode;
00928        SUNode = SUNode->getGluedNode()) {
00929     if (SUNode->isOperandOf(N))
00930       return true;
00931   }
00932   return false;
00933 }
00934 
00935 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
00936 /// successors to the newly created node.
00937 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
00938   SDNode *N = SU->getNode();
00939   if (!N)
00940     return nullptr;
00941 
00942   if (SU->getNode()->getGluedNode())
00943     return nullptr;
00944 
00945   SUnit *NewSU;
00946   bool TryUnfold = false;
00947   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
00948     EVT VT = N->getValueType(i);
00949     if (VT == MVT::Glue)
00950       return nullptr;
00951     else if (VT == MVT::Other)
00952       TryUnfold = true;
00953   }
00954   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00955     const SDValue &Op = N->getOperand(i);
00956     EVT VT = Op.getNode()->getValueType(Op.getResNo());
00957     if (VT == MVT::Glue)
00958       return nullptr;
00959   }
00960 
00961   if (TryUnfold) {
00962     SmallVector<SDNode*, 2> NewNodes;
00963     if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
00964       return nullptr;
00965 
00966     // unfolding an x86 DEC64m operation results in store, dec, load which
00967     // can't be handled here so quit
00968     if (NewNodes.size() == 3)
00969       return nullptr;
00970 
00971     DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
00972     assert(NewNodes.size() == 2 && "Expected a load folding node!");
00973 
00974     N = NewNodes[1];
00975     SDNode *LoadNode = NewNodes[0];
00976     unsigned NumVals = N->getNumValues();
00977     unsigned OldNumVals = SU->getNode()->getNumValues();
00978     for (unsigned i = 0; i != NumVals; ++i)
00979       DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
00980     DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
00981                                    SDValue(LoadNode, 1));
00982 
00983     // LoadNode may already exist. This can happen when there is another
00984     // load from the same location and producing the same type of value
00985     // but it has different alignment or volatileness.
00986     bool isNewLoad = true;
00987     SUnit *LoadSU;
00988     if (LoadNode->getNodeId() != -1) {
00989       LoadSU = &SUnits[LoadNode->getNodeId()];
00990       isNewLoad = false;
00991     } else {
00992       LoadSU = CreateNewSUnit(LoadNode);
00993       LoadNode->setNodeId(LoadSU->NodeNum);
00994 
00995       InitNumRegDefsLeft(LoadSU);
00996       computeLatency(LoadSU);
00997     }
00998 
00999     SUnit *NewSU = CreateNewSUnit(N);
01000     assert(N->getNodeId() == -1 && "Node already inserted!");
01001     N->setNodeId(NewSU->NodeNum);
01002 
01003     const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
01004     for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
01005       if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
01006         NewSU->isTwoAddress = true;
01007         break;
01008       }
01009     }
01010     if (MCID.isCommutable())
01011       NewSU->isCommutable = true;
01012 
01013     InitNumRegDefsLeft(NewSU);
01014     computeLatency(NewSU);
01015 
01016     // Record all the edges to and from the old SU, by category.
01017     SmallVector<SDep, 4> ChainPreds;
01018     SmallVector<SDep, 4> ChainSuccs;
01019     SmallVector<SDep, 4> LoadPreds;
01020     SmallVector<SDep, 4> NodePreds;
01021     SmallVector<SDep, 4> NodeSuccs;
01022     for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
01023          I != E; ++I) {
01024       if (I->isCtrl())
01025         ChainPreds.push_back(*I);
01026       else if (isOperandOf(I->getSUnit(), LoadNode))
01027         LoadPreds.push_back(*I);
01028       else
01029         NodePreds.push_back(*I);
01030     }
01031     for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
01032          I != E; ++I) {
01033       if (I->isCtrl())
01034         ChainSuccs.push_back(*I);
01035       else
01036         NodeSuccs.push_back(*I);
01037     }
01038 
01039     // Now assign edges to the newly-created nodes.
01040     for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
01041       const SDep &Pred = ChainPreds[i];
01042       RemovePred(SU, Pred);
01043       if (isNewLoad)
01044         AddPred(LoadSU, Pred);
01045     }
01046     for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
01047       const SDep &Pred = LoadPreds[i];
01048       RemovePred(SU, Pred);
01049       if (isNewLoad)
01050         AddPred(LoadSU, Pred);
01051     }
01052     for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
01053       const SDep &Pred = NodePreds[i];
01054       RemovePred(SU, Pred);
01055       AddPred(NewSU, Pred);
01056     }
01057     for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
01058       SDep D = NodeSuccs[i];
01059       SUnit *SuccDep = D.getSUnit();
01060       D.setSUnit(SU);
01061       RemovePred(SuccDep, D);
01062       D.setSUnit(NewSU);
01063       AddPred(SuccDep, D);
01064       // Balance register pressure.
01065       if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
01066           && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
01067         --NewSU->NumRegDefsLeft;
01068     }
01069     for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
01070       SDep D = ChainSuccs[i];
01071       SUnit *SuccDep = D.getSUnit();
01072       D.setSUnit(SU);
01073       RemovePred(SuccDep, D);
01074       if (isNewLoad) {
01075         D.setSUnit(LoadSU);
01076         AddPred(SuccDep, D);
01077       }
01078     }
01079 
01080     // Add a data dependency to reflect that NewSU reads the value defined
01081     // by LoadSU.
01082     SDep D(LoadSU, SDep::Data, 0);
01083     D.setLatency(LoadSU->Latency);
01084     AddPred(NewSU, D);
01085 
01086     if (isNewLoad)
01087       AvailableQueue->addNode(LoadSU);
01088     AvailableQueue->addNode(NewSU);
01089 
01090     ++NumUnfolds;
01091 
01092     if (NewSU->NumSuccsLeft == 0) {
01093       NewSU->isAvailable = true;
01094       return NewSU;
01095     }
01096     SU = NewSU;
01097   }
01098 
01099   DEBUG(dbgs() << "    Duplicating SU #" << SU->NodeNum << "\n");
01100   NewSU = CreateClone(SU);
01101 
01102   // New SUnit has the exact same predecessors.
01103   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
01104        I != E; ++I)
01105     if (!I->isArtificial())
01106       AddPred(NewSU, *I);
01107 
01108   // Only copy scheduled successors. Cut them from old node's successor
01109   // list and move them over.
01110   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
01111   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
01112        I != E; ++I) {
01113     if (I->isArtificial())
01114       continue;
01115     SUnit *SuccSU = I->getSUnit();
01116     if (SuccSU->isScheduled) {
01117       SDep D = *I;
01118       D.setSUnit(NewSU);
01119       AddPred(SuccSU, D);
01120       D.setSUnit(SU);
01121       DelDeps.push_back(std::make_pair(SuccSU, D));
01122     }
01123   }
01124   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
01125     RemovePred(DelDeps[i].first, DelDeps[i].second);
01126 
01127   AvailableQueue->updateNode(SU);
01128   AvailableQueue->addNode(NewSU);
01129 
01130   ++NumDups;
01131   return NewSU;
01132 }
01133 
01134 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
01135 /// scheduled successors of the given SUnit to the last copy.
01136 void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
01137                                               const TargetRegisterClass *DestRC,
01138                                               const TargetRegisterClass *SrcRC,
01139                                               SmallVectorImpl<SUnit*> &Copies) {
01140   SUnit *CopyFromSU = CreateNewSUnit(nullptr);
01141   CopyFromSU->CopySrcRC = SrcRC;
01142   CopyFromSU->CopyDstRC = DestRC;
01143 
01144   SUnit *CopyToSU = CreateNewSUnit(nullptr);
01145   CopyToSU->CopySrcRC = DestRC;
01146   CopyToSU->CopyDstRC = SrcRC;
01147 
01148   // Only copy scheduled successors. Cut them from old node's successor
01149   // list and move them over.
01150   SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
01151   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
01152        I != E; ++I) {
01153     if (I->isArtificial())
01154       continue;
01155     SUnit *SuccSU = I->getSUnit();
01156     if (SuccSU->isScheduled) {
01157       SDep D = *I;
01158       D.setSUnit(CopyToSU);
01159       AddPred(SuccSU, D);
01160       DelDeps.push_back(std::make_pair(SuccSU, *I));
01161     }
01162     else {
01163       // Avoid scheduling the def-side copy before other successors. Otherwise
01164       // we could introduce another physreg interference on the copy and
01165       // continue inserting copies indefinitely.
01166       AddPred(SuccSU, SDep(CopyFromSU, SDep::Artificial));
01167     }
01168   }
01169   for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
01170     RemovePred(DelDeps[i].first, DelDeps[i].second);
01171 
01172   SDep FromDep(SU, SDep::Data, Reg);
01173   FromDep.setLatency(SU->Latency);
01174   AddPred(CopyFromSU, FromDep);
01175   SDep ToDep(CopyFromSU, SDep::Data, 0);
01176   ToDep.setLatency(CopyFromSU->Latency);
01177   AddPred(CopyToSU, ToDep);
01178 
01179   AvailableQueue->updateNode(SU);
01180   AvailableQueue->addNode(CopyFromSU);
01181   AvailableQueue->addNode(CopyToSU);
01182   Copies.push_back(CopyFromSU);
01183   Copies.push_back(CopyToSU);
01184 
01185   ++NumPRCopies;
01186 }
01187 
01188 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
01189 /// definition of the specified node.
01190 /// FIXME: Move to SelectionDAG?
01191 static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
01192                                  const TargetInstrInfo *TII) {
01193   unsigned NumRes;
01194   if (N->getOpcode() == ISD::CopyFromReg) {
01195     // CopyFromReg has: "chain, Val, glue" so operand 1 gives the type.
01196     NumRes = 1;
01197   } else {
01198     const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
01199     assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
01200     NumRes = MCID.getNumDefs();
01201     for (const uint16_t *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
01202       if (Reg == *ImpDef)
01203         break;
01204       ++NumRes;
01205     }
01206   }
01207   return N->getValueType(NumRes);
01208 }
01209 
01210 /// CheckForLiveRegDef - Return true and update live register vector if the
01211 /// specified register def of the specified SUnit clobbers any "live" registers.
01212 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
01213                                std::vector<SUnit*> &LiveRegDefs,
01214                                SmallSet<unsigned, 4> &RegAdded,
01215                                SmallVectorImpl<unsigned> &LRegs,
01216                                const TargetRegisterInfo *TRI) {
01217   for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
01218 
01219     // Check if Ref is live.
01220     if (!LiveRegDefs[*AliasI]) continue;
01221 
01222     // Allow multiple uses of the same def.
01223     if (LiveRegDefs[*AliasI] == SU) continue;
01224 
01225     // Add Reg to the set of interfering live regs.
01226     if (RegAdded.insert(*AliasI)) {
01227       LRegs.push_back(*AliasI);
01228     }
01229   }
01230 }
01231 
01232 /// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
01233 /// by RegMask, and add them to LRegs.
01234 static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
01235                                      std::vector<SUnit*> &LiveRegDefs,
01236                                      SmallSet<unsigned, 4> &RegAdded,
01237                                      SmallVectorImpl<unsigned> &LRegs) {
01238   // Look at all live registers. Skip Reg0 and the special CallResource.
01239   for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
01240     if (!LiveRegDefs[i]) continue;
01241     if (LiveRegDefs[i] == SU) continue;
01242     if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
01243     if (RegAdded.insert(i))
01244       LRegs.push_back(i);
01245   }
01246 }
01247 
01248 /// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
01249 static const uint32_t *getNodeRegMask(const SDNode *N) {
01250   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
01251     if (const RegisterMaskSDNode *Op =
01252         dyn_cast<RegisterMaskSDNode>(N->getOperand(i).getNode()))
01253       return Op->getRegMask();
01254   return nullptr;
01255 }
01256 
01257 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
01258 /// scheduling of the given node to satisfy live physical register dependencies.
01259 /// If the specific node is the last one that's available to schedule, do
01260 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
01261 bool ScheduleDAGRRList::
01262 DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) {
01263   if (NumLiveRegs == 0)
01264     return false;
01265 
01266   SmallSet<unsigned, 4> RegAdded;
01267   // If this node would clobber any "live" register, then it's not ready.
01268   //
01269   // If SU is the currently live definition of the same register that it uses,
01270   // then we are free to schedule it.
01271   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
01272        I != E; ++I) {
01273     if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
01274       CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
01275                          RegAdded, LRegs, TRI);
01276   }
01277 
01278   for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
01279     if (Node->getOpcode() == ISD::INLINEASM) {
01280       // Inline asm can clobber physical defs.
01281       unsigned NumOps = Node->getNumOperands();
01282       if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
01283         --NumOps;  // Ignore the glue operand.
01284 
01285       for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
01286         unsigned Flags =
01287           cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
01288         unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
01289 
01290         ++i; // Skip the ID value.
01291         if (InlineAsm::isRegDefKind(Flags) ||
01292             InlineAsm::isRegDefEarlyClobberKind(Flags) ||
01293             InlineAsm::isClobberKind(Flags)) {
01294           // Check for def of register or earlyclobber register.
01295           for (; NumVals; --NumVals, ++i) {
01296             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
01297             if (TargetRegisterInfo::isPhysicalRegister(Reg))
01298               CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
01299           }
01300         } else
01301           i += NumVals;
01302       }
01303       continue;
01304     }
01305 
01306     if (!Node->isMachineOpcode())
01307       continue;
01308     // If we're in the middle of scheduling a call, don't begin scheduling
01309     // another call. Also, don't allow any physical registers to be live across
01310     // the call.
01311     if (Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
01312       // Check the special calling-sequence resource.
01313       unsigned CallResource = TRI->getNumRegs();
01314       if (LiveRegDefs[CallResource]) {
01315         SDNode *Gen = LiveRegGens[CallResource]->getNode();
01316         while (SDNode *Glued = Gen->getGluedNode())
01317           Gen = Glued;
01318         if (!IsChainDependent(Gen, Node, 0, TII) && RegAdded.insert(CallResource))
01319           LRegs.push_back(CallResource);
01320       }
01321     }
01322     if (const uint32_t *RegMask = getNodeRegMask(Node))
01323       CheckForLiveRegDefMasked(SU, RegMask, LiveRegDefs, RegAdded, LRegs);
01324 
01325     const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
01326     if (!MCID.ImplicitDefs)
01327       continue;
01328     for (const uint16_t *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
01329       CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
01330   }
01331 
01332   return !LRegs.empty();
01333 }
01334 
01335 void ScheduleDAGRRList::releaseInterferences(unsigned Reg) {
01336   // Add the nodes that aren't ready back onto the available list.
01337   for (unsigned i = Interferences.size(); i > 0; --i) {
01338     SUnit *SU = Interferences[i-1];
01339     LRegsMapT::iterator LRegsPos = LRegsMap.find(SU);
01340     if (Reg) {
01341       SmallVectorImpl<unsigned> &LRegs = LRegsPos->second;
01342       if (std::find(LRegs.begin(), LRegs.end(), Reg) == LRegs.end())
01343         continue;
01344     }
01345     SU->isPending = false;
01346     // The interfering node may no longer be available due to backtracking.
01347     // Furthermore, it may have been made available again, in which case it is
01348     // now already in the AvailableQueue.
01349     if (SU->isAvailable && !SU->NodeQueueId) {
01350       DEBUG(dbgs() << "    Repushing SU #" << SU->NodeNum << '\n');
01351       AvailableQueue->push(SU);
01352     }
01353     if (i < Interferences.size())
01354       Interferences[i-1] = Interferences.back();
01355     Interferences.pop_back();
01356     LRegsMap.erase(LRegsPos);
01357   }
01358 }
01359 
01360 /// Return a node that can be scheduled in this cycle. Requirements:
01361 /// (1) Ready: latency has been satisfied
01362 /// (2) No Hazards: resources are available
01363 /// (3) No Interferences: may unschedule to break register interferences.
01364 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
01365   SUnit *CurSU = AvailableQueue->empty() ? nullptr : AvailableQueue->pop();
01366   while (CurSU) {
01367     SmallVector<unsigned, 4> LRegs;
01368     if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
01369       break;
01370     DEBUG(dbgs() << "    Interfering reg " <<
01371           (LRegs[0] == TRI->getNumRegs() ? "CallResource"
01372            : TRI->getName(LRegs[0]))
01373            << " SU #" << CurSU->NodeNum << '\n');
01374     std::pair<LRegsMapT::iterator, bool> LRegsPair =
01375       LRegsMap.insert(std::make_pair(CurSU, LRegs));
01376     if (LRegsPair.second) {
01377       CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
01378       Interferences.push_back(CurSU);
01379     }
01380     else {
01381       assert(CurSU->isPending && "Interferences are pending");
01382       // Update the interference with current live regs.
01383       LRegsPair.first->second = LRegs;
01384     }
01385     CurSU = AvailableQueue->pop();
01386   }
01387   if (CurSU)
01388     return CurSU;
01389 
01390   // All candidates are delayed due to live physical reg dependencies.
01391   // Try backtracking, code duplication, or inserting cross class copies
01392   // to resolve it.
01393   for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
01394     SUnit *TrySU = Interferences[i];
01395     SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
01396 
01397     // Try unscheduling up to the point where it's safe to schedule
01398     // this node.
01399     SUnit *BtSU = nullptr;
01400     unsigned LiveCycle = UINT_MAX;
01401     for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
01402       unsigned Reg = LRegs[j];
01403       if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
01404         BtSU = LiveRegGens[Reg];
01405         LiveCycle = BtSU->getHeight();
01406       }
01407     }
01408     if (!WillCreateCycle(TrySU, BtSU))  {
01409       // BacktrackBottomUp mutates Interferences!
01410       BacktrackBottomUp(TrySU, BtSU);
01411 
01412       // Force the current node to be scheduled before the node that
01413       // requires the physical reg dep.
01414       if (BtSU->isAvailable) {
01415         BtSU->isAvailable = false;
01416         if (!BtSU->isPending)
01417           AvailableQueue->remove(BtSU);
01418       }
01419       DEBUG(dbgs() << "ARTIFICIAL edge from SU(" << BtSU->NodeNum << ") to SU("
01420             << TrySU->NodeNum << ")\n");
01421       AddPred(TrySU, SDep(BtSU, SDep::Artificial));
01422 
01423       // If one or more successors has been unscheduled, then the current
01424       // node is no longer available.
01425       if (!TrySU->isAvailable)
01426         CurSU = AvailableQueue->pop();
01427       else {
01428         AvailableQueue->remove(TrySU);
01429         CurSU = TrySU;
01430       }
01431       // Interferences has been mutated. We must break.
01432       break;
01433     }
01434   }
01435 
01436   if (!CurSU) {
01437     // Can't backtrack. If it's too expensive to copy the value, then try
01438     // duplicate the nodes that produces these "too expensive to copy"
01439     // values to break the dependency. In case even that doesn't work,
01440     // insert cross class copies.
01441     // If it's not too expensive, i.e. cost != -1, issue copies.
01442     SUnit *TrySU = Interferences[0];
01443     SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
01444     assert(LRegs.size() == 1 && "Can't handle this yet!");
01445     unsigned Reg = LRegs[0];
01446     SUnit *LRDef = LiveRegDefs[Reg];
01447     EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
01448     const TargetRegisterClass *RC =
01449       TRI->getMinimalPhysRegClass(Reg, VT);
01450     const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
01451 
01452     // If cross copy register class is the same as RC, then it must be possible
01453     // copy the value directly. Do not try duplicate the def.
01454     // If cross copy register class is not the same as RC, then it's possible to
01455     // copy the value but it require cross register class copies and it is
01456     // expensive.
01457     // If cross copy register class is null, then it's not possible to copy
01458     // the value at all.
01459     SUnit *NewDef = nullptr;
01460     if (DestRC != RC) {
01461       NewDef = CopyAndMoveSuccessors(LRDef);
01462       if (!DestRC && !NewDef)
01463         report_fatal_error("Can't handle live physical register dependency!");
01464     }
01465     if (!NewDef) {
01466       // Issue copies, these can be expensive cross register class copies.
01467       SmallVector<SUnit*, 2> Copies;
01468       InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
01469       DEBUG(dbgs() << "    Adding an edge from SU #" << TrySU->NodeNum
01470             << " to SU #" << Copies.front()->NodeNum << "\n");
01471       AddPred(TrySU, SDep(Copies.front(), SDep::Artificial));
01472       NewDef = Copies.back();
01473     }
01474 
01475     DEBUG(dbgs() << "    Adding an edge from SU #" << NewDef->NodeNum
01476           << " to SU #" << TrySU->NodeNum << "\n");
01477     LiveRegDefs[Reg] = NewDef;
01478     AddPred(NewDef, SDep(TrySU, SDep::Artificial));
01479     TrySU->isAvailable = false;
01480     CurSU = NewDef;
01481   }
01482   assert(CurSU && "Unable to resolve live physical register dependencies!");
01483   return CurSU;
01484 }
01485 
01486 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
01487 /// schedulers.
01488 void ScheduleDAGRRList::ListScheduleBottomUp() {
01489   // Release any predecessors of the special Exit node.
01490   ReleasePredecessors(&ExitSU);
01491 
01492   // Add root to Available queue.
01493   if (!SUnits.empty()) {
01494     SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
01495     assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
01496     RootSU->isAvailable = true;
01497     AvailableQueue->push(RootSU);
01498   }
01499 
01500   // While Available queue is not empty, grab the node with the highest
01501   // priority. If it is not ready put it back.  Schedule the node.
01502   Sequence.reserve(SUnits.size());
01503   while (!AvailableQueue->empty() || !Interferences.empty()) {
01504     DEBUG(dbgs() << "\nExamining Available:\n";
01505           AvailableQueue->dump(this));
01506 
01507     // Pick the best node to schedule taking all constraints into
01508     // consideration.
01509     SUnit *SU = PickNodeToScheduleBottomUp();
01510 
01511     AdvancePastStalls(SU);
01512 
01513     ScheduleNodeBottomUp(SU);
01514 
01515     while (AvailableQueue->empty() && !PendingQueue.empty()) {
01516       // Advance the cycle to free resources. Skip ahead to the next ready SU.
01517       assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
01518       AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
01519     }
01520   }
01521 
01522   // Reverse the order if it is bottom up.
01523   std::reverse(Sequence.begin(), Sequence.end());
01524 
01525 #ifndef NDEBUG
01526   VerifyScheduledSequence(/*isBottomUp=*/true);
01527 #endif
01528 }
01529 
01530 //===----------------------------------------------------------------------===//
01531 //                RegReductionPriorityQueue Definition
01532 //===----------------------------------------------------------------------===//
01533 //
01534 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
01535 // to reduce register pressure.
01536 //
01537 namespace {
01538 class RegReductionPQBase;
01539 
01540 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
01541   bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
01542 };
01543 
01544 #ifndef NDEBUG
01545 template<class SF>
01546 struct reverse_sort : public queue_sort {
01547   SF &SortFunc;
01548   reverse_sort(SF &sf) : SortFunc(sf) {}
01549 
01550   bool operator()(SUnit* left, SUnit* right) const {
01551     // reverse left/right rather than simply !SortFunc(left, right)
01552     // to expose different paths in the comparison logic.
01553     return SortFunc(right, left);
01554   }
01555 };
01556 #endif // NDEBUG
01557 
01558 /// bu_ls_rr_sort - Priority function for bottom up register pressure
01559 // reduction scheduler.
01560 struct bu_ls_rr_sort : public queue_sort {
01561   enum {
01562     IsBottomUp = true,
01563     HasReadyFilter = false
01564   };
01565 
01566   RegReductionPQBase *SPQ;
01567   bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
01568 
01569   bool operator()(SUnit* left, SUnit* right) const;
01570 };
01571 
01572 // src_ls_rr_sort - Priority function for source order scheduler.
01573 struct src_ls_rr_sort : public queue_sort {
01574   enum {
01575     IsBottomUp = true,
01576     HasReadyFilter = false
01577   };
01578 
01579   RegReductionPQBase *SPQ;
01580   src_ls_rr_sort(RegReductionPQBase *spq)
01581     : SPQ(spq) {}
01582 
01583   bool operator()(SUnit* left, SUnit* right) const;
01584 };
01585 
01586 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
01587 struct hybrid_ls_rr_sort : public queue_sort {
01588   enum {
01589     IsBottomUp = true,
01590     HasReadyFilter = false
01591   };
01592 
01593   RegReductionPQBase *SPQ;
01594   hybrid_ls_rr_sort(RegReductionPQBase *spq)
01595     : SPQ(spq) {}
01596 
01597   bool isReady(SUnit *SU, unsigned CurCycle) const;
01598 
01599   bool operator()(SUnit* left, SUnit* right) const;
01600 };
01601 
01602 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
01603 // scheduler.
01604 struct ilp_ls_rr_sort : public queue_sort {
01605   enum {
01606     IsBottomUp = true,
01607     HasReadyFilter = false
01608   };
01609 
01610   RegReductionPQBase *SPQ;
01611   ilp_ls_rr_sort(RegReductionPQBase *spq)
01612     : SPQ(spq) {}
01613 
01614   bool isReady(SUnit *SU, unsigned CurCycle) const;
01615 
01616   bool operator()(SUnit* left, SUnit* right) const;
01617 };
01618 
01619 class RegReductionPQBase : public SchedulingPriorityQueue {
01620 protected:
01621   std::vector<SUnit*> Queue;
01622   unsigned CurQueueId;
01623   bool TracksRegPressure;
01624   bool SrcOrder;
01625 
01626   // SUnits - The SUnits for the current graph.
01627   std::vector<SUnit> *SUnits;
01628 
01629   MachineFunction &MF;
01630   const TargetInstrInfo *TII;
01631   const TargetRegisterInfo *TRI;
01632   const TargetLowering *TLI;
01633   ScheduleDAGRRList *scheduleDAG;
01634 
01635   // SethiUllmanNumbers - The SethiUllman number for each node.
01636   std::vector<unsigned> SethiUllmanNumbers;
01637 
01638   /// RegPressure - Tracking current reg pressure per register class.
01639   ///
01640   std::vector<unsigned> RegPressure;
01641 
01642   /// RegLimit - Tracking the number of allocatable registers per register
01643   /// class.
01644   std::vector<unsigned> RegLimit;
01645 
01646 public:
01647   RegReductionPQBase(MachineFunction &mf,
01648                      bool hasReadyFilter,
01649                      bool tracksrp,
01650                      bool srcorder,
01651                      const TargetInstrInfo *tii,
01652                      const TargetRegisterInfo *tri,
01653                      const TargetLowering *tli)
01654     : SchedulingPriorityQueue(hasReadyFilter),
01655       CurQueueId(0), TracksRegPressure(tracksrp), SrcOrder(srcorder),
01656       MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(nullptr) {
01657     if (TracksRegPressure) {
01658       unsigned NumRC = TRI->getNumRegClasses();
01659       RegLimit.resize(NumRC);
01660       RegPressure.resize(NumRC);
01661       std::fill(RegLimit.begin(), RegLimit.end(), 0);
01662       std::fill(RegPressure.begin(), RegPressure.end(), 0);
01663       for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
01664              E = TRI->regclass_end(); I != E; ++I)
01665         RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
01666     }
01667   }
01668 
01669   void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
01670     scheduleDAG = scheduleDag;
01671   }
01672 
01673   ScheduleHazardRecognizer* getHazardRec() {
01674     return scheduleDAG->getHazardRec();
01675   }
01676 
01677   void initNodes(std::vector<SUnit> &sunits) override;
01678 
01679   void addNode(const SUnit *SU) override;
01680 
01681   void updateNode(const SUnit *SU) override;
01682 
01683   void releaseState() override {
01684     SUnits = nullptr;
01685     SethiUllmanNumbers.clear();
01686     std::fill(RegPressure.begin(), RegPressure.end(), 0);
01687   }
01688 
01689   unsigned getNodePriority(const SUnit *SU) const;
01690 
01691   unsigned getNodeOrdering(const SUnit *SU) const {
01692     if (!SU->getNode()) return 0;
01693 
01694     return SU->getNode()->getIROrder();
01695   }
01696 
01697   bool empty() const override { return Queue.empty(); }
01698 
01699   void push(SUnit *U) override {
01700     assert(!U->NodeQueueId && "Node in the queue already");
01701     U->NodeQueueId = ++CurQueueId;
01702     Queue.push_back(U);
01703   }
01704 
01705   void remove(SUnit *SU) override {
01706     assert(!Queue.empty() && "Queue is empty!");
01707     assert(SU->NodeQueueId != 0 && "Not in queue!");
01708     std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
01709                                                  SU);
01710     if (I != std::prev(Queue.end()))
01711       std::swap(*I, Queue.back());
01712     Queue.pop_back();
01713     SU->NodeQueueId = 0;
01714   }
01715 
01716   bool tracksRegPressure() const override { return TracksRegPressure; }
01717 
01718   void dumpRegPressure() const;
01719 
01720   bool HighRegPressure(const SUnit *SU) const;
01721 
01722   bool MayReduceRegPressure(SUnit *SU) const;
01723 
01724   int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
01725 
01726   void scheduledNode(SUnit *SU) override;
01727 
01728   void unscheduledNode(SUnit *SU) override;
01729 
01730 protected:
01731   bool canClobber(const SUnit *SU, const SUnit *Op);
01732   void AddPseudoTwoAddrDeps();
01733   void PrescheduleNodesWithMultipleUses();
01734   void CalculateSethiUllmanNumbers();
01735 };
01736 
01737 template<class SF>
01738 static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
01739   std::vector<SUnit *>::iterator Best = Q.begin();
01740   for (std::vector<SUnit *>::iterator I = std::next(Q.begin()),
01741          E = Q.end(); I != E; ++I)
01742     if (Picker(*Best, *I))
01743       Best = I;
01744   SUnit *V = *Best;
01745   if (Best != std::prev(Q.end()))
01746     std::swap(*Best, Q.back());
01747   Q.pop_back();
01748   return V;
01749 }
01750 
01751 template<class SF>
01752 SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
01753 #ifndef NDEBUG
01754   if (DAG->StressSched) {
01755     reverse_sort<SF> RPicker(Picker);
01756     return popFromQueueImpl(Q, RPicker);
01757   }
01758 #endif
01759   (void)DAG;
01760   return popFromQueueImpl(Q, Picker);
01761 }
01762 
01763 template<class SF>
01764 class RegReductionPriorityQueue : public RegReductionPQBase {
01765   SF Picker;
01766 
01767 public:
01768   RegReductionPriorityQueue(MachineFunction &mf,
01769                             bool tracksrp,
01770                             bool srcorder,
01771                             const TargetInstrInfo *tii,
01772                             const TargetRegisterInfo *tri,
01773                             const TargetLowering *tli)
01774     : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
01775                          tii, tri, tli),
01776       Picker(this) {}
01777 
01778   bool isBottomUp() const override { return SF::IsBottomUp; }
01779 
01780   bool isReady(SUnit *U) const override {
01781     return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
01782   }
01783 
01784   SUnit *pop() override {
01785     if (Queue.empty()) return nullptr;
01786 
01787     SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
01788     V->NodeQueueId = 0;
01789     return V;
01790   }
01791 
01792 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01793   void dump(ScheduleDAG *DAG) const override {
01794     // Emulate pop() without clobbering NodeQueueIds.
01795     std::vector<SUnit*> DumpQueue = Queue;
01796     SF DumpPicker = Picker;
01797     while (!DumpQueue.empty()) {
01798       SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
01799       dbgs() << "Height " << SU->getHeight() << ": ";
01800       SU->dump(DAG);
01801     }
01802   }
01803 #endif
01804 };
01805 
01806 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
01807 BURegReductionPriorityQueue;
01808 
01809 typedef RegReductionPriorityQueue<src_ls_rr_sort>
01810 SrcRegReductionPriorityQueue;
01811 
01812 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
01813 HybridBURRPriorityQueue;
01814 
01815 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
01816 ILPBURRPriorityQueue;
01817 } // end anonymous namespace
01818 
01819 //===----------------------------------------------------------------------===//
01820 //           Static Node Priority for Register Pressure Reduction
01821 //===----------------------------------------------------------------------===//
01822 
01823 // Check for special nodes that bypass scheduling heuristics.
01824 // Currently this pushes TokenFactor nodes down, but may be used for other
01825 // pseudo-ops as well.
01826 //
01827 // Return -1 to schedule right above left, 1 for left above right.
01828 // Return 0 if no bias exists.
01829 static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
01830   bool LSchedLow = left->isScheduleLow;
01831   bool RSchedLow = right->isScheduleLow;
01832   if (LSchedLow != RSchedLow)
01833     return LSchedLow < RSchedLow ? 1 : -1;
01834   return 0;
01835 }
01836 
01837 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
01838 /// Smaller number is the higher priority.
01839 static unsigned
01840 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
01841   unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
01842   if (SethiUllmanNumber != 0)
01843     return SethiUllmanNumber;
01844 
01845   unsigned Extra = 0;
01846   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
01847        I != E; ++I) {
01848     if (I->isCtrl()) continue;  // ignore chain preds
01849     SUnit *PredSU = I->getSUnit();
01850     unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
01851     if (PredSethiUllman > SethiUllmanNumber) {
01852       SethiUllmanNumber = PredSethiUllman;
01853       Extra = 0;
01854     } else if (PredSethiUllman == SethiUllmanNumber)
01855       ++Extra;
01856   }
01857 
01858   SethiUllmanNumber += Extra;
01859 
01860   if (SethiUllmanNumber == 0)
01861     SethiUllmanNumber = 1;
01862 
01863   return SethiUllmanNumber;
01864 }
01865 
01866 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
01867 /// scheduling units.
01868 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
01869   SethiUllmanNumbers.assign(SUnits->size(), 0);
01870 
01871   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
01872     CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
01873 }
01874 
01875 void RegReductionPQBase::addNode(const SUnit *SU) {
01876   unsigned SUSize = SethiUllmanNumbers.size();
01877   if (SUnits->size() > SUSize)
01878     SethiUllmanNumbers.resize(SUSize*2, 0);
01879   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
01880 }
01881 
01882 void RegReductionPQBase::updateNode(const SUnit *SU) {
01883   SethiUllmanNumbers[SU->NodeNum] = 0;
01884   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
01885 }
01886 
01887 // Lower priority means schedule further down. For bottom-up scheduling, lower
01888 // priority SUs are scheduled before higher priority SUs.
01889 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
01890   assert(SU->NodeNum < SethiUllmanNumbers.size());
01891   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
01892   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
01893     // CopyToReg should be close to its uses to facilitate coalescing and
01894     // avoid spilling.
01895     return 0;
01896   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
01897       Opc == TargetOpcode::SUBREG_TO_REG ||
01898       Opc == TargetOpcode::INSERT_SUBREG)
01899     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
01900     // close to their uses to facilitate coalescing.
01901     return 0;
01902   if (SU->NumSuccs == 0 && SU->NumPreds != 0)
01903     // If SU does not have a register use, i.e. it doesn't produce a value
01904     // that would be consumed (e.g. store), then it terminates a chain of
01905     // computation.  Give it a large SethiUllman number so it will be
01906     // scheduled right before its predecessors that it doesn't lengthen
01907     // their live ranges.
01908     return 0xffff;
01909   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
01910     // If SU does not have a register def, schedule it close to its uses
01911     // because it does not lengthen any live ranges.
01912     return 0;
01913 #if 1
01914   return SethiUllmanNumbers[SU->NodeNum];
01915 #else
01916   unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
01917   if (SU->isCallOp) {
01918     // FIXME: This assumes all of the defs are used as call operands.
01919     int NP = (int)Priority - SU->getNode()->getNumValues();
01920     return (NP > 0) ? NP : 0;
01921   }
01922   return Priority;
01923 #endif
01924 }
01925 
01926 //===----------------------------------------------------------------------===//
01927 //                     Register Pressure Tracking
01928 //===----------------------------------------------------------------------===//
01929 
01930 void RegReductionPQBase::dumpRegPressure() const {
01931 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01932   for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
01933          E = TRI->regclass_end(); I != E; ++I) {
01934     const TargetRegisterClass *RC = *I;
01935     unsigned Id = RC->getID();
01936     unsigned RP = RegPressure[Id];
01937     if (!RP) continue;
01938     DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
01939           << '\n');
01940   }
01941 #endif
01942 }
01943 
01944 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
01945   if (!TLI)
01946     return false;
01947 
01948   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
01949        I != E; ++I) {
01950     if (I->isCtrl())
01951       continue;
01952     SUnit *PredSU = I->getSUnit();
01953     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
01954     // to cover the number of registers defined (they are all live).
01955     if (PredSU->NumRegDefsLeft == 0) {
01956       continue;
01957     }
01958     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
01959          RegDefPos.IsValid(); RegDefPos.Advance()) {
01960       unsigned RCId, Cost;
01961       GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
01962 
01963       if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
01964         return true;
01965     }
01966   }
01967   return false;
01968 }
01969 
01970 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
01971   const SDNode *N = SU->getNode();
01972 
01973   if (!N->isMachineOpcode() || !SU->NumSuccs)
01974     return false;
01975 
01976   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
01977   for (unsigned i = 0; i != NumDefs; ++i) {
01978     MVT VT = N->getSimpleValueType(i);
01979     if (!N->hasAnyUseOfValue(i))
01980       continue;
01981     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
01982     if (RegPressure[RCId] >= RegLimit[RCId])
01983       return true;
01984   }
01985   return false;
01986 }
01987 
01988 // Compute the register pressure contribution by this instruction by count up
01989 // for uses that are not live and down for defs. Only count register classes
01990 // that are already under high pressure. As a side effect, compute the number of
01991 // uses of registers that are already live.
01992 //
01993 // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
01994 // so could probably be factored.
01995 int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
01996   LiveUses = 0;
01997   int PDiff = 0;
01998   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
01999        I != E; ++I) {
02000     if (I->isCtrl())
02001       continue;
02002     SUnit *PredSU = I->getSUnit();
02003     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
02004     // to cover the number of registers defined (they are all live).
02005     if (PredSU->NumRegDefsLeft == 0) {
02006       if (PredSU->getNode()->isMachineOpcode())
02007         ++LiveUses;
02008       continue;
02009     }
02010     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
02011          RegDefPos.IsValid(); RegDefPos.Advance()) {
02012       MVT VT = RegDefPos.GetValue();
02013       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02014       if (RegPressure[RCId] >= RegLimit[RCId])
02015         ++PDiff;
02016     }
02017   }
02018   const SDNode *N = SU->getNode();
02019 
02020   if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
02021     return PDiff;
02022 
02023   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
02024   for (unsigned i = 0; i != NumDefs; ++i) {
02025     MVT VT = N->getSimpleValueType(i);
02026     if (!N->hasAnyUseOfValue(i))
02027       continue;
02028     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02029     if (RegPressure[RCId] >= RegLimit[RCId])
02030       --PDiff;
02031   }
02032   return PDiff;
02033 }
02034 
02035 void RegReductionPQBase::scheduledNode(SUnit *SU) {
02036   if (!TracksRegPressure)
02037     return;
02038 
02039   if (!SU->getNode())
02040     return;
02041 
02042   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02043        I != E; ++I) {
02044     if (I->isCtrl())
02045       continue;
02046     SUnit *PredSU = I->getSUnit();
02047     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
02048     // to cover the number of registers defined (they are all live).
02049     if (PredSU->NumRegDefsLeft == 0) {
02050       continue;
02051     }
02052     // FIXME: The ScheduleDAG currently loses information about which of a
02053     // node's values is consumed by each dependence. Consequently, if the node
02054     // defines multiple register classes, we don't know which to pressurize
02055     // here. Instead the following loop consumes the register defs in an
02056     // arbitrary order. At least it handles the common case of clustered loads
02057     // to the same class. For precise liveness, each SDep needs to indicate the
02058     // result number. But that tightly couples the ScheduleDAG with the
02059     // SelectionDAG making updates tricky. A simpler hack would be to attach a
02060     // value type or register class to SDep.
02061     //
02062     // The most important aspect of register tracking is balancing the increase
02063     // here with the reduction further below. Note that this SU may use multiple
02064     // defs in PredSU. The can't be determined here, but we've already
02065     // compensated by reducing NumRegDefsLeft in PredSU during
02066     // ScheduleDAGSDNodes::AddSchedEdges.
02067     --PredSU->NumRegDefsLeft;
02068     unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
02069     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
02070          RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
02071       if (SkipRegDefs)
02072         continue;
02073 
02074       unsigned RCId, Cost;
02075       GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
02076       RegPressure[RCId] += Cost;
02077       break;
02078     }
02079   }
02080 
02081   // We should have this assert, but there may be dead SDNodes that never
02082   // materialize as SUnits, so they don't appear to generate liveness.
02083   //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
02084   int SkipRegDefs = (int)SU->NumRegDefsLeft;
02085   for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
02086        RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
02087     if (SkipRegDefs > 0)
02088       continue;
02089     unsigned RCId, Cost;
02090     GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
02091     if (RegPressure[RCId] < Cost) {
02092       // Register pressure tracking is imprecise. This can happen. But we try
02093       // hard not to let it happen because it likely results in poor scheduling.
02094       DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") has too many regdefs\n");
02095       RegPressure[RCId] = 0;
02096     }
02097     else {
02098       RegPressure[RCId] -= Cost;
02099     }
02100   }
02101   dumpRegPressure();
02102 }
02103 
02104 void RegReductionPQBase::unscheduledNode(SUnit *SU) {
02105   if (!TracksRegPressure)
02106     return;
02107 
02108   const SDNode *N = SU->getNode();
02109   if (!N) return;
02110 
02111   if (!N->isMachineOpcode()) {
02112     if (N->getOpcode() != ISD::CopyToReg)
02113       return;
02114   } else {
02115     unsigned Opc = N->getMachineOpcode();
02116     if (Opc == TargetOpcode::EXTRACT_SUBREG ||
02117         Opc == TargetOpcode::INSERT_SUBREG ||
02118         Opc == TargetOpcode::SUBREG_TO_REG ||
02119         Opc == TargetOpcode::REG_SEQUENCE ||
02120         Opc == TargetOpcode::IMPLICIT_DEF)
02121       return;
02122   }
02123 
02124   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02125        I != E; ++I) {
02126     if (I->isCtrl())
02127       continue;
02128     SUnit *PredSU = I->getSUnit();
02129     // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
02130     // counts data deps.
02131     if (PredSU->NumSuccsLeft != PredSU->Succs.size())
02132       continue;
02133     const SDNode *PN = PredSU->getNode();
02134     if (!PN->isMachineOpcode()) {
02135       if (PN->getOpcode() == ISD::CopyFromReg) {
02136         MVT VT = PN->getSimpleValueType(0);
02137         unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02138         RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
02139       }
02140       continue;
02141     }
02142     unsigned POpc = PN->getMachineOpcode();
02143     if (POpc == TargetOpcode::IMPLICIT_DEF)
02144       continue;
02145     if (POpc == TargetOpcode::EXTRACT_SUBREG ||
02146         POpc == TargetOpcode::INSERT_SUBREG ||
02147         POpc == TargetOpcode::SUBREG_TO_REG) {
02148       MVT VT = PN->getSimpleValueType(0);
02149       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02150       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
02151       continue;
02152     }
02153     unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
02154     for (unsigned i = 0; i != NumDefs; ++i) {
02155       MVT VT = PN->getSimpleValueType(i);
02156       if (!PN->hasAnyUseOfValue(i))
02157         continue;
02158       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02159       if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
02160         // Register pressure tracking is imprecise. This can happen.
02161         RegPressure[RCId] = 0;
02162       else
02163         RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
02164     }
02165   }
02166 
02167   // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
02168   // may transfer data dependencies to CopyToReg.
02169   if (SU->NumSuccs && N->isMachineOpcode()) {
02170     unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
02171     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
02172       MVT VT = N->getSimpleValueType(i);
02173       if (VT == MVT::Glue || VT == MVT::Other)
02174         continue;
02175       if (!N->hasAnyUseOfValue(i))
02176         continue;
02177       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02178       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
02179     }
02180   }
02181 
02182   dumpRegPressure();
02183 }
02184 
02185 //===----------------------------------------------------------------------===//
02186 //           Dynamic Node Priority for Register Pressure Reduction
02187 //===----------------------------------------------------------------------===//
02188 
02189 /// closestSucc - Returns the scheduled cycle of the successor which is
02190 /// closest to the current cycle.
02191 static unsigned closestSucc(const SUnit *SU) {
02192   unsigned MaxHeight = 0;
02193   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
02194        I != E; ++I) {
02195     if (I->isCtrl()) continue;  // ignore chain succs
02196     unsigned Height = I->getSUnit()->getHeight();
02197     // If there are bunch of CopyToRegs stacked up, they should be considered
02198     // to be at the same position.
02199     if (I->getSUnit()->getNode() &&
02200         I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
02201       Height = closestSucc(I->getSUnit())+1;
02202     if (Height > MaxHeight)
02203       MaxHeight = Height;
02204   }
02205   return MaxHeight;
02206 }
02207 
02208 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
02209 /// for scratch registers, i.e. number of data dependencies.
02210 static unsigned calcMaxScratches(const SUnit *SU) {
02211   unsigned Scratches = 0;
02212   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02213        I != E; ++I) {
02214     if (I->isCtrl()) continue;  // ignore chain preds
02215     Scratches++;
02216   }
02217   return Scratches;
02218 }
02219 
02220 /// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
02221 /// CopyFromReg from a virtual register.
02222 static bool hasOnlyLiveInOpers(const SUnit *SU) {
02223   bool RetVal = false;
02224   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02225        I != E; ++I) {
02226     if (I->isCtrl()) continue;
02227     const SUnit *PredSU = I->getSUnit();
02228     if (PredSU->getNode() &&
02229         PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
02230       unsigned Reg =
02231         cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
02232       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
02233         RetVal = true;
02234         continue;
02235       }
02236     }
02237     return false;
02238   }
02239   return RetVal;
02240 }
02241 
02242 /// hasOnlyLiveOutUses - Return true if SU has only value successors that are
02243 /// CopyToReg to a virtual register. This SU def is probably a liveout and
02244 /// it has no other use. It should be scheduled closer to the terminator.
02245 static bool hasOnlyLiveOutUses(const SUnit *SU) {
02246   bool RetVal = false;
02247   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
02248        I != E; ++I) {
02249     if (I->isCtrl()) continue;
02250     const SUnit *SuccSU = I->getSUnit();
02251     if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
02252       unsigned Reg =
02253         cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
02254       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
02255         RetVal = true;
02256         continue;
02257       }
02258     }
02259     return false;
02260   }
02261   return RetVal;
02262 }
02263 
02264 // Set isVRegCycle for a node with only live in opers and live out uses. Also
02265 // set isVRegCycle for its CopyFromReg operands.
02266 //
02267 // This is only relevant for single-block loops, in which case the VRegCycle
02268 // node is likely an induction variable in which the operand and target virtual
02269 // registers should be coalesced (e.g. pre/post increment values). Setting the
02270 // isVRegCycle flag helps the scheduler prioritize other uses of the same
02271 // CopyFromReg so that this node becomes the virtual register "kill". This
02272 // avoids interference between the values live in and out of the block and
02273 // eliminates a copy inside the loop.
02274 static void initVRegCycle(SUnit *SU) {
02275   if (DisableSchedVRegCycle)
02276     return;
02277 
02278   if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
02279     return;
02280 
02281   DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
02282 
02283   SU->isVRegCycle = true;
02284 
02285   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02286        I != E; ++I) {
02287     if (I->isCtrl()) continue;
02288     I->getSUnit()->isVRegCycle = true;
02289   }
02290 }
02291 
02292 // After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
02293 // CopyFromReg operands. We should no longer penalize other uses of this VReg.
02294 static void resetVRegCycle(SUnit *SU) {
02295   if (!SU->isVRegCycle)
02296     return;
02297 
02298   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
02299        I != E; ++I) {
02300     if (I->isCtrl()) continue;  // ignore chain preds
02301     SUnit *PredSU = I->getSUnit();
02302     if (PredSU->isVRegCycle) {
02303       assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
02304              "VRegCycle def must be CopyFromReg");
02305       I->getSUnit()->isVRegCycle = 0;
02306     }
02307   }
02308 }
02309 
02310 // Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
02311 // means a node that defines the VRegCycle has not been scheduled yet.
02312 static bool hasVRegCycleUse(const SUnit *SU) {
02313   // If this SU also defines the VReg, don't hoist it as a "use".
02314   if (SU->isVRegCycle)
02315     return false;
02316 
02317   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
02318        I != E; ++I) {
02319     if (I->isCtrl()) continue;  // ignore chain preds
02320     if (I->getSUnit()->isVRegCycle &&
02321         I->getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
02322       DEBUG(dbgs() << "  VReg cycle use: SU (" << SU->NodeNum << ")\n");
02323       return true;
02324     }
02325   }
02326   return false;
02327 }
02328 
02329 // Check for either a dependence (latency) or resource (hazard) stall.
02330 //
02331 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
02332 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
02333   if ((int)SPQ->getCurCycle() < Height) return true;
02334   if (SPQ->getHazardRec()->getHazardType(SU, 0)
02335       != ScheduleHazardRecognizer::NoHazard)
02336     return true;
02337   return false;
02338 }
02339 
02340 // Return -1 if left has higher priority, 1 if right has higher priority.
02341 // Return 0 if latency-based priority is equivalent.
02342 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
02343                             RegReductionPQBase *SPQ) {
02344   // Scheduling an instruction that uses a VReg whose postincrement has not yet
02345   // been scheduled will induce a copy. Model this as an extra cycle of latency.
02346   int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
02347   int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
02348   int LHeight = (int)left->getHeight() + LPenalty;
02349   int RHeight = (int)right->getHeight() + RPenalty;
02350 
02351   bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
02352     BUHasStall(left, LHeight, SPQ);
02353   bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
02354     BUHasStall(right, RHeight, SPQ);
02355 
02356   // If scheduling one of the node will cause a pipeline stall, delay it.
02357   // If scheduling either one of the node will cause a pipeline stall, sort
02358   // them according to their height.
02359   if (LStall) {
02360     if (!RStall)
02361       return 1;
02362     if (LHeight != RHeight)
02363       return LHeight > RHeight ? 1 : -1;
02364   } else if (RStall)
02365     return -1;
02366 
02367   // If either node is scheduling for latency, sort them by height/depth
02368   // and latency.
02369   if (!checkPref || (left->SchedulingPref == Sched::ILP ||
02370                      right->SchedulingPref == Sched::ILP)) {
02371     // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
02372     // is enabled, grouping instructions by cycle, then its height is already
02373     // covered so only its depth matters. We also reach this point if both stall
02374     // but have the same height.
02375     if (!SPQ->getHazardRec()->isEnabled()) {
02376       if (LHeight != RHeight)
02377         return LHeight > RHeight ? 1 : -1;
02378     }
02379     int LDepth = left->getDepth() - LPenalty;
02380     int RDepth = right->getDepth() - RPenalty;
02381     if (LDepth != RDepth) {
02382       DEBUG(dbgs() << "  Comparing latency of SU (" << left->NodeNum
02383             << ") depth " << LDepth << " vs SU (" << right->NodeNum
02384             << ") depth " << RDepth << "\n");
02385       return LDepth < RDepth ? 1 : -1;
02386     }
02387     if (left->Latency != right->Latency)
02388       return left->Latency > right->Latency ? 1 : -1;
02389   }
02390   return 0;
02391 }
02392 
02393 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
02394   // Schedule physical register definitions close to their use. This is
02395   // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
02396   // long as shortening physreg live ranges is generally good, we can defer
02397   // creating a subtarget hook.
02398   if (!DisableSchedPhysRegJoin) {
02399     bool LHasPhysReg = left->hasPhysRegDefs;
02400     bool RHasPhysReg = right->hasPhysRegDefs;
02401     if (LHasPhysReg != RHasPhysReg) {
02402       #ifndef NDEBUG
02403       static const char *const PhysRegMsg[] = { " has no physreg",
02404                                                 " defines a physreg" };
02405       #endif
02406       DEBUG(dbgs() << "  SU (" << left->NodeNum << ") "
02407             << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
02408             << PhysRegMsg[RHasPhysReg] << "\n");
02409       return LHasPhysReg < RHasPhysReg;
02410     }
02411   }
02412 
02413   // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
02414   unsigned LPriority = SPQ->getNodePriority(left);
02415   unsigned RPriority = SPQ->getNodePriority(right);
02416 
02417   // Be really careful about hoisting call operands above previous calls.
02418   // Only allows it if it would reduce register pressure.
02419   if (left->isCall && right->isCallOp) {
02420     unsigned RNumVals = right->getNode()->getNumValues();
02421     RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
02422   }
02423   if (right->isCall && left->isCallOp) {
02424     unsigned LNumVals = left->getNode()->getNumValues();
02425     LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
02426   }
02427 
02428   if (LPriority != RPriority)
02429     return LPriority > RPriority;
02430 
02431   // One or both of the nodes are calls and their sethi-ullman numbers are the
02432   // same, then keep source order.
02433   if (left->isCall || right->isCall) {
02434     unsigned LOrder = SPQ->getNodeOrdering(left);
02435     unsigned ROrder = SPQ->getNodeOrdering(right);
02436 
02437     // Prefer an ordering where the lower the non-zero order number, the higher
02438     // the preference.
02439     if ((LOrder || ROrder) && LOrder != ROrder)
02440       return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
02441   }
02442 
02443   // Try schedule def + use closer when Sethi-Ullman numbers are the same.
02444   // e.g.
02445   // t1 = op t2, c1
02446   // t3 = op t4, c2
02447   //
02448   // and the following instructions are both ready.
02449   // t2 = op c3
02450   // t4 = op c4
02451   //
02452   // Then schedule t2 = op first.
02453   // i.e.
02454   // t4 = op c4
02455   // t2 = op c3
02456   // t1 = op t2, c1
02457   // t3 = op t4, c2
02458   //
02459   // This creates more short live intervals.
02460   unsigned LDist = closestSucc(left);
02461   unsigned RDist = closestSucc(right);
02462   if (LDist != RDist)
02463     return LDist < RDist;
02464 
02465   // How many registers becomes live when the node is scheduled.
02466   unsigned LScratch = calcMaxScratches(left);
02467   unsigned RScratch = calcMaxScratches(right);
02468   if (LScratch != RScratch)
02469     return LScratch > RScratch;
02470 
02471   // Comparing latency against a call makes little sense unless the node
02472   // is register pressure-neutral.
02473   if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
02474     return (left->NodeQueueId > right->NodeQueueId);
02475 
02476   // Do not compare latencies when one or both of the nodes are calls.
02477   if (!DisableSchedCycles &&
02478       !(left->isCall || right->isCall)) {
02479     int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
02480     if (result != 0)
02481       return result > 0;
02482   }
02483   else {
02484     if (left->getHeight() != right->getHeight())
02485       return left->getHeight() > right->getHeight();
02486 
02487     if (left->getDepth() != right->getDepth())
02488       return left->getDepth() < right->getDepth();
02489   }
02490 
02491   assert(left->NodeQueueId && right->NodeQueueId &&
02492          "NodeQueueId cannot be zero");
02493   return (left->NodeQueueId > right->NodeQueueId);
02494 }
02495 
02496 // Bottom up
02497 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02498   if (int res = checkSpecialNodes(left, right))
02499     return res > 0;
02500 
02501   return BURRSort(left, right, SPQ);
02502 }
02503 
02504 // Source order, otherwise bottom up.
02505 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02506   if (int res = checkSpecialNodes(left, right))
02507     return res > 0;
02508 
02509   unsigned LOrder = SPQ->getNodeOrdering(left);
02510   unsigned ROrder = SPQ->getNodeOrdering(right);
02511 
02512   // Prefer an ordering where the lower the non-zero order number, the higher
02513   // the preference.
02514   if ((LOrder || ROrder) && LOrder != ROrder)
02515     return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
02516 
02517   return BURRSort(left, right, SPQ);
02518 }
02519 
02520 // If the time between now and when the instruction will be ready can cover
02521 // the spill code, then avoid adding it to the ready queue. This gives long
02522 // stalls highest priority and allows hoisting across calls. It should also
02523 // speed up processing the available queue.
02524 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
02525   static const unsigned ReadyDelay = 3;
02526 
02527   if (SPQ->MayReduceRegPressure(SU)) return true;
02528 
02529   if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
02530 
02531   if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
02532       != ScheduleHazardRecognizer::NoHazard)
02533     return false;
02534 
02535   return true;
02536 }
02537 
02538 // Return true if right should be scheduled with higher priority than left.
02539 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02540   if (int res = checkSpecialNodes(left, right))
02541     return res > 0;
02542 
02543   if (left->isCall || right->isCall)
02544     // No way to compute latency of calls.
02545     return BURRSort(left, right, SPQ);
02546 
02547   bool LHigh = SPQ->HighRegPressure(left);
02548   bool RHigh = SPQ->HighRegPressure(right);
02549   // Avoid causing spills. If register pressure is high, schedule for
02550   // register pressure reduction.
02551   if (LHigh && !RHigh) {
02552     DEBUG(dbgs() << "  pressure SU(" << left->NodeNum << ") > SU("
02553           << right->NodeNum << ")\n");
02554     return true;
02555   }
02556   else if (!LHigh && RHigh) {
02557     DEBUG(dbgs() << "  pressure SU(" << right->NodeNum << ") > SU("
02558           << left->NodeNum << ")\n");
02559     return false;
02560   }
02561   if (!LHigh && !RHigh) {
02562     int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
02563     if (result != 0)
02564       return result > 0;
02565   }
02566   return BURRSort(left, right, SPQ);
02567 }
02568 
02569 // Schedule as many instructions in each cycle as possible. So don't make an
02570 // instruction available unless it is ready in the current cycle.
02571 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
02572   if (SU->getHeight() > CurCycle) return false;
02573 
02574   if (SPQ->getHazardRec()->getHazardType(SU, 0)
02575       != ScheduleHazardRecognizer::NoHazard)
02576     return false;
02577 
02578   return true;
02579 }
02580 
02581 static bool canEnableCoalescing(SUnit *SU) {
02582   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
02583   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
02584     // CopyToReg should be close to its uses to facilitate coalescing and
02585     // avoid spilling.
02586     return true;
02587 
02588   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
02589       Opc == TargetOpcode::SUBREG_TO_REG ||
02590       Opc == TargetOpcode::INSERT_SUBREG)
02591     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
02592     // close to their uses to facilitate coalescing.
02593     return true;
02594 
02595   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
02596     // If SU does not have a register def, schedule it close to its uses
02597     // because it does not lengthen any live ranges.
02598     return true;
02599 
02600   return false;
02601 }
02602 
02603 // list-ilp is currently an experimental scheduler that allows various
02604 // heuristics to be enabled prior to the normal register reduction logic.
02605 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02606   if (int res = checkSpecialNodes(left, right))
02607     return res > 0;
02608 
02609   if (left->isCall || right->isCall)
02610     // No way to compute latency of calls.
02611     return BURRSort(left, right, SPQ);
02612 
02613   unsigned LLiveUses = 0, RLiveUses = 0;
02614   int LPDiff = 0, RPDiff = 0;
02615   if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
02616     LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
02617     RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
02618   }
02619   if (!DisableSchedRegPressure && LPDiff != RPDiff) {
02620     DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
02621           << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
02622     return LPDiff > RPDiff;
02623   }
02624 
02625   if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
02626     bool LReduce = canEnableCoalescing(left);
02627     bool RReduce = canEnableCoalescing(right);
02628     if (LReduce && !RReduce) return false;
02629     if (RReduce && !LReduce) return true;
02630   }
02631 
02632   if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
02633     DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
02634           << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
02635     return LLiveUses < RLiveUses;
02636   }
02637 
02638   if (!DisableSchedStalls) {
02639     bool LStall = BUHasStall(left, left->getHeight(), SPQ);
02640     bool RStall = BUHasStall(right, right->getHeight(), SPQ);
02641     if (LStall != RStall)
02642       return left->getHeight() > right->getHeight();
02643   }
02644 
02645   if (!DisableSchedCriticalPath) {
02646     int spread = (int)left->getDepth() - (int)right->getDepth();
02647     if (std::abs(spread) > MaxReorderWindow) {
02648       DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
02649             << left->getDepth() << " != SU(" << right->NodeNum << "): "
02650             << right->getDepth() << "\n");
02651       return left->getDepth() < right->getDepth();
02652     }
02653   }
02654 
02655   if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
02656     int spread = (int)left->getHeight() - (int)right->getHeight();
02657     if (std::abs(spread) > MaxReorderWindow)
02658       return left->getHeight() > right->getHeight();
02659   }
02660 
02661   return BURRSort(left, right, SPQ);
02662 }
02663 
02664 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
02665   SUnits = &sunits;
02666   // Add pseudo dependency edges for two-address nodes.
02667   if (!Disable2AddrHack)
02668     AddPseudoTwoAddrDeps();
02669   // Reroute edges to nodes with multiple uses.
02670   if (!TracksRegPressure && !SrcOrder)
02671     PrescheduleNodesWithMultipleUses();
02672   // Calculate node priorities.
02673   CalculateSethiUllmanNumbers();
02674 
02675   // For single block loops, mark nodes that look like canonical IV increments.
02676   if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) {
02677     for (unsigned i = 0, e = sunits.size(); i != e; ++i) {
02678       initVRegCycle(&sunits[i]);
02679     }
02680   }
02681 }
02682 
02683 //===----------------------------------------------------------------------===//
02684 //                    Preschedule for Register Pressure
02685 //===----------------------------------------------------------------------===//
02686 
02687 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
02688   if (SU->isTwoAddress) {
02689     unsigned Opc = SU->getNode()->getMachineOpcode();
02690     const MCInstrDesc &MCID = TII->get(Opc);
02691     unsigned NumRes = MCID.getNumDefs();
02692     unsigned NumOps = MCID.getNumOperands() - NumRes;
02693     for (unsigned i = 0; i != NumOps; ++i) {
02694       if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
02695         SDNode *DU = SU->getNode()->getOperand(i).getNode();
02696         if (DU->getNodeId() != -1 &&
02697             Op->OrigNode == &(*SUnits)[DU->getNodeId()])
02698           return true;
02699       }
02700     }
02701   }
02702   return false;
02703 }
02704 
02705 /// canClobberReachingPhysRegUse - True if SU would clobber one of it's
02706 /// successor's explicit physregs whose definition can reach DepSU.
02707 /// i.e. DepSU should not be scheduled above SU.
02708 static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
02709                                          ScheduleDAGRRList *scheduleDAG,
02710                                          const TargetInstrInfo *TII,
02711                                          const TargetRegisterInfo *TRI) {
02712   const uint16_t *ImpDefs
02713     = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
02714   const uint32_t *RegMask = getNodeRegMask(SU->getNode());
02715   if(!ImpDefs && !RegMask)
02716     return false;
02717 
02718   for (SUnit::const_succ_iterator SI = SU->Succs.begin(), SE = SU->Succs.end();
02719        SI != SE; ++SI) {
02720     SUnit *SuccSU = SI->getSUnit();
02721     for (SUnit::const_pred_iterator PI = SuccSU->Preds.begin(),
02722            PE = SuccSU->Preds.end(); PI != PE; ++PI) {
02723       if (!PI->isAssignedRegDep())
02724         continue;
02725 
02726       if (RegMask && MachineOperand::clobbersPhysReg(RegMask, PI->getReg()) &&
02727           scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
02728         return true;
02729 
02730       if (ImpDefs)
02731         for (const uint16_t *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
02732           // Return true if SU clobbers this physical register use and the
02733           // definition of the register reaches from DepSU. IsReachable queries
02734           // a topological forward sort of the DAG (following the successors).
02735           if (TRI->regsOverlap(*ImpDef, PI->getReg()) &&
02736               scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
02737             return true;
02738     }
02739   }
02740   return false;
02741 }
02742 
02743 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
02744 /// physical register defs.
02745 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
02746                                   const TargetInstrInfo *TII,
02747                                   const TargetRegisterInfo *TRI) {
02748   SDNode *N = SuccSU->getNode();
02749   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
02750   const uint16_t *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
02751   assert(ImpDefs && "Caller should check hasPhysRegDefs");
02752   for (const SDNode *SUNode = SU->getNode(); SUNode;
02753        SUNode = SUNode->getGluedNode()) {
02754     if (!SUNode->isMachineOpcode())
02755       continue;
02756     const uint16_t *SUImpDefs =
02757       TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
02758     const uint32_t *SURegMask = getNodeRegMask(SUNode);
02759     if (!SUImpDefs && !SURegMask)
02760       continue;
02761     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
02762       EVT VT = N->getValueType(i);
02763       if (VT == MVT::Glue || VT == MVT::Other)
02764         continue;
02765       if (!N->hasAnyUseOfValue(i))
02766         continue;
02767       unsigned Reg = ImpDefs[i - NumDefs];
02768       if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
02769         return true;
02770       if (!SUImpDefs)
02771         continue;
02772       for (;*SUImpDefs; ++SUImpDefs) {
02773         unsigned SUReg = *SUImpDefs;
02774         if (TRI->regsOverlap(Reg, SUReg))
02775           return true;
02776       }
02777     }
02778   }
02779   return false;
02780 }
02781 
02782 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
02783 /// are not handled well by the general register pressure reduction
02784 /// heuristics. When presented with code like this:
02785 ///
02786 ///      N
02787 ///    / |
02788 ///   /  |
02789 ///  U  store
02790 ///  |
02791 /// ...
02792 ///
02793 /// the heuristics tend to push the store up, but since the
02794 /// operand of the store has another use (U), this would increase
02795 /// the length of that other use (the U->N edge).
02796 ///
02797 /// This function transforms code like the above to route U's
02798 /// dependence through the store when possible, like this:
02799 ///
02800 ///      N
02801 ///      ||
02802 ///      ||
02803 ///     store
02804 ///       |
02805 ///       U
02806 ///       |
02807 ///      ...
02808 ///
02809 /// This results in the store being scheduled immediately
02810 /// after N, which shortens the U->N live range, reducing
02811 /// register pressure.
02812 ///
02813 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
02814   // Visit all the nodes in topological order, working top-down.
02815   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
02816     SUnit *SU = &(*SUnits)[i];
02817     // For now, only look at nodes with no data successors, such as stores.
02818     // These are especially important, due to the heuristics in
02819     // getNodePriority for nodes with no data successors.
02820     if (SU->NumSuccs != 0)
02821       continue;
02822     // For now, only look at nodes with exactly one data predecessor.
02823     if (SU->NumPreds != 1)
02824       continue;
02825     // Avoid prescheduling copies to virtual registers, which don't behave
02826     // like other nodes from the perspective of scheduling heuristics.
02827     if (SDNode *N = SU->getNode())
02828       if (N->getOpcode() == ISD::CopyToReg &&
02829           TargetRegisterInfo::isVirtualRegister
02830             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
02831         continue;
02832 
02833     // Locate the single data predecessor.
02834     SUnit *PredSU = nullptr;
02835     for (SUnit::const_pred_iterator II = SU->Preds.begin(),
02836          EE = SU->Preds.end(); II != EE; ++II)
02837       if (!II->isCtrl()) {
02838         PredSU = II->getSUnit();
02839         break;
02840       }
02841     assert(PredSU);
02842 
02843     // Don't rewrite edges that carry physregs, because that requires additional
02844     // support infrastructure.
02845     if (PredSU->hasPhysRegDefs)
02846       continue;
02847     // Short-circuit the case where SU is PredSU's only data successor.
02848     if (PredSU->NumSuccs == 1)
02849       continue;
02850     // Avoid prescheduling to copies from virtual registers, which don't behave
02851     // like other nodes from the perspective of scheduling heuristics.
02852     if (SDNode *N = SU->getNode())
02853       if (N->getOpcode() == ISD::CopyFromReg &&
02854           TargetRegisterInfo::isVirtualRegister
02855             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
02856         continue;
02857 
02858     // Perform checks on the successors of PredSU.
02859     for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
02860          EE = PredSU->Succs.end(); II != EE; ++II) {
02861       SUnit *PredSuccSU = II->getSUnit();
02862       if (PredSuccSU == SU) continue;
02863       // If PredSU has another successor with no data successors, for
02864       // now don't attempt to choose either over the other.
02865       if (PredSuccSU->NumSuccs == 0)
02866         goto outer_loop_continue;
02867       // Don't break physical register dependencies.
02868       if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
02869         if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
02870           goto outer_loop_continue;
02871       // Don't introduce graph cycles.
02872       if (scheduleDAG->IsReachable(SU, PredSuccSU))
02873         goto outer_loop_continue;
02874     }
02875 
02876     // Ok, the transformation is safe and the heuristics suggest it is
02877     // profitable. Update the graph.
02878     DEBUG(dbgs() << "    Prescheduling SU #" << SU->NodeNum
02879                  << " next to PredSU #" << PredSU->NodeNum
02880                  << " to guide scheduling in the presence of multiple uses\n");
02881     for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
02882       SDep Edge = PredSU->Succs[i];
02883       assert(!Edge.isAssignedRegDep());
02884       SUnit *SuccSU = Edge.getSUnit();
02885       if (SuccSU != SU) {
02886         Edge.setSUnit(PredSU);
02887         scheduleDAG->RemovePred(SuccSU, Edge);
02888         scheduleDAG->AddPred(SU, Edge);
02889         Edge.setSUnit(SU);
02890         scheduleDAG->AddPred(SuccSU, Edge);
02891         --i;
02892       }
02893     }
02894   outer_loop_continue:;
02895   }
02896 }
02897 
02898 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
02899 /// it as a def&use operand. Add a pseudo control edge from it to the other
02900 /// node (if it won't create a cycle) so the two-address one will be scheduled
02901 /// first (lower in the schedule). If both nodes are two-address, favor the
02902 /// one that has a CopyToReg use (more likely to be a loop induction update).
02903 /// If both are two-address, but one is commutable while the other is not
02904 /// commutable, favor the one that's not commutable.
02905 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
02906   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
02907     SUnit *SU = &(*SUnits)[i];
02908     if (!SU->isTwoAddress)
02909       continue;
02910 
02911     SDNode *Node = SU->getNode();
02912     if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
02913       continue;
02914 
02915     bool isLiveOut = hasOnlyLiveOutUses(SU);
02916     unsigned Opc = Node->getMachineOpcode();
02917     const MCInstrDesc &MCID = TII->get(Opc);
02918     unsigned NumRes = MCID.getNumDefs();
02919     unsigned NumOps = MCID.getNumOperands() - NumRes;
02920     for (unsigned j = 0; j != NumOps; ++j) {
02921       if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
02922         continue;
02923       SDNode *DU = SU->getNode()->getOperand(j).getNode();
02924       if (DU->getNodeId() == -1)
02925         continue;
02926       const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
02927       if (!DUSU) continue;
02928       for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
02929            E = DUSU->Succs.end(); I != E; ++I) {
02930         if (I->isCtrl()) continue;
02931         SUnit *SuccSU = I->getSUnit();
02932         if (SuccSU == SU)
02933           continue;
02934         // Be conservative. Ignore if nodes aren't at roughly the same
02935         // depth and height.
02936         if (SuccSU->getHeight() < SU->getHeight() &&
02937             (SU->getHeight() - SuccSU->getHeight()) > 1)
02938           continue;
02939         // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
02940         // constrains whatever is using the copy, instead of the copy
02941         // itself. In the case that the copy is coalesced, this
02942         // preserves the intent of the pseudo two-address heurietics.
02943         while (SuccSU->Succs.size() == 1 &&
02944                SuccSU->getNode()->isMachineOpcode() &&
02945                SuccSU->getNode()->getMachineOpcode() ==
02946                  TargetOpcode::COPY_TO_REGCLASS)
02947           SuccSU = SuccSU->Succs.front().getSUnit();
02948         // Don't constrain non-instruction nodes.
02949         if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
02950           continue;
02951         // Don't constrain nodes with physical register defs if the
02952         // predecessor can clobber them.
02953         if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
02954           if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
02955             continue;
02956         }
02957         // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
02958         // these may be coalesced away. We want them close to their uses.
02959         unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
02960         if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
02961             SuccOpc == TargetOpcode::INSERT_SUBREG ||
02962             SuccOpc == TargetOpcode::SUBREG_TO_REG)
02963           continue;
02964         if (!canClobberReachingPhysRegUse(SuccSU, SU, scheduleDAG, TII, TRI) &&
02965             (!canClobber(SuccSU, DUSU) ||
02966              (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
02967              (!SU->isCommutable && SuccSU->isCommutable)) &&
02968             !scheduleDAG->IsReachable(SuccSU, SU)) {
02969           DEBUG(dbgs() << "    Adding a pseudo-two-addr edge from SU #"
02970                        << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
02971           scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Artificial));
02972         }
02973       }
02974     }
02975   }
02976 }
02977 
02978 //===----------------------------------------------------------------------===//
02979 //                         Public Constructor Functions
02980 //===----------------------------------------------------------------------===//
02981 
02982 llvm::ScheduleDAGSDNodes *
02983 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
02984                                  CodeGenOpt::Level OptLevel) {
02985   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
02986   const TargetInstrInfo *TII = STI.getInstrInfo();
02987   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
02988 
02989   BURegReductionPriorityQueue *PQ =
02990     new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, nullptr);
02991   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
02992   PQ->setScheduleDAG(SD);
02993   return SD;
02994 }
02995 
02996 llvm::ScheduleDAGSDNodes *
02997 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
02998                                    CodeGenOpt::Level OptLevel) {
02999   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
03000   const TargetInstrInfo *TII = STI.getInstrInfo();
03001   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
03002 
03003   SrcRegReductionPriorityQueue *PQ =
03004     new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, nullptr);
03005   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
03006   PQ->setScheduleDAG(SD);
03007   return SD;
03008 }
03009 
03010 llvm::ScheduleDAGSDNodes *
03011 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
03012                                    CodeGenOpt::Level OptLevel) {
03013   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
03014   const TargetInstrInfo *TII = STI.getInstrInfo();
03015   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
03016   const TargetLowering *TLI = IS->TLI;
03017 
03018   HybridBURRPriorityQueue *PQ =
03019     new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
03020 
03021   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
03022   PQ->setScheduleDAG(SD);
03023   return SD;
03024 }
03025 
03026 llvm::ScheduleDAGSDNodes *
03027 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
03028                                 CodeGenOpt::Level OptLevel) {
03029   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
03030   const TargetInstrInfo *TII = STI.getInstrInfo();
03031   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
03032   const TargetLowering *TLI = IS->TLI;
03033 
03034   ILPBURRPriorityQueue *PQ =
03035     new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
03036   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
03037   PQ->setScheduleDAG(SD);
03038   return SD;
03039 }