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     MVT VT = N->getSimpleValueType(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     MVT VT = Op.getNode()->getSimpleValueType(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 MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
01192                                  const TargetInstrInfo *TII) {
01193   unsigned NumRes;
01194   if (N->getOpcode() == ISD::CopyFromReg) {
01195     // CopyFromReg has: "chain, Val, glue" so operand 1 gives the type.
01196     NumRes = 1;
01197   } else {
01198     const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
01199     assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
01200     NumRes = MCID.getNumDefs();
01201     for (const uint16_t *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
01202       if (Reg == *ImpDef)
01203         break;
01204       ++NumRes;
01205     }
01206   }
01207   return N->getSimpleValueType(NumRes);
01208 }
01209 
01210 /// CheckForLiveRegDef - Return true and update live register vector if the
01211 /// specified register def of the specified SUnit clobbers any "live" registers.
01212 static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
01213                                std::vector<SUnit*> &LiveRegDefs,
01214                                SmallSet<unsigned, 4> &RegAdded,
01215                                SmallVectorImpl<unsigned> &LRegs,
01216                                const TargetRegisterInfo *TRI) {
01217   for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
01218 
01219     // Check if Ref is live.
01220     if (!LiveRegDefs[*AliasI]) continue;
01221 
01222     // Allow multiple uses of the same def.
01223     if (LiveRegDefs[*AliasI] == SU) continue;
01224 
01225     // Add Reg to the set of interfering live regs.
01226     if (RegAdded.insert(*AliasI).second) {
01227       LRegs.push_back(*AliasI);
01228     }
01229   }
01230 }
01231 
01232 /// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
01233 /// by RegMask, and add them to LRegs.
01234 static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
01235                                      std::vector<SUnit*> &LiveRegDefs,
01236                                      SmallSet<unsigned, 4> &RegAdded,
01237                                      SmallVectorImpl<unsigned> &LRegs) {
01238   // Look at all live registers. Skip Reg0 and the special CallResource.
01239   for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
01240     if (!LiveRegDefs[i]) continue;
01241     if (LiveRegDefs[i] == SU) continue;
01242     if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
01243     if (RegAdded.insert(i).second)
01244       LRegs.push_back(i);
01245   }
01246 }
01247 
01248 /// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
01249 static const uint32_t *getNodeRegMask(const SDNode *N) {
01250   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
01251     if (const RegisterMaskSDNode *Op =
01252         dyn_cast<RegisterMaskSDNode>(N->getOperand(i).getNode()))
01253       return Op->getRegMask();
01254   return nullptr;
01255 }
01256 
01257 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
01258 /// scheduling of the given node to satisfy live physical register dependencies.
01259 /// If the specific node is the last one that's available to schedule, do
01260 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
01261 bool ScheduleDAGRRList::
01262 DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) {
01263   if (NumLiveRegs == 0)
01264     return false;
01265 
01266   SmallSet<unsigned, 4> RegAdded;
01267   // If this node would clobber any "live" register, then it's not ready.
01268   //
01269   // If SU is the currently live definition of the same register that it uses,
01270   // then we are free to schedule it.
01271   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
01272        I != E; ++I) {
01273     if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
01274       CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
01275                          RegAdded, LRegs, TRI);
01276   }
01277 
01278   for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
01279     if (Node->getOpcode() == ISD::INLINEASM) {
01280       // Inline asm can clobber physical defs.
01281       unsigned NumOps = Node->getNumOperands();
01282       if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
01283         --NumOps;  // Ignore the glue operand.
01284 
01285       for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
01286         unsigned Flags =
01287           cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
01288         unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
01289 
01290         ++i; // Skip the ID value.
01291         if (InlineAsm::isRegDefKind(Flags) ||
01292             InlineAsm::isRegDefEarlyClobberKind(Flags) ||
01293             InlineAsm::isClobberKind(Flags)) {
01294           // Check for def of register or earlyclobber register.
01295           for (; NumVals; --NumVals, ++i) {
01296             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
01297             if (TargetRegisterInfo::isPhysicalRegister(Reg))
01298               CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
01299           }
01300         } else
01301           i += NumVals;
01302       }
01303       continue;
01304     }
01305 
01306     if (!Node->isMachineOpcode())
01307       continue;
01308     // If we're in the middle of scheduling a call, don't begin scheduling
01309     // another call. Also, don't allow any physical registers to be live across
01310     // the call.
01311     if (Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
01312       // Check the special calling-sequence resource.
01313       unsigned CallResource = TRI->getNumRegs();
01314       if (LiveRegDefs[CallResource]) {
01315         SDNode *Gen = LiveRegGens[CallResource]->getNode();
01316         while (SDNode *Glued = Gen->getGluedNode())
01317           Gen = Glued;
01318         if (!IsChainDependent(Gen, Node, 0, TII) &&
01319             RegAdded.insert(CallResource).second)
01320           LRegs.push_back(CallResource);
01321       }
01322     }
01323     if (const uint32_t *RegMask = getNodeRegMask(Node))
01324       CheckForLiveRegDefMasked(SU, RegMask, LiveRegDefs, RegAdded, LRegs);
01325 
01326     const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
01327     if (!MCID.ImplicitDefs)
01328       continue;
01329     for (const uint16_t *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
01330       CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
01331   }
01332 
01333   return !LRegs.empty();
01334 }
01335 
01336 void ScheduleDAGRRList::releaseInterferences(unsigned Reg) {
01337   // Add the nodes that aren't ready back onto the available list.
01338   for (unsigned i = Interferences.size(); i > 0; --i) {
01339     SUnit *SU = Interferences[i-1];
01340     LRegsMapT::iterator LRegsPos = LRegsMap.find(SU);
01341     if (Reg) {
01342       SmallVectorImpl<unsigned> &LRegs = LRegsPos->second;
01343       if (std::find(LRegs.begin(), LRegs.end(), Reg) == LRegs.end())
01344         continue;
01345     }
01346     SU->isPending = false;
01347     // The interfering node may no longer be available due to backtracking.
01348     // Furthermore, it may have been made available again, in which case it is
01349     // now already in the AvailableQueue.
01350     if (SU->isAvailable && !SU->NodeQueueId) {
01351       DEBUG(dbgs() << "    Repushing SU #" << SU->NodeNum << '\n');
01352       AvailableQueue->push(SU);
01353     }
01354     if (i < Interferences.size())
01355       Interferences[i-1] = Interferences.back();
01356     Interferences.pop_back();
01357     LRegsMap.erase(LRegsPos);
01358   }
01359 }
01360 
01361 /// Return a node that can be scheduled in this cycle. Requirements:
01362 /// (1) Ready: latency has been satisfied
01363 /// (2) No Hazards: resources are available
01364 /// (3) No Interferences: may unschedule to break register interferences.
01365 SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
01366   SUnit *CurSU = AvailableQueue->empty() ? nullptr : AvailableQueue->pop();
01367   while (CurSU) {
01368     SmallVector<unsigned, 4> LRegs;
01369     if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
01370       break;
01371     DEBUG(dbgs() << "    Interfering reg " <<
01372           (LRegs[0] == TRI->getNumRegs() ? "CallResource"
01373            : TRI->getName(LRegs[0]))
01374            << " SU #" << CurSU->NodeNum << '\n');
01375     std::pair<LRegsMapT::iterator, bool> LRegsPair =
01376       LRegsMap.insert(std::make_pair(CurSU, LRegs));
01377     if (LRegsPair.second) {
01378       CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
01379       Interferences.push_back(CurSU);
01380     }
01381     else {
01382       assert(CurSU->isPending && "Interferences are pending");
01383       // Update the interference with current live regs.
01384       LRegsPair.first->second = LRegs;
01385     }
01386     CurSU = AvailableQueue->pop();
01387   }
01388   if (CurSU)
01389     return CurSU;
01390 
01391   // All candidates are delayed due to live physical reg dependencies.
01392   // Try backtracking, code duplication, or inserting cross class copies
01393   // to resolve it.
01394   for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
01395     SUnit *TrySU = Interferences[i];
01396     SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
01397 
01398     // Try unscheduling up to the point where it's safe to schedule
01399     // this node.
01400     SUnit *BtSU = nullptr;
01401     unsigned LiveCycle = UINT_MAX;
01402     for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
01403       unsigned Reg = LRegs[j];
01404       if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
01405         BtSU = LiveRegGens[Reg];
01406         LiveCycle = BtSU->getHeight();
01407       }
01408     }
01409     if (!WillCreateCycle(TrySU, BtSU))  {
01410       // BacktrackBottomUp mutates Interferences!
01411       BacktrackBottomUp(TrySU, BtSU);
01412 
01413       // Force the current node to be scheduled before the node that
01414       // requires the physical reg dep.
01415       if (BtSU->isAvailable) {
01416         BtSU->isAvailable = false;
01417         if (!BtSU->isPending)
01418           AvailableQueue->remove(BtSU);
01419       }
01420       DEBUG(dbgs() << "ARTIFICIAL edge from SU(" << BtSU->NodeNum << ") to SU("
01421             << TrySU->NodeNum << ")\n");
01422       AddPred(TrySU, SDep(BtSU, SDep::Artificial));
01423 
01424       // If one or more successors has been unscheduled, then the current
01425       // node is no longer available.
01426       if (!TrySU->isAvailable)
01427         CurSU = AvailableQueue->pop();
01428       else {
01429         AvailableQueue->remove(TrySU);
01430         CurSU = TrySU;
01431       }
01432       // Interferences has been mutated. We must break.
01433       break;
01434     }
01435   }
01436 
01437   if (!CurSU) {
01438     // Can't backtrack. If it's too expensive to copy the value, then try
01439     // duplicate the nodes that produces these "too expensive to copy"
01440     // values to break the dependency. In case even that doesn't work,
01441     // insert cross class copies.
01442     // If it's not too expensive, i.e. cost != -1, issue copies.
01443     SUnit *TrySU = Interferences[0];
01444     SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
01445     assert(LRegs.size() == 1 && "Can't handle this yet!");
01446     unsigned Reg = LRegs[0];
01447     SUnit *LRDef = LiveRegDefs[Reg];
01448     MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
01449     const TargetRegisterClass *RC =
01450       TRI->getMinimalPhysRegClass(Reg, VT);
01451     const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
01452 
01453     // If cross copy register class is the same as RC, then it must be possible
01454     // copy the value directly. Do not try duplicate the def.
01455     // If cross copy register class is not the same as RC, then it's possible to
01456     // copy the value but it require cross register class copies and it is
01457     // expensive.
01458     // If cross copy register class is null, then it's not possible to copy
01459     // the value at all.
01460     SUnit *NewDef = nullptr;
01461     if (DestRC != RC) {
01462       NewDef = CopyAndMoveSuccessors(LRDef);
01463       if (!DestRC && !NewDef)
01464         report_fatal_error("Can't handle live physical register dependency!");
01465     }
01466     if (!NewDef) {
01467       // Issue copies, these can be expensive cross register class copies.
01468       SmallVector<SUnit*, 2> Copies;
01469       InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
01470       DEBUG(dbgs() << "    Adding an edge from SU #" << TrySU->NodeNum
01471             << " to SU #" << Copies.front()->NodeNum << "\n");
01472       AddPred(TrySU, SDep(Copies.front(), SDep::Artificial));
01473       NewDef = Copies.back();
01474     }
01475 
01476     DEBUG(dbgs() << "    Adding an edge from SU #" << NewDef->NodeNum
01477           << " to SU #" << TrySU->NodeNum << "\n");
01478     LiveRegDefs[Reg] = NewDef;
01479     AddPred(NewDef, SDep(TrySU, SDep::Artificial));
01480     TrySU->isAvailable = false;
01481     CurSU = NewDef;
01482   }
01483   assert(CurSU && "Unable to resolve live physical register dependencies!");
01484   return CurSU;
01485 }
01486 
01487 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
01488 /// schedulers.
01489 void ScheduleDAGRRList::ListScheduleBottomUp() {
01490   // Release any predecessors of the special Exit node.
01491   ReleasePredecessors(&ExitSU);
01492 
01493   // Add root to Available queue.
01494   if (!SUnits.empty()) {
01495     SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
01496     assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
01497     RootSU->isAvailable = true;
01498     AvailableQueue->push(RootSU);
01499   }
01500 
01501   // While Available queue is not empty, grab the node with the highest
01502   // priority. If it is not ready put it back.  Schedule the node.
01503   Sequence.reserve(SUnits.size());
01504   while (!AvailableQueue->empty() || !Interferences.empty()) {
01505     DEBUG(dbgs() << "\nExamining Available:\n";
01506           AvailableQueue->dump(this));
01507 
01508     // Pick the best node to schedule taking all constraints into
01509     // consideration.
01510     SUnit *SU = PickNodeToScheduleBottomUp();
01511 
01512     AdvancePastStalls(SU);
01513 
01514     ScheduleNodeBottomUp(SU);
01515 
01516     while (AvailableQueue->empty() && !PendingQueue.empty()) {
01517       // Advance the cycle to free resources. Skip ahead to the next ready SU.
01518       assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
01519       AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
01520     }
01521   }
01522 
01523   // Reverse the order if it is bottom up.
01524   std::reverse(Sequence.begin(), Sequence.end());
01525 
01526 #ifndef NDEBUG
01527   VerifyScheduledSequence(/*isBottomUp=*/true);
01528 #endif
01529 }
01530 
01531 //===----------------------------------------------------------------------===//
01532 //                RegReductionPriorityQueue Definition
01533 //===----------------------------------------------------------------------===//
01534 //
01535 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
01536 // to reduce register pressure.
01537 //
01538 namespace {
01539 class RegReductionPQBase;
01540 
01541 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
01542   bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
01543 };
01544 
01545 #ifndef NDEBUG
01546 template<class SF>
01547 struct reverse_sort : public queue_sort {
01548   SF &SortFunc;
01549   reverse_sort(SF &sf) : SortFunc(sf) {}
01550 
01551   bool operator()(SUnit* left, SUnit* right) const {
01552     // reverse left/right rather than simply !SortFunc(left, right)
01553     // to expose different paths in the comparison logic.
01554     return SortFunc(right, left);
01555   }
01556 };
01557 #endif // NDEBUG
01558 
01559 /// bu_ls_rr_sort - Priority function for bottom up register pressure
01560 // reduction scheduler.
01561 struct bu_ls_rr_sort : public queue_sort {
01562   enum {
01563     IsBottomUp = true,
01564     HasReadyFilter = false
01565   };
01566 
01567   RegReductionPQBase *SPQ;
01568   bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
01569 
01570   bool operator()(SUnit* left, SUnit* right) const;
01571 };
01572 
01573 // src_ls_rr_sort - Priority function for source order scheduler.
01574 struct src_ls_rr_sort : public queue_sort {
01575   enum {
01576     IsBottomUp = true,
01577     HasReadyFilter = false
01578   };
01579 
01580   RegReductionPQBase *SPQ;
01581   src_ls_rr_sort(RegReductionPQBase *spq)
01582     : SPQ(spq) {}
01583 
01584   bool operator()(SUnit* left, SUnit* right) const;
01585 };
01586 
01587 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
01588 struct hybrid_ls_rr_sort : public queue_sort {
01589   enum {
01590     IsBottomUp = true,
01591     HasReadyFilter = false
01592   };
01593 
01594   RegReductionPQBase *SPQ;
01595   hybrid_ls_rr_sort(RegReductionPQBase *spq)
01596     : SPQ(spq) {}
01597 
01598   bool isReady(SUnit *SU, unsigned CurCycle) const;
01599 
01600   bool operator()(SUnit* left, SUnit* right) const;
01601 };
01602 
01603 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
01604 // scheduler.
01605 struct ilp_ls_rr_sort : public queue_sort {
01606   enum {
01607     IsBottomUp = true,
01608     HasReadyFilter = false
01609   };
01610 
01611   RegReductionPQBase *SPQ;
01612   ilp_ls_rr_sort(RegReductionPQBase *spq)
01613     : SPQ(spq) {}
01614 
01615   bool isReady(SUnit *SU, unsigned CurCycle) const;
01616 
01617   bool operator()(SUnit* left, SUnit* right) const;
01618 };
01619 
01620 class RegReductionPQBase : public SchedulingPriorityQueue {
01621 protected:
01622   std::vector<SUnit*> Queue;
01623   unsigned CurQueueId;
01624   bool TracksRegPressure;
01625   bool SrcOrder;
01626 
01627   // SUnits - The SUnits for the current graph.
01628   std::vector<SUnit> *SUnits;
01629 
01630   MachineFunction &MF;
01631   const TargetInstrInfo *TII;
01632   const TargetRegisterInfo *TRI;
01633   const TargetLowering *TLI;
01634   ScheduleDAGRRList *scheduleDAG;
01635 
01636   // SethiUllmanNumbers - The SethiUllman number for each node.
01637   std::vector<unsigned> SethiUllmanNumbers;
01638 
01639   /// RegPressure - Tracking current reg pressure per register class.
01640   ///
01641   std::vector<unsigned> RegPressure;
01642 
01643   /// RegLimit - Tracking the number of allocatable registers per register
01644   /// class.
01645   std::vector<unsigned> RegLimit;
01646 
01647 public:
01648   RegReductionPQBase(MachineFunction &mf,
01649                      bool hasReadyFilter,
01650                      bool tracksrp,
01651                      bool srcorder,
01652                      const TargetInstrInfo *tii,
01653                      const TargetRegisterInfo *tri,
01654                      const TargetLowering *tli)
01655     : SchedulingPriorityQueue(hasReadyFilter),
01656       CurQueueId(0), TracksRegPressure(tracksrp), SrcOrder(srcorder),
01657       MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(nullptr) {
01658     if (TracksRegPressure) {
01659       unsigned NumRC = TRI->getNumRegClasses();
01660       RegLimit.resize(NumRC);
01661       RegPressure.resize(NumRC);
01662       std::fill(RegLimit.begin(), RegLimit.end(), 0);
01663       std::fill(RegPressure.begin(), RegPressure.end(), 0);
01664       for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
01665              E = TRI->regclass_end(); I != E; ++I)
01666         RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
01667     }
01668   }
01669 
01670   void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
01671     scheduleDAG = scheduleDag;
01672   }
01673 
01674   ScheduleHazardRecognizer* getHazardRec() {
01675     return scheduleDAG->getHazardRec();
01676   }
01677 
01678   void initNodes(std::vector<SUnit> &sunits) override;
01679 
01680   void addNode(const SUnit *SU) override;
01681 
01682   void updateNode(const SUnit *SU) override;
01683 
01684   void releaseState() override {
01685     SUnits = nullptr;
01686     SethiUllmanNumbers.clear();
01687     std::fill(RegPressure.begin(), RegPressure.end(), 0);
01688   }
01689 
01690   unsigned getNodePriority(const SUnit *SU) const;
01691 
01692   unsigned getNodeOrdering(const SUnit *SU) const {
01693     if (!SU->getNode()) return 0;
01694 
01695     return SU->getNode()->getIROrder();
01696   }
01697 
01698   bool empty() const override { return Queue.empty(); }
01699 
01700   void push(SUnit *U) override {
01701     assert(!U->NodeQueueId && "Node in the queue already");
01702     U->NodeQueueId = ++CurQueueId;
01703     Queue.push_back(U);
01704   }
01705 
01706   void remove(SUnit *SU) override {
01707     assert(!Queue.empty() && "Queue is empty!");
01708     assert(SU->NodeQueueId != 0 && "Not in queue!");
01709     std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
01710                                                  SU);
01711     if (I != std::prev(Queue.end()))
01712       std::swap(*I, Queue.back());
01713     Queue.pop_back();
01714     SU->NodeQueueId = 0;
01715   }
01716 
01717   bool tracksRegPressure() const override { return TracksRegPressure; }
01718 
01719   void dumpRegPressure() const;
01720 
01721   bool HighRegPressure(const SUnit *SU) const;
01722 
01723   bool MayReduceRegPressure(SUnit *SU) const;
01724 
01725   int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
01726 
01727   void scheduledNode(SUnit *SU) override;
01728 
01729   void unscheduledNode(SUnit *SU) override;
01730 
01731 protected:
01732   bool canClobber(const SUnit *SU, const SUnit *Op);
01733   void AddPseudoTwoAddrDeps();
01734   void PrescheduleNodesWithMultipleUses();
01735   void CalculateSethiUllmanNumbers();
01736 };
01737 
01738 template<class SF>
01739 static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
01740   std::vector<SUnit *>::iterator Best = Q.begin();
01741   for (std::vector<SUnit *>::iterator I = std::next(Q.begin()),
01742          E = Q.end(); I != E; ++I)
01743     if (Picker(*Best, *I))
01744       Best = I;
01745   SUnit *V = *Best;
01746   if (Best != std::prev(Q.end()))
01747     std::swap(*Best, Q.back());
01748   Q.pop_back();
01749   return V;
01750 }
01751 
01752 template<class SF>
01753 SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
01754 #ifndef NDEBUG
01755   if (DAG->StressSched) {
01756     reverse_sort<SF> RPicker(Picker);
01757     return popFromQueueImpl(Q, RPicker);
01758   }
01759 #endif
01760   (void)DAG;
01761   return popFromQueueImpl(Q, Picker);
01762 }
01763 
01764 template<class SF>
01765 class RegReductionPriorityQueue : public RegReductionPQBase {
01766   SF Picker;
01767 
01768 public:
01769   RegReductionPriorityQueue(MachineFunction &mf,
01770                             bool tracksrp,
01771                             bool srcorder,
01772                             const TargetInstrInfo *tii,
01773                             const TargetRegisterInfo *tri,
01774                             const TargetLowering *tli)
01775     : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
01776                          tii, tri, tli),
01777       Picker(this) {}
01778 
01779   bool isBottomUp() const override { return SF::IsBottomUp; }
01780 
01781   bool isReady(SUnit *U) const override {
01782     return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
01783   }
01784 
01785   SUnit *pop() override {
01786     if (Queue.empty()) return nullptr;
01787 
01788     SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
01789     V->NodeQueueId = 0;
01790     return V;
01791   }
01792 
01793 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01794   void dump(ScheduleDAG *DAG) const override {
01795     // Emulate pop() without clobbering NodeQueueIds.
01796     std::vector<SUnit*> DumpQueue = Queue;
01797     SF DumpPicker = Picker;
01798     while (!DumpQueue.empty()) {
01799       SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
01800       dbgs() << "Height " << SU->getHeight() << ": ";
01801       SU->dump(DAG);
01802     }
01803   }
01804 #endif
01805 };
01806 
01807 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
01808 BURegReductionPriorityQueue;
01809 
01810 typedef RegReductionPriorityQueue<src_ls_rr_sort>
01811 SrcRegReductionPriorityQueue;
01812 
01813 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
01814 HybridBURRPriorityQueue;
01815 
01816 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
01817 ILPBURRPriorityQueue;
01818 } // end anonymous namespace
01819 
01820 //===----------------------------------------------------------------------===//
01821 //           Static Node Priority for Register Pressure Reduction
01822 //===----------------------------------------------------------------------===//
01823 
01824 // Check for special nodes that bypass scheduling heuristics.
01825 // Currently this pushes TokenFactor nodes down, but may be used for other
01826 // pseudo-ops as well.
01827 //
01828 // Return -1 to schedule right above left, 1 for left above right.
01829 // Return 0 if no bias exists.
01830 static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
01831   bool LSchedLow = left->isScheduleLow;
01832   bool RSchedLow = right->isScheduleLow;
01833   if (LSchedLow != RSchedLow)
01834     return LSchedLow < RSchedLow ? 1 : -1;
01835   return 0;
01836 }
01837 
01838 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
01839 /// Smaller number is the higher priority.
01840 static unsigned
01841 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
01842   unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
01843   if (SethiUllmanNumber != 0)
01844     return SethiUllmanNumber;
01845 
01846   unsigned Extra = 0;
01847   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
01848        I != E; ++I) {
01849     if (I->isCtrl()) continue;  // ignore chain preds
01850     SUnit *PredSU = I->getSUnit();
01851     unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
01852     if (PredSethiUllman > SethiUllmanNumber) {
01853       SethiUllmanNumber = PredSethiUllman;
01854       Extra = 0;
01855     } else if (PredSethiUllman == SethiUllmanNumber)
01856       ++Extra;
01857   }
01858 
01859   SethiUllmanNumber += Extra;
01860 
01861   if (SethiUllmanNumber == 0)
01862     SethiUllmanNumber = 1;
01863 
01864   return SethiUllmanNumber;
01865 }
01866 
01867 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
01868 /// scheduling units.
01869 void RegReductionPQBase::CalculateSethiUllmanNumbers() {
01870   SethiUllmanNumbers.assign(SUnits->size(), 0);
01871 
01872   for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
01873     CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
01874 }
01875 
01876 void RegReductionPQBase::addNode(const SUnit *SU) {
01877   unsigned SUSize = SethiUllmanNumbers.size();
01878   if (SUnits->size() > SUSize)
01879     SethiUllmanNumbers.resize(SUSize*2, 0);
01880   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
01881 }
01882 
01883 void RegReductionPQBase::updateNode(const SUnit *SU) {
01884   SethiUllmanNumbers[SU->NodeNum] = 0;
01885   CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
01886 }
01887 
01888 // Lower priority means schedule further down. For bottom-up scheduling, lower
01889 // priority SUs are scheduled before higher priority SUs.
01890 unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
01891   assert(SU->NodeNum < SethiUllmanNumbers.size());
01892   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
01893   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
01894     // CopyToReg should be close to its uses to facilitate coalescing and
01895     // avoid spilling.
01896     return 0;
01897   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
01898       Opc == TargetOpcode::SUBREG_TO_REG ||
01899       Opc == TargetOpcode::INSERT_SUBREG)
01900     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
01901     // close to their uses to facilitate coalescing.
01902     return 0;
01903   if (SU->NumSuccs == 0 && SU->NumPreds != 0)
01904     // If SU does not have a register use, i.e. it doesn't produce a value
01905     // that would be consumed (e.g. store), then it terminates a chain of
01906     // computation.  Give it a large SethiUllman number so it will be
01907     // scheduled right before its predecessors that it doesn't lengthen
01908     // their live ranges.
01909     return 0xffff;
01910   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
01911     // If SU does not have a register def, schedule it close to its uses
01912     // because it does not lengthen any live ranges.
01913     return 0;
01914 #if 1
01915   return SethiUllmanNumbers[SU->NodeNum];
01916 #else
01917   unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
01918   if (SU->isCallOp) {
01919     // FIXME: This assumes all of the defs are used as call operands.
01920     int NP = (int)Priority - SU->getNode()->getNumValues();
01921     return (NP > 0) ? NP : 0;
01922   }
01923   return Priority;
01924 #endif
01925 }
01926 
01927 //===----------------------------------------------------------------------===//
01928 //                     Register Pressure Tracking
01929 //===----------------------------------------------------------------------===//
01930 
01931 void RegReductionPQBase::dumpRegPressure() const {
01932 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01933   for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
01934          E = TRI->regclass_end(); I != E; ++I) {
01935     const TargetRegisterClass *RC = *I;
01936     unsigned Id = RC->getID();
01937     unsigned RP = RegPressure[Id];
01938     if (!RP) continue;
01939     DEBUG(dbgs() << TRI->getRegClassName(RC) << ": " << RP << " / "
01940           << RegLimit[Id] << '\n');
01941   }
01942 #endif
01943 }
01944 
01945 bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
01946   if (!TLI)
01947     return false;
01948 
01949   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
01950        I != E; ++I) {
01951     if (I->isCtrl())
01952       continue;
01953     SUnit *PredSU = I->getSUnit();
01954     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
01955     // to cover the number of registers defined (they are all live).
01956     if (PredSU->NumRegDefsLeft == 0) {
01957       continue;
01958     }
01959     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
01960          RegDefPos.IsValid(); RegDefPos.Advance()) {
01961       unsigned RCId, Cost;
01962       GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
01963 
01964       if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
01965         return true;
01966     }
01967   }
01968   return false;
01969 }
01970 
01971 bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
01972   const SDNode *N = SU->getNode();
01973 
01974   if (!N->isMachineOpcode() || !SU->NumSuccs)
01975     return false;
01976 
01977   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
01978   for (unsigned i = 0; i != NumDefs; ++i) {
01979     MVT VT = N->getSimpleValueType(i);
01980     if (!N->hasAnyUseOfValue(i))
01981       continue;
01982     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
01983     if (RegPressure[RCId] >= RegLimit[RCId])
01984       return true;
01985   }
01986   return false;
01987 }
01988 
01989 // Compute the register pressure contribution by this instruction by count up
01990 // for uses that are not live and down for defs. Only count register classes
01991 // that are already under high pressure. As a side effect, compute the number of
01992 // uses of registers that are already live.
01993 //
01994 // FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
01995 // so could probably be factored.
01996 int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
01997   LiveUses = 0;
01998   int PDiff = 0;
01999   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
02000        I != E; ++I) {
02001     if (I->isCtrl())
02002       continue;
02003     SUnit *PredSU = I->getSUnit();
02004     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
02005     // to cover the number of registers defined (they are all live).
02006     if (PredSU->NumRegDefsLeft == 0) {
02007       if (PredSU->getNode()->isMachineOpcode())
02008         ++LiveUses;
02009       continue;
02010     }
02011     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
02012          RegDefPos.IsValid(); RegDefPos.Advance()) {
02013       MVT VT = RegDefPos.GetValue();
02014       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02015       if (RegPressure[RCId] >= RegLimit[RCId])
02016         ++PDiff;
02017     }
02018   }
02019   const SDNode *N = SU->getNode();
02020 
02021   if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
02022     return PDiff;
02023 
02024   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
02025   for (unsigned i = 0; i != NumDefs; ++i) {
02026     MVT VT = N->getSimpleValueType(i);
02027     if (!N->hasAnyUseOfValue(i))
02028       continue;
02029     unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02030     if (RegPressure[RCId] >= RegLimit[RCId])
02031       --PDiff;
02032   }
02033   return PDiff;
02034 }
02035 
02036 void RegReductionPQBase::scheduledNode(SUnit *SU) {
02037   if (!TracksRegPressure)
02038     return;
02039 
02040   if (!SU->getNode())
02041     return;
02042 
02043   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02044        I != E; ++I) {
02045     if (I->isCtrl())
02046       continue;
02047     SUnit *PredSU = I->getSUnit();
02048     // NumRegDefsLeft is zero when enough uses of this node have been scheduled
02049     // to cover the number of registers defined (they are all live).
02050     if (PredSU->NumRegDefsLeft == 0) {
02051       continue;
02052     }
02053     // FIXME: The ScheduleDAG currently loses information about which of a
02054     // node's values is consumed by each dependence. Consequently, if the node
02055     // defines multiple register classes, we don't know which to pressurize
02056     // here. Instead the following loop consumes the register defs in an
02057     // arbitrary order. At least it handles the common case of clustered loads
02058     // to the same class. For precise liveness, each SDep needs to indicate the
02059     // result number. But that tightly couples the ScheduleDAG with the
02060     // SelectionDAG making updates tricky. A simpler hack would be to attach a
02061     // value type or register class to SDep.
02062     //
02063     // The most important aspect of register tracking is balancing the increase
02064     // here with the reduction further below. Note that this SU may use multiple
02065     // defs in PredSU. The can't be determined here, but we've already
02066     // compensated by reducing NumRegDefsLeft in PredSU during
02067     // ScheduleDAGSDNodes::AddSchedEdges.
02068     --PredSU->NumRegDefsLeft;
02069     unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
02070     for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
02071          RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
02072       if (SkipRegDefs)
02073         continue;
02074 
02075       unsigned RCId, Cost;
02076       GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
02077       RegPressure[RCId] += Cost;
02078       break;
02079     }
02080   }
02081 
02082   // We should have this assert, but there may be dead SDNodes that never
02083   // materialize as SUnits, so they don't appear to generate liveness.
02084   //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
02085   int SkipRegDefs = (int)SU->NumRegDefsLeft;
02086   for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
02087        RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
02088     if (SkipRegDefs > 0)
02089       continue;
02090     unsigned RCId, Cost;
02091     GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
02092     if (RegPressure[RCId] < Cost) {
02093       // Register pressure tracking is imprecise. This can happen. But we try
02094       // hard not to let it happen because it likely results in poor scheduling.
02095       DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") has too many regdefs\n");
02096       RegPressure[RCId] = 0;
02097     }
02098     else {
02099       RegPressure[RCId] -= Cost;
02100     }
02101   }
02102   dumpRegPressure();
02103 }
02104 
02105 void RegReductionPQBase::unscheduledNode(SUnit *SU) {
02106   if (!TracksRegPressure)
02107     return;
02108 
02109   const SDNode *N = SU->getNode();
02110   if (!N) return;
02111 
02112   if (!N->isMachineOpcode()) {
02113     if (N->getOpcode() != ISD::CopyToReg)
02114       return;
02115   } else {
02116     unsigned Opc = N->getMachineOpcode();
02117     if (Opc == TargetOpcode::EXTRACT_SUBREG ||
02118         Opc == TargetOpcode::INSERT_SUBREG ||
02119         Opc == TargetOpcode::SUBREG_TO_REG ||
02120         Opc == TargetOpcode::REG_SEQUENCE ||
02121         Opc == TargetOpcode::IMPLICIT_DEF)
02122       return;
02123   }
02124 
02125   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02126        I != E; ++I) {
02127     if (I->isCtrl())
02128       continue;
02129     SUnit *PredSU = I->getSUnit();
02130     // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
02131     // counts data deps.
02132     if (PredSU->NumSuccsLeft != PredSU->Succs.size())
02133       continue;
02134     const SDNode *PN = PredSU->getNode();
02135     if (!PN->isMachineOpcode()) {
02136       if (PN->getOpcode() == ISD::CopyFromReg) {
02137         MVT VT = PN->getSimpleValueType(0);
02138         unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02139         RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
02140       }
02141       continue;
02142     }
02143     unsigned POpc = PN->getMachineOpcode();
02144     if (POpc == TargetOpcode::IMPLICIT_DEF)
02145       continue;
02146     if (POpc == TargetOpcode::EXTRACT_SUBREG ||
02147         POpc == TargetOpcode::INSERT_SUBREG ||
02148         POpc == TargetOpcode::SUBREG_TO_REG) {
02149       MVT VT = PN->getSimpleValueType(0);
02150       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02151       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
02152       continue;
02153     }
02154     unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
02155     for (unsigned i = 0; i != NumDefs; ++i) {
02156       MVT VT = PN->getSimpleValueType(i);
02157       if (!PN->hasAnyUseOfValue(i))
02158         continue;
02159       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02160       if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
02161         // Register pressure tracking is imprecise. This can happen.
02162         RegPressure[RCId] = 0;
02163       else
02164         RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
02165     }
02166   }
02167 
02168   // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
02169   // may transfer data dependencies to CopyToReg.
02170   if (SU->NumSuccs && N->isMachineOpcode()) {
02171     unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
02172     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
02173       MVT VT = N->getSimpleValueType(i);
02174       if (VT == MVT::Glue || VT == MVT::Other)
02175         continue;
02176       if (!N->hasAnyUseOfValue(i))
02177         continue;
02178       unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
02179       RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
02180     }
02181   }
02182 
02183   dumpRegPressure();
02184 }
02185 
02186 //===----------------------------------------------------------------------===//
02187 //           Dynamic Node Priority for Register Pressure Reduction
02188 //===----------------------------------------------------------------------===//
02189 
02190 /// closestSucc - Returns the scheduled cycle of the successor which is
02191 /// closest to the current cycle.
02192 static unsigned closestSucc(const SUnit *SU) {
02193   unsigned MaxHeight = 0;
02194   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
02195        I != E; ++I) {
02196     if (I->isCtrl()) continue;  // ignore chain succs
02197     unsigned Height = I->getSUnit()->getHeight();
02198     // If there are bunch of CopyToRegs stacked up, they should be considered
02199     // to be at the same position.
02200     if (I->getSUnit()->getNode() &&
02201         I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
02202       Height = closestSucc(I->getSUnit())+1;
02203     if (Height > MaxHeight)
02204       MaxHeight = Height;
02205   }
02206   return MaxHeight;
02207 }
02208 
02209 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
02210 /// for scratch registers, i.e. number of data dependencies.
02211 static unsigned calcMaxScratches(const SUnit *SU) {
02212   unsigned Scratches = 0;
02213   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02214        I != E; ++I) {
02215     if (I->isCtrl()) continue;  // ignore chain preds
02216     Scratches++;
02217   }
02218   return Scratches;
02219 }
02220 
02221 /// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
02222 /// CopyFromReg from a virtual register.
02223 static bool hasOnlyLiveInOpers(const SUnit *SU) {
02224   bool RetVal = false;
02225   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02226        I != E; ++I) {
02227     if (I->isCtrl()) continue;
02228     const SUnit *PredSU = I->getSUnit();
02229     if (PredSU->getNode() &&
02230         PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
02231       unsigned Reg =
02232         cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
02233       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
02234         RetVal = true;
02235         continue;
02236       }
02237     }
02238     return false;
02239   }
02240   return RetVal;
02241 }
02242 
02243 /// hasOnlyLiveOutUses - Return true if SU has only value successors that are
02244 /// CopyToReg to a virtual register. This SU def is probably a liveout and
02245 /// it has no other use. It should be scheduled closer to the terminator.
02246 static bool hasOnlyLiveOutUses(const SUnit *SU) {
02247   bool RetVal = false;
02248   for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
02249        I != E; ++I) {
02250     if (I->isCtrl()) continue;
02251     const SUnit *SuccSU = I->getSUnit();
02252     if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
02253       unsigned Reg =
02254         cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
02255       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
02256         RetVal = true;
02257         continue;
02258       }
02259     }
02260     return false;
02261   }
02262   return RetVal;
02263 }
02264 
02265 // Set isVRegCycle for a node with only live in opers and live out uses. Also
02266 // set isVRegCycle for its CopyFromReg operands.
02267 //
02268 // This is only relevant for single-block loops, in which case the VRegCycle
02269 // node is likely an induction variable in which the operand and target virtual
02270 // registers should be coalesced (e.g. pre/post increment values). Setting the
02271 // isVRegCycle flag helps the scheduler prioritize other uses of the same
02272 // CopyFromReg so that this node becomes the virtual register "kill". This
02273 // avoids interference between the values live in and out of the block and
02274 // eliminates a copy inside the loop.
02275 static void initVRegCycle(SUnit *SU) {
02276   if (DisableSchedVRegCycle)
02277     return;
02278 
02279   if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
02280     return;
02281 
02282   DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
02283 
02284   SU->isVRegCycle = true;
02285 
02286   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
02287        I != E; ++I) {
02288     if (I->isCtrl()) continue;
02289     I->getSUnit()->isVRegCycle = true;
02290   }
02291 }
02292 
02293 // After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
02294 // CopyFromReg operands. We should no longer penalize other uses of this VReg.
02295 static void resetVRegCycle(SUnit *SU) {
02296   if (!SU->isVRegCycle)
02297     return;
02298 
02299   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
02300        I != E; ++I) {
02301     if (I->isCtrl()) continue;  // ignore chain preds
02302     SUnit *PredSU = I->getSUnit();
02303     if (PredSU->isVRegCycle) {
02304       assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
02305              "VRegCycle def must be CopyFromReg");
02306       I->getSUnit()->isVRegCycle = 0;
02307     }
02308   }
02309 }
02310 
02311 // Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
02312 // means a node that defines the VRegCycle has not been scheduled yet.
02313 static bool hasVRegCycleUse(const SUnit *SU) {
02314   // If this SU also defines the VReg, don't hoist it as a "use".
02315   if (SU->isVRegCycle)
02316     return false;
02317 
02318   for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
02319        I != E; ++I) {
02320     if (I->isCtrl()) continue;  // ignore chain preds
02321     if (I->getSUnit()->isVRegCycle &&
02322         I->getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
02323       DEBUG(dbgs() << "  VReg cycle use: SU (" << SU->NodeNum << ")\n");
02324       return true;
02325     }
02326   }
02327   return false;
02328 }
02329 
02330 // Check for either a dependence (latency) or resource (hazard) stall.
02331 //
02332 // Note: The ScheduleHazardRecognizer interface requires a non-const SU.
02333 static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
02334   if ((int)SPQ->getCurCycle() < Height) return true;
02335   if (SPQ->getHazardRec()->getHazardType(SU, 0)
02336       != ScheduleHazardRecognizer::NoHazard)
02337     return true;
02338   return false;
02339 }
02340 
02341 // Return -1 if left has higher priority, 1 if right has higher priority.
02342 // Return 0 if latency-based priority is equivalent.
02343 static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
02344                             RegReductionPQBase *SPQ) {
02345   // Scheduling an instruction that uses a VReg whose postincrement has not yet
02346   // been scheduled will induce a copy. Model this as an extra cycle of latency.
02347   int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
02348   int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
02349   int LHeight = (int)left->getHeight() + LPenalty;
02350   int RHeight = (int)right->getHeight() + RPenalty;
02351 
02352   bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
02353     BUHasStall(left, LHeight, SPQ);
02354   bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
02355     BUHasStall(right, RHeight, SPQ);
02356 
02357   // If scheduling one of the node will cause a pipeline stall, delay it.
02358   // If scheduling either one of the node will cause a pipeline stall, sort
02359   // them according to their height.
02360   if (LStall) {
02361     if (!RStall)
02362       return 1;
02363     if (LHeight != RHeight)
02364       return LHeight > RHeight ? 1 : -1;
02365   } else if (RStall)
02366     return -1;
02367 
02368   // If either node is scheduling for latency, sort them by height/depth
02369   // and latency.
02370   if (!checkPref || (left->SchedulingPref == Sched::ILP ||
02371                      right->SchedulingPref == Sched::ILP)) {
02372     // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
02373     // is enabled, grouping instructions by cycle, then its height is already
02374     // covered so only its depth matters. We also reach this point if both stall
02375     // but have the same height.
02376     if (!SPQ->getHazardRec()->isEnabled()) {
02377       if (LHeight != RHeight)
02378         return LHeight > RHeight ? 1 : -1;
02379     }
02380     int LDepth = left->getDepth() - LPenalty;
02381     int RDepth = right->getDepth() - RPenalty;
02382     if (LDepth != RDepth) {
02383       DEBUG(dbgs() << "  Comparing latency of SU (" << left->NodeNum
02384             << ") depth " << LDepth << " vs SU (" << right->NodeNum
02385             << ") depth " << RDepth << "\n");
02386       return LDepth < RDepth ? 1 : -1;
02387     }
02388     if (left->Latency != right->Latency)
02389       return left->Latency > right->Latency ? 1 : -1;
02390   }
02391   return 0;
02392 }
02393 
02394 static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
02395   // Schedule physical register definitions close to their use. This is
02396   // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
02397   // long as shortening physreg live ranges is generally good, we can defer
02398   // creating a subtarget hook.
02399   if (!DisableSchedPhysRegJoin) {
02400     bool LHasPhysReg = left->hasPhysRegDefs;
02401     bool RHasPhysReg = right->hasPhysRegDefs;
02402     if (LHasPhysReg != RHasPhysReg) {
02403       #ifndef NDEBUG
02404       static const char *const PhysRegMsg[] = { " has no physreg",
02405                                                 " defines a physreg" };
02406       #endif
02407       DEBUG(dbgs() << "  SU (" << left->NodeNum << ") "
02408             << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
02409             << PhysRegMsg[RHasPhysReg] << "\n");
02410       return LHasPhysReg < RHasPhysReg;
02411     }
02412   }
02413 
02414   // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
02415   unsigned LPriority = SPQ->getNodePriority(left);
02416   unsigned RPriority = SPQ->getNodePriority(right);
02417 
02418   // Be really careful about hoisting call operands above previous calls.
02419   // Only allows it if it would reduce register pressure.
02420   if (left->isCall && right->isCallOp) {
02421     unsigned RNumVals = right->getNode()->getNumValues();
02422     RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
02423   }
02424   if (right->isCall && left->isCallOp) {
02425     unsigned LNumVals = left->getNode()->getNumValues();
02426     LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
02427   }
02428 
02429   if (LPriority != RPriority)
02430     return LPriority > RPriority;
02431 
02432   // One or both of the nodes are calls and their sethi-ullman numbers are the
02433   // same, then keep source order.
02434   if (left->isCall || right->isCall) {
02435     unsigned LOrder = SPQ->getNodeOrdering(left);
02436     unsigned ROrder = SPQ->getNodeOrdering(right);
02437 
02438     // Prefer an ordering where the lower the non-zero order number, the higher
02439     // the preference.
02440     if ((LOrder || ROrder) && LOrder != ROrder)
02441       return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
02442   }
02443 
02444   // Try schedule def + use closer when Sethi-Ullman numbers are the same.
02445   // e.g.
02446   // t1 = op t2, c1
02447   // t3 = op t4, c2
02448   //
02449   // and the following instructions are both ready.
02450   // t2 = op c3
02451   // t4 = op c4
02452   //
02453   // Then schedule t2 = op first.
02454   // i.e.
02455   // t4 = op c4
02456   // t2 = op c3
02457   // t1 = op t2, c1
02458   // t3 = op t4, c2
02459   //
02460   // This creates more short live intervals.
02461   unsigned LDist = closestSucc(left);
02462   unsigned RDist = closestSucc(right);
02463   if (LDist != RDist)
02464     return LDist < RDist;
02465 
02466   // How many registers becomes live when the node is scheduled.
02467   unsigned LScratch = calcMaxScratches(left);
02468   unsigned RScratch = calcMaxScratches(right);
02469   if (LScratch != RScratch)
02470     return LScratch > RScratch;
02471 
02472   // Comparing latency against a call makes little sense unless the node
02473   // is register pressure-neutral.
02474   if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
02475     return (left->NodeQueueId > right->NodeQueueId);
02476 
02477   // Do not compare latencies when one or both of the nodes are calls.
02478   if (!DisableSchedCycles &&
02479       !(left->isCall || right->isCall)) {
02480     int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
02481     if (result != 0)
02482       return result > 0;
02483   }
02484   else {
02485     if (left->getHeight() != right->getHeight())
02486       return left->getHeight() > right->getHeight();
02487 
02488     if (left->getDepth() != right->getDepth())
02489       return left->getDepth() < right->getDepth();
02490   }
02491 
02492   assert(left->NodeQueueId && right->NodeQueueId &&
02493          "NodeQueueId cannot be zero");
02494   return (left->NodeQueueId > right->NodeQueueId);
02495 }
02496 
02497 // Bottom up
02498 bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02499   if (int res = checkSpecialNodes(left, right))
02500     return res > 0;
02501 
02502   return BURRSort(left, right, SPQ);
02503 }
02504 
02505 // Source order, otherwise bottom up.
02506 bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02507   if (int res = checkSpecialNodes(left, right))
02508     return res > 0;
02509 
02510   unsigned LOrder = SPQ->getNodeOrdering(left);
02511   unsigned ROrder = SPQ->getNodeOrdering(right);
02512 
02513   // Prefer an ordering where the lower the non-zero order number, the higher
02514   // the preference.
02515   if ((LOrder || ROrder) && LOrder != ROrder)
02516     return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
02517 
02518   return BURRSort(left, right, SPQ);
02519 }
02520 
02521 // If the time between now and when the instruction will be ready can cover
02522 // the spill code, then avoid adding it to the ready queue. This gives long
02523 // stalls highest priority and allows hoisting across calls. It should also
02524 // speed up processing the available queue.
02525 bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
02526   static const unsigned ReadyDelay = 3;
02527 
02528   if (SPQ->MayReduceRegPressure(SU)) return true;
02529 
02530   if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
02531 
02532   if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
02533       != ScheduleHazardRecognizer::NoHazard)
02534     return false;
02535 
02536   return true;
02537 }
02538 
02539 // Return true if right should be scheduled with higher priority than left.
02540 bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02541   if (int res = checkSpecialNodes(left, right))
02542     return res > 0;
02543 
02544   if (left->isCall || right->isCall)
02545     // No way to compute latency of calls.
02546     return BURRSort(left, right, SPQ);
02547 
02548   bool LHigh = SPQ->HighRegPressure(left);
02549   bool RHigh = SPQ->HighRegPressure(right);
02550   // Avoid causing spills. If register pressure is high, schedule for
02551   // register pressure reduction.
02552   if (LHigh && !RHigh) {
02553     DEBUG(dbgs() << "  pressure SU(" << left->NodeNum << ") > SU("
02554           << right->NodeNum << ")\n");
02555     return true;
02556   }
02557   else if (!LHigh && RHigh) {
02558     DEBUG(dbgs() << "  pressure SU(" << right->NodeNum << ") > SU("
02559           << left->NodeNum << ")\n");
02560     return false;
02561   }
02562   if (!LHigh && !RHigh) {
02563     int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
02564     if (result != 0)
02565       return result > 0;
02566   }
02567   return BURRSort(left, right, SPQ);
02568 }
02569 
02570 // Schedule as many instructions in each cycle as possible. So don't make an
02571 // instruction available unless it is ready in the current cycle.
02572 bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
02573   if (SU->getHeight() > CurCycle) return false;
02574 
02575   if (SPQ->getHazardRec()->getHazardType(SU, 0)
02576       != ScheduleHazardRecognizer::NoHazard)
02577     return false;
02578 
02579   return true;
02580 }
02581 
02582 static bool canEnableCoalescing(SUnit *SU) {
02583   unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
02584   if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
02585     // CopyToReg should be close to its uses to facilitate coalescing and
02586     // avoid spilling.
02587     return true;
02588 
02589   if (Opc == TargetOpcode::EXTRACT_SUBREG ||
02590       Opc == TargetOpcode::SUBREG_TO_REG ||
02591       Opc == TargetOpcode::INSERT_SUBREG)
02592     // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
02593     // close to their uses to facilitate coalescing.
02594     return true;
02595 
02596   if (SU->NumPreds == 0 && SU->NumSuccs != 0)
02597     // If SU does not have a register def, schedule it close to its uses
02598     // because it does not lengthen any live ranges.
02599     return true;
02600 
02601   return false;
02602 }
02603 
02604 // list-ilp is currently an experimental scheduler that allows various
02605 // heuristics to be enabled prior to the normal register reduction logic.
02606 bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
02607   if (int res = checkSpecialNodes(left, right))
02608     return res > 0;
02609 
02610   if (left->isCall || right->isCall)
02611     // No way to compute latency of calls.
02612     return BURRSort(left, right, SPQ);
02613 
02614   unsigned LLiveUses = 0, RLiveUses = 0;
02615   int LPDiff = 0, RPDiff = 0;
02616   if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
02617     LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
02618     RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
02619   }
02620   if (!DisableSchedRegPressure && LPDiff != RPDiff) {
02621     DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
02622           << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
02623     return LPDiff > RPDiff;
02624   }
02625 
02626   if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
02627     bool LReduce = canEnableCoalescing(left);
02628     bool RReduce = canEnableCoalescing(right);
02629     if (LReduce && !RReduce) return false;
02630     if (RReduce && !LReduce) return true;
02631   }
02632 
02633   if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
02634     DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
02635           << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
02636     return LLiveUses < RLiveUses;
02637   }
02638 
02639   if (!DisableSchedStalls) {
02640     bool LStall = BUHasStall(left, left->getHeight(), SPQ);
02641     bool RStall = BUHasStall(right, right->getHeight(), SPQ);
02642     if (LStall != RStall)
02643       return left->getHeight() > right->getHeight();
02644   }
02645 
02646   if (!DisableSchedCriticalPath) {
02647     int spread = (int)left->getDepth() - (int)right->getDepth();
02648     if (std::abs(spread) > MaxReorderWindow) {
02649       DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
02650             << left->getDepth() << " != SU(" << right->NodeNum << "): "
02651             << right->getDepth() << "\n");
02652       return left->getDepth() < right->getDepth();
02653     }
02654   }
02655 
02656   if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
02657     int spread = (int)left->getHeight() - (int)right->getHeight();
02658     if (std::abs(spread) > MaxReorderWindow)
02659       return left->getHeight() > right->getHeight();
02660   }
02661 
02662   return BURRSort(left, right, SPQ);
02663 }
02664 
02665 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
02666   SUnits = &sunits;
02667   // Add pseudo dependency edges for two-address nodes.
02668   if (!Disable2AddrHack)
02669     AddPseudoTwoAddrDeps();
02670   // Reroute edges to nodes with multiple uses.
02671   if (!TracksRegPressure && !SrcOrder)
02672     PrescheduleNodesWithMultipleUses();
02673   // Calculate node priorities.
02674   CalculateSethiUllmanNumbers();
02675 
02676   // For single block loops, mark nodes that look like canonical IV increments.
02677   if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) {
02678     for (unsigned i = 0, e = sunits.size(); i != e; ++i) {
02679       initVRegCycle(&sunits[i]);
02680     }
02681   }
02682 }
02683 
02684 //===----------------------------------------------------------------------===//
02685 //                    Preschedule for Register Pressure
02686 //===----------------------------------------------------------------------===//
02687 
02688 bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
02689   if (SU->isTwoAddress) {
02690     unsigned Opc = SU->getNode()->getMachineOpcode();
02691     const MCInstrDesc &MCID = TII->get(Opc);
02692     unsigned NumRes = MCID.getNumDefs();
02693     unsigned NumOps = MCID.getNumOperands() - NumRes;
02694     for (unsigned i = 0; i != NumOps; ++i) {
02695       if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
02696         SDNode *DU = SU->getNode()->getOperand(i).getNode();
02697         if (DU->getNodeId() != -1 &&
02698             Op->OrigNode == &(*SUnits)[DU->getNodeId()])
02699           return true;
02700       }
02701     }
02702   }
02703   return false;
02704 }
02705 
02706 /// canClobberReachingPhysRegUse - True if SU would clobber one of it's
02707 /// successor's explicit physregs whose definition can reach DepSU.
02708 /// i.e. DepSU should not be scheduled above SU.
02709 static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
02710                                          ScheduleDAGRRList *scheduleDAG,
02711                                          const TargetInstrInfo *TII,
02712                                          const TargetRegisterInfo *TRI) {
02713   const uint16_t *ImpDefs
02714     = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
02715   const uint32_t *RegMask = getNodeRegMask(SU->getNode());
02716   if(!ImpDefs && !RegMask)
02717     return false;
02718 
02719   for (SUnit::const_succ_iterator SI = SU->Succs.begin(), SE = SU->Succs.end();
02720        SI != SE; ++SI) {
02721     SUnit *SuccSU = SI->getSUnit();
02722     for (SUnit::const_pred_iterator PI = SuccSU->Preds.begin(),
02723            PE = SuccSU->Preds.end(); PI != PE; ++PI) {
02724       if (!PI->isAssignedRegDep())
02725         continue;
02726 
02727       if (RegMask && MachineOperand::clobbersPhysReg(RegMask, PI->getReg()) &&
02728           scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
02729         return true;
02730 
02731       if (ImpDefs)
02732         for (const uint16_t *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
02733           // Return true if SU clobbers this physical register use and the
02734           // definition of the register reaches from DepSU. IsReachable queries
02735           // a topological forward sort of the DAG (following the successors).
02736           if (TRI->regsOverlap(*ImpDef, PI->getReg()) &&
02737               scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
02738             return true;
02739     }
02740   }
02741   return false;
02742 }
02743 
02744 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
02745 /// physical register defs.
02746 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
02747                                   const TargetInstrInfo *TII,
02748                                   const TargetRegisterInfo *TRI) {
02749   SDNode *N = SuccSU->getNode();
02750   unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
02751   const uint16_t *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
02752   assert(ImpDefs && "Caller should check hasPhysRegDefs");
02753   for (const SDNode *SUNode = SU->getNode(); SUNode;
02754        SUNode = SUNode->getGluedNode()) {
02755     if (!SUNode->isMachineOpcode())
02756       continue;
02757     const uint16_t *SUImpDefs =
02758       TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
02759     const uint32_t *SURegMask = getNodeRegMask(SUNode);
02760     if (!SUImpDefs && !SURegMask)
02761       continue;
02762     for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
02763       MVT VT = N->getSimpleValueType(i);
02764       if (VT == MVT::Glue || VT == MVT::Other)
02765         continue;
02766       if (!N->hasAnyUseOfValue(i))
02767         continue;
02768       unsigned Reg = ImpDefs[i - NumDefs];
02769       if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
02770         return true;
02771       if (!SUImpDefs)
02772         continue;
02773       for (;*SUImpDefs; ++SUImpDefs) {
02774         unsigned SUReg = *SUImpDefs;
02775         if (TRI->regsOverlap(Reg, SUReg))
02776           return true;
02777       }
02778     }
02779   }
02780   return false;
02781 }
02782 
02783 /// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
02784 /// are not handled well by the general register pressure reduction
02785 /// heuristics. When presented with code like this:
02786 ///
02787 ///      N
02788 ///    / |
02789 ///   /  |
02790 ///  U  store
02791 ///  |
02792 /// ...
02793 ///
02794 /// the heuristics tend to push the store up, but since the
02795 /// operand of the store has another use (U), this would increase
02796 /// the length of that other use (the U->N edge).
02797 ///
02798 /// This function transforms code like the above to route U's
02799 /// dependence through the store when possible, like this:
02800 ///
02801 ///      N
02802 ///      ||
02803 ///      ||
02804 ///     store
02805 ///       |
02806 ///       U
02807 ///       |
02808 ///      ...
02809 ///
02810 /// This results in the store being scheduled immediately
02811 /// after N, which shortens the U->N live range, reducing
02812 /// register pressure.
02813 ///
02814 void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
02815   // Visit all the nodes in topological order, working top-down.
02816   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
02817     SUnit *SU = &(*SUnits)[i];
02818     // For now, only look at nodes with no data successors, such as stores.
02819     // These are especially important, due to the heuristics in
02820     // getNodePriority for nodes with no data successors.
02821     if (SU->NumSuccs != 0)
02822       continue;
02823     // For now, only look at nodes with exactly one data predecessor.
02824     if (SU->NumPreds != 1)
02825       continue;
02826     // Avoid prescheduling copies to virtual registers, which don't behave
02827     // like other nodes from the perspective of scheduling heuristics.
02828     if (SDNode *N = SU->getNode())
02829       if (N->getOpcode() == ISD::CopyToReg &&
02830           TargetRegisterInfo::isVirtualRegister
02831             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
02832         continue;
02833 
02834     // Locate the single data predecessor.
02835     SUnit *PredSU = nullptr;
02836     for (SUnit::const_pred_iterator II = SU->Preds.begin(),
02837          EE = SU->Preds.end(); II != EE; ++II)
02838       if (!II->isCtrl()) {
02839         PredSU = II->getSUnit();
02840         break;
02841       }
02842     assert(PredSU);
02843 
02844     // Don't rewrite edges that carry physregs, because that requires additional
02845     // support infrastructure.
02846     if (PredSU->hasPhysRegDefs)
02847       continue;
02848     // Short-circuit the case where SU is PredSU's only data successor.
02849     if (PredSU->NumSuccs == 1)
02850       continue;
02851     // Avoid prescheduling to copies from virtual registers, which don't behave
02852     // like other nodes from the perspective of scheduling heuristics.
02853     if (SDNode *N = SU->getNode())
02854       if (N->getOpcode() == ISD::CopyFromReg &&
02855           TargetRegisterInfo::isVirtualRegister
02856             (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
02857         continue;
02858 
02859     // Perform checks on the successors of PredSU.
02860     for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
02861          EE = PredSU->Succs.end(); II != EE; ++II) {
02862       SUnit *PredSuccSU = II->getSUnit();
02863       if (PredSuccSU == SU) continue;
02864       // If PredSU has another successor with no data successors, for
02865       // now don't attempt to choose either over the other.
02866       if (PredSuccSU->NumSuccs == 0)
02867         goto outer_loop_continue;
02868       // Don't break physical register dependencies.
02869       if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
02870         if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
02871           goto outer_loop_continue;
02872       // Don't introduce graph cycles.
02873       if (scheduleDAG->IsReachable(SU, PredSuccSU))
02874         goto outer_loop_continue;
02875     }
02876 
02877     // Ok, the transformation is safe and the heuristics suggest it is
02878     // profitable. Update the graph.
02879     DEBUG(dbgs() << "    Prescheduling SU #" << SU->NodeNum
02880                  << " next to PredSU #" << PredSU->NodeNum
02881                  << " to guide scheduling in the presence of multiple uses\n");
02882     for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
02883       SDep Edge = PredSU->Succs[i];
02884       assert(!Edge.isAssignedRegDep());
02885       SUnit *SuccSU = Edge.getSUnit();
02886       if (SuccSU != SU) {
02887         Edge.setSUnit(PredSU);
02888         scheduleDAG->RemovePred(SuccSU, Edge);
02889         scheduleDAG->AddPred(SU, Edge);
02890         Edge.setSUnit(SU);
02891         scheduleDAG->AddPred(SuccSU, Edge);
02892         --i;
02893       }
02894     }
02895   outer_loop_continue:;
02896   }
02897 }
02898 
02899 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
02900 /// it as a def&use operand. Add a pseudo control edge from it to the other
02901 /// node (if it won't create a cycle) so the two-address one will be scheduled
02902 /// first (lower in the schedule). If both nodes are two-address, favor the
02903 /// one that has a CopyToReg use (more likely to be a loop induction update).
02904 /// If both are two-address, but one is commutable while the other is not
02905 /// commutable, favor the one that's not commutable.
02906 void RegReductionPQBase::AddPseudoTwoAddrDeps() {
02907   for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
02908     SUnit *SU = &(*SUnits)[i];
02909     if (!SU->isTwoAddress)
02910       continue;
02911 
02912     SDNode *Node = SU->getNode();
02913     if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
02914       continue;
02915 
02916     bool isLiveOut = hasOnlyLiveOutUses(SU);
02917     unsigned Opc = Node->getMachineOpcode();
02918     const MCInstrDesc &MCID = TII->get(Opc);
02919     unsigned NumRes = MCID.getNumDefs();
02920     unsigned NumOps = MCID.getNumOperands() - NumRes;
02921     for (unsigned j = 0; j != NumOps; ++j) {
02922       if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
02923         continue;
02924       SDNode *DU = SU->getNode()->getOperand(j).getNode();
02925       if (DU->getNodeId() == -1)
02926         continue;
02927       const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
02928       if (!DUSU) continue;
02929       for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
02930            E = DUSU->Succs.end(); I != E; ++I) {
02931         if (I->isCtrl()) continue;
02932         SUnit *SuccSU = I->getSUnit();
02933         if (SuccSU == SU)
02934           continue;
02935         // Be conservative. Ignore if nodes aren't at roughly the same
02936         // depth and height.
02937         if (SuccSU->getHeight() < SU->getHeight() &&
02938             (SU->getHeight() - SuccSU->getHeight()) > 1)
02939           continue;
02940         // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
02941         // constrains whatever is using the copy, instead of the copy
02942         // itself. In the case that the copy is coalesced, this
02943         // preserves the intent of the pseudo two-address heurietics.
02944         while (SuccSU->Succs.size() == 1 &&
02945                SuccSU->getNode()->isMachineOpcode() &&
02946                SuccSU->getNode()->getMachineOpcode() ==
02947                  TargetOpcode::COPY_TO_REGCLASS)
02948           SuccSU = SuccSU->Succs.front().getSUnit();
02949         // Don't constrain non-instruction nodes.
02950         if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
02951           continue;
02952         // Don't constrain nodes with physical register defs if the
02953         // predecessor can clobber them.
02954         if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
02955           if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
02956             continue;
02957         }
02958         // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
02959         // these may be coalesced away. We want them close to their uses.
02960         unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
02961         if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
02962             SuccOpc == TargetOpcode::INSERT_SUBREG ||
02963             SuccOpc == TargetOpcode::SUBREG_TO_REG)
02964           continue;
02965         if (!canClobberReachingPhysRegUse(SuccSU, SU, scheduleDAG, TII, TRI) &&
02966             (!canClobber(SuccSU, DUSU) ||
02967              (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
02968              (!SU->isCommutable && SuccSU->isCommutable)) &&
02969             !scheduleDAG->IsReachable(SuccSU, SU)) {
02970           DEBUG(dbgs() << "    Adding a pseudo-two-addr edge from SU #"
02971                        << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
02972           scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Artificial));
02973         }
02974       }
02975     }
02976   }
02977 }
02978 
02979 //===----------------------------------------------------------------------===//
02980 //                         Public Constructor Functions
02981 //===----------------------------------------------------------------------===//
02982 
02983 llvm::ScheduleDAGSDNodes *
02984 llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
02985                                  CodeGenOpt::Level OptLevel) {
02986   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
02987   const TargetInstrInfo *TII = STI.getInstrInfo();
02988   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
02989 
02990   BURegReductionPriorityQueue *PQ =
02991     new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, nullptr);
02992   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
02993   PQ->setScheduleDAG(SD);
02994   return SD;
02995 }
02996 
02997 llvm::ScheduleDAGSDNodes *
02998 llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
02999                                    CodeGenOpt::Level OptLevel) {
03000   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
03001   const TargetInstrInfo *TII = STI.getInstrInfo();
03002   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
03003 
03004   SrcRegReductionPriorityQueue *PQ =
03005     new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, nullptr);
03006   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
03007   PQ->setScheduleDAG(SD);
03008   return SD;
03009 }
03010 
03011 llvm::ScheduleDAGSDNodes *
03012 llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
03013                                    CodeGenOpt::Level OptLevel) {
03014   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
03015   const TargetInstrInfo *TII = STI.getInstrInfo();
03016   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
03017   const TargetLowering *TLI = IS->TLI;
03018 
03019   HybridBURRPriorityQueue *PQ =
03020     new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
03021 
03022   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
03023   PQ->setScheduleDAG(SD);
03024   return SD;
03025 }
03026 
03027 llvm::ScheduleDAGSDNodes *
03028 llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
03029                                 CodeGenOpt::Level OptLevel) {
03030   const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
03031   const TargetInstrInfo *TII = STI.getInstrInfo();
03032   const TargetRegisterInfo *TRI = STI.getRegisterInfo();
03033   const TargetLowering *TLI = IS->TLI;
03034 
03035   ILPBURRPriorityQueue *PQ =
03036     new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
03037   ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
03038   PQ->setScheduleDAG(SD);
03039   return SD;
03040 }