blob: 0b548b277f4cf001b0f381adb59bc02f29262297 [file] [log] [blame]
Dan Gohman23785a12008-08-12 17:42:33 +00001//===----- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler --===//
Evan Chengd38c22b2006-05-11 23:55:42 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengd38c22b2006-05-11 23:55:42 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This implements bottom-up and top-down register pressure reduction list
11// schedulers, using standard algorithms. The basic approach uses a priority
12// queue of available nodes to schedule. One at a time, nodes are taken from
13// the priority queue (thus in priority order), checked for legality to
14// schedule, and emitted if legal.
15//
16//===----------------------------------------------------------------------===//
17
Dale Johannesen2182f062007-07-13 17:13:54 +000018#define DEBUG_TYPE "pre-RA-sched"
Dan Gohman483377c2009-02-06 17:22:58 +000019#include "ScheduleDAGSDNodes.h"
Chris Lattner3b9f02a2010-04-07 05:20:54 +000020#include "llvm/InlineAsm.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000021#include "llvm/CodeGen/SchedulerRegistry.h"
Dan Gohman619ef482009-01-15 19:20:50 +000022#include "llvm/CodeGen/SelectionDAGISel.h"
Andrew Trick10ffc2b2010-12-24 05:03:26 +000023#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Dan Gohman3a4be0f2008-02-10 18:45:23 +000024#include "llvm/Target/TargetRegisterInfo.h"
Owen Anderson8c2c1e92006-05-12 06:33:49 +000025#include "llvm/Target/TargetData.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000026#include "llvm/Target/TargetMachine.h"
27#include "llvm/Target/TargetInstrInfo.h"
Evan Chenga77f3d32010-07-21 06:09:07 +000028#include "llvm/Target/TargetLowering.h"
Evan Cheng5924bf72007-09-25 01:54:36 +000029#include "llvm/ADT/SmallSet.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000030#include "llvm/ADT/Statistic.h"
Roman Levenstein6b371142008-04-29 09:07:59 +000031#include "llvm/ADT/STLExtras.h"
Chris Lattner3b9f02a2010-04-07 05:20:54 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000034#include "llvm/Support/raw_ostream.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000035#include <climits>
Evan Chengd38c22b2006-05-11 23:55:42 +000036using namespace llvm;
37
Dan Gohmanfd227e92008-03-25 17:10:29 +000038STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
Evan Cheng79e97132007-10-05 01:39:18 +000039STATISTIC(NumUnfolds, "Number of nodes unfolded");
Evan Cheng1ec79b42007-09-27 07:09:03 +000040STATISTIC(NumDups, "Number of duplicated nodes");
Evan Chengb2c42c62009-01-12 03:19:55 +000041STATISTIC(NumPRCopies, "Number of physical register copies");
Evan Cheng1ec79b42007-09-27 07:09:03 +000042
Jim Laskey95eda5b2006-08-01 14:21:23 +000043static RegisterScheduler
44 burrListDAGScheduler("list-burr",
Dan Gohman9c4b7d52008-10-14 20:25:08 +000045 "Bottom-up register reduction list scheduling",
Jim Laskey95eda5b2006-08-01 14:21:23 +000046 createBURRListDAGScheduler);
47static RegisterScheduler
48 tdrListrDAGScheduler("list-tdrr",
Dan Gohman9c4b7d52008-10-14 20:25:08 +000049 "Top-down register reduction list scheduling",
Jim Laskey95eda5b2006-08-01 14:21:23 +000050 createTDRRListDAGScheduler);
Bill Wendling8cbc25d2010-01-23 10:26:57 +000051static RegisterScheduler
52 sourceListDAGScheduler("source",
53 "Similar to list-burr but schedules in source "
54 "order when possible",
55 createSourceListDAGScheduler);
Jim Laskey95eda5b2006-08-01 14:21:23 +000056
Evan Chengbdd062d2010-05-20 06:13:19 +000057static RegisterScheduler
Evan Cheng725211e2010-05-21 00:42:32 +000058 hybridListDAGScheduler("list-hybrid",
Evan Cheng37b740c2010-07-24 00:39:05 +000059 "Bottom-up register pressure aware list scheduling "
60 "which tries to balance latency and register pressure",
Evan Chengbdd062d2010-05-20 06:13:19 +000061 createHybridListDAGScheduler);
62
Evan Cheng37b740c2010-07-24 00:39:05 +000063static RegisterScheduler
64 ILPListDAGScheduler("list-ilp",
65 "Bottom-up register pressure aware list scheduling "
66 "which tries to balance ILP and register pressure",
67 createILPListDAGScheduler);
68
Andrew Trick47ff14b2011-01-21 05:51:33 +000069static cl::opt<bool> DisableSchedCycles(
Andrew Trickbd428ec2011-01-21 06:19:05 +000070 "disable-sched-cycles", cl::Hidden, cl::init(false),
Andrew Trick47ff14b2011-01-21 05:51:33 +000071 cl::desc("Disable cycle-level precision during preRA scheduling"));
Andrew Trick10ffc2b2010-12-24 05:03:26 +000072
Evan Chengd38c22b2006-05-11 23:55:42 +000073namespace {
Evan Chengd38c22b2006-05-11 23:55:42 +000074//===----------------------------------------------------------------------===//
75/// ScheduleDAGRRList - The actual register reduction list scheduler
76/// implementation. This supports both top-down and bottom-up scheduling.
77///
Nick Lewycky02d5f772009-10-25 06:33:48 +000078class ScheduleDAGRRList : public ScheduleDAGSDNodes {
Evan Chengd38c22b2006-05-11 23:55:42 +000079private:
80 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
81 /// it is top-down.
82 bool isBottomUp;
Evan Cheng2c977312008-07-01 18:05:03 +000083
Evan Chengbdd062d2010-05-20 06:13:19 +000084 /// NeedLatency - True if the scheduler will make use of latency information.
85 ///
86 bool NeedLatency;
87
Evan Chengd38c22b2006-05-11 23:55:42 +000088 /// AvailableQueue - The priority queue to use for the available SUnits.
Evan Chengd38c22b2006-05-11 23:55:42 +000089 SchedulingPriorityQueue *AvailableQueue;
90
Andrew Trick10ffc2b2010-12-24 05:03:26 +000091 /// PendingQueue - This contains all of the instructions whose operands have
92 /// been issued, but their results are not ready yet (due to the latency of
93 /// the operation). Once the operands becomes available, the instruction is
94 /// added to the AvailableQueue.
95 std::vector<SUnit*> PendingQueue;
96
97 /// HazardRec - The hazard recognizer to use.
98 ScheduleHazardRecognizer *HazardRec;
99
Andrew Trick528fad92010-12-23 05:42:20 +0000100 /// CurCycle - The current scheduler state corresponds to this cycle.
101 unsigned CurCycle;
102
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000103 /// MinAvailableCycle - Cycle of the soonest available instruction.
104 unsigned MinAvailableCycle;
105
Dan Gohmanc07f6862008-09-23 18:50:48 +0000106 /// LiveRegDefs - A set of physical registers and their definition
Evan Cheng5924bf72007-09-25 01:54:36 +0000107 /// that are "live". These nodes must be scheduled before any other nodes that
108 /// modifies the registers can be scheduled.
Dan Gohmanc07f6862008-09-23 18:50:48 +0000109 unsigned NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000110 std::vector<SUnit*> LiveRegDefs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000111 std::vector<SUnit*> LiveRegGens;
Evan Cheng5924bf72007-09-25 01:54:36 +0000112
Dan Gohmanad2134d2008-11-25 00:52:40 +0000113 /// Topo - A topological ordering for SUnits which permits fast IsReachable
114 /// and similar queries.
115 ScheduleDAGTopologicalSort Topo;
116
Evan Chengd38c22b2006-05-11 23:55:42 +0000117public:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000118 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
119 SchedulingPriorityQueue *availqueue,
120 CodeGenOpt::Level OptLevel)
121 : ScheduleDAGSDNodes(mf), isBottomUp(availqueue->isBottomUp()),
122 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
123 Topo(SUnits) {
124
125 const TargetMachine &tm = mf.getTarget();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000126 if (DisableSchedCycles || !NeedLatency)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000127 HazardRec = new ScheduleHazardRecognizer();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000128 else
129 HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000130 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000131
132 ~ScheduleDAGRRList() {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000133 delete HazardRec;
Evan Chengd38c22b2006-05-11 23:55:42 +0000134 delete AvailableQueue;
135 }
136
137 void Schedule();
138
Andrew Trick9ccce772011-01-14 21:11:41 +0000139 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
140
Roman Levenstein733a4d62008-03-26 11:23:38 +0000141 /// IsReachable - Checks if SU is reachable from TargetSU.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000142 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
143 return Topo.IsReachable(SU, TargetSU);
144 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000145
Dan Gohman60d68442009-01-29 19:49:27 +0000146 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000147 /// create a cycle.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000148 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
149 return Topo.WillCreateCycle(SU, TargetSU);
150 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000151
Dan Gohman2d170892008-12-09 22:54:47 +0000152 /// AddPred - adds a predecessor edge to SUnit SU.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000153 /// This returns true if this is a new predecessor.
154 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000155 void AddPred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000156 Topo.AddPred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000157 SU->addPred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000158 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000159
Dan Gohman2d170892008-12-09 22:54:47 +0000160 /// RemovePred - removes a predecessor edge from SUnit SU.
161 /// This returns true if an edge was removed.
162 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000163 void RemovePred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000164 Topo.RemovePred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000165 SU->removePred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000166 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000167
Evan Chengd38c22b2006-05-11 23:55:42 +0000168private:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000169 bool isReady(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000170 return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000171 AvailableQueue->isReady(SU);
172 }
173
Dan Gohman60d68442009-01-29 19:49:27 +0000174 void ReleasePred(SUnit *SU, const SDep *PredEdge);
Andrew Tricka52f3252010-12-23 04:16:14 +0000175 void ReleasePredecessors(SUnit *SU);
Dan Gohman60d68442009-01-29 19:49:27 +0000176 void ReleaseSucc(SUnit *SU, const SDep *SuccEdge);
Dan Gohmanb9543432009-02-10 23:27:53 +0000177 void ReleaseSuccessors(SUnit *SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000178 void ReleasePending();
179 void AdvanceToCycle(unsigned NextCycle);
180 void AdvancePastStalls(SUnit *SU);
181 void EmitNode(SUnit *SU);
Andrew Trick528fad92010-12-23 05:42:20 +0000182 void ScheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000183 void CapturePred(SDep *PredEdge);
Evan Cheng8e136a92007-09-26 21:36:17 +0000184 void UnscheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000185 void RestoreHazardCheckerBottomUp();
186 void BacktrackBottomUp(SUnit*, SUnit*);
Evan Cheng8e136a92007-09-26 21:36:17 +0000187 SUnit *CopyAndMoveSuccessors(SUnit*);
Evan Chengb2c42c62009-01-12 03:19:55 +0000188 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
189 const TargetRegisterClass*,
190 const TargetRegisterClass*,
191 SmallVector<SUnit*, 2>&);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000192 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000193
Andrew Trick528fad92010-12-23 05:42:20 +0000194 SUnit *PickNodeToScheduleBottomUp();
Evan Chengd38c22b2006-05-11 23:55:42 +0000195 void ListScheduleBottomUp();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000196
Andrew Trick528fad92010-12-23 05:42:20 +0000197 void ScheduleNodeTopDown(SUnit*);
198 void ListScheduleTopDown();
199
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000200
201 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000202 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000203 SUnit *CreateNewSUnit(SDNode *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000204 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000205 SUnit *NewNode = NewSUnit(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000206 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000207 if (NewNode->NodeNum >= NumSUnits)
208 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000209 return NewNode;
210 }
211
Roman Levenstein733a4d62008-03-26 11:23:38 +0000212 /// CreateClone - Creates a new SUnit from an existing one.
213 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000214 SUnit *CreateClone(SUnit *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000215 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000216 SUnit *NewNode = Clone(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000217 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000218 if (NewNode->NodeNum >= NumSUnits)
219 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000220 return NewNode;
221 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000222
Evan Chengbdd062d2010-05-20 06:13:19 +0000223 /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
224 /// need actual latency information but the hybrid scheduler does.
225 bool ForceUnitLatencies() const {
226 return !NeedLatency;
227 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000228};
229} // end anonymous namespace
230
231
232/// Schedule - Schedule the DAG using list scheduling.
233void ScheduleDAGRRList::Schedule() {
Evan Chenga77f3d32010-07-21 06:09:07 +0000234 DEBUG(dbgs()
235 << "********** List Scheduling BB#" << BB->getNumber()
Evan Cheng6c1414f2010-10-29 18:09:28 +0000236 << " '" << BB->getName() << "' **********\n");
Evan Cheng5924bf72007-09-25 01:54:36 +0000237
Andrew Trick528fad92010-12-23 05:42:20 +0000238 CurCycle = 0;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000239 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
Dan Gohmanc07f6862008-09-23 18:50:48 +0000240 NumLiveRegs = 0;
Andrew Trick2085a962010-12-21 22:25:04 +0000241 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
Andrew Tricka52f3252010-12-23 04:16:14 +0000242 LiveRegGens.resize(TRI->getNumRegs(), NULL);
Evan Cheng5924bf72007-09-25 01:54:36 +0000243
Dan Gohman04543e72008-12-23 18:36:58 +0000244 // Build the scheduling graph.
Dan Gohman918ec532009-10-09 23:33:48 +0000245 BuildSchedGraph(NULL);
Evan Chengd38c22b2006-05-11 23:55:42 +0000246
Evan Chengd38c22b2006-05-11 23:55:42 +0000247 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Dan Gohman22d07b12008-11-18 02:06:40 +0000248 SUnits[su].dumpAll(this));
Dan Gohmanad2134d2008-11-25 00:52:40 +0000249 Topo.InitDAGTopologicalSorting();
Evan Chengd38c22b2006-05-11 23:55:42 +0000250
Dan Gohman46520a22008-06-21 19:18:17 +0000251 AvailableQueue->initNodes(SUnits);
Andrew Trick2085a962010-12-21 22:25:04 +0000252
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000253 HazardRec->Reset();
254
Evan Chengd38c22b2006-05-11 23:55:42 +0000255 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
256 if (isBottomUp)
257 ListScheduleBottomUp();
258 else
259 ListScheduleTopDown();
Andrew Trick2085a962010-12-21 22:25:04 +0000260
Evan Chengd38c22b2006-05-11 23:55:42 +0000261 AvailableQueue->releaseState();
Evan Chengafed73e2006-05-12 01:58:24 +0000262}
Evan Chengd38c22b2006-05-11 23:55:42 +0000263
264//===----------------------------------------------------------------------===//
265// Bottom-Up Scheduling
266//===----------------------------------------------------------------------===//
267
Evan Chengd38c22b2006-05-11 23:55:42 +0000268/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000269/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +0000270void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000271 SUnit *PredSU = PredEdge->getSUnit();
Reid Klecknercea8dab2009-09-30 20:43:07 +0000272
Evan Chengd38c22b2006-05-11 23:55:42 +0000273#ifndef NDEBUG
Reid Klecknercea8dab2009-09-30 20:43:07 +0000274 if (PredSU->NumSuccsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +0000275 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +0000276 PredSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +0000277 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +0000278 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +0000279 }
280#endif
Reid Klecknercea8dab2009-09-30 20:43:07 +0000281 --PredSU->NumSuccsLeft;
282
Evan Chengbdd062d2010-05-20 06:13:19 +0000283 if (!ForceUnitLatencies()) {
284 // Updating predecessor's height. This is now the cycle when the
285 // predecessor can be scheduled without causing a pipeline stall.
286 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
287 }
288
Dan Gohmanb9543432009-02-10 23:27:53 +0000289 // If all the node's successors are scheduled, this node is ready
290 // to be scheduled. Ignore the special EntrySU node.
291 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
Dan Gohman4370f262008-04-15 01:22:18 +0000292 PredSU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000293
294 unsigned Height = PredSU->getHeight();
295 if (Height < MinAvailableCycle)
296 MinAvailableCycle = Height;
297
298 if (isReady(SU)) {
299 AvailableQueue->push(PredSU);
300 }
301 // CapturePred and others may have left the node in the pending queue, avoid
302 // adding it twice.
303 else if (!PredSU->isPending) {
304 PredSU->isPending = true;
305 PendingQueue.push_back(PredSU);
306 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000307 }
308}
309
Andrew Trick033efdf2010-12-23 03:15:51 +0000310/// Call ReleasePred for each predecessor, then update register live def/gen.
311/// Always update LiveRegDefs for a register dependence even if the current SU
312/// also defines the register. This effectively create one large live range
313/// across a sequence of two-address node. This is important because the
314/// entire chain must be scheduled together. Example:
315///
316/// flags = (3) add
317/// flags = (2) addc flags
318/// flags = (1) addc flags
319///
320/// results in
321///
322/// LiveRegDefs[flags] = 3
Andrew Tricka52f3252010-12-23 04:16:14 +0000323/// LiveRegGens[flags] = 1
Andrew Trick033efdf2010-12-23 03:15:51 +0000324///
325/// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
326/// interference on flags.
Andrew Tricka52f3252010-12-23 04:16:14 +0000327void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000328 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000329 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000330 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000331 ReleasePred(SU, &*I);
332 if (I->isAssignedRegDep()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000333 // This is a physical register dependency and it's impossible or
Andrew Trick2085a962010-12-21 22:25:04 +0000334 // expensive to copy the register. Make sure nothing that can
Evan Cheng5924bf72007-09-25 01:54:36 +0000335 // clobber the register is scheduled between the predecessor and
336 // this node.
Andrew Tricka52f3252010-12-23 04:16:14 +0000337 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
Andrew Trick033efdf2010-12-23 03:15:51 +0000338 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
339 "interference on register dependence");
Andrew Tricka52f3252010-12-23 04:16:14 +0000340 LiveRegDefs[I->getReg()] = I->getSUnit();
341 if (!LiveRegGens[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000342 ++NumLiveRegs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000343 LiveRegGens[I->getReg()] = SU;
Evan Cheng5924bf72007-09-25 01:54:36 +0000344 }
345 }
346 }
Dan Gohmanb9543432009-02-10 23:27:53 +0000347}
348
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000349/// Check to see if any of the pending instructions are ready to issue. If
350/// so, add them to the available queue.
351void ScheduleDAGRRList::ReleasePending() {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000352 if (DisableSchedCycles) {
Andrew Trick5ce945c2010-12-24 07:10:19 +0000353 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
354 return;
355 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000356
357 // If the available queue is empty, it is safe to reset MinAvailableCycle.
358 if (AvailableQueue->empty())
359 MinAvailableCycle = UINT_MAX;
360
361 // Check to see if any of the pending instructions are ready to issue. If
362 // so, add them to the available queue.
363 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
364 unsigned ReadyCycle =
365 isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDepth();
366 if (ReadyCycle < MinAvailableCycle)
367 MinAvailableCycle = ReadyCycle;
368
369 if (PendingQueue[i]->isAvailable) {
370 if (!isReady(PendingQueue[i]))
371 continue;
372 AvailableQueue->push(PendingQueue[i]);
373 }
374 PendingQueue[i]->isPending = false;
375 PendingQueue[i] = PendingQueue.back();
376 PendingQueue.pop_back();
377 --i; --e;
378 }
379}
380
381/// Move the scheduler state forward by the specified number of Cycles.
382void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
383 if (NextCycle <= CurCycle)
384 return;
385
386 AvailableQueue->setCurCycle(NextCycle);
Andrew Trick47ff14b2011-01-21 05:51:33 +0000387 if (!HazardRec->isEnabled()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000388 // Bypass lots of virtual calls in case of long latency.
389 CurCycle = NextCycle;
390 }
391 else {
392 for (; CurCycle != NextCycle; ++CurCycle) {
393 if (isBottomUp)
394 HazardRec->RecedeCycle();
395 else
396 HazardRec->AdvanceCycle();
397 }
398 }
399 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
400 // available Q to release pending nodes at least once before popping.
401 ReleasePending();
402}
403
404/// Move the scheduler state forward until the specified node's dependents are
405/// ready and can be scheduled with no resource conflicts.
406void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000407 if (DisableSchedCycles)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000408 return;
409
410 unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
411
412 // Bump CurCycle to account for latency. We assume the latency of other
413 // available instructions may be hidden by the stall (not a full pipe stall).
414 // This updates the hazard recognizer's cycle before reserving resources for
415 // this instruction.
416 AdvanceToCycle(ReadyCycle);
417
418 // Calls are scheduled in their preceding cycle, so don't conflict with
419 // hazards from instructions after the call. EmitNode will reset the
420 // scoreboard state before emitting the call.
421 if (isBottomUp && SU->isCall)
422 return;
423
424 // FIXME: For resource conflicts in very long non-pipelined stages, we
425 // should probably skip ahead here to avoid useless scoreboard checks.
426 int Stalls = 0;
427 while (true) {
428 ScheduleHazardRecognizer::HazardType HT =
429 HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
430
431 if (HT == ScheduleHazardRecognizer::NoHazard)
432 break;
433
434 ++Stalls;
435 }
436 AdvanceToCycle(CurCycle + Stalls);
437}
438
439/// Record this SUnit in the HazardRecognizer.
440/// Does not update CurCycle.
441void ScheduleDAGRRList::EmitNode(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000442 if (!HazardRec->isEnabled())
Andrew Trickc9405662010-12-24 06:46:50 +0000443 return;
444
445 // Check for phys reg copy.
446 if (!SU->getNode())
447 return;
448
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000449 switch (SU->getNode()->getOpcode()) {
450 default:
451 assert(SU->getNode()->isMachineOpcode() &&
452 "This target-independent node should not be scheduled.");
453 break;
454 case ISD::MERGE_VALUES:
455 case ISD::TokenFactor:
456 case ISD::CopyToReg:
457 case ISD::CopyFromReg:
458 case ISD::EH_LABEL:
459 // Noops don't affect the scoreboard state. Copies are likely to be
460 // removed.
461 return;
462 case ISD::INLINEASM:
463 // For inline asm, clear the pipeline state.
464 HazardRec->Reset();
465 return;
466 }
467 if (isBottomUp && SU->isCall) {
468 // Calls are scheduled with their preceding instructions. For bottom-up
469 // scheduling, clear the pipeline state before emitting.
470 HazardRec->Reset();
471 }
472
473 HazardRec->EmitInstruction(SU);
474
475 if (!isBottomUp && SU->isCall) {
476 HazardRec->Reset();
477 }
478}
479
Dan Gohmanb9543432009-02-10 23:27:53 +0000480/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
481/// count of its predecessors. If a predecessor pending count is zero, add it to
482/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000483void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Evan Chengbdd062d2010-05-20 06:13:19 +0000484 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000485 DEBUG(SU->dump(this));
486
Evan Chengbdd062d2010-05-20 06:13:19 +0000487#ifndef NDEBUG
488 if (CurCycle < SU->getHeight())
489 DEBUG(dbgs() << " Height [" << SU->getHeight() << "] pipeline stall!\n");
490#endif
491
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000492 // FIXME: Do not modify node height. It may interfere with
493 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
494 // node it's ready cycle can aid heuristics, and after scheduling it can
495 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000496 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000497
498 // Reserve resources for the scheduled intruction.
499 EmitNode(SU);
500
Dan Gohmanb9543432009-02-10 23:27:53 +0000501 Sequence.push_back(SU);
502
Evan Cheng28590382010-07-21 23:53:58 +0000503 AvailableQueue->ScheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000504
Andrew Trick033efdf2010-12-23 03:15:51 +0000505 // Update liveness of predecessors before successors to avoid treating a
506 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000507 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000508
509 // Release all the implicit physical register defs that are live.
510 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
511 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000512 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
513 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
514 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
515 --NumLiveRegs;
516 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000517 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000518 }
519 }
520
Evan Chengd38c22b2006-05-11 23:55:42 +0000521 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000522
523 // Conditions under which the scheduler should eagerly advance the cycle:
524 // (1) No available instructions
525 // (2) All pipelines full, so available instructions must have hazards.
526 //
Andrew Trick47ff14b2011-01-21 05:51:33 +0000527 // If HazardRec is disabled, count each inst as one cycle.
528 if (!HazardRec->isEnabled() || HazardRec->atIssueLimit()
529 || AvailableQueue->empty())
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000530 AdvanceToCycle(CurCycle + 1);
Evan Chengd38c22b2006-05-11 23:55:42 +0000531}
532
Evan Cheng5924bf72007-09-25 01:54:36 +0000533/// CapturePred - This does the opposite of ReleasePred. Since SU is being
534/// unscheduled, incrcease the succ left count of its predecessors. Remove
535/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000536void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000537 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000538 if (PredSU->isAvailable) {
539 PredSU->isAvailable = false;
540 if (!PredSU->isPending)
541 AvailableQueue->remove(PredSU);
542 }
543
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000544 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000545 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000546}
547
548/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
549/// its predecessor states to reflect the change.
550void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000551 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000552 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000553
Evan Cheng5924bf72007-09-25 01:54:36 +0000554 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
555 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000556 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000557 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000558 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000559 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000560 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000561 --NumLiveRegs;
Dan Gohman2d170892008-12-09 22:54:47 +0000562 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000563 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000564 }
565 }
566
567 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
568 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000569 if (I->isAssignedRegDep()) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000570 // This becomes the nearest def. Note that an earlier def may still be
571 // pending if this is a two-address node.
572 LiveRegDefs[I->getReg()] = SU;
Dan Gohman2d170892008-12-09 22:54:47 +0000573 if (!LiveRegDefs[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000574 ++NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000575 }
Andrew Tricka52f3252010-12-23 04:16:14 +0000576 if (LiveRegGens[I->getReg()] == NULL ||
577 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
578 LiveRegGens[I->getReg()] = I->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000579 }
580 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000581 if (SU->getHeight() < MinAvailableCycle)
582 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000583
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000584 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000585 SU->isScheduled = false;
586 SU->isAvailable = true;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000587 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000588 // Don't make available until backtracking is complete.
589 SU->isPending = true;
590 PendingQueue.push_back(SU);
591 }
592 else {
593 AvailableQueue->push(SU);
594 }
Evan Cheng28590382010-07-21 23:53:58 +0000595 AvailableQueue->UnscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000596}
597
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000598/// After backtracking, the hazard checker needs to be restored to a state
599/// corresponding the the current cycle.
600void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
601 HazardRec->Reset();
602
603 unsigned LookAhead = std::min((unsigned)Sequence.size(),
604 HazardRec->getMaxLookAhead());
605 if (LookAhead == 0)
606 return;
607
608 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
609 unsigned HazardCycle = (*I)->getHeight();
610 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
611 SUnit *SU = *I;
612 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
613 HazardRec->RecedeCycle();
614 }
615 EmitNode(SU);
616 }
617}
618
Evan Cheng8e136a92007-09-26 21:36:17 +0000619/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000620/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000621void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
622 SUnit *OldSU = Sequence.back();
623 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000624 Sequence.pop_back();
625 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000626 // Don't try to remove SU from AvailableQueue.
627 SU->isAvailable = false;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000628 // FIXME: use ready cycle instead of height
629 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000630 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000631 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000632 if (OldSU == BtSU)
633 break;
634 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000635 }
636
Dan Gohman60d68442009-01-29 19:49:27 +0000637 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000638
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000639 RestoreHazardCheckerBottomUp();
640
Andrew Trick5ce945c2010-12-24 07:10:19 +0000641 ReleasePending();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000642
Evan Cheng1ec79b42007-09-27 07:09:03 +0000643 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000644}
645
Evan Cheng3b245872010-02-05 01:27:11 +0000646static bool isOperandOf(const SUnit *SU, SDNode *N) {
647 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000648 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000649 if (SUNode->isOperandOf(N))
650 return true;
651 }
652 return false;
653}
654
Evan Cheng5924bf72007-09-25 01:54:36 +0000655/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
656/// successors to the newly created node.
657SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000658 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000659 if (!N)
660 return NULL;
661
Andrew Trickc9405662010-12-24 06:46:50 +0000662 if (SU->getNode()->getGluedNode())
663 return NULL;
664
Evan Cheng79e97132007-10-05 01:39:18 +0000665 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000666 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000667 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000668 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000669 if (VT == MVT::Glue)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000670 return NULL;
Owen Anderson9f944592009-08-11 20:47:22 +0000671 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000672 TryUnfold = true;
673 }
Evan Cheng79e97132007-10-05 01:39:18 +0000674 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000675 const SDValue &Op = N->getOperand(i);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000676 EVT VT = Op.getNode()->getValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000677 if (VT == MVT::Glue)
Evan Cheng79e97132007-10-05 01:39:18 +0000678 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000679 }
680
681 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000682 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000683 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000684 return NULL;
685
Evan Chengbdd062d2010-05-20 06:13:19 +0000686 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000687 assert(NewNodes.size() == 2 && "Expected a load folding node!");
688
689 N = NewNodes[1];
690 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000691 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000692 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000693 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000694 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
695 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000696 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000697
Dan Gohmane52e0892008-11-11 21:34:44 +0000698 // LoadNode may already exist. This can happen when there is another
699 // load from the same location and producing the same type of value
700 // but it has different alignment or volatileness.
701 bool isNewLoad = true;
702 SUnit *LoadSU;
703 if (LoadNode->getNodeId() != -1) {
704 LoadSU = &SUnits[LoadNode->getNodeId()];
705 isNewLoad = false;
706 } else {
707 LoadSU = CreateNewSUnit(LoadNode);
708 LoadNode->setNodeId(LoadSU->NodeNum);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000709
710 InitNumRegDefsLeft(LoadSU);
Dan Gohmane52e0892008-11-11 21:34:44 +0000711 ComputeLatency(LoadSU);
712 }
713
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000714 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000715 assert(N->getNodeId() == -1 && "Node already inserted!");
716 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +0000717
Dan Gohman17059682008-07-17 19:10:17 +0000718 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Dan Gohman856c0122008-02-16 00:25:40 +0000719 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000720 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000721 NewSU->isTwoAddress = true;
722 break;
723 }
724 }
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000725 if (TID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000726 NewSU->isCommutable = true;
Andrew Trickd0548ae2011-02-04 03:18:17 +0000727
728 InitNumRegDefsLeft(NewSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000729 ComputeLatency(NewSU);
730
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000731 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +0000732 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +0000733 SmallVector<SDep, 4> ChainSuccs;
734 SmallVector<SDep, 4> LoadPreds;
735 SmallVector<SDep, 4> NodePreds;
736 SmallVector<SDep, 4> NodeSuccs;
737 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
738 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000739 if (I->isCtrl())
Dan Gohman15af5522009-03-06 02:23:01 +0000740 ChainPreds.push_back(*I);
Evan Cheng3b245872010-02-05 01:27:11 +0000741 else if (isOperandOf(I->getSUnit(), LoadNode))
Dan Gohman2d170892008-12-09 22:54:47 +0000742 LoadPreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000743 else
Dan Gohman2d170892008-12-09 22:54:47 +0000744 NodePreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000745 }
746 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
747 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000748 if (I->isCtrl())
749 ChainSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000750 else
Dan Gohman2d170892008-12-09 22:54:47 +0000751 NodeSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000752 }
753
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000754 // Now assign edges to the newly-created nodes.
Dan Gohman15af5522009-03-06 02:23:01 +0000755 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
756 const SDep &Pred = ChainPreds[i];
757 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +0000758 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +0000759 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000760 }
Evan Cheng79e97132007-10-05 01:39:18 +0000761 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000762 const SDep &Pred = LoadPreds[i];
763 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +0000764 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +0000765 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000766 }
767 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000768 const SDep &Pred = NodePreds[i];
769 RemovePred(SU, Pred);
770 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000771 }
772 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000773 SDep D = NodeSuccs[i];
774 SUnit *SuccDep = D.getSUnit();
775 D.setSUnit(SU);
776 RemovePred(SuccDep, D);
777 D.setSUnit(NewSU);
778 AddPred(SuccDep, D);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000779 // Balance register pressure.
780 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
781 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
782 --NewSU->NumRegDefsLeft;
Evan Cheng79e97132007-10-05 01:39:18 +0000783 }
784 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000785 SDep D = ChainSuccs[i];
786 SUnit *SuccDep = D.getSUnit();
787 D.setSUnit(SU);
788 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000789 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +0000790 D.setSUnit(LoadSU);
791 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000792 }
Andrew Trick2085a962010-12-21 22:25:04 +0000793 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000794
795 // Add a data dependency to reflect that NewSU reads the value defined
796 // by LoadSU.
797 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
Evan Cheng79e97132007-10-05 01:39:18 +0000798
Evan Cheng91e0fc92007-12-18 08:42:10 +0000799 if (isNewLoad)
800 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000801 AvailableQueue->addNode(NewSU);
802
803 ++NumUnfolds;
804
805 if (NewSU->NumSuccsLeft == 0) {
806 NewSU->isAvailable = true;
807 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +0000808 }
809 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000810 }
811
Evan Chengbdd062d2010-05-20 06:13:19 +0000812 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000813 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000814
815 // New SUnit has the exact same predecessors.
816 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
817 I != E; ++I)
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000818 if (!I->isArtificial())
Dan Gohman2d170892008-12-09 22:54:47 +0000819 AddPred(NewSU, *I);
Evan Cheng5924bf72007-09-25 01:54:36 +0000820
821 // Only copy scheduled successors. Cut them from old node's successor
822 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000823 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +0000824 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
825 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000826 if (I->isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +0000827 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000828 SUnit *SuccSU = I->getSUnit();
829 if (SuccSU->isScheduled) {
Dan Gohman2d170892008-12-09 22:54:47 +0000830 SDep D = *I;
831 D.setSUnit(NewSU);
832 AddPred(SuccSU, D);
833 D.setSUnit(SU);
834 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +0000835 }
836 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000837 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000838 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng5924bf72007-09-25 01:54:36 +0000839
840 AvailableQueue->updateNode(SU);
841 AvailableQueue->addNode(NewSU);
842
Evan Cheng1ec79b42007-09-27 07:09:03 +0000843 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000844 return NewSU;
845}
846
Evan Chengb2c42c62009-01-12 03:19:55 +0000847/// InsertCopiesAndMoveSuccs - Insert register copies and move all
848/// scheduled successors of the given SUnit to the last copy.
849void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
850 const TargetRegisterClass *DestRC,
851 const TargetRegisterClass *SrcRC,
Evan Cheng1ec79b42007-09-27 07:09:03 +0000852 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000853 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000854 CopyFromSU->CopySrcRC = SrcRC;
855 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +0000856
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000857 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000858 CopyToSU->CopySrcRC = DestRC;
859 CopyToSU->CopyDstRC = SrcRC;
860
861 // Only copy scheduled successors. Cut them from old node's successor
862 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000863 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +0000864 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
865 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000866 if (I->isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +0000867 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000868 SUnit *SuccSU = I->getSUnit();
869 if (SuccSU->isScheduled) {
870 SDep D = *I;
871 D.setSUnit(CopyToSU);
872 AddPred(SuccSU, D);
873 DelDeps.push_back(std::make_pair(SuccSU, *I));
Evan Cheng8e136a92007-09-26 21:36:17 +0000874 }
875 }
Evan Chengb2c42c62009-01-12 03:19:55 +0000876 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000877 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng8e136a92007-09-26 21:36:17 +0000878
Dan Gohman2d170892008-12-09 22:54:47 +0000879 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
880 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
Evan Cheng8e136a92007-09-26 21:36:17 +0000881
882 AvailableQueue->updateNode(SU);
883 AvailableQueue->addNode(CopyFromSU);
884 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000885 Copies.push_back(CopyFromSU);
886 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +0000887
Evan Chengb2c42c62009-01-12 03:19:55 +0000888 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +0000889}
890
891/// getPhysicalRegisterVT - Returns the ValueType of the physical register
892/// definition of the specified node.
893/// FIXME: Move to SelectionDAG?
Owen Anderson53aa7a92009-08-10 22:56:29 +0000894static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +0000895 const TargetInstrInfo *TII) {
Dan Gohman17059682008-07-17 19:10:17 +0000896 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Evan Cheng8e136a92007-09-26 21:36:17 +0000897 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
Chris Lattnerb0d06b42008-01-07 03:13:06 +0000898 unsigned NumRes = TID.getNumDefs();
899 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000900 if (Reg == *ImpDef)
901 break;
902 ++NumRes;
903 }
904 return N->getValueType(NumRes);
905}
906
Evan Chengb8905c42009-03-04 01:41:49 +0000907/// CheckForLiveRegDef - Return true and update live register vector if the
908/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000909static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Evan Chengb8905c42009-03-04 01:41:49 +0000910 std::vector<SUnit*> &LiveRegDefs,
911 SmallSet<unsigned, 4> &RegAdded,
912 SmallVector<unsigned, 4> &LRegs,
913 const TargetRegisterInfo *TRI) {
Andrew Trick12acde112010-12-23 03:43:21 +0000914 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
915
916 // Check if Ref is live.
917 if (!LiveRegDefs[Reg]) continue;
918
919 // Allow multiple uses of the same def.
920 if (LiveRegDefs[Reg] == SU) continue;
921
922 // Add Reg to the set of interfering live regs.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000923 if (RegAdded.insert(Reg))
Evan Chengb8905c42009-03-04 01:41:49 +0000924 LRegs.push_back(Reg);
Evan Chengb8905c42009-03-04 01:41:49 +0000925 }
Evan Chengb8905c42009-03-04 01:41:49 +0000926}
927
Evan Cheng5924bf72007-09-25 01:54:36 +0000928/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
929/// scheduling of the given node to satisfy live physical register dependencies.
930/// If the specific node is the last one that's available to schedule, do
931/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000932bool ScheduleDAGRRList::
933DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000934 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +0000935 return false;
936
Evan Chenge6f92252007-09-27 18:46:06 +0000937 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +0000938 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +0000939 //
940 // If SU is the currently live definition of the same register that it uses,
941 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +0000942 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
943 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +0000944 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Evan Chengb8905c42009-03-04 01:41:49 +0000945 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
946 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +0000947 }
948
Chris Lattner11a33812010-12-23 17:24:32 +0000949 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +0000950 if (Node->getOpcode() == ISD::INLINEASM) {
951 // Inline asm can clobber physical defs.
952 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000953 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +0000954 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +0000955
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000956 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +0000957 unsigned Flags =
958 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000959 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +0000960
961 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000962 if (InlineAsm::isRegDefKind(Flags) ||
963 InlineAsm::isRegDefEarlyClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +0000964 // Check for def of register or earlyclobber register.
965 for (; NumVals; --NumVals, ++i) {
966 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
967 if (TargetRegisterInfo::isPhysicalRegister(Reg))
968 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
969 }
970 } else
971 i += NumVals;
972 }
973 continue;
974 }
975
Dan Gohman072734e2008-11-13 23:24:17 +0000976 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +0000977 continue;
Dan Gohman17059682008-07-17 19:10:17 +0000978 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
Evan Cheng5924bf72007-09-25 01:54:36 +0000979 if (!TID.ImplicitDefs)
980 continue;
Evan Chengb8905c42009-03-04 01:41:49 +0000981 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
982 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +0000983 }
Andrew Trick2085a962010-12-21 22:25:04 +0000984
Evan Cheng5924bf72007-09-25 01:54:36 +0000985 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +0000986}
987
Andrew Trick528fad92010-12-23 05:42:20 +0000988/// Return a node that can be scheduled in this cycle. Requirements:
989/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000990/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +0000991/// (3) No Interferences: may unschedule to break register interferences.
992SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
993 SmallVector<SUnit*, 4> Interferences;
994 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
995
996 SUnit *CurSU = AvailableQueue->pop();
997 while (CurSU) {
998 SmallVector<unsigned, 4> LRegs;
999 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1000 break;
1001 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1002
1003 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1004 Interferences.push_back(CurSU);
1005 CurSU = AvailableQueue->pop();
1006 }
1007 if (CurSU) {
1008 // Add the nodes that aren't ready back onto the available list.
1009 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1010 Interferences[i]->isPending = false;
1011 assert(Interferences[i]->isAvailable && "must still be available");
1012 AvailableQueue->push(Interferences[i]);
1013 }
1014 return CurSU;
1015 }
1016
1017 // All candidates are delayed due to live physical reg dependencies.
1018 // Try backtracking, code duplication, or inserting cross class copies
1019 // to resolve it.
1020 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1021 SUnit *TrySU = Interferences[i];
1022 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1023
1024 // Try unscheduling up to the point where it's safe to schedule
1025 // this node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001026 SUnit *BtSU = NULL;
1027 unsigned LiveCycle = UINT_MAX;
Andrew Trick528fad92010-12-23 05:42:20 +00001028 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1029 unsigned Reg = LRegs[j];
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001030 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1031 BtSU = LiveRegGens[Reg];
1032 LiveCycle = BtSU->getHeight();
1033 }
Andrew Trick528fad92010-12-23 05:42:20 +00001034 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001035 if (!WillCreateCycle(TrySU, BtSU)) {
1036 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001037
1038 // Force the current node to be scheduled before the node that
1039 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001040 if (BtSU->isAvailable) {
1041 BtSU->isAvailable = false;
1042 if (!BtSU->isPending)
1043 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001044 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001045 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
Andrew Trick528fad92010-12-23 05:42:20 +00001046 /*Reg=*/0, /*isNormalMemory=*/false,
1047 /*isMustAlias=*/false, /*isArtificial=*/true));
1048
1049 // If one or more successors has been unscheduled, then the current
1050 // node is no longer avaialable. Schedule a successor that's now
1051 // available instead.
1052 if (!TrySU->isAvailable) {
1053 CurSU = AvailableQueue->pop();
1054 }
1055 else {
1056 CurSU = TrySU;
1057 TrySU->isPending = false;
1058 Interferences.erase(Interferences.begin()+i);
1059 }
1060 break;
1061 }
1062 }
1063
1064 if (!CurSU) {
1065 // Can't backtrack. If it's too expensive to copy the value, then try
1066 // duplicate the nodes that produces these "too expensive to copy"
1067 // values to break the dependency. In case even that doesn't work,
1068 // insert cross class copies.
1069 // If it's not too expensive, i.e. cost != -1, issue copies.
1070 SUnit *TrySU = Interferences[0];
1071 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1072 assert(LRegs.size() == 1 && "Can't handle this yet!");
1073 unsigned Reg = LRegs[0];
1074 SUnit *LRDef = LiveRegDefs[Reg];
1075 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1076 const TargetRegisterClass *RC =
1077 TRI->getMinimalPhysRegClass(Reg, VT);
1078 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1079
1080 // If cross copy register class is null, then it must be possible copy
1081 // the value directly. Do not try duplicate the def.
1082 SUnit *NewDef = 0;
1083 if (DestRC)
1084 NewDef = CopyAndMoveSuccessors(LRDef);
1085 else
1086 DestRC = RC;
1087 if (!NewDef) {
1088 // Issue copies, these can be expensive cross register class copies.
1089 SmallVector<SUnit*, 2> Copies;
1090 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1091 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1092 << " to SU #" << Copies.front()->NodeNum << "\n");
1093 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1094 /*Reg=*/0, /*isNormalMemory=*/false,
1095 /*isMustAlias=*/false,
1096 /*isArtificial=*/true));
1097 NewDef = Copies.back();
1098 }
1099
1100 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1101 << " to SU #" << TrySU->NodeNum << "\n");
1102 LiveRegDefs[Reg] = NewDef;
1103 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1104 /*Reg=*/0, /*isNormalMemory=*/false,
1105 /*isMustAlias=*/false,
1106 /*isArtificial=*/true));
1107 TrySU->isAvailable = false;
1108 CurSU = NewDef;
1109 }
1110
1111 assert(CurSU && "Unable to resolve live physical register dependencies!");
1112
1113 // Add the nodes that aren't ready back onto the available list.
1114 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1115 Interferences[i]->isPending = false;
1116 // May no longer be available due to backtracking.
1117 if (Interferences[i]->isAvailable) {
1118 AvailableQueue->push(Interferences[i]);
1119 }
1120 }
1121 return CurSU;
1122}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001123
Evan Chengd38c22b2006-05-11 23:55:42 +00001124/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1125/// schedulers.
1126void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001127 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001128 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001129
Evan Chengd38c22b2006-05-11 23:55:42 +00001130 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001131 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001132 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001133 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1134 RootSU->isAvailable = true;
1135 AvailableQueue->push(RootSU);
1136 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001137
1138 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001139 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001140 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001141 while (!AvailableQueue->empty()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001142 DEBUG(dbgs() << "\n*** Examining Available\n";
1143 AvailableQueue->dump(this));
1144
Andrew Trick528fad92010-12-23 05:42:20 +00001145 // Pick the best node to schedule taking all constraints into
1146 // consideration.
1147 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001148
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001149 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001150
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001151 ScheduleNodeBottomUp(SU);
1152
1153 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1154 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1155 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1156 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1157 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001158 }
1159
Evan Chengd38c22b2006-05-11 23:55:42 +00001160 // Reverse the order if it is bottom up.
1161 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001162
Evan Chengd38c22b2006-05-11 23:55:42 +00001163#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001164 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001165#endif
1166}
1167
1168//===----------------------------------------------------------------------===//
1169// Top-Down Scheduling
1170//===----------------------------------------------------------------------===//
1171
1172/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +00001173/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +00001174void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +00001175 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001176
Evan Chengd38c22b2006-05-11 23:55:42 +00001177#ifndef NDEBUG
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001178 if (SuccSU->NumPredsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +00001179 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +00001180 SuccSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +00001181 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +00001182 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +00001183 }
1184#endif
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001185 --SuccSU->NumPredsLeft;
1186
Dan Gohmanb9543432009-02-10 23:27:53 +00001187 // If all the node's predecessors are scheduled, this node is ready
1188 // to be scheduled. Ignore the special ExitSU node.
1189 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001190 SuccSU->isAvailable = true;
1191 AvailableQueue->push(SuccSU);
1192 }
1193}
1194
Dan Gohmanb9543432009-02-10 23:27:53 +00001195void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1196 // Top down: release successors
1197 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1198 I != E; ++I) {
1199 assert(!I->isAssignedRegDep() &&
1200 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1201
1202 ReleaseSucc(SU, &*I);
1203 }
1204}
1205
Evan Chengd38c22b2006-05-11 23:55:42 +00001206/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1207/// count of its successors. If a successor pending count is zero, add it to
1208/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +00001209void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +00001210 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +00001211 DEBUG(SU->dump(this));
Evan Chengd38c22b2006-05-11 23:55:42 +00001212
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001213 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1214 SU->setDepthToAtLeast(CurCycle);
Dan Gohman92a36d72008-11-17 21:31:02 +00001215 Sequence.push_back(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001216
Dan Gohmanb9543432009-02-10 23:27:53 +00001217 ReleaseSuccessors(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001218 SU->isScheduled = true;
Dan Gohman92a36d72008-11-17 21:31:02 +00001219 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001220}
1221
Dan Gohman54a187e2007-08-20 19:28:38 +00001222/// ListScheduleTopDown - The main loop of list scheduling for top-down
1223/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +00001224void ScheduleDAGRRList::ListScheduleTopDown() {
Evan Chengbdd062d2010-05-20 06:13:19 +00001225 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001226
Dan Gohmanb9543432009-02-10 23:27:53 +00001227 // Release any successors of the special Entry node.
1228 ReleaseSuccessors(&EntrySU);
1229
Evan Chengd38c22b2006-05-11 23:55:42 +00001230 // All leaves to Available queue.
1231 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1232 // It is available if it has no predecessors.
Dan Gohman4370f262008-04-15 01:22:18 +00001233 if (SUnits[i].Preds.empty()) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001234 AvailableQueue->push(&SUnits[i]);
1235 SUnits[i].isAvailable = true;
1236 }
1237 }
Andrew Trick2085a962010-12-21 22:25:04 +00001238
Evan Chengd38c22b2006-05-11 23:55:42 +00001239 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001240 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001241 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001242 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +00001243 SUnit *CurSU = AvailableQueue->pop();
Andrew Trick2085a962010-12-21 22:25:04 +00001244
Dan Gohmanc602dd42008-11-21 00:10:42 +00001245 if (CurSU)
Andrew Trick528fad92010-12-23 05:42:20 +00001246 ScheduleNodeTopDown(CurSU);
Dan Gohman4370f262008-04-15 01:22:18 +00001247 ++CurCycle;
Evan Chengbdd062d2010-05-20 06:13:19 +00001248 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001249 }
Andrew Trick2085a962010-12-21 22:25:04 +00001250
Evan Chengd38c22b2006-05-11 23:55:42 +00001251#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001252 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001253#endif
1254}
1255
1256
Evan Chengd38c22b2006-05-11 23:55:42 +00001257//===----------------------------------------------------------------------===//
Andrew Trick9ccce772011-01-14 21:11:41 +00001258// RegReductionPriorityQueue Definition
Evan Chengd38c22b2006-05-11 23:55:42 +00001259//===----------------------------------------------------------------------===//
1260//
1261// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1262// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001263//
Evan Chengd38c22b2006-05-11 23:55:42 +00001264namespace {
Andrew Trick9ccce772011-01-14 21:11:41 +00001265class RegReductionPQBase;
Andrew Trick2085a962010-12-21 22:25:04 +00001266
Andrew Trick9ccce772011-01-14 21:11:41 +00001267struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1268 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1269};
1270
1271/// bu_ls_rr_sort - Priority function for bottom up register pressure
1272// reduction scheduler.
1273struct bu_ls_rr_sort : public queue_sort {
1274 enum {
1275 IsBottomUp = true,
1276 HasReadyFilter = false
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001277 };
1278
Andrew Trick9ccce772011-01-14 21:11:41 +00001279 RegReductionPQBase *SPQ;
1280 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1281 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001282
Andrew Trick9ccce772011-01-14 21:11:41 +00001283 bool operator()(SUnit* left, SUnit* right) const;
1284};
Andrew Trick2085a962010-12-21 22:25:04 +00001285
Andrew Trick9ccce772011-01-14 21:11:41 +00001286// td_ls_rr_sort - Priority function for top down register pressure reduction
1287// scheduler.
1288struct td_ls_rr_sort : public queue_sort {
1289 enum {
1290 IsBottomUp = false,
1291 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001292 };
1293
Andrew Trick9ccce772011-01-14 21:11:41 +00001294 RegReductionPQBase *SPQ;
1295 td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1296 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001297
Andrew Trick9ccce772011-01-14 21:11:41 +00001298 bool operator()(const SUnit* left, const SUnit* right) const;
1299};
Andrew Trick2085a962010-12-21 22:25:04 +00001300
Andrew Trick9ccce772011-01-14 21:11:41 +00001301// src_ls_rr_sort - Priority function for source order scheduler.
1302struct src_ls_rr_sort : public queue_sort {
1303 enum {
1304 IsBottomUp = true,
1305 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001306 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001307
Andrew Trick9ccce772011-01-14 21:11:41 +00001308 RegReductionPQBase *SPQ;
1309 src_ls_rr_sort(RegReductionPQBase *spq)
1310 : SPQ(spq) {}
1311 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1312 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001313
Andrew Trick9ccce772011-01-14 21:11:41 +00001314 bool operator()(SUnit* left, SUnit* right) const;
1315};
Andrew Trick2085a962010-12-21 22:25:04 +00001316
Andrew Trick9ccce772011-01-14 21:11:41 +00001317// hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1318struct hybrid_ls_rr_sort : public queue_sort {
1319 enum {
1320 IsBottomUp = true,
1321 HasReadyFilter = true
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001322 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001323
Andrew Trick9ccce772011-01-14 21:11:41 +00001324 RegReductionPQBase *SPQ;
1325 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1326 : SPQ(spq) {}
1327 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1328 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001329
Andrew Trick9ccce772011-01-14 21:11:41 +00001330 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Chenga77f3d32010-07-21 06:09:07 +00001331
Andrew Trick9ccce772011-01-14 21:11:41 +00001332 bool operator()(SUnit* left, SUnit* right) const;
1333};
1334
1335// ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1336// scheduler.
1337struct ilp_ls_rr_sort : public queue_sort {
1338 enum {
1339 IsBottomUp = true,
1340 HasReadyFilter = true
Evan Chengbdd062d2010-05-20 06:13:19 +00001341 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001342
Andrew Trick9ccce772011-01-14 21:11:41 +00001343 RegReductionPQBase *SPQ;
1344 ilp_ls_rr_sort(RegReductionPQBase *spq)
1345 : SPQ(spq) {}
1346 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1347 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001348
Andrew Trick9ccce772011-01-14 21:11:41 +00001349 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Cheng37b740c2010-07-24 00:39:05 +00001350
Andrew Trick9ccce772011-01-14 21:11:41 +00001351 bool operator()(SUnit* left, SUnit* right) const;
1352};
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001353
Andrew Trick9ccce772011-01-14 21:11:41 +00001354class RegReductionPQBase : public SchedulingPriorityQueue {
1355protected:
1356 std::vector<SUnit*> Queue;
1357 unsigned CurQueueId;
1358 bool TracksRegPressure;
1359
1360 // SUnits - The SUnits for the current graph.
1361 std::vector<SUnit> *SUnits;
1362
1363 MachineFunction &MF;
1364 const TargetInstrInfo *TII;
1365 const TargetRegisterInfo *TRI;
1366 const TargetLowering *TLI;
1367 ScheduleDAGRRList *scheduleDAG;
1368
1369 // SethiUllmanNumbers - The SethiUllman number for each node.
1370 std::vector<unsigned> SethiUllmanNumbers;
1371
1372 /// RegPressure - Tracking current reg pressure per register class.
1373 ///
1374 std::vector<unsigned> RegPressure;
1375
1376 /// RegLimit - Tracking the number of allocatable registers per register
1377 /// class.
1378 std::vector<unsigned> RegLimit;
1379
1380public:
1381 RegReductionPQBase(MachineFunction &mf,
1382 bool hasReadyFilter,
1383 bool tracksrp,
1384 const TargetInstrInfo *tii,
1385 const TargetRegisterInfo *tri,
1386 const TargetLowering *tli)
1387 : SchedulingPriorityQueue(hasReadyFilter),
1388 CurQueueId(0), TracksRegPressure(tracksrp),
1389 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1390 if (TracksRegPressure) {
1391 unsigned NumRC = TRI->getNumRegClasses();
1392 RegLimit.resize(NumRC);
1393 RegPressure.resize(NumRC);
1394 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1395 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1396 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1397 E = TRI->regclass_end(); I != E; ++I)
1398 RegLimit[(*I)->getID()] = tli->getRegPressureLimit(*I, MF);
1399 }
1400 }
1401
1402 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1403 scheduleDAG = scheduleDag;
1404 }
1405
1406 ScheduleHazardRecognizer* getHazardRec() {
1407 return scheduleDAG->getHazardRec();
1408 }
1409
1410 void initNodes(std::vector<SUnit> &sunits);
1411
1412 void addNode(const SUnit *SU);
1413
1414 void updateNode(const SUnit *SU);
1415
1416 void releaseState() {
1417 SUnits = 0;
1418 SethiUllmanNumbers.clear();
1419 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1420 }
1421
1422 unsigned getNodePriority(const SUnit *SU) const;
1423
1424 unsigned getNodeOrdering(const SUnit *SU) const {
1425 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1426 }
1427
1428 bool empty() const { return Queue.empty(); }
1429
1430 void push(SUnit *U) {
1431 assert(!U->NodeQueueId && "Node in the queue already");
1432 U->NodeQueueId = ++CurQueueId;
1433 Queue.push_back(U);
1434 }
1435
1436 void remove(SUnit *SU) {
1437 assert(!Queue.empty() && "Queue is empty!");
1438 assert(SU->NodeQueueId != 0 && "Not in queue!");
1439 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1440 SU);
1441 if (I != prior(Queue.end()))
1442 std::swap(*I, Queue.back());
1443 Queue.pop_back();
1444 SU->NodeQueueId = 0;
1445 }
1446
Andrew Trickd0548ae2011-02-04 03:18:17 +00001447 bool tracksRegPressure() const { return TracksRegPressure; }
1448
Andrew Trick9ccce772011-01-14 21:11:41 +00001449 void dumpRegPressure() const;
1450
1451 bool HighRegPressure(const SUnit *SU) const;
1452
1453 bool MayReduceRegPressure(SUnit *SU);
1454
1455 void ScheduledNode(SUnit *SU);
1456
1457 void UnscheduledNode(SUnit *SU);
1458
1459protected:
1460 bool canClobber(const SUnit *SU, const SUnit *Op);
1461 void AddPseudoTwoAddrDeps();
1462 void PrescheduleNodesWithMultipleUses();
1463 void CalculateSethiUllmanNumbers();
1464};
1465
1466template<class SF>
1467class RegReductionPriorityQueue : public RegReductionPQBase {
1468 static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1469 std::vector<SUnit *>::iterator Best = Q.begin();
1470 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1471 E = Q.end(); I != E; ++I)
1472 if (Picker(*Best, *I))
1473 Best = I;
1474 SUnit *V = *Best;
1475 if (Best != prior(Q.end()))
1476 std::swap(*Best, Q.back());
1477 Q.pop_back();
1478 return V;
1479 }
1480
1481 SF Picker;
1482
1483public:
1484 RegReductionPriorityQueue(MachineFunction &mf,
1485 bool tracksrp,
1486 const TargetInstrInfo *tii,
1487 const TargetRegisterInfo *tri,
1488 const TargetLowering *tli)
1489 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1490 Picker(this) {}
1491
1492 bool isBottomUp() const { return SF::IsBottomUp; }
1493
1494 bool isReady(SUnit *U) const {
1495 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1496 }
1497
1498 SUnit *pop() {
1499 if (Queue.empty()) return NULL;
1500
1501 SUnit *V = popFromQueue(Queue, Picker);
1502 V->NodeQueueId = 0;
1503 return V;
1504 }
1505
1506 void dump(ScheduleDAG *DAG) const {
1507 // Emulate pop() without clobbering NodeQueueIds.
1508 std::vector<SUnit*> DumpQueue = Queue;
1509 SF DumpPicker = Picker;
1510 while (!DumpQueue.empty()) {
1511 SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1512 if (isBottomUp())
1513 dbgs() << "Height " << SU->getHeight() << ": ";
1514 else
1515 dbgs() << "Depth " << SU->getDepth() << ": ";
1516 SU->dump(DAG);
1517 }
1518 }
1519};
1520
1521typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1522BURegReductionPriorityQueue;
1523
1524typedef RegReductionPriorityQueue<td_ls_rr_sort>
1525TDRegReductionPriorityQueue;
1526
1527typedef RegReductionPriorityQueue<src_ls_rr_sort>
1528SrcRegReductionPriorityQueue;
1529
1530typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1531HybridBURRPriorityQueue;
1532
1533typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1534ILPBURRPriorityQueue;
1535} // end anonymous namespace
1536
1537//===----------------------------------------------------------------------===//
1538// Static Node Priority for Register Pressure Reduction
1539//===----------------------------------------------------------------------===//
Evan Chengd38c22b2006-05-11 23:55:42 +00001540
Dan Gohman186f65d2008-11-20 03:30:37 +00001541/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1542/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001543static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001544CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001545 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1546 if (SethiUllmanNumber != 0)
1547 return SethiUllmanNumber;
1548
1549 unsigned Extra = 0;
1550 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1551 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001552 if (I->isCtrl()) continue; // ignore chain preds
1553 SUnit *PredSU = I->getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001554 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001555 if (PredSethiUllman > SethiUllmanNumber) {
1556 SethiUllmanNumber = PredSethiUllman;
1557 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001558 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001559 ++Extra;
1560 }
1561
1562 SethiUllmanNumber += Extra;
1563
1564 if (SethiUllmanNumber == 0)
1565 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001566
Evan Cheng7e4abde2008-07-02 09:23:51 +00001567 return SethiUllmanNumber;
1568}
1569
Andrew Trick9ccce772011-01-14 21:11:41 +00001570/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1571/// scheduling units.
1572void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1573 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001574
Andrew Trick9ccce772011-01-14 21:11:41 +00001575 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1576 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
Evan Chengd38c22b2006-05-11 23:55:42 +00001577}
1578
Andrew Trick9ccce772011-01-14 21:11:41 +00001579void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
1580 SUnits = &sunits;
1581 // Add pseudo dependency edges for two-address nodes.
1582 AddPseudoTwoAddrDeps();
1583 // Reroute edges to nodes with multiple uses.
Andrew Trickd0548ae2011-02-04 03:18:17 +00001584 if (!TracksRegPressure)
1585 PrescheduleNodesWithMultipleUses();
Andrew Trick9ccce772011-01-14 21:11:41 +00001586 // Calculate node priorities.
1587 CalculateSethiUllmanNumbers();
1588}
1589
1590void RegReductionPQBase::addNode(const SUnit *SU) {
1591 unsigned SUSize = SethiUllmanNumbers.size();
1592 if (SUnits->size() > SUSize)
1593 SethiUllmanNumbers.resize(SUSize*2, 0);
1594 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1595}
1596
1597void RegReductionPQBase::updateNode(const SUnit *SU) {
1598 SethiUllmanNumbers[SU->NodeNum] = 0;
1599 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1600}
1601
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001602// Lower priority means schedule further down. For bottom-up scheduling, lower
1603// priority SUs are scheduled before higher priority SUs.
Andrew Trick9ccce772011-01-14 21:11:41 +00001604unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1605 assert(SU->NodeNum < SethiUllmanNumbers.size());
1606 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1607 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1608 // CopyToReg should be close to its uses to facilitate coalescing and
1609 // avoid spilling.
1610 return 0;
1611 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1612 Opc == TargetOpcode::SUBREG_TO_REG ||
1613 Opc == TargetOpcode::INSERT_SUBREG)
1614 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1615 // close to their uses to facilitate coalescing.
1616 return 0;
1617 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1618 // If SU does not have a register use, i.e. it doesn't produce a value
1619 // that would be consumed (e.g. store), then it terminates a chain of
1620 // computation. Give it a large SethiUllman number so it will be
1621 // scheduled right before its predecessors that it doesn't lengthen
1622 // their live ranges.
1623 return 0xffff;
1624 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1625 // If SU does not have a register def, schedule it close to its uses
1626 // because it does not lengthen any live ranges.
1627 return 0;
1628 return SethiUllmanNumbers[SU->NodeNum];
1629}
1630
1631//===----------------------------------------------------------------------===//
1632// Register Pressure Tracking
1633//===----------------------------------------------------------------------===//
1634
1635void RegReductionPQBase::dumpRegPressure() const {
1636 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1637 E = TRI->regclass_end(); I != E; ++I) {
1638 const TargetRegisterClass *RC = *I;
1639 unsigned Id = RC->getID();
1640 unsigned RP = RegPressure[Id];
1641 if (!RP) continue;
1642 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1643 << '\n');
1644 }
1645}
1646
1647bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1648 if (!TLI)
1649 return false;
1650
1651 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1652 I != E; ++I) {
1653 if (I->isCtrl())
1654 continue;
1655 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001656 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1657 // to cover the number of registers defined (they are all live).
1658 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001659 continue;
1660 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001661 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1662 RegDefPos.IsValid(); RegDefPos.Advance()) {
1663 EVT VT = RegDefPos.GetValue();
Andrew Trick9ccce772011-01-14 21:11:41 +00001664 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1665 unsigned Cost = TLI->getRepRegClassCostFor(VT);
Andrew Trick9ccce772011-01-14 21:11:41 +00001666 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1667 return true;
1668 }
1669 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001670 return false;
1671}
1672
1673bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) {
1674 const SDNode *N = SU->getNode();
1675
1676 if (!N->isMachineOpcode() || !SU->NumSuccs)
1677 return false;
1678
1679 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1680 for (unsigned i = 0; i != NumDefs; ++i) {
1681 EVT VT = N->getValueType(i);
1682 if (!N->hasAnyUseOfValue(i))
1683 continue;
1684 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1685 if (RegPressure[RCId] >= RegLimit[RCId])
1686 return true;
1687 }
1688 return false;
1689}
1690
1691void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1692 if (!TracksRegPressure)
1693 return;
1694
Andrew Trick9ccce772011-01-14 21:11:41 +00001695 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1696 I != E; ++I) {
1697 if (I->isCtrl())
1698 continue;
1699 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001700 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1701 // to cover the number of registers defined (they are all live).
1702 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick9ccce772011-01-14 21:11:41 +00001703 continue;
1704 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001705 // FIXME: The ScheduleDAG currently loses information about which of a
1706 // node's values is consumed by each dependence. Consequently, if the node
1707 // defines multiple register classes, we don't know which to pressurize
1708 // here. Instead the following loop consumes the register defs in an
1709 // arbitrary order. At least it handles the common case of clustered loads
1710 // to the same class. For precise liveness, each SDep needs to indicate the
1711 // result number. But that tightly couples the ScheduleDAG with the
1712 // SelectionDAG making updates tricky. A simpler hack would be to attach a
1713 // value type or register class to SDep.
1714 //
1715 // The most important aspect of register tracking is balancing the increase
1716 // here with the reduction further below. Note that this SU may use multiple
1717 // defs in PredSU. The can't be determined here, but we've already
1718 // compensated by reducing NumRegDefsLeft in PredSU during
1719 // ScheduleDAGSDNodes::AddSchedEdges.
1720 --PredSU->NumRegDefsLeft;
1721 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
1722 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1723 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1724 if (SkipRegDefs)
Andrew Trick9ccce772011-01-14 21:11:41 +00001725 continue;
Andrew Trickd0548ae2011-02-04 03:18:17 +00001726 EVT VT = RegDefPos.GetValue();
Andrew Trick9ccce772011-01-14 21:11:41 +00001727 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1728 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
Andrew Trickd0548ae2011-02-04 03:18:17 +00001729 break;
Andrew Trick9ccce772011-01-14 21:11:41 +00001730 }
1731 }
1732
Andrew Trickd0548ae2011-02-04 03:18:17 +00001733 // We should have this assert, but there may be dead SDNodes that never
1734 // materialize as SUnits, so they don't appear to generate liveness.
1735 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
1736 int SkipRegDefs = (int)SU->NumRegDefsLeft;
1737 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
1738 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1739 if (SkipRegDefs > 0)
1740 continue;
1741 EVT VT = RegDefPos.GetValue();
1742 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1743 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT)) {
1744 // Register pressure tracking is imprecise. This can happen. But we try
1745 // hard not to let it happen because it likely results in poor scheduling.
1746 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
1747 RegPressure[RCId] = 0;
1748 }
1749 else {
1750 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
Andrew Trick9ccce772011-01-14 21:11:41 +00001751 }
1752 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001753 dumpRegPressure();
1754}
1755
1756void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
1757 if (!TracksRegPressure)
1758 return;
1759
1760 const SDNode *N = SU->getNode();
1761 if (!N->isMachineOpcode()) {
1762 if (N->getOpcode() != ISD::CopyToReg)
1763 return;
1764 } else {
1765 unsigned Opc = N->getMachineOpcode();
1766 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1767 Opc == TargetOpcode::INSERT_SUBREG ||
1768 Opc == TargetOpcode::SUBREG_TO_REG ||
1769 Opc == TargetOpcode::REG_SEQUENCE ||
1770 Opc == TargetOpcode::IMPLICIT_DEF)
1771 return;
1772 }
1773
1774 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1775 I != E; ++I) {
1776 if (I->isCtrl())
1777 continue;
1778 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001779 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1780 // counts data deps.
1781 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00001782 continue;
1783 const SDNode *PN = PredSU->getNode();
1784 if (!PN->isMachineOpcode()) {
1785 if (PN->getOpcode() == ISD::CopyFromReg) {
1786 EVT VT = PN->getValueType(0);
1787 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1788 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1789 }
1790 continue;
1791 }
1792 unsigned POpc = PN->getMachineOpcode();
1793 if (POpc == TargetOpcode::IMPLICIT_DEF)
1794 continue;
1795 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1796 EVT VT = PN->getOperand(0).getValueType();
1797 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1798 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1799 continue;
1800 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1801 POpc == TargetOpcode::SUBREG_TO_REG) {
1802 EVT VT = PN->getValueType(0);
1803 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1804 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1805 continue;
1806 }
1807 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1808 for (unsigned i = 0; i != NumDefs; ++i) {
1809 EVT VT = PN->getValueType(i);
1810 if (!PN->hasAnyUseOfValue(i))
1811 continue;
1812 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1813 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1814 // Register pressure tracking is imprecise. This can happen.
1815 RegPressure[RCId] = 0;
1816 else
1817 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1818 }
1819 }
1820
1821 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1822 // may transfer data dependencies to CopyToReg.
1823 if (SU->NumSuccs && N->isMachineOpcode()) {
1824 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1825 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1826 EVT VT = N->getValueType(i);
1827 if (VT == MVT::Glue || VT == MVT::Other)
1828 continue;
1829 if (!N->hasAnyUseOfValue(i))
1830 continue;
1831 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1832 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1833 }
1834 }
1835
1836 dumpRegPressure();
1837}
1838
1839//===----------------------------------------------------------------------===//
1840// Dynamic Node Priority for Register Pressure Reduction
1841//===----------------------------------------------------------------------===//
1842
Evan Chengb9e3db62007-03-14 22:43:40 +00001843/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00001844/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00001845static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001846 unsigned MaxHeight = 0;
Evan Cheng28748552007-03-13 23:25:11 +00001847 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00001848 I != E; ++I) {
Evan Chengce3bbe52009-02-10 08:30:11 +00001849 if (I->isCtrl()) continue; // ignore chain succs
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001850 unsigned Height = I->getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00001851 // If there are bunch of CopyToRegs stacked up, they should be considered
1852 // to be at the same position.
Dan Gohman2d170892008-12-09 22:54:47 +00001853 if (I->getSUnit()->getNode() &&
1854 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001855 Height = closestSucc(I->getSUnit())+1;
1856 if (Height > MaxHeight)
1857 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00001858 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001859 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00001860}
1861
Evan Cheng61bc51e2007-12-20 02:22:36 +00001862/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00001863/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00001864static unsigned calcMaxScratches(const SUnit *SU) {
1865 unsigned Scratches = 0;
1866 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Chengb5704992009-02-12 09:52:13 +00001867 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001868 if (I->isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00001869 Scratches++;
1870 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00001871 return Scratches;
1872}
1873
Evan Cheng6c1414f2010-10-29 18:09:28 +00001874/// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
1875/// CopyToReg to a virtual register. This SU def is probably a liveout and
1876/// it has no other use. It should be scheduled closer to the terminator.
1877static bool hasOnlyLiveOutUses(const SUnit *SU) {
1878 bool RetVal = false;
1879 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1880 I != E; ++I) {
1881 if (I->isCtrl()) continue;
1882 const SUnit *SuccSU = I->getSUnit();
1883 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
1884 unsigned Reg =
1885 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
1886 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1887 RetVal = true;
1888 continue;
1889 }
1890 }
1891 return false;
1892 }
1893 return RetVal;
1894}
1895
1896/// UnitsSharePred - Return true if the two scheduling units share a common
1897/// data predecessor.
1898static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
1899 SmallSet<const SUnit*, 4> Preds;
1900 for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
1901 I != E; ++I) {
1902 if (I->isCtrl()) continue; // ignore chain preds
1903 Preds.insert(I->getSUnit());
1904 }
1905 for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
1906 I != E; ++I) {
1907 if (I->isCtrl()) continue; // ignore chain preds
1908 if (Preds.count(I->getSUnit()))
1909 return true;
1910 }
1911 return false;
1912}
1913
Andrew Trick9ccce772011-01-14 21:11:41 +00001914// Check for either a dependence (latency) or resource (hazard) stall.
1915//
1916// Note: The ScheduleHazardRecognizer interface requires a non-const SU.
1917static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
1918 if ((int)SPQ->getCurCycle() < Height) return true;
1919 if (SPQ->getHazardRec()->getHazardType(SU, 0)
1920 != ScheduleHazardRecognizer::NoHazard)
1921 return true;
1922 return false;
1923}
1924
1925// Return -1 if left has higher priority, 1 if right has higher priority.
1926// Return 0 if latency-based priority is equivalent.
1927static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
1928 RegReductionPQBase *SPQ) {
1929 // If the two nodes share an operand and one of them has a single
1930 // use that is a live out copy, favor the one that is live out. Otherwise
1931 // it will be difficult to eliminate the copy if the instruction is a
1932 // loop induction variable update. e.g.
1933 // BB:
1934 // sub r1, r3, #1
1935 // str r0, [r2, r3]
1936 // mov r3, r1
1937 // cmp
1938 // bne BB
1939 bool SharePred = UnitsSharePred(left, right);
1940 // FIXME: Only adjust if BB is a loop back edge.
1941 // FIXME: What's the cost of a copy?
1942 int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
1943 int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
1944 int LHeight = (int)left->getHeight() - LBonus;
1945 int RHeight = (int)right->getHeight() - RBonus;
1946
1947 bool LStall = (!checkPref || left->SchedulingPref == Sched::Latency) &&
1948 BUHasStall(left, LHeight, SPQ);
1949 bool RStall = (!checkPref || right->SchedulingPref == Sched::Latency) &&
1950 BUHasStall(right, RHeight, SPQ);
1951
1952 // If scheduling one of the node will cause a pipeline stall, delay it.
1953 // If scheduling either one of the node will cause a pipeline stall, sort
1954 // them according to their height.
1955 if (LStall) {
1956 if (!RStall)
1957 return 1;
1958 if (LHeight != RHeight)
1959 return LHeight > RHeight ? 1 : -1;
1960 } else if (RStall)
1961 return -1;
1962
Andrew Trick47ff14b2011-01-21 05:51:33 +00001963 // If either node is scheduling for latency, sort them by height/depth
Andrew Trick9ccce772011-01-14 21:11:41 +00001964 // and latency.
1965 if (!checkPref || (left->SchedulingPref == Sched::Latency ||
1966 right->SchedulingPref == Sched::Latency)) {
Andrew Trick47ff14b2011-01-21 05:51:33 +00001967 if (DisableSchedCycles) {
Andrew Trick9ccce772011-01-14 21:11:41 +00001968 if (LHeight != RHeight)
1969 return LHeight > RHeight ? 1 : -1;
1970 }
Andrew Trick47ff14b2011-01-21 05:51:33 +00001971 else {
1972 // If neither instruction stalls (!LStall && !RStall) then
1973 // it's height is already covered so only its depth matters. We also reach
1974 // this if both stall but have the same height.
1975 unsigned LDepth = left->getDepth();
1976 unsigned RDepth = right->getDepth();
1977 if (LDepth != RDepth) {
1978 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
1979 << ") depth " << LDepth << " vs SU (" << right->NodeNum
1980 << ") depth " << RDepth << "\n");
1981 return LDepth < RDepth ? 1 : -1;
1982 }
1983 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001984 if (left->Latency != right->Latency)
1985 return left->Latency > right->Latency ? 1 : -1;
1986 }
1987 return 0;
1988}
1989
1990static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
Evan Cheng6730f032007-01-08 23:55:53 +00001991 unsigned LPriority = SPQ->getNodePriority(left);
1992 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng73bdf042008-03-01 00:39:47 +00001993 if (LPriority != RPriority)
1994 return LPriority > RPriority;
1995
1996 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1997 // e.g.
1998 // t1 = op t2, c1
1999 // t3 = op t4, c2
2000 //
2001 // and the following instructions are both ready.
2002 // t2 = op c3
2003 // t4 = op c4
2004 //
2005 // Then schedule t2 = op first.
2006 // i.e.
2007 // t4 = op c4
2008 // t2 = op c3
2009 // t1 = op t2, c1
2010 // t3 = op t4, c2
2011 //
2012 // This creates more short live intervals.
2013 unsigned LDist = closestSucc(left);
2014 unsigned RDist = closestSucc(right);
2015 if (LDist != RDist)
2016 return LDist < RDist;
2017
Evan Cheng3a14efa2009-02-12 08:59:45 +00002018 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00002019 unsigned LScratch = calcMaxScratches(left);
2020 unsigned RScratch = calcMaxScratches(right);
2021 if (LScratch != RScratch)
2022 return LScratch > RScratch;
2023
Andrew Trick47ff14b2011-01-21 05:51:33 +00002024 if (!DisableSchedCycles) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002025 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2026 if (result != 0)
2027 return result > 0;
2028 }
2029 else {
2030 if (left->getHeight() != right->getHeight())
2031 return left->getHeight() > right->getHeight();
Andrew Trick2085a962010-12-21 22:25:04 +00002032
Andrew Trick9ccce772011-01-14 21:11:41 +00002033 if (left->getDepth() != right->getDepth())
2034 return left->getDepth() < right->getDepth();
2035 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002036
Andrew Trick2085a962010-12-21 22:25:04 +00002037 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002038 "NodeQueueId cannot be zero");
2039 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002040}
2041
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002042// Bottom up
Andrew Trick9ccce772011-01-14 21:11:41 +00002043bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002044 return BURRSort(left, right, SPQ);
2045}
2046
2047// Source order, otherwise bottom up.
Andrew Trick9ccce772011-01-14 21:11:41 +00002048bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002049 unsigned LOrder = SPQ->getNodeOrdering(left);
2050 unsigned ROrder = SPQ->getNodeOrdering(right);
2051
2052 // Prefer an ordering where the lower the non-zero order number, the higher
2053 // the preference.
2054 if ((LOrder || ROrder) && LOrder != ROrder)
2055 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2056
2057 return BURRSort(left, right, SPQ);
2058}
2059
Andrew Trick9ccce772011-01-14 21:11:41 +00002060// If the time between now and when the instruction will be ready can cover
2061// the spill code, then avoid adding it to the ready queue. This gives long
2062// stalls highest priority and allows hoisting across calls. It should also
2063// speed up processing the available queue.
2064bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2065 static const unsigned ReadyDelay = 3;
2066
2067 if (SPQ->MayReduceRegPressure(SU)) return true;
2068
2069 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2070
2071 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2072 != ScheduleHazardRecognizer::NoHazard)
2073 return false;
2074
2075 return true;
2076}
2077
2078// Return true if right should be scheduled with higher priority than left.
2079bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002080 if (left->isCall || right->isCall)
2081 // No way to compute latency of calls.
2082 return BURRSort(left, right, SPQ);
2083
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002084 bool LHigh = SPQ->HighRegPressure(left);
2085 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002086 // Avoid causing spills. If register pressure is high, schedule for
2087 // register pressure reduction.
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002088 if (LHigh && !RHigh) {
2089 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2090 << right->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002091 return true;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002092 }
2093 else if (!LHigh && RHigh) {
2094 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2095 << left->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002096 return false;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002097 }
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002098 else if (!LHigh && !RHigh) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002099 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2100 if (result != 0)
2101 return result > 0;
Evan Chengcc2efe12010-05-28 23:26:21 +00002102 }
Evan Chengbdd062d2010-05-20 06:13:19 +00002103 return BURRSort(left, right, SPQ);
2104}
2105
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002106// Schedule as many instructions in each cycle as possible. So don't make an
2107// instruction available unless it is ready in the current cycle.
2108bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00002109 if (SU->getHeight() > CurCycle) return false;
2110
2111 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2112 != ScheduleHazardRecognizer::NoHazard)
2113 return false;
2114
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002115 return SU->getHeight() <= CurCycle;
2116}
2117
Andrew Trick9ccce772011-01-14 21:11:41 +00002118bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002119 if (left->isCall || right->isCall)
2120 // No way to compute latency of calls.
2121 return BURRSort(left, right, SPQ);
2122
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002123 bool LHigh = SPQ->HighRegPressure(left);
2124 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002125 // Avoid causing spills. If register pressure is high, schedule for
2126 // register pressure reduction.
2127 if (LHigh && !RHigh)
2128 return true;
2129 else if (!LHigh && RHigh)
2130 return false;
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002131 else if (!LHigh && !RHigh) {
Evan Cheng8ae3eca2010-07-25 18:59:43 +00002132 // Low register pressure situation, schedule to maximize instruction level
2133 // parallelism.
Evan Cheng37b740c2010-07-24 00:39:05 +00002134 if (left->NumPreds > right->NumPreds)
2135 return false;
2136 else if (left->NumPreds < right->NumPreds)
2137 return false;
2138 }
2139
2140 return BURRSort(left, right, SPQ);
2141}
2142
Andrew Trick9ccce772011-01-14 21:11:41 +00002143//===----------------------------------------------------------------------===//
2144// Preschedule for Register Pressure
2145//===----------------------------------------------------------------------===//
2146
2147bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002148 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002149 unsigned Opc = SU->getNode()->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002150 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002151 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002152 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002153 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002154 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002155 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002156 if (DU->getNodeId() != -1 &&
2157 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002158 return true;
2159 }
2160 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002161 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002162 return false;
2163}
2164
Evan Chengf9891412007-12-20 09:25:31 +00002165/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002166/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002167static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002168 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002169 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002170 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002171 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2172 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002173 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002174 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002175 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002176 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002177 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002178 const unsigned *SUImpDefs =
2179 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2180 if (!SUImpDefs)
2181 return false;
2182 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002183 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002184 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002185 continue;
2186 if (!N->hasAnyUseOfValue(i))
2187 continue;
2188 unsigned Reg = ImpDefs[i - NumDefs];
2189 for (;*SUImpDefs; ++SUImpDefs) {
2190 unsigned SUReg = *SUImpDefs;
2191 if (TRI->regsOverlap(Reg, SUReg))
2192 return true;
2193 }
Evan Chengf9891412007-12-20 09:25:31 +00002194 }
2195 }
2196 return false;
2197}
2198
Dan Gohman9a658d72009-03-24 00:49:12 +00002199/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2200/// are not handled well by the general register pressure reduction
2201/// heuristics. When presented with code like this:
2202///
2203/// N
2204/// / |
2205/// / |
2206/// U store
2207/// |
2208/// ...
2209///
2210/// the heuristics tend to push the store up, but since the
2211/// operand of the store has another use (U), this would increase
2212/// the length of that other use (the U->N edge).
2213///
2214/// This function transforms code like the above to route U's
2215/// dependence through the store when possible, like this:
2216///
2217/// N
2218/// ||
2219/// ||
2220/// store
2221/// |
2222/// U
2223/// |
2224/// ...
2225///
2226/// This results in the store being scheduled immediately
2227/// after N, which shortens the U->N live range, reducing
2228/// register pressure.
2229///
Andrew Trick9ccce772011-01-14 21:11:41 +00002230void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
Dan Gohman9a658d72009-03-24 00:49:12 +00002231 // Visit all the nodes in topological order, working top-down.
2232 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2233 SUnit *SU = &(*SUnits)[i];
2234 // For now, only look at nodes with no data successors, such as stores.
2235 // These are especially important, due to the heuristics in
2236 // getNodePriority for nodes with no data successors.
2237 if (SU->NumSuccs != 0)
2238 continue;
2239 // For now, only look at nodes with exactly one data predecessor.
2240 if (SU->NumPreds != 1)
2241 continue;
2242 // Avoid prescheduling copies to virtual registers, which don't behave
2243 // like other nodes from the perspective of scheduling heuristics.
2244 if (SDNode *N = SU->getNode())
2245 if (N->getOpcode() == ISD::CopyToReg &&
2246 TargetRegisterInfo::isVirtualRegister
2247 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2248 continue;
2249
2250 // Locate the single data predecessor.
2251 SUnit *PredSU = 0;
2252 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2253 EE = SU->Preds.end(); II != EE; ++II)
2254 if (!II->isCtrl()) {
2255 PredSU = II->getSUnit();
2256 break;
2257 }
2258 assert(PredSU);
2259
2260 // Don't rewrite edges that carry physregs, because that requires additional
2261 // support infrastructure.
2262 if (PredSU->hasPhysRegDefs)
2263 continue;
2264 // Short-circuit the case where SU is PredSU's only data successor.
2265 if (PredSU->NumSuccs == 1)
2266 continue;
2267 // Avoid prescheduling to copies from virtual registers, which don't behave
Andrew Trickd0548ae2011-02-04 03:18:17 +00002268 // like other nodes from the perspective of scheduling heuristics.
Dan Gohman9a658d72009-03-24 00:49:12 +00002269 if (SDNode *N = SU->getNode())
2270 if (N->getOpcode() == ISD::CopyFromReg &&
2271 TargetRegisterInfo::isVirtualRegister
2272 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2273 continue;
2274
2275 // Perform checks on the successors of PredSU.
2276 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2277 EE = PredSU->Succs.end(); II != EE; ++II) {
2278 SUnit *PredSuccSU = II->getSUnit();
2279 if (PredSuccSU == SU) continue;
2280 // If PredSU has another successor with no data successors, for
2281 // now don't attempt to choose either over the other.
2282 if (PredSuccSU->NumSuccs == 0)
2283 goto outer_loop_continue;
2284 // Don't break physical register dependencies.
2285 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2286 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2287 goto outer_loop_continue;
2288 // Don't introduce graph cycles.
2289 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2290 goto outer_loop_continue;
2291 }
2292
2293 // Ok, the transformation is safe and the heuristics suggest it is
2294 // profitable. Update the graph.
Evan Chengbdd062d2010-05-20 06:13:19 +00002295 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2296 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002297 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002298 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2299 SDep Edge = PredSU->Succs[i];
2300 assert(!Edge.isAssignedRegDep());
2301 SUnit *SuccSU = Edge.getSUnit();
2302 if (SuccSU != SU) {
2303 Edge.setSUnit(PredSU);
2304 scheduleDAG->RemovePred(SuccSU, Edge);
2305 scheduleDAG->AddPred(SU, Edge);
2306 Edge.setSUnit(SU);
2307 scheduleDAG->AddPred(SuccSU, Edge);
2308 --i;
2309 }
2310 }
2311 outer_loop_continue:;
2312 }
2313}
2314
Evan Chengd38c22b2006-05-11 23:55:42 +00002315/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2316/// it as a def&use operand. Add a pseudo control edge from it to the other
2317/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002318/// first (lower in the schedule). If both nodes are two-address, favor the
2319/// one that has a CopyToReg use (more likely to be a loop induction update).
2320/// If both are two-address, but one is commutable while the other is not
2321/// commutable, favor the one that's not commutable.
Andrew Trick9ccce772011-01-14 21:11:41 +00002322void RegReductionPQBase::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002323 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
Dan Gohmane955c482008-08-05 14:45:15 +00002324 SUnit *SU = &(*SUnits)[i];
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002325 if (!SU->isTwoAddress)
2326 continue;
2327
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002328 SDNode *Node = SU->getNode();
Chris Lattner11a33812010-12-23 17:24:32 +00002329 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002330 continue;
2331
Evan Cheng6c1414f2010-10-29 18:09:28 +00002332 bool isLiveOut = hasOnlyLiveOutUses(SU);
Dan Gohman17059682008-07-17 19:10:17 +00002333 unsigned Opc = Node->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002334 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002335 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002336 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002337 for (unsigned j = 0; j != NumOps; ++j) {
Dan Gohman82016c22008-11-19 02:00:32 +00002338 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2339 continue;
2340 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2341 if (DU->getNodeId() == -1)
2342 continue;
2343 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2344 if (!DUSU) continue;
2345 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2346 E = DUSU->Succs.end(); I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002347 if (I->isCtrl()) continue;
2348 SUnit *SuccSU = I->getSUnit();
Dan Gohman82016c22008-11-19 02:00:32 +00002349 if (SuccSU == SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002350 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002351 // Be conservative. Ignore if nodes aren't at roughly the same
2352 // depth and height.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002353 if (SuccSU->getHeight() < SU->getHeight() &&
2354 (SU->getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002355 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002356 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2357 // constrains whatever is using the copy, instead of the copy
2358 // itself. In the case that the copy is coalesced, this
2359 // preserves the intent of the pseudo two-address heurietics.
2360 while (SuccSU->Succs.size() == 1 &&
2361 SuccSU->getNode()->isMachineOpcode() &&
2362 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002363 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002364 SuccSU = SuccSU->Succs.front().getSUnit();
2365 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002366 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2367 continue;
2368 // Don't constrain nodes with physical register defs if the
2369 // predecessor can clobber them.
Dan Gohmanf3746cb2009-03-24 00:50:07 +00002370 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
Dan Gohman82016c22008-11-19 02:00:32 +00002371 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002372 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002373 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002374 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2375 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002376 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002377 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2378 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2379 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002380 continue;
2381 if ((!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002382 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Dan Gohman82016c22008-11-19 02:00:32 +00002383 (!SU->isCommutable && SuccSU->isCommutable)) &&
2384 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002385 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002386 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
Dan Gohman79c35162009-01-06 01:19:04 +00002387 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
Dan Gohmanbf8e5202009-01-06 01:28:56 +00002388 /*Reg=*/0, /*isNormalMemory=*/false,
2389 /*isMustAlias=*/false,
Dan Gohman2d170892008-12-09 22:54:47 +00002390 /*isArtificial=*/true));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002391 }
2392 }
2393 }
2394 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002395}
2396
Roman Levenstein30d09512008-03-27 09:44:37 +00002397/// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
Roman Levensteinbc674502008-03-27 09:14:57 +00002398/// predecessors of the successors of the SUnit SU. Stop when the provided
2399/// limit is exceeded.
Andrew Trick2085a962010-12-21 22:25:04 +00002400static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
Roman Levensteinbc674502008-03-27 09:14:57 +00002401 unsigned Limit) {
2402 unsigned Sum = 0;
2403 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2404 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002405 const SUnit *SuccSU = I->getSUnit();
Roman Levensteinbc674502008-03-27 09:14:57 +00002406 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2407 EE = SuccSU->Preds.end(); II != EE; ++II) {
Dan Gohman2d170892008-12-09 22:54:47 +00002408 SUnit *PredSU = II->getSUnit();
Evan Cheng16d72072008-03-29 18:34:22 +00002409 if (!PredSU->isScheduled)
2410 if (++Sum > Limit)
2411 return Sum;
Roman Levensteinbc674502008-03-27 09:14:57 +00002412 }
2413 }
2414 return Sum;
2415}
2416
Evan Chengd38c22b2006-05-11 23:55:42 +00002417
2418// Top down
2419bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Evan Cheng6730f032007-01-08 23:55:53 +00002420 unsigned LPriority = SPQ->getNodePriority(left);
2421 unsigned RPriority = SPQ->getNodePriority(right);
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002422 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2423 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00002424 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2425 bool RIsFloater = RIsTarget && right->NumPreds == 0;
Roman Levensteinbc674502008-03-27 09:14:57 +00002426 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2427 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00002428
2429 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2430 return false;
2431 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2432 return true;
2433
Evan Chengd38c22b2006-05-11 23:55:42 +00002434 if (LIsFloater)
2435 LBonus -= 2;
2436 if (RIsFloater)
2437 RBonus -= 2;
2438 if (left->NumSuccs == 1)
2439 LBonus += 2;
2440 if (right->NumSuccs == 1)
2441 RBonus += 2;
2442
Evan Cheng73bdf042008-03-01 00:39:47 +00002443 if (LPriority+LBonus != RPriority+RBonus)
2444 return LPriority+LBonus < RPriority+RBonus;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00002445
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002446 if (left->getDepth() != right->getDepth())
2447 return left->getDepth() < right->getDepth();
Evan Cheng73bdf042008-03-01 00:39:47 +00002448
2449 if (left->NumSuccsLeft != right->NumSuccsLeft)
2450 return left->NumSuccsLeft > right->NumSuccsLeft;
2451
Andrew Trick2085a962010-12-21 22:25:04 +00002452 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002453 "NodeQueueId cannot be zero");
2454 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002455}
2456
Evan Chengd38c22b2006-05-11 23:55:42 +00002457//===----------------------------------------------------------------------===//
2458// Public Constructor Functions
2459//===----------------------------------------------------------------------===//
2460
Dan Gohmandfaf6462009-02-11 04:27:20 +00002461llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002462llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2463 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002464 const TargetMachine &TM = IS->TM;
2465 const TargetInstrInfo *TII = TM.getInstrInfo();
2466 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002467
Evan Chenga77f3d32010-07-21 06:09:07 +00002468 BURegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002469 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002470 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002471 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002472 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002473}
2474
Dan Gohmandfaf6462009-02-11 04:27:20 +00002475llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002476llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2477 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002478 const TargetMachine &TM = IS->TM;
2479 const TargetInstrInfo *TII = TM.getInstrInfo();
2480 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002481
Evan Chenga77f3d32010-07-21 06:09:07 +00002482 TDRegReductionPriorityQueue *PQ =
2483 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002484 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Dan Gohman3f656df2008-11-20 02:45:51 +00002485 PQ->setScheduleDAG(SD);
2486 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002487}
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002488
2489llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002490llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2491 CodeGenOpt::Level OptLevel) {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002492 const TargetMachine &TM = IS->TM;
2493 const TargetInstrInfo *TII = TM.getInstrInfo();
2494 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002495
Evan Chenga77f3d32010-07-21 06:09:07 +00002496 SrcRegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002497 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002498 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002499 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002500 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002501}
2502
2503llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002504llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2505 CodeGenOpt::Level OptLevel) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002506 const TargetMachine &TM = IS->TM;
2507 const TargetInstrInfo *TII = TM.getInstrInfo();
2508 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Evan Chenga77f3d32010-07-21 06:09:07 +00002509 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002510
Evan Chenga77f3d32010-07-21 06:09:07 +00002511 HybridBURRPriorityQueue *PQ =
Evan Chengdf907f42010-07-23 22:39:59 +00002512 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002513
2514 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002515 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002516 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002517}
Evan Cheng37b740c2010-07-24 00:39:05 +00002518
2519llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002520llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2521 CodeGenOpt::Level OptLevel) {
Evan Cheng37b740c2010-07-24 00:39:05 +00002522 const TargetMachine &TM = IS->TM;
2523 const TargetInstrInfo *TII = TM.getInstrInfo();
2524 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2525 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002526
Evan Cheng37b740c2010-07-24 00:39:05 +00002527 ILPBURRPriorityQueue *PQ =
2528 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002529 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00002530 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002531 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00002532}