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