LLVM API Documentation

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