blob: 1a564f1505b4eba08637849105748d45c2787694 [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 Trick10ffc2b2010-12-24 05:03:26 +000069static cl::opt<bool> EnableSchedCycles(
70 "enable-sched-cycles",
71 cl::desc("Enable cycle-level precision during preRA scheduling"),
72 cl::init(false), cl::Hidden);
73
Evan Chengd38c22b2006-05-11 23:55:42 +000074namespace {
Evan Chengd38c22b2006-05-11 23:55:42 +000075//===----------------------------------------------------------------------===//
76/// ScheduleDAGRRList - The actual register reduction list scheduler
77/// implementation. This supports both top-down and bottom-up scheduling.
78///
Nick Lewycky02d5f772009-10-25 06:33:48 +000079class ScheduleDAGRRList : public ScheduleDAGSDNodes {
Evan Chengd38c22b2006-05-11 23:55:42 +000080private:
81 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
82 /// it is top-down.
83 bool isBottomUp;
Evan Cheng2c977312008-07-01 18:05:03 +000084
Evan Chengbdd062d2010-05-20 06:13:19 +000085 /// NeedLatency - True if the scheduler will make use of latency information.
86 ///
87 bool NeedLatency;
88
Evan Chengd38c22b2006-05-11 23:55:42 +000089 /// AvailableQueue - The priority queue to use for the available SUnits.
Evan Chengd38c22b2006-05-11 23:55:42 +000090 SchedulingPriorityQueue *AvailableQueue;
91
Andrew Trick10ffc2b2010-12-24 05:03:26 +000092 /// PendingQueue - This contains all of the instructions whose operands have
93 /// been issued, but their results are not ready yet (due to the latency of
94 /// the operation). Once the operands becomes available, the instruction is
95 /// added to the AvailableQueue.
96 std::vector<SUnit*> PendingQueue;
97
98 /// HazardRec - The hazard recognizer to use.
99 ScheduleHazardRecognizer *HazardRec;
100
Andrew Trick528fad92010-12-23 05:42:20 +0000101 /// CurCycle - The current scheduler state corresponds to this cycle.
102 unsigned CurCycle;
103
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000104 /// MinAvailableCycle - Cycle of the soonest available instruction.
105 unsigned MinAvailableCycle;
106
Dan Gohmanc07f6862008-09-23 18:50:48 +0000107 /// LiveRegDefs - A set of physical registers and their definition
Evan Cheng5924bf72007-09-25 01:54:36 +0000108 /// that are "live". These nodes must be scheduled before any other nodes that
109 /// modifies the registers can be scheduled.
Dan Gohmanc07f6862008-09-23 18:50:48 +0000110 unsigned NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000111 std::vector<SUnit*> LiveRegDefs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000112 std::vector<SUnit*> LiveRegGens;
Evan Cheng5924bf72007-09-25 01:54:36 +0000113
Dan Gohmanad2134d2008-11-25 00:52:40 +0000114 /// Topo - A topological ordering for SUnits which permits fast IsReachable
115 /// and similar queries.
116 ScheduleDAGTopologicalSort Topo;
117
Evan Chengd38c22b2006-05-11 23:55:42 +0000118public:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000119 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
120 SchedulingPriorityQueue *availqueue,
121 CodeGenOpt::Level OptLevel)
122 : ScheduleDAGSDNodes(mf), isBottomUp(availqueue->isBottomUp()),
123 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
124 Topo(SUnits) {
125
126 const TargetMachine &tm = mf.getTarget();
127 if (EnableSchedCycles && OptLevel != CodeGenOpt::None)
128 HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
129 else
130 HazardRec = new ScheduleHazardRecognizer();
131 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000132
133 ~ScheduleDAGRRList() {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000134 delete HazardRec;
Evan Chengd38c22b2006-05-11 23:55:42 +0000135 delete AvailableQueue;
136 }
137
138 void Schedule();
139
Andrew Trick9ccce772011-01-14 21:11:41 +0000140 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
141
Roman Levenstein733a4d62008-03-26 11:23:38 +0000142 /// IsReachable - Checks if SU is reachable from TargetSU.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000143 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
144 return Topo.IsReachable(SU, TargetSU);
145 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000146
Dan Gohman60d68442009-01-29 19:49:27 +0000147 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000148 /// create a cycle.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000149 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
150 return Topo.WillCreateCycle(SU, TargetSU);
151 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000152
Dan Gohman2d170892008-12-09 22:54:47 +0000153 /// AddPred - adds a predecessor edge to SUnit SU.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000154 /// This returns true if this is a new predecessor.
155 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000156 void AddPred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000157 Topo.AddPred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000158 SU->addPred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000159 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000160
Dan Gohman2d170892008-12-09 22:54:47 +0000161 /// RemovePred - removes a predecessor edge from SUnit SU.
162 /// This returns true if an edge was removed.
163 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000164 void RemovePred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000165 Topo.RemovePred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000166 SU->removePred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000167 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000168
Evan Chengd38c22b2006-05-11 23:55:42 +0000169private:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000170 bool isReady(SUnit *SU) {
171 return !EnableSchedCycles || !AvailableQueue->hasReadyFilter() ||
172 AvailableQueue->isReady(SU);
173 }
174
Dan Gohman60d68442009-01-29 19:49:27 +0000175 void ReleasePred(SUnit *SU, const SDep *PredEdge);
Andrew Tricka52f3252010-12-23 04:16:14 +0000176 void ReleasePredecessors(SUnit *SU);
Dan Gohman60d68442009-01-29 19:49:27 +0000177 void ReleaseSucc(SUnit *SU, const SDep *SuccEdge);
Dan Gohmanb9543432009-02-10 23:27:53 +0000178 void ReleaseSuccessors(SUnit *SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000179 void ReleasePending();
180 void AdvanceToCycle(unsigned NextCycle);
181 void AdvancePastStalls(SUnit *SU);
182 void EmitNode(SUnit *SU);
Andrew Trick528fad92010-12-23 05:42:20 +0000183 void ScheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000184 void CapturePred(SDep *PredEdge);
Evan Cheng8e136a92007-09-26 21:36:17 +0000185 void UnscheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000186 void RestoreHazardCheckerBottomUp();
187 void BacktrackBottomUp(SUnit*, SUnit*);
Evan Cheng8e136a92007-09-26 21:36:17 +0000188 SUnit *CopyAndMoveSuccessors(SUnit*);
Evan Chengb2c42c62009-01-12 03:19:55 +0000189 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
190 const TargetRegisterClass*,
191 const TargetRegisterClass*,
192 SmallVector<SUnit*, 2>&);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000193 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000194
Andrew Trick528fad92010-12-23 05:42:20 +0000195 SUnit *PickNodeToScheduleBottomUp();
Evan Chengd38c22b2006-05-11 23:55:42 +0000196 void ListScheduleBottomUp();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000197
Andrew Trick528fad92010-12-23 05:42:20 +0000198 void ScheduleNodeTopDown(SUnit*);
199 void ListScheduleTopDown();
200
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000201
202 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000203 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000204 SUnit *CreateNewSUnit(SDNode *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000205 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000206 SUnit *NewNode = NewSUnit(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000207 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000208 if (NewNode->NodeNum >= NumSUnits)
209 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000210 return NewNode;
211 }
212
Roman Levenstein733a4d62008-03-26 11:23:38 +0000213 /// CreateClone - Creates a new SUnit from an existing one.
214 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000215 SUnit *CreateClone(SUnit *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000216 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000217 SUnit *NewNode = Clone(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000218 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000219 if (NewNode->NodeNum >= NumSUnits)
220 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000221 return NewNode;
222 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000223
Evan Chengbdd062d2010-05-20 06:13:19 +0000224 /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
225 /// need actual latency information but the hybrid scheduler does.
226 bool ForceUnitLatencies() const {
227 return !NeedLatency;
228 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000229};
230} // end anonymous namespace
231
232
233/// Schedule - Schedule the DAG using list scheduling.
234void ScheduleDAGRRList::Schedule() {
Evan Chenga77f3d32010-07-21 06:09:07 +0000235 DEBUG(dbgs()
236 << "********** List Scheduling BB#" << BB->getNumber()
Evan Cheng6c1414f2010-10-29 18:09:28 +0000237 << " '" << BB->getName() << "' **********\n");
Evan Cheng5924bf72007-09-25 01:54:36 +0000238
Andrew Trick528fad92010-12-23 05:42:20 +0000239 CurCycle = 0;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000240 MinAvailableCycle = EnableSchedCycles ? UINT_MAX : 0;
Dan Gohmanc07f6862008-09-23 18:50:48 +0000241 NumLiveRegs = 0;
Andrew Trick2085a962010-12-21 22:25:04 +0000242 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
Andrew Tricka52f3252010-12-23 04:16:14 +0000243 LiveRegGens.resize(TRI->getNumRegs(), NULL);
Evan Cheng5924bf72007-09-25 01:54:36 +0000244
Dan Gohman04543e72008-12-23 18:36:58 +0000245 // Build the scheduling graph.
Dan Gohman918ec532009-10-09 23:33:48 +0000246 BuildSchedGraph(NULL);
Evan Chengd38c22b2006-05-11 23:55:42 +0000247
Evan Chengd38c22b2006-05-11 23:55:42 +0000248 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Dan Gohman22d07b12008-11-18 02:06:40 +0000249 SUnits[su].dumpAll(this));
Dan Gohmanad2134d2008-11-25 00:52:40 +0000250 Topo.InitDAGTopologicalSorting();
Evan Chengd38c22b2006-05-11 23:55:42 +0000251
Dan Gohman46520a22008-06-21 19:18:17 +0000252 AvailableQueue->initNodes(SUnits);
Andrew Trick2085a962010-12-21 22:25:04 +0000253
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000254 HazardRec->Reset();
255
Evan Chengd38c22b2006-05-11 23:55:42 +0000256 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
257 if (isBottomUp)
258 ListScheduleBottomUp();
259 else
260 ListScheduleTopDown();
Andrew Trick2085a962010-12-21 22:25:04 +0000261
Evan Chengd38c22b2006-05-11 23:55:42 +0000262 AvailableQueue->releaseState();
Evan Chengafed73e2006-05-12 01:58:24 +0000263}
Evan Chengd38c22b2006-05-11 23:55:42 +0000264
265//===----------------------------------------------------------------------===//
266// Bottom-Up Scheduling
267//===----------------------------------------------------------------------===//
268
Evan Chengd38c22b2006-05-11 23:55:42 +0000269/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000270/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +0000271void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000272 SUnit *PredSU = PredEdge->getSUnit();
Reid Klecknercea8dab2009-09-30 20:43:07 +0000273
Evan Chengd38c22b2006-05-11 23:55:42 +0000274#ifndef NDEBUG
Reid Klecknercea8dab2009-09-30 20:43:07 +0000275 if (PredSU->NumSuccsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +0000276 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +0000277 PredSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +0000278 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +0000279 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +0000280 }
281#endif
Reid Klecknercea8dab2009-09-30 20:43:07 +0000282 --PredSU->NumSuccsLeft;
283
Evan Chengbdd062d2010-05-20 06:13:19 +0000284 if (!ForceUnitLatencies()) {
285 // Updating predecessor's height. This is now the cycle when the
286 // predecessor can be scheduled without causing a pipeline stall.
287 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
288 }
289
Dan Gohmanb9543432009-02-10 23:27:53 +0000290 // If all the node's successors are scheduled, this node is ready
291 // to be scheduled. Ignore the special EntrySU node.
292 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
Dan Gohman4370f262008-04-15 01:22:18 +0000293 PredSU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000294
295 unsigned Height = PredSU->getHeight();
296 if (Height < MinAvailableCycle)
297 MinAvailableCycle = Height;
298
299 if (isReady(SU)) {
300 AvailableQueue->push(PredSU);
301 }
302 // CapturePred and others may have left the node in the pending queue, avoid
303 // adding it twice.
304 else if (!PredSU->isPending) {
305 PredSU->isPending = true;
306 PendingQueue.push_back(PredSU);
307 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000308 }
309}
310
Andrew Trick033efdf2010-12-23 03:15:51 +0000311/// Call ReleasePred for each predecessor, then update register live def/gen.
312/// Always update LiveRegDefs for a register dependence even if the current SU
313/// also defines the register. This effectively create one large live range
314/// across a sequence of two-address node. This is important because the
315/// entire chain must be scheduled together. Example:
316///
317/// flags = (3) add
318/// flags = (2) addc flags
319/// flags = (1) addc flags
320///
321/// results in
322///
323/// LiveRegDefs[flags] = 3
Andrew Tricka52f3252010-12-23 04:16:14 +0000324/// LiveRegGens[flags] = 1
Andrew Trick033efdf2010-12-23 03:15:51 +0000325///
326/// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
327/// interference on flags.
Andrew Tricka52f3252010-12-23 04:16:14 +0000328void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000329 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000330 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000331 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000332 ReleasePred(SU, &*I);
333 if (I->isAssignedRegDep()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000334 // This is a physical register dependency and it's impossible or
Andrew Trick2085a962010-12-21 22:25:04 +0000335 // expensive to copy the register. Make sure nothing that can
Evan Cheng5924bf72007-09-25 01:54:36 +0000336 // clobber the register is scheduled between the predecessor and
337 // this node.
Andrew Tricka52f3252010-12-23 04:16:14 +0000338 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
Andrew Trick033efdf2010-12-23 03:15:51 +0000339 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
340 "interference on register dependence");
Andrew Tricka52f3252010-12-23 04:16:14 +0000341 LiveRegDefs[I->getReg()] = I->getSUnit();
342 if (!LiveRegGens[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000343 ++NumLiveRegs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000344 LiveRegGens[I->getReg()] = SU;
Evan Cheng5924bf72007-09-25 01:54:36 +0000345 }
346 }
347 }
Dan Gohmanb9543432009-02-10 23:27:53 +0000348}
349
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000350/// Check to see if any of the pending instructions are ready to issue. If
351/// so, add them to the available queue.
352void ScheduleDAGRRList::ReleasePending() {
Andrew Trick5ce945c2010-12-24 07:10:19 +0000353 if (!EnableSchedCycles) {
354 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
355 return;
356 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000357
358 // If the available queue is empty, it is safe to reset MinAvailableCycle.
359 if (AvailableQueue->empty())
360 MinAvailableCycle = UINT_MAX;
361
362 // Check to see if any of the pending instructions are ready to issue. If
363 // so, add them to the available queue.
364 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
365 unsigned ReadyCycle =
366 isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDepth();
367 if (ReadyCycle < MinAvailableCycle)
368 MinAvailableCycle = ReadyCycle;
369
370 if (PendingQueue[i]->isAvailable) {
371 if (!isReady(PendingQueue[i]))
372 continue;
373 AvailableQueue->push(PendingQueue[i]);
374 }
375 PendingQueue[i]->isPending = false;
376 PendingQueue[i] = PendingQueue.back();
377 PendingQueue.pop_back();
378 --i; --e;
379 }
380}
381
382/// Move the scheduler state forward by the specified number of Cycles.
383void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
384 if (NextCycle <= CurCycle)
385 return;
386
387 AvailableQueue->setCurCycle(NextCycle);
388 if (HazardRec->getMaxLookAhead() == 0) {
389 // Bypass lots of virtual calls in case of long latency.
390 CurCycle = NextCycle;
391 }
392 else {
393 for (; CurCycle != NextCycle; ++CurCycle) {
394 if (isBottomUp)
395 HazardRec->RecedeCycle();
396 else
397 HazardRec->AdvanceCycle();
398 }
399 }
400 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
401 // available Q to release pending nodes at least once before popping.
402 ReleasePending();
403}
404
405/// Move the scheduler state forward until the specified node's dependents are
406/// ready and can be scheduled with no resource conflicts.
407void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
408 if (!EnableSchedCycles)
409 return;
410
411 unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
412
413 // Bump CurCycle to account for latency. We assume the latency of other
414 // available instructions may be hidden by the stall (not a full pipe stall).
415 // This updates the hazard recognizer's cycle before reserving resources for
416 // this instruction.
417 AdvanceToCycle(ReadyCycle);
418
419 // Calls are scheduled in their preceding cycle, so don't conflict with
420 // hazards from instructions after the call. EmitNode will reset the
421 // scoreboard state before emitting the call.
422 if (isBottomUp && SU->isCall)
423 return;
424
425 // FIXME: For resource conflicts in very long non-pipelined stages, we
426 // should probably skip ahead here to avoid useless scoreboard checks.
427 int Stalls = 0;
428 while (true) {
429 ScheduleHazardRecognizer::HazardType HT =
430 HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
431
432 if (HT == ScheduleHazardRecognizer::NoHazard)
433 break;
434
435 ++Stalls;
436 }
437 AdvanceToCycle(CurCycle + Stalls);
438}
439
440/// Record this SUnit in the HazardRecognizer.
441/// Does not update CurCycle.
442void ScheduleDAGRRList::EmitNode(SUnit *SU) {
Andrew Trickc9405662010-12-24 06:46:50 +0000443 if (!EnableSchedCycles || HazardRec->getMaxLookAhead() == 0)
444 return;
445
446 // Check for phys reg copy.
447 if (!SU->getNode())
448 return;
449
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000450 switch (SU->getNode()->getOpcode()) {
451 default:
452 assert(SU->getNode()->isMachineOpcode() &&
453 "This target-independent node should not be scheduled.");
454 break;
455 case ISD::MERGE_VALUES:
456 case ISD::TokenFactor:
457 case ISD::CopyToReg:
458 case ISD::CopyFromReg:
459 case ISD::EH_LABEL:
460 // Noops don't affect the scoreboard state. Copies are likely to be
461 // removed.
462 return;
463 case ISD::INLINEASM:
464 // For inline asm, clear the pipeline state.
465 HazardRec->Reset();
466 return;
467 }
468 if (isBottomUp && SU->isCall) {
469 // Calls are scheduled with their preceding instructions. For bottom-up
470 // scheduling, clear the pipeline state before emitting.
471 HazardRec->Reset();
472 }
473
474 HazardRec->EmitInstruction(SU);
475
476 if (!isBottomUp && SU->isCall) {
477 HazardRec->Reset();
478 }
479}
480
Dan Gohmanb9543432009-02-10 23:27:53 +0000481/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
482/// count of its predecessors. If a predecessor pending count is zero, add it to
483/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000484void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Evan Chengbdd062d2010-05-20 06:13:19 +0000485 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000486 DEBUG(SU->dump(this));
487
Evan Chengbdd062d2010-05-20 06:13:19 +0000488#ifndef NDEBUG
489 if (CurCycle < SU->getHeight())
490 DEBUG(dbgs() << " Height [" << SU->getHeight() << "] pipeline stall!\n");
491#endif
492
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000493 // FIXME: Do not modify node height. It may interfere with
494 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
495 // node it's ready cycle can aid heuristics, and after scheduling it can
496 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000497 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000498
499 // Reserve resources for the scheduled intruction.
500 EmitNode(SU);
501
Dan Gohmanb9543432009-02-10 23:27:53 +0000502 Sequence.push_back(SU);
503
Evan Cheng28590382010-07-21 23:53:58 +0000504 AvailableQueue->ScheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000505
Andrew Trick033efdf2010-12-23 03:15:51 +0000506 // Update liveness of predecessors before successors to avoid treating a
507 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000508 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000509
510 // Release all the implicit physical register defs that are live.
511 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
512 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000513 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
514 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
515 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
516 --NumLiveRegs;
517 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000518 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000519 }
520 }
521
Evan Chengd38c22b2006-05-11 23:55:42 +0000522 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000523
524 // Conditions under which the scheduler should eagerly advance the cycle:
525 // (1) No available instructions
526 // (2) All pipelines full, so available instructions must have hazards.
527 //
528 // If SchedCycles is disabled, count each inst as one cycle.
529 if (!EnableSchedCycles ||
530 AvailableQueue->empty() || HazardRec->atIssueLimit())
531 AdvanceToCycle(CurCycle + 1);
Evan Chengd38c22b2006-05-11 23:55:42 +0000532}
533
Evan Cheng5924bf72007-09-25 01:54:36 +0000534/// CapturePred - This does the opposite of ReleasePred. Since SU is being
535/// unscheduled, incrcease the succ left count of its predecessors. Remove
536/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000537void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000538 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000539 if (PredSU->isAvailable) {
540 PredSU->isAvailable = false;
541 if (!PredSU->isPending)
542 AvailableQueue->remove(PredSU);
543 }
544
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000545 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000546 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000547}
548
549/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
550/// its predecessor states to reflect the change.
551void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000552 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000553 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000554
Evan Cheng5924bf72007-09-25 01:54:36 +0000555 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
556 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000557 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000558 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000559 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000560 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000561 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000562 --NumLiveRegs;
Dan Gohman2d170892008-12-09 22:54:47 +0000563 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000564 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000565 }
566 }
567
568 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
569 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000570 if (I->isAssignedRegDep()) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000571 // This becomes the nearest def. Note that an earlier def may still be
572 // pending if this is a two-address node.
573 LiveRegDefs[I->getReg()] = SU;
Dan Gohman2d170892008-12-09 22:54:47 +0000574 if (!LiveRegDefs[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000575 ++NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000576 }
Andrew Tricka52f3252010-12-23 04:16:14 +0000577 if (LiveRegGens[I->getReg()] == NULL ||
578 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
579 LiveRegGens[I->getReg()] = I->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000580 }
581 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000582 if (SU->getHeight() < MinAvailableCycle)
583 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000584
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000585 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000586 SU->isScheduled = false;
587 SU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000588 if (EnableSchedCycles && AvailableQueue->hasReadyFilter()) {
589 // Don't make available until backtracking is complete.
590 SU->isPending = true;
591 PendingQueue.push_back(SU);
592 }
593 else {
594 AvailableQueue->push(SU);
595 }
Evan Cheng28590382010-07-21 23:53:58 +0000596 AvailableQueue->UnscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000597}
598
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000599/// After backtracking, the hazard checker needs to be restored to a state
600/// corresponding the the current cycle.
601void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
602 HazardRec->Reset();
603
604 unsigned LookAhead = std::min((unsigned)Sequence.size(),
605 HazardRec->getMaxLookAhead());
606 if (LookAhead == 0)
607 return;
608
609 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
610 unsigned HazardCycle = (*I)->getHeight();
611 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
612 SUnit *SU = *I;
613 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
614 HazardRec->RecedeCycle();
615 }
616 EmitNode(SU);
617 }
618}
619
Evan Cheng8e136a92007-09-26 21:36:17 +0000620/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000621/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000622void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
623 SUnit *OldSU = Sequence.back();
624 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000625 Sequence.pop_back();
626 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000627 // Don't try to remove SU from AvailableQueue.
628 SU->isAvailable = false;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000629 // FIXME: use ready cycle instead of height
630 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000631 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000632 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000633 if (OldSU == BtSU)
634 break;
635 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000636 }
637
Dan Gohman60d68442009-01-29 19:49:27 +0000638 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000639
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000640 RestoreHazardCheckerBottomUp();
641
Andrew Trick5ce945c2010-12-24 07:10:19 +0000642 ReleasePending();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000643
Evan Cheng1ec79b42007-09-27 07:09:03 +0000644 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000645}
646
Evan Cheng3b245872010-02-05 01:27:11 +0000647static bool isOperandOf(const SUnit *SU, SDNode *N) {
648 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000649 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000650 if (SUNode->isOperandOf(N))
651 return true;
652 }
653 return false;
654}
655
Evan Cheng5924bf72007-09-25 01:54:36 +0000656/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
657/// successors to the newly created node.
658SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000659 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000660 if (!N)
661 return NULL;
662
Andrew Trickc9405662010-12-24 06:46:50 +0000663 if (SU->getNode()->getGluedNode())
664 return NULL;
665
Evan Cheng79e97132007-10-05 01:39:18 +0000666 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000667 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000668 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000669 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000670 if (VT == MVT::Glue)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000671 return NULL;
Owen Anderson9f944592009-08-11 20:47:22 +0000672 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000673 TryUnfold = true;
674 }
Evan Cheng79e97132007-10-05 01:39:18 +0000675 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000676 const SDValue &Op = N->getOperand(i);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000677 EVT VT = Op.getNode()->getValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000678 if (VT == MVT::Glue)
Evan Cheng79e97132007-10-05 01:39:18 +0000679 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000680 }
681
682 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000683 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000684 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000685 return NULL;
686
Evan Chengbdd062d2010-05-20 06:13:19 +0000687 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000688 assert(NewNodes.size() == 2 && "Expected a load folding node!");
689
690 N = NewNodes[1];
691 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000692 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000693 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000694 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000695 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
696 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000697 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000698
Dan Gohmane52e0892008-11-11 21:34:44 +0000699 // LoadNode may already exist. This can happen when there is another
700 // load from the same location and producing the same type of value
701 // but it has different alignment or volatileness.
702 bool isNewLoad = true;
703 SUnit *LoadSU;
704 if (LoadNode->getNodeId() != -1) {
705 LoadSU = &SUnits[LoadNode->getNodeId()];
706 isNewLoad = false;
707 } else {
708 LoadSU = CreateNewSUnit(LoadNode);
709 LoadNode->setNodeId(LoadSU->NodeNum);
Dan Gohmane52e0892008-11-11 21:34:44 +0000710 ComputeLatency(LoadSU);
711 }
712
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000713 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000714 assert(N->getNodeId() == -1 && "Node already inserted!");
715 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +0000716
Dan Gohman17059682008-07-17 19:10:17 +0000717 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Dan Gohman856c0122008-02-16 00:25:40 +0000718 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000719 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000720 NewSU->isTwoAddress = true;
721 break;
722 }
723 }
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000724 if (TID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000725 NewSU->isCommutable = true;
Evan Cheng79e97132007-10-05 01:39:18 +0000726 ComputeLatency(NewSU);
727
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000728 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +0000729 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +0000730 SmallVector<SDep, 4> ChainSuccs;
731 SmallVector<SDep, 4> LoadPreds;
732 SmallVector<SDep, 4> NodePreds;
733 SmallVector<SDep, 4> NodeSuccs;
734 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
735 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000736 if (I->isCtrl())
Dan Gohman15af5522009-03-06 02:23:01 +0000737 ChainPreds.push_back(*I);
Evan Cheng3b245872010-02-05 01:27:11 +0000738 else if (isOperandOf(I->getSUnit(), LoadNode))
Dan Gohman2d170892008-12-09 22:54:47 +0000739 LoadPreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000740 else
Dan Gohman2d170892008-12-09 22:54:47 +0000741 NodePreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000742 }
743 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
744 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000745 if (I->isCtrl())
746 ChainSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000747 else
Dan Gohman2d170892008-12-09 22:54:47 +0000748 NodeSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000749 }
750
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000751 // Now assign edges to the newly-created nodes.
Dan Gohman15af5522009-03-06 02:23:01 +0000752 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
753 const SDep &Pred = ChainPreds[i];
754 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +0000755 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +0000756 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000757 }
Evan Cheng79e97132007-10-05 01:39:18 +0000758 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000759 const SDep &Pred = LoadPreds[i];
760 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +0000761 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +0000762 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000763 }
764 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000765 const SDep &Pred = NodePreds[i];
766 RemovePred(SU, Pred);
767 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000768 }
769 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000770 SDep D = NodeSuccs[i];
771 SUnit *SuccDep = D.getSUnit();
772 D.setSUnit(SU);
773 RemovePred(SuccDep, D);
774 D.setSUnit(NewSU);
775 AddPred(SuccDep, D);
Evan Cheng79e97132007-10-05 01:39:18 +0000776 }
777 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000778 SDep D = ChainSuccs[i];
779 SUnit *SuccDep = D.getSUnit();
780 D.setSUnit(SU);
781 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000782 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +0000783 D.setSUnit(LoadSU);
784 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000785 }
Andrew Trick2085a962010-12-21 22:25:04 +0000786 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000787
788 // Add a data dependency to reflect that NewSU reads the value defined
789 // by LoadSU.
790 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
Evan Cheng79e97132007-10-05 01:39:18 +0000791
Evan Cheng91e0fc92007-12-18 08:42:10 +0000792 if (isNewLoad)
793 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000794 AvailableQueue->addNode(NewSU);
795
796 ++NumUnfolds;
797
798 if (NewSU->NumSuccsLeft == 0) {
799 NewSU->isAvailable = true;
800 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +0000801 }
802 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000803 }
804
Evan Chengbdd062d2010-05-20 06:13:19 +0000805 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000806 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000807
808 // New SUnit has the exact same predecessors.
809 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
810 I != E; ++I)
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000811 if (!I->isArtificial())
Dan Gohman2d170892008-12-09 22:54:47 +0000812 AddPred(NewSU, *I);
Evan Cheng5924bf72007-09-25 01:54:36 +0000813
814 // Only copy scheduled successors. Cut them from old node's successor
815 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000816 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +0000817 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
818 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000819 if (I->isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +0000820 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000821 SUnit *SuccSU = I->getSUnit();
822 if (SuccSU->isScheduled) {
Dan Gohman2d170892008-12-09 22:54:47 +0000823 SDep D = *I;
824 D.setSUnit(NewSU);
825 AddPred(SuccSU, D);
826 D.setSUnit(SU);
827 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +0000828 }
829 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000830 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000831 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng5924bf72007-09-25 01:54:36 +0000832
833 AvailableQueue->updateNode(SU);
834 AvailableQueue->addNode(NewSU);
835
Evan Cheng1ec79b42007-09-27 07:09:03 +0000836 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000837 return NewSU;
838}
839
Evan Chengb2c42c62009-01-12 03:19:55 +0000840/// InsertCopiesAndMoveSuccs - Insert register copies and move all
841/// scheduled successors of the given SUnit to the last copy.
842void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
843 const TargetRegisterClass *DestRC,
844 const TargetRegisterClass *SrcRC,
Evan Cheng1ec79b42007-09-27 07:09:03 +0000845 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000846 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000847 CopyFromSU->CopySrcRC = SrcRC;
848 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +0000849
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000850 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000851 CopyToSU->CopySrcRC = DestRC;
852 CopyToSU->CopyDstRC = SrcRC;
853
854 // Only copy scheduled successors. Cut them from old node's successor
855 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000856 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +0000857 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
858 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000859 if (I->isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +0000860 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000861 SUnit *SuccSU = I->getSUnit();
862 if (SuccSU->isScheduled) {
863 SDep D = *I;
864 D.setSUnit(CopyToSU);
865 AddPred(SuccSU, D);
866 DelDeps.push_back(std::make_pair(SuccSU, *I));
Evan Cheng8e136a92007-09-26 21:36:17 +0000867 }
868 }
Evan Chengb2c42c62009-01-12 03:19:55 +0000869 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000870 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng8e136a92007-09-26 21:36:17 +0000871
Dan Gohman2d170892008-12-09 22:54:47 +0000872 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
873 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
Evan Cheng8e136a92007-09-26 21:36:17 +0000874
875 AvailableQueue->updateNode(SU);
876 AvailableQueue->addNode(CopyFromSU);
877 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000878 Copies.push_back(CopyFromSU);
879 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +0000880
Evan Chengb2c42c62009-01-12 03:19:55 +0000881 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +0000882}
883
884/// getPhysicalRegisterVT - Returns the ValueType of the physical register
885/// definition of the specified node.
886/// FIXME: Move to SelectionDAG?
Owen Anderson53aa7a92009-08-10 22:56:29 +0000887static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +0000888 const TargetInstrInfo *TII) {
Dan Gohman17059682008-07-17 19:10:17 +0000889 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Evan Cheng8e136a92007-09-26 21:36:17 +0000890 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
Chris Lattnerb0d06b42008-01-07 03:13:06 +0000891 unsigned NumRes = TID.getNumDefs();
892 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000893 if (Reg == *ImpDef)
894 break;
895 ++NumRes;
896 }
897 return N->getValueType(NumRes);
898}
899
Evan Chengb8905c42009-03-04 01:41:49 +0000900/// CheckForLiveRegDef - Return true and update live register vector if the
901/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000902static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Evan Chengb8905c42009-03-04 01:41:49 +0000903 std::vector<SUnit*> &LiveRegDefs,
904 SmallSet<unsigned, 4> &RegAdded,
905 SmallVector<unsigned, 4> &LRegs,
906 const TargetRegisterInfo *TRI) {
Andrew Trick12acde112010-12-23 03:43:21 +0000907 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
908
909 // Check if Ref is live.
910 if (!LiveRegDefs[Reg]) continue;
911
912 // Allow multiple uses of the same def.
913 if (LiveRegDefs[Reg] == SU) continue;
914
915 // Add Reg to the set of interfering live regs.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000916 if (RegAdded.insert(Reg))
Evan Chengb8905c42009-03-04 01:41:49 +0000917 LRegs.push_back(Reg);
Evan Chengb8905c42009-03-04 01:41:49 +0000918 }
Evan Chengb8905c42009-03-04 01:41:49 +0000919}
920
Evan Cheng5924bf72007-09-25 01:54:36 +0000921/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
922/// scheduling of the given node to satisfy live physical register dependencies.
923/// If the specific node is the last one that's available to schedule, do
924/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000925bool ScheduleDAGRRList::
926DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000927 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +0000928 return false;
929
Evan Chenge6f92252007-09-27 18:46:06 +0000930 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +0000931 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +0000932 //
933 // If SU is the currently live definition of the same register that it uses,
934 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +0000935 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
936 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +0000937 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Evan Chengb8905c42009-03-04 01:41:49 +0000938 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
939 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +0000940 }
941
Chris Lattner11a33812010-12-23 17:24:32 +0000942 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +0000943 if (Node->getOpcode() == ISD::INLINEASM) {
944 // Inline asm can clobber physical defs.
945 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000946 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +0000947 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +0000948
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000949 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +0000950 unsigned Flags =
951 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000952 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +0000953
954 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000955 if (InlineAsm::isRegDefKind(Flags) ||
956 InlineAsm::isRegDefEarlyClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +0000957 // Check for def of register or earlyclobber register.
958 for (; NumVals; --NumVals, ++i) {
959 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
960 if (TargetRegisterInfo::isPhysicalRegister(Reg))
961 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
962 }
963 } else
964 i += NumVals;
965 }
966 continue;
967 }
968
Dan Gohman072734e2008-11-13 23:24:17 +0000969 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +0000970 continue;
Dan Gohman17059682008-07-17 19:10:17 +0000971 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
Evan Cheng5924bf72007-09-25 01:54:36 +0000972 if (!TID.ImplicitDefs)
973 continue;
Evan Chengb8905c42009-03-04 01:41:49 +0000974 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
975 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +0000976 }
Andrew Trick2085a962010-12-21 22:25:04 +0000977
Evan Cheng5924bf72007-09-25 01:54:36 +0000978 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +0000979}
980
Andrew Trick528fad92010-12-23 05:42:20 +0000981/// Return a node that can be scheduled in this cycle. Requirements:
982/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000983/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +0000984/// (3) No Interferences: may unschedule to break register interferences.
985SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
986 SmallVector<SUnit*, 4> Interferences;
987 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
988
989 SUnit *CurSU = AvailableQueue->pop();
990 while (CurSU) {
991 SmallVector<unsigned, 4> LRegs;
992 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
993 break;
994 LRegsMap.insert(std::make_pair(CurSU, LRegs));
995
996 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
997 Interferences.push_back(CurSU);
998 CurSU = AvailableQueue->pop();
999 }
1000 if (CurSU) {
1001 // Add the nodes that aren't ready back onto the available list.
1002 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1003 Interferences[i]->isPending = false;
1004 assert(Interferences[i]->isAvailable && "must still be available");
1005 AvailableQueue->push(Interferences[i]);
1006 }
1007 return CurSU;
1008 }
1009
1010 // All candidates are delayed due to live physical reg dependencies.
1011 // Try backtracking, code duplication, or inserting cross class copies
1012 // to resolve it.
1013 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1014 SUnit *TrySU = Interferences[i];
1015 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1016
1017 // Try unscheduling up to the point where it's safe to schedule
1018 // this node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001019 SUnit *BtSU = NULL;
1020 unsigned LiveCycle = UINT_MAX;
Andrew Trick528fad92010-12-23 05:42:20 +00001021 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1022 unsigned Reg = LRegs[j];
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001023 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1024 BtSU = LiveRegGens[Reg];
1025 LiveCycle = BtSU->getHeight();
1026 }
Andrew Trick528fad92010-12-23 05:42:20 +00001027 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001028 if (!WillCreateCycle(TrySU, BtSU)) {
1029 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001030
1031 // Force the current node to be scheduled before the node that
1032 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001033 if (BtSU->isAvailable) {
1034 BtSU->isAvailable = false;
1035 if (!BtSU->isPending)
1036 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001037 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001038 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
Andrew Trick528fad92010-12-23 05:42:20 +00001039 /*Reg=*/0, /*isNormalMemory=*/false,
1040 /*isMustAlias=*/false, /*isArtificial=*/true));
1041
1042 // If one or more successors has been unscheduled, then the current
1043 // node is no longer avaialable. Schedule a successor that's now
1044 // available instead.
1045 if (!TrySU->isAvailable) {
1046 CurSU = AvailableQueue->pop();
1047 }
1048 else {
1049 CurSU = TrySU;
1050 TrySU->isPending = false;
1051 Interferences.erase(Interferences.begin()+i);
1052 }
1053 break;
1054 }
1055 }
1056
1057 if (!CurSU) {
1058 // Can't backtrack. If it's too expensive to copy the value, then try
1059 // duplicate the nodes that produces these "too expensive to copy"
1060 // values to break the dependency. In case even that doesn't work,
1061 // insert cross class copies.
1062 // If it's not too expensive, i.e. cost != -1, issue copies.
1063 SUnit *TrySU = Interferences[0];
1064 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1065 assert(LRegs.size() == 1 && "Can't handle this yet!");
1066 unsigned Reg = LRegs[0];
1067 SUnit *LRDef = LiveRegDefs[Reg];
1068 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1069 const TargetRegisterClass *RC =
1070 TRI->getMinimalPhysRegClass(Reg, VT);
1071 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1072
1073 // If cross copy register class is null, then it must be possible copy
1074 // the value directly. Do not try duplicate the def.
1075 SUnit *NewDef = 0;
1076 if (DestRC)
1077 NewDef = CopyAndMoveSuccessors(LRDef);
1078 else
1079 DestRC = RC;
1080 if (!NewDef) {
1081 // Issue copies, these can be expensive cross register class copies.
1082 SmallVector<SUnit*, 2> Copies;
1083 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1084 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1085 << " to SU #" << Copies.front()->NodeNum << "\n");
1086 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1087 /*Reg=*/0, /*isNormalMemory=*/false,
1088 /*isMustAlias=*/false,
1089 /*isArtificial=*/true));
1090 NewDef = Copies.back();
1091 }
1092
1093 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1094 << " to SU #" << TrySU->NodeNum << "\n");
1095 LiveRegDefs[Reg] = NewDef;
1096 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1097 /*Reg=*/0, /*isNormalMemory=*/false,
1098 /*isMustAlias=*/false,
1099 /*isArtificial=*/true));
1100 TrySU->isAvailable = false;
1101 CurSU = NewDef;
1102 }
1103
1104 assert(CurSU && "Unable to resolve live physical register dependencies!");
1105
1106 // Add the nodes that aren't ready back onto the available list.
1107 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1108 Interferences[i]->isPending = false;
1109 // May no longer be available due to backtracking.
1110 if (Interferences[i]->isAvailable) {
1111 AvailableQueue->push(Interferences[i]);
1112 }
1113 }
1114 return CurSU;
1115}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001116
Evan Chengd38c22b2006-05-11 23:55:42 +00001117/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1118/// schedulers.
1119void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001120 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001121 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001122
Evan Chengd38c22b2006-05-11 23:55:42 +00001123 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001124 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001125 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001126 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1127 RootSU->isAvailable = true;
1128 AvailableQueue->push(RootSU);
1129 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001130
1131 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001132 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001133 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001134 while (!AvailableQueue->empty()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001135 DEBUG(dbgs() << "\n*** Examining Available\n";
1136 AvailableQueue->dump(this));
1137
Andrew Trick528fad92010-12-23 05:42:20 +00001138 // Pick the best node to schedule taking all constraints into
1139 // consideration.
1140 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001141
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001142 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001143
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001144 ScheduleNodeBottomUp(SU);
1145
1146 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1147 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1148 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1149 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1150 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001151 }
1152
Evan Chengd38c22b2006-05-11 23:55:42 +00001153 // Reverse the order if it is bottom up.
1154 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001155
Evan Chengd38c22b2006-05-11 23:55:42 +00001156#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001157 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001158#endif
1159}
1160
1161//===----------------------------------------------------------------------===//
1162// Top-Down Scheduling
1163//===----------------------------------------------------------------------===//
1164
1165/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +00001166/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +00001167void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +00001168 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001169
Evan Chengd38c22b2006-05-11 23:55:42 +00001170#ifndef NDEBUG
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001171 if (SuccSU->NumPredsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +00001172 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +00001173 SuccSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +00001174 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +00001175 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +00001176 }
1177#endif
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001178 --SuccSU->NumPredsLeft;
1179
Dan Gohmanb9543432009-02-10 23:27:53 +00001180 // If all the node's predecessors are scheduled, this node is ready
1181 // to be scheduled. Ignore the special ExitSU node.
1182 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001183 SuccSU->isAvailable = true;
1184 AvailableQueue->push(SuccSU);
1185 }
1186}
1187
Dan Gohmanb9543432009-02-10 23:27:53 +00001188void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1189 // Top down: release successors
1190 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1191 I != E; ++I) {
1192 assert(!I->isAssignedRegDep() &&
1193 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1194
1195 ReleaseSucc(SU, &*I);
1196 }
1197}
1198
Evan Chengd38c22b2006-05-11 23:55:42 +00001199/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1200/// count of its successors. If a successor pending count is zero, add it to
1201/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +00001202void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +00001203 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +00001204 DEBUG(SU->dump(this));
Evan Chengd38c22b2006-05-11 23:55:42 +00001205
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001206 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1207 SU->setDepthToAtLeast(CurCycle);
Dan Gohman92a36d72008-11-17 21:31:02 +00001208 Sequence.push_back(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001209
Dan Gohmanb9543432009-02-10 23:27:53 +00001210 ReleaseSuccessors(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001211 SU->isScheduled = true;
Dan Gohman92a36d72008-11-17 21:31:02 +00001212 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001213}
1214
Dan Gohman54a187e2007-08-20 19:28:38 +00001215/// ListScheduleTopDown - The main loop of list scheduling for top-down
1216/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +00001217void ScheduleDAGRRList::ListScheduleTopDown() {
Evan Chengbdd062d2010-05-20 06:13:19 +00001218 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001219
Dan Gohmanb9543432009-02-10 23:27:53 +00001220 // Release any successors of the special Entry node.
1221 ReleaseSuccessors(&EntrySU);
1222
Evan Chengd38c22b2006-05-11 23:55:42 +00001223 // All leaves to Available queue.
1224 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1225 // It is available if it has no predecessors.
Dan Gohman4370f262008-04-15 01:22:18 +00001226 if (SUnits[i].Preds.empty()) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001227 AvailableQueue->push(&SUnits[i]);
1228 SUnits[i].isAvailable = true;
1229 }
1230 }
Andrew Trick2085a962010-12-21 22:25:04 +00001231
Evan Chengd38c22b2006-05-11 23:55:42 +00001232 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001233 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001234 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001235 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +00001236 SUnit *CurSU = AvailableQueue->pop();
Andrew Trick2085a962010-12-21 22:25:04 +00001237
Dan Gohmanc602dd42008-11-21 00:10:42 +00001238 if (CurSU)
Andrew Trick528fad92010-12-23 05:42:20 +00001239 ScheduleNodeTopDown(CurSU);
Dan Gohman4370f262008-04-15 01:22:18 +00001240 ++CurCycle;
Evan Chengbdd062d2010-05-20 06:13:19 +00001241 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001242 }
Andrew Trick2085a962010-12-21 22:25:04 +00001243
Evan Chengd38c22b2006-05-11 23:55:42 +00001244#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001245 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001246#endif
1247}
1248
1249
Evan Chengd38c22b2006-05-11 23:55:42 +00001250//===----------------------------------------------------------------------===//
Andrew Trick9ccce772011-01-14 21:11:41 +00001251// RegReductionPriorityQueue Definition
Evan Chengd38c22b2006-05-11 23:55:42 +00001252//===----------------------------------------------------------------------===//
1253//
1254// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1255// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001256//
Evan Chengd38c22b2006-05-11 23:55:42 +00001257namespace {
Andrew Trick9ccce772011-01-14 21:11:41 +00001258class RegReductionPQBase;
Andrew Trick2085a962010-12-21 22:25:04 +00001259
Andrew Trick9ccce772011-01-14 21:11:41 +00001260struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1261 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1262};
1263
1264/// bu_ls_rr_sort - Priority function for bottom up register pressure
1265// reduction scheduler.
1266struct bu_ls_rr_sort : public queue_sort {
1267 enum {
1268 IsBottomUp = true,
1269 HasReadyFilter = false
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001270 };
1271
Andrew Trick9ccce772011-01-14 21:11:41 +00001272 RegReductionPQBase *SPQ;
1273 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1274 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001275
Andrew Trick9ccce772011-01-14 21:11:41 +00001276 bool operator()(SUnit* left, SUnit* right) const;
1277};
Andrew Trick2085a962010-12-21 22:25:04 +00001278
Andrew Trick9ccce772011-01-14 21:11:41 +00001279// td_ls_rr_sort - Priority function for top down register pressure reduction
1280// scheduler.
1281struct td_ls_rr_sort : public queue_sort {
1282 enum {
1283 IsBottomUp = false,
1284 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001285 };
1286
Andrew Trick9ccce772011-01-14 21:11:41 +00001287 RegReductionPQBase *SPQ;
1288 td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1289 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001290
Andrew Trick9ccce772011-01-14 21:11:41 +00001291 bool operator()(const SUnit* left, const SUnit* right) const;
1292};
Andrew Trick2085a962010-12-21 22:25:04 +00001293
Andrew Trick9ccce772011-01-14 21:11:41 +00001294// src_ls_rr_sort - Priority function for source order scheduler.
1295struct src_ls_rr_sort : public queue_sort {
1296 enum {
1297 IsBottomUp = true,
1298 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001299 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001300
Andrew Trick9ccce772011-01-14 21:11:41 +00001301 RegReductionPQBase *SPQ;
1302 src_ls_rr_sort(RegReductionPQBase *spq)
1303 : SPQ(spq) {}
1304 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1305 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001306
Andrew Trick9ccce772011-01-14 21:11:41 +00001307 bool operator()(SUnit* left, SUnit* right) const;
1308};
Andrew Trick2085a962010-12-21 22:25:04 +00001309
Andrew Trick9ccce772011-01-14 21:11:41 +00001310// hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1311struct hybrid_ls_rr_sort : public queue_sort {
1312 enum {
1313 IsBottomUp = true,
1314 HasReadyFilter = true
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001315 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001316
Andrew Trick9ccce772011-01-14 21:11:41 +00001317 RegReductionPQBase *SPQ;
1318 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1319 : SPQ(spq) {}
1320 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1321 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001322
Andrew Trick9ccce772011-01-14 21:11:41 +00001323 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Chenga77f3d32010-07-21 06:09:07 +00001324
Andrew Trick9ccce772011-01-14 21:11:41 +00001325 bool operator()(SUnit* left, SUnit* right) const;
1326};
1327
1328// ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1329// scheduler.
1330struct ilp_ls_rr_sort : public queue_sort {
1331 enum {
1332 IsBottomUp = true,
1333 HasReadyFilter = true
Evan Chengbdd062d2010-05-20 06:13:19 +00001334 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001335
Andrew Trick9ccce772011-01-14 21:11:41 +00001336 RegReductionPQBase *SPQ;
1337 ilp_ls_rr_sort(RegReductionPQBase *spq)
1338 : SPQ(spq) {}
1339 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1340 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001341
Andrew Trick9ccce772011-01-14 21:11:41 +00001342 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Cheng37b740c2010-07-24 00:39:05 +00001343
Andrew Trick9ccce772011-01-14 21:11:41 +00001344 bool operator()(SUnit* left, SUnit* right) const;
1345};
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001346
Andrew Trick9ccce772011-01-14 21:11:41 +00001347class RegReductionPQBase : public SchedulingPriorityQueue {
1348protected:
1349 std::vector<SUnit*> Queue;
1350 unsigned CurQueueId;
1351 bool TracksRegPressure;
1352
1353 // SUnits - The SUnits for the current graph.
1354 std::vector<SUnit> *SUnits;
1355
1356 MachineFunction &MF;
1357 const TargetInstrInfo *TII;
1358 const TargetRegisterInfo *TRI;
1359 const TargetLowering *TLI;
1360 ScheduleDAGRRList *scheduleDAG;
1361
1362 // SethiUllmanNumbers - The SethiUllman number for each node.
1363 std::vector<unsigned> SethiUllmanNumbers;
1364
1365 /// RegPressure - Tracking current reg pressure per register class.
1366 ///
1367 std::vector<unsigned> RegPressure;
1368
1369 /// RegLimit - Tracking the number of allocatable registers per register
1370 /// class.
1371 std::vector<unsigned> RegLimit;
1372
1373public:
1374 RegReductionPQBase(MachineFunction &mf,
1375 bool hasReadyFilter,
1376 bool tracksrp,
1377 const TargetInstrInfo *tii,
1378 const TargetRegisterInfo *tri,
1379 const TargetLowering *tli)
1380 : SchedulingPriorityQueue(hasReadyFilter),
1381 CurQueueId(0), TracksRegPressure(tracksrp),
1382 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1383 if (TracksRegPressure) {
1384 unsigned NumRC = TRI->getNumRegClasses();
1385 RegLimit.resize(NumRC);
1386 RegPressure.resize(NumRC);
1387 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1388 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1389 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1390 E = TRI->regclass_end(); I != E; ++I)
1391 RegLimit[(*I)->getID()] = tli->getRegPressureLimit(*I, MF);
1392 }
1393 }
1394
1395 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1396 scheduleDAG = scheduleDag;
1397 }
1398
1399 ScheduleHazardRecognizer* getHazardRec() {
1400 return scheduleDAG->getHazardRec();
1401 }
1402
1403 void initNodes(std::vector<SUnit> &sunits);
1404
1405 void addNode(const SUnit *SU);
1406
1407 void updateNode(const SUnit *SU);
1408
1409 void releaseState() {
1410 SUnits = 0;
1411 SethiUllmanNumbers.clear();
1412 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1413 }
1414
1415 unsigned getNodePriority(const SUnit *SU) const;
1416
1417 unsigned getNodeOrdering(const SUnit *SU) const {
1418 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1419 }
1420
1421 bool empty() const { return Queue.empty(); }
1422
1423 void push(SUnit *U) {
1424 assert(!U->NodeQueueId && "Node in the queue already");
1425 U->NodeQueueId = ++CurQueueId;
1426 Queue.push_back(U);
1427 }
1428
1429 void remove(SUnit *SU) {
1430 assert(!Queue.empty() && "Queue is empty!");
1431 assert(SU->NodeQueueId != 0 && "Not in queue!");
1432 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1433 SU);
1434 if (I != prior(Queue.end()))
1435 std::swap(*I, Queue.back());
1436 Queue.pop_back();
1437 SU->NodeQueueId = 0;
1438 }
1439
1440 void dumpRegPressure() const;
1441
1442 bool HighRegPressure(const SUnit *SU) const;
1443
1444 bool MayReduceRegPressure(SUnit *SU);
1445
1446 void ScheduledNode(SUnit *SU);
1447
1448 void UnscheduledNode(SUnit *SU);
1449
1450protected:
1451 bool canClobber(const SUnit *SU, const SUnit *Op);
1452 void AddPseudoTwoAddrDeps();
1453 void PrescheduleNodesWithMultipleUses();
1454 void CalculateSethiUllmanNumbers();
1455};
1456
1457template<class SF>
1458class RegReductionPriorityQueue : public RegReductionPQBase {
1459 static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1460 std::vector<SUnit *>::iterator Best = Q.begin();
1461 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1462 E = Q.end(); I != E; ++I)
1463 if (Picker(*Best, *I))
1464 Best = I;
1465 SUnit *V = *Best;
1466 if (Best != prior(Q.end()))
1467 std::swap(*Best, Q.back());
1468 Q.pop_back();
1469 return V;
1470 }
1471
1472 SF Picker;
1473
1474public:
1475 RegReductionPriorityQueue(MachineFunction &mf,
1476 bool tracksrp,
1477 const TargetInstrInfo *tii,
1478 const TargetRegisterInfo *tri,
1479 const TargetLowering *tli)
1480 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1481 Picker(this) {}
1482
1483 bool isBottomUp() const { return SF::IsBottomUp; }
1484
1485 bool isReady(SUnit *U) const {
1486 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1487 }
1488
1489 SUnit *pop() {
1490 if (Queue.empty()) return NULL;
1491
1492 SUnit *V = popFromQueue(Queue, Picker);
1493 V->NodeQueueId = 0;
1494 return V;
1495 }
1496
1497 void dump(ScheduleDAG *DAG) const {
1498 // Emulate pop() without clobbering NodeQueueIds.
1499 std::vector<SUnit*> DumpQueue = Queue;
1500 SF DumpPicker = Picker;
1501 while (!DumpQueue.empty()) {
1502 SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1503 if (isBottomUp())
1504 dbgs() << "Height " << SU->getHeight() << ": ";
1505 else
1506 dbgs() << "Depth " << SU->getDepth() << ": ";
1507 SU->dump(DAG);
1508 }
1509 }
1510};
1511
1512typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1513BURegReductionPriorityQueue;
1514
1515typedef RegReductionPriorityQueue<td_ls_rr_sort>
1516TDRegReductionPriorityQueue;
1517
1518typedef RegReductionPriorityQueue<src_ls_rr_sort>
1519SrcRegReductionPriorityQueue;
1520
1521typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1522HybridBURRPriorityQueue;
1523
1524typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1525ILPBURRPriorityQueue;
1526} // end anonymous namespace
1527
1528//===----------------------------------------------------------------------===//
1529// Static Node Priority for Register Pressure Reduction
1530//===----------------------------------------------------------------------===//
Evan Chengd38c22b2006-05-11 23:55:42 +00001531
Dan Gohman186f65d2008-11-20 03:30:37 +00001532/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1533/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001534static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001535CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001536 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1537 if (SethiUllmanNumber != 0)
1538 return SethiUllmanNumber;
1539
1540 unsigned Extra = 0;
1541 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1542 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001543 if (I->isCtrl()) continue; // ignore chain preds
1544 SUnit *PredSU = I->getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001545 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001546 if (PredSethiUllman > SethiUllmanNumber) {
1547 SethiUllmanNumber = PredSethiUllman;
1548 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001549 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001550 ++Extra;
1551 }
1552
1553 SethiUllmanNumber += Extra;
1554
1555 if (SethiUllmanNumber == 0)
1556 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001557
Evan Cheng7e4abde2008-07-02 09:23:51 +00001558 return SethiUllmanNumber;
1559}
1560
Andrew Trick9ccce772011-01-14 21:11:41 +00001561/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1562/// scheduling units.
1563void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1564 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001565
Andrew Trick9ccce772011-01-14 21:11:41 +00001566 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1567 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
Evan Chengd38c22b2006-05-11 23:55:42 +00001568}
1569
Andrew Trick9ccce772011-01-14 21:11:41 +00001570void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
1571 SUnits = &sunits;
1572 // Add pseudo dependency edges for two-address nodes.
1573 AddPseudoTwoAddrDeps();
1574 // Reroute edges to nodes with multiple uses.
1575 PrescheduleNodesWithMultipleUses();
1576 // Calculate node priorities.
1577 CalculateSethiUllmanNumbers();
1578}
1579
1580void RegReductionPQBase::addNode(const SUnit *SU) {
1581 unsigned SUSize = SethiUllmanNumbers.size();
1582 if (SUnits->size() > SUSize)
1583 SethiUllmanNumbers.resize(SUSize*2, 0);
1584 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1585}
1586
1587void RegReductionPQBase::updateNode(const SUnit *SU) {
1588 SethiUllmanNumbers[SU->NodeNum] = 0;
1589 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1590}
1591
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001592// Lower priority means schedule further down. For bottom-up scheduling, lower
1593// priority SUs are scheduled before higher priority SUs.
Andrew Trick9ccce772011-01-14 21:11:41 +00001594unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1595 assert(SU->NodeNum < SethiUllmanNumbers.size());
1596 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1597 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1598 // CopyToReg should be close to its uses to facilitate coalescing and
1599 // avoid spilling.
1600 return 0;
1601 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1602 Opc == TargetOpcode::SUBREG_TO_REG ||
1603 Opc == TargetOpcode::INSERT_SUBREG)
1604 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1605 // close to their uses to facilitate coalescing.
1606 return 0;
1607 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1608 // If SU does not have a register use, i.e. it doesn't produce a value
1609 // that would be consumed (e.g. store), then it terminates a chain of
1610 // computation. Give it a large SethiUllman number so it will be
1611 // scheduled right before its predecessors that it doesn't lengthen
1612 // their live ranges.
1613 return 0xffff;
1614 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1615 // If SU does not have a register def, schedule it close to its uses
1616 // because it does not lengthen any live ranges.
1617 return 0;
1618 return SethiUllmanNumbers[SU->NodeNum];
1619}
1620
1621//===----------------------------------------------------------------------===//
1622// Register Pressure Tracking
1623//===----------------------------------------------------------------------===//
1624
1625void RegReductionPQBase::dumpRegPressure() const {
1626 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1627 E = TRI->regclass_end(); I != E; ++I) {
1628 const TargetRegisterClass *RC = *I;
1629 unsigned Id = RC->getID();
1630 unsigned RP = RegPressure[Id];
1631 if (!RP) continue;
1632 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1633 << '\n');
1634 }
1635}
1636
1637bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1638 if (!TLI)
1639 return false;
1640
1641 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1642 I != E; ++I) {
1643 if (I->isCtrl())
1644 continue;
1645 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001646 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1647 // counts data deps. To be more precise, we could maintain a
1648 // NumDataSuccsLeft count.
1649 if (PredSU->NumSuccsLeft != PredSU->Succs.size()) {
1650 DEBUG(dbgs() << " SU(" << PredSU->NodeNum << ") live across SU("
1651 << SU->NodeNum << ")\n");
1652 continue;
1653 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001654 const SDNode *PN = PredSU->getNode();
1655 if (!PN->isMachineOpcode()) {
1656 if (PN->getOpcode() == ISD::CopyFromReg) {
1657 EVT VT = PN->getValueType(0);
1658 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1659 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1660 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1661 return true;
1662 }
1663 continue;
1664 }
1665 unsigned POpc = PN->getMachineOpcode();
1666 if (POpc == TargetOpcode::IMPLICIT_DEF)
1667 continue;
1668 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1669 EVT VT = PN->getOperand(0).getValueType();
1670 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1671 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1672 // Check if this increases register pressure of the specific register
1673 // class to the point where it would cause spills.
1674 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1675 return true;
1676 continue;
1677 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1678 POpc == TargetOpcode::SUBREG_TO_REG) {
1679 EVT VT = PN->getValueType(0);
1680 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1681 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1682 // Check if this increases register pressure of the specific register
1683 // class to the point where it would cause spills.
1684 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1685 return true;
1686 continue;
1687 }
1688 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1689 for (unsigned i = 0; i != NumDefs; ++i) {
1690 EVT VT = PN->getValueType(i);
1691 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1692 if (RegPressure[RCId] >= RegLimit[RCId])
1693 return true; // Reg pressure already high.
1694 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1695 if (!PN->hasAnyUseOfValue(i))
1696 continue;
1697 // Check if this increases register pressure of the specific register
1698 // class to the point where it would cause spills.
1699 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1700 return true;
1701 }
1702 }
1703
1704 return false;
1705}
1706
1707bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) {
1708 const SDNode *N = SU->getNode();
1709
1710 if (!N->isMachineOpcode() || !SU->NumSuccs)
1711 return false;
1712
1713 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1714 for (unsigned i = 0; i != NumDefs; ++i) {
1715 EVT VT = N->getValueType(i);
1716 if (!N->hasAnyUseOfValue(i))
1717 continue;
1718 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1719 if (RegPressure[RCId] >= RegLimit[RCId])
1720 return true;
1721 }
1722 return false;
1723}
1724
1725void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1726 if (!TracksRegPressure)
1727 return;
1728
1729 const SDNode *N = SU->getNode();
1730 if (!N->isMachineOpcode()) {
1731 if (N->getOpcode() != ISD::CopyToReg)
1732 return;
1733 } else {
1734 unsigned Opc = N->getMachineOpcode();
1735 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1736 Opc == TargetOpcode::INSERT_SUBREG ||
1737 Opc == TargetOpcode::SUBREG_TO_REG ||
1738 Opc == TargetOpcode::REG_SEQUENCE ||
1739 Opc == TargetOpcode::IMPLICIT_DEF)
1740 return;
1741 }
1742
1743 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1744 I != E; ++I) {
1745 if (I->isCtrl())
1746 continue;
1747 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001748 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1749 // counts data deps.
1750 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00001751 continue;
1752 const SDNode *PN = PredSU->getNode();
1753 if (!PN->isMachineOpcode()) {
1754 if (PN->getOpcode() == ISD::CopyFromReg) {
1755 EVT VT = PN->getValueType(0);
1756 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1757 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1758 }
1759 continue;
1760 }
1761 unsigned POpc = PN->getMachineOpcode();
1762 if (POpc == TargetOpcode::IMPLICIT_DEF)
1763 continue;
1764 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1765 EVT VT = PN->getOperand(0).getValueType();
1766 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1767 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1768 continue;
1769 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1770 POpc == TargetOpcode::SUBREG_TO_REG) {
1771 EVT VT = PN->getValueType(0);
1772 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1773 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1774 continue;
1775 }
1776 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1777 for (unsigned i = 0; i != NumDefs; ++i) {
1778 EVT VT = PN->getValueType(i);
1779 if (!PN->hasAnyUseOfValue(i))
1780 continue;
1781 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1782 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1783 }
1784 }
1785
1786 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1787 // may transfer data dependencies to CopyToReg.
1788 if (SU->NumSuccs && N->isMachineOpcode()) {
1789 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1790 for (unsigned i = 0; i != NumDefs; ++i) {
1791 EVT VT = N->getValueType(i);
1792 if (!N->hasAnyUseOfValue(i))
1793 continue;
1794 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1795 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1796 // Register pressure tracking is imprecise. This can happen.
1797 RegPressure[RCId] = 0;
1798 else
1799 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1800 }
1801 }
1802
1803 dumpRegPressure();
1804}
1805
1806void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
1807 if (!TracksRegPressure)
1808 return;
1809
1810 const SDNode *N = SU->getNode();
1811 if (!N->isMachineOpcode()) {
1812 if (N->getOpcode() != ISD::CopyToReg)
1813 return;
1814 } else {
1815 unsigned Opc = N->getMachineOpcode();
1816 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1817 Opc == TargetOpcode::INSERT_SUBREG ||
1818 Opc == TargetOpcode::SUBREG_TO_REG ||
1819 Opc == TargetOpcode::REG_SEQUENCE ||
1820 Opc == TargetOpcode::IMPLICIT_DEF)
1821 return;
1822 }
1823
1824 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1825 I != E; ++I) {
1826 if (I->isCtrl())
1827 continue;
1828 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001829 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
1830 // counts data deps.
1831 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00001832 continue;
1833 const SDNode *PN = PredSU->getNode();
1834 if (!PN->isMachineOpcode()) {
1835 if (PN->getOpcode() == ISD::CopyFromReg) {
1836 EVT VT = PN->getValueType(0);
1837 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1838 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1839 }
1840 continue;
1841 }
1842 unsigned POpc = PN->getMachineOpcode();
1843 if (POpc == TargetOpcode::IMPLICIT_DEF)
1844 continue;
1845 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1846 EVT VT = PN->getOperand(0).getValueType();
1847 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1848 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1849 continue;
1850 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1851 POpc == TargetOpcode::SUBREG_TO_REG) {
1852 EVT VT = PN->getValueType(0);
1853 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1854 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1855 continue;
1856 }
1857 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1858 for (unsigned i = 0; i != NumDefs; ++i) {
1859 EVT VT = PN->getValueType(i);
1860 if (!PN->hasAnyUseOfValue(i))
1861 continue;
1862 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1863 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1864 // Register pressure tracking is imprecise. This can happen.
1865 RegPressure[RCId] = 0;
1866 else
1867 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1868 }
1869 }
1870
1871 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1872 // may transfer data dependencies to CopyToReg.
1873 if (SU->NumSuccs && N->isMachineOpcode()) {
1874 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1875 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1876 EVT VT = N->getValueType(i);
1877 if (VT == MVT::Glue || VT == MVT::Other)
1878 continue;
1879 if (!N->hasAnyUseOfValue(i))
1880 continue;
1881 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1882 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1883 }
1884 }
1885
1886 dumpRegPressure();
1887}
1888
1889//===----------------------------------------------------------------------===//
1890// Dynamic Node Priority for Register Pressure Reduction
1891//===----------------------------------------------------------------------===//
1892
Evan Chengb9e3db62007-03-14 22:43:40 +00001893/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00001894/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00001895static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001896 unsigned MaxHeight = 0;
Evan Cheng28748552007-03-13 23:25:11 +00001897 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00001898 I != E; ++I) {
Evan Chengce3bbe52009-02-10 08:30:11 +00001899 if (I->isCtrl()) continue; // ignore chain succs
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001900 unsigned Height = I->getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00001901 // If there are bunch of CopyToRegs stacked up, they should be considered
1902 // to be at the same position.
Dan Gohman2d170892008-12-09 22:54:47 +00001903 if (I->getSUnit()->getNode() &&
1904 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001905 Height = closestSucc(I->getSUnit())+1;
1906 if (Height > MaxHeight)
1907 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00001908 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001909 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00001910}
1911
Evan Cheng61bc51e2007-12-20 02:22:36 +00001912/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00001913/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00001914static unsigned calcMaxScratches(const SUnit *SU) {
1915 unsigned Scratches = 0;
1916 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Chengb5704992009-02-12 09:52:13 +00001917 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001918 if (I->isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00001919 Scratches++;
1920 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00001921 return Scratches;
1922}
1923
Evan Cheng6c1414f2010-10-29 18:09:28 +00001924/// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
1925/// CopyToReg to a virtual register. This SU def is probably a liveout and
1926/// it has no other use. It should be scheduled closer to the terminator.
1927static bool hasOnlyLiveOutUses(const SUnit *SU) {
1928 bool RetVal = false;
1929 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1930 I != E; ++I) {
1931 if (I->isCtrl()) continue;
1932 const SUnit *SuccSU = I->getSUnit();
1933 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
1934 unsigned Reg =
1935 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
1936 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1937 RetVal = true;
1938 continue;
1939 }
1940 }
1941 return false;
1942 }
1943 return RetVal;
1944}
1945
1946/// UnitsSharePred - Return true if the two scheduling units share a common
1947/// data predecessor.
1948static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
1949 SmallSet<const SUnit*, 4> Preds;
1950 for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
1951 I != E; ++I) {
1952 if (I->isCtrl()) continue; // ignore chain preds
1953 Preds.insert(I->getSUnit());
1954 }
1955 for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
1956 I != E; ++I) {
1957 if (I->isCtrl()) continue; // ignore chain preds
1958 if (Preds.count(I->getSUnit()))
1959 return true;
1960 }
1961 return false;
1962}
1963
Andrew Trick9ccce772011-01-14 21:11:41 +00001964// Check for either a dependence (latency) or resource (hazard) stall.
1965//
1966// Note: The ScheduleHazardRecognizer interface requires a non-const SU.
1967static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
1968 if ((int)SPQ->getCurCycle() < Height) return true;
1969 if (SPQ->getHazardRec()->getHazardType(SU, 0)
1970 != ScheduleHazardRecognizer::NoHazard)
1971 return true;
1972 return false;
1973}
1974
1975// Return -1 if left has higher priority, 1 if right has higher priority.
1976// Return 0 if latency-based priority is equivalent.
1977static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
1978 RegReductionPQBase *SPQ) {
1979 // If the two nodes share an operand and one of them has a single
1980 // use that is a live out copy, favor the one that is live out. Otherwise
1981 // it will be difficult to eliminate the copy if the instruction is a
1982 // loop induction variable update. e.g.
1983 // BB:
1984 // sub r1, r3, #1
1985 // str r0, [r2, r3]
1986 // mov r3, r1
1987 // cmp
1988 // bne BB
1989 bool SharePred = UnitsSharePred(left, right);
1990 // FIXME: Only adjust if BB is a loop back edge.
1991 // FIXME: What's the cost of a copy?
1992 int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
1993 int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
1994 int LHeight = (int)left->getHeight() - LBonus;
1995 int RHeight = (int)right->getHeight() - RBonus;
1996
1997 bool LStall = (!checkPref || left->SchedulingPref == Sched::Latency) &&
1998 BUHasStall(left, LHeight, SPQ);
1999 bool RStall = (!checkPref || right->SchedulingPref == Sched::Latency) &&
2000 BUHasStall(right, RHeight, SPQ);
2001
2002 // If scheduling one of the node will cause a pipeline stall, delay it.
2003 // If scheduling either one of the node will cause a pipeline stall, sort
2004 // them according to their height.
2005 if (LStall) {
2006 if (!RStall)
2007 return 1;
2008 if (LHeight != RHeight)
2009 return LHeight > RHeight ? 1 : -1;
2010 } else if (RStall)
2011 return -1;
2012
2013 // If either node is scheduling for latency, sort them by depth
2014 // and latency.
2015 if (!checkPref || (left->SchedulingPref == Sched::Latency ||
2016 right->SchedulingPref == Sched::Latency)) {
2017 int LDepth = (int)left->getDepth();
2018 int RDepth = (int)right->getDepth();
2019
Andrew Trick9ccce772011-01-14 21:11:41 +00002020 if (EnableSchedCycles) {
2021 if (LDepth != RDepth)
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002022 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2023 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2024 << ") depth " << RDepth << ")\n");
Andrew Trick9ccce772011-01-14 21:11:41 +00002025 return LDepth < RDepth ? 1 : -1;
2026 }
2027 else {
2028 if (LHeight != RHeight)
2029 return LHeight > RHeight ? 1 : -1;
2030 }
2031 if (left->Latency != right->Latency)
2032 return left->Latency > right->Latency ? 1 : -1;
2033 }
2034 return 0;
2035}
2036
2037static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
Evan Cheng6730f032007-01-08 23:55:53 +00002038 unsigned LPriority = SPQ->getNodePriority(left);
2039 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng73bdf042008-03-01 00:39:47 +00002040 if (LPriority != RPriority)
2041 return LPriority > RPriority;
2042
2043 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2044 // e.g.
2045 // t1 = op t2, c1
2046 // t3 = op t4, c2
2047 //
2048 // and the following instructions are both ready.
2049 // t2 = op c3
2050 // t4 = op c4
2051 //
2052 // Then schedule t2 = op first.
2053 // i.e.
2054 // t4 = op c4
2055 // t2 = op c3
2056 // t1 = op t2, c1
2057 // t3 = op t4, c2
2058 //
2059 // This creates more short live intervals.
2060 unsigned LDist = closestSucc(left);
2061 unsigned RDist = closestSucc(right);
2062 if (LDist != RDist)
2063 return LDist < RDist;
2064
Evan Cheng3a14efa2009-02-12 08:59:45 +00002065 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00002066 unsigned LScratch = calcMaxScratches(left);
2067 unsigned RScratch = calcMaxScratches(right);
2068 if (LScratch != RScratch)
2069 return LScratch > RScratch;
2070
Andrew Trick9ccce772011-01-14 21:11:41 +00002071 if (EnableSchedCycles) {
2072 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2073 if (result != 0)
2074 return result > 0;
2075 }
2076 else {
2077 if (left->getHeight() != right->getHeight())
2078 return left->getHeight() > right->getHeight();
Andrew Trick2085a962010-12-21 22:25:04 +00002079
Andrew Trick9ccce772011-01-14 21:11:41 +00002080 if (left->getDepth() != right->getDepth())
2081 return left->getDepth() < right->getDepth();
2082 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002083
Andrew Trick2085a962010-12-21 22:25:04 +00002084 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002085 "NodeQueueId cannot be zero");
2086 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002087}
2088
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002089// Bottom up
Andrew Trick9ccce772011-01-14 21:11:41 +00002090bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002091 return BURRSort(left, right, SPQ);
2092}
2093
2094// Source order, otherwise bottom up.
Andrew Trick9ccce772011-01-14 21:11:41 +00002095bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002096 unsigned LOrder = SPQ->getNodeOrdering(left);
2097 unsigned ROrder = SPQ->getNodeOrdering(right);
2098
2099 // Prefer an ordering where the lower the non-zero order number, the higher
2100 // the preference.
2101 if ((LOrder || ROrder) && LOrder != ROrder)
2102 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2103
2104 return BURRSort(left, right, SPQ);
2105}
2106
Andrew Trick9ccce772011-01-14 21:11:41 +00002107// If the time between now and when the instruction will be ready can cover
2108// the spill code, then avoid adding it to the ready queue. This gives long
2109// stalls highest priority and allows hoisting across calls. It should also
2110// speed up processing the available queue.
2111bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2112 static const unsigned ReadyDelay = 3;
2113
2114 if (SPQ->MayReduceRegPressure(SU)) return true;
2115
2116 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2117
2118 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2119 != ScheduleHazardRecognizer::NoHazard)
2120 return false;
2121
2122 return true;
2123}
2124
2125// Return true if right should be scheduled with higher priority than left.
2126bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002127 if (left->isCall || right->isCall)
2128 // No way to compute latency of calls.
2129 return BURRSort(left, right, SPQ);
2130
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002131 bool LHigh = SPQ->HighRegPressure(left);
2132 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002133 // Avoid causing spills. If register pressure is high, schedule for
2134 // register pressure reduction.
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002135 if (LHigh && !RHigh) {
2136 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2137 << right->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002138 return true;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002139 }
2140 else if (!LHigh && RHigh) {
2141 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2142 << left->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002143 return false;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002144 }
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002145 else if (!LHigh && !RHigh) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002146 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2147 if (result != 0)
2148 return result > 0;
Evan Chengcc2efe12010-05-28 23:26:21 +00002149 }
Evan Chengbdd062d2010-05-20 06:13:19 +00002150 return BURRSort(left, right, SPQ);
2151}
2152
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002153// Schedule as many instructions in each cycle as possible. So don't make an
2154// instruction available unless it is ready in the current cycle.
2155bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00002156 if (SU->getHeight() > CurCycle) return false;
2157
2158 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2159 != ScheduleHazardRecognizer::NoHazard)
2160 return false;
2161
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002162 return SU->getHeight() <= CurCycle;
2163}
2164
Andrew Trick9ccce772011-01-14 21:11:41 +00002165bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002166 if (left->isCall || right->isCall)
2167 // No way to compute latency of calls.
2168 return BURRSort(left, right, SPQ);
2169
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002170 bool LHigh = SPQ->HighRegPressure(left);
2171 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002172 // Avoid causing spills. If register pressure is high, schedule for
2173 // register pressure reduction.
2174 if (LHigh && !RHigh)
2175 return true;
2176 else if (!LHigh && RHigh)
2177 return false;
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002178 else if (!LHigh && !RHigh) {
Evan Cheng8ae3eca2010-07-25 18:59:43 +00002179 // Low register pressure situation, schedule to maximize instruction level
2180 // parallelism.
Evan Cheng37b740c2010-07-24 00:39:05 +00002181 if (left->NumPreds > right->NumPreds)
2182 return false;
2183 else if (left->NumPreds < right->NumPreds)
2184 return false;
2185 }
2186
2187 return BURRSort(left, right, SPQ);
2188}
2189
Andrew Trick9ccce772011-01-14 21:11:41 +00002190//===----------------------------------------------------------------------===//
2191// Preschedule for Register Pressure
2192//===----------------------------------------------------------------------===//
2193
2194bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002195 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002196 unsigned Opc = SU->getNode()->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002197 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002198 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002199 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002200 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002201 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002202 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002203 if (DU->getNodeId() != -1 &&
2204 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002205 return true;
2206 }
2207 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002208 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002209 return false;
2210}
2211
Evan Chengf9891412007-12-20 09:25:31 +00002212/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002213/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002214static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002215 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002216 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002217 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002218 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2219 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002220 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002221 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002222 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002223 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002224 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002225 const unsigned *SUImpDefs =
2226 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2227 if (!SUImpDefs)
2228 return false;
2229 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002230 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002231 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002232 continue;
2233 if (!N->hasAnyUseOfValue(i))
2234 continue;
2235 unsigned Reg = ImpDefs[i - NumDefs];
2236 for (;*SUImpDefs; ++SUImpDefs) {
2237 unsigned SUReg = *SUImpDefs;
2238 if (TRI->regsOverlap(Reg, SUReg))
2239 return true;
2240 }
Evan Chengf9891412007-12-20 09:25:31 +00002241 }
2242 }
2243 return false;
2244}
2245
Dan Gohman9a658d72009-03-24 00:49:12 +00002246/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2247/// are not handled well by the general register pressure reduction
2248/// heuristics. When presented with code like this:
2249///
2250/// N
2251/// / |
2252/// / |
2253/// U store
2254/// |
2255/// ...
2256///
2257/// the heuristics tend to push the store up, but since the
2258/// operand of the store has another use (U), this would increase
2259/// the length of that other use (the U->N edge).
2260///
2261/// This function transforms code like the above to route U's
2262/// dependence through the store when possible, like this:
2263///
2264/// N
2265/// ||
2266/// ||
2267/// store
2268/// |
2269/// U
2270/// |
2271/// ...
2272///
2273/// This results in the store being scheduled immediately
2274/// after N, which shortens the U->N live range, reducing
2275/// register pressure.
2276///
Andrew Trick9ccce772011-01-14 21:11:41 +00002277void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
Dan Gohman9a658d72009-03-24 00:49:12 +00002278 // Visit all the nodes in topological order, working top-down.
2279 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2280 SUnit *SU = &(*SUnits)[i];
2281 // For now, only look at nodes with no data successors, such as stores.
2282 // These are especially important, due to the heuristics in
2283 // getNodePriority for nodes with no data successors.
2284 if (SU->NumSuccs != 0)
2285 continue;
2286 // For now, only look at nodes with exactly one data predecessor.
2287 if (SU->NumPreds != 1)
2288 continue;
2289 // Avoid prescheduling copies to virtual registers, which don't behave
2290 // like other nodes from the perspective of scheduling heuristics.
2291 if (SDNode *N = SU->getNode())
2292 if (N->getOpcode() == ISD::CopyToReg &&
2293 TargetRegisterInfo::isVirtualRegister
2294 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2295 continue;
2296
2297 // Locate the single data predecessor.
2298 SUnit *PredSU = 0;
2299 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2300 EE = SU->Preds.end(); II != EE; ++II)
2301 if (!II->isCtrl()) {
2302 PredSU = II->getSUnit();
2303 break;
2304 }
2305 assert(PredSU);
2306
2307 // Don't rewrite edges that carry physregs, because that requires additional
2308 // support infrastructure.
2309 if (PredSU->hasPhysRegDefs)
2310 continue;
2311 // Short-circuit the case where SU is PredSU's only data successor.
2312 if (PredSU->NumSuccs == 1)
2313 continue;
2314 // Avoid prescheduling to copies from virtual registers, which don't behave
2315 // like other nodes from the perspective of scheduling // heuristics.
2316 if (SDNode *N = SU->getNode())
2317 if (N->getOpcode() == ISD::CopyFromReg &&
2318 TargetRegisterInfo::isVirtualRegister
2319 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2320 continue;
2321
2322 // Perform checks on the successors of PredSU.
2323 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2324 EE = PredSU->Succs.end(); II != EE; ++II) {
2325 SUnit *PredSuccSU = II->getSUnit();
2326 if (PredSuccSU == SU) continue;
2327 // If PredSU has another successor with no data successors, for
2328 // now don't attempt to choose either over the other.
2329 if (PredSuccSU->NumSuccs == 0)
2330 goto outer_loop_continue;
2331 // Don't break physical register dependencies.
2332 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2333 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2334 goto outer_loop_continue;
2335 // Don't introduce graph cycles.
2336 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2337 goto outer_loop_continue;
2338 }
2339
2340 // Ok, the transformation is safe and the heuristics suggest it is
2341 // profitable. Update the graph.
Evan Chengbdd062d2010-05-20 06:13:19 +00002342 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2343 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002344 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002345 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2346 SDep Edge = PredSU->Succs[i];
2347 assert(!Edge.isAssignedRegDep());
2348 SUnit *SuccSU = Edge.getSUnit();
2349 if (SuccSU != SU) {
2350 Edge.setSUnit(PredSU);
2351 scheduleDAG->RemovePred(SuccSU, Edge);
2352 scheduleDAG->AddPred(SU, Edge);
2353 Edge.setSUnit(SU);
2354 scheduleDAG->AddPred(SuccSU, Edge);
2355 --i;
2356 }
2357 }
2358 outer_loop_continue:;
2359 }
2360}
2361
Evan Chengd38c22b2006-05-11 23:55:42 +00002362/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2363/// it as a def&use operand. Add a pseudo control edge from it to the other
2364/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002365/// first (lower in the schedule). If both nodes are two-address, favor the
2366/// one that has a CopyToReg use (more likely to be a loop induction update).
2367/// If both are two-address, but one is commutable while the other is not
2368/// commutable, favor the one that's not commutable.
Andrew Trick9ccce772011-01-14 21:11:41 +00002369void RegReductionPQBase::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002370 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
Dan Gohmane955c482008-08-05 14:45:15 +00002371 SUnit *SU = &(*SUnits)[i];
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002372 if (!SU->isTwoAddress)
2373 continue;
2374
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002375 SDNode *Node = SU->getNode();
Chris Lattner11a33812010-12-23 17:24:32 +00002376 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002377 continue;
2378
Evan Cheng6c1414f2010-10-29 18:09:28 +00002379 bool isLiveOut = hasOnlyLiveOutUses(SU);
Dan Gohman17059682008-07-17 19:10:17 +00002380 unsigned Opc = Node->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002381 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002382 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002383 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002384 for (unsigned j = 0; j != NumOps; ++j) {
Dan Gohman82016c22008-11-19 02:00:32 +00002385 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2386 continue;
2387 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2388 if (DU->getNodeId() == -1)
2389 continue;
2390 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2391 if (!DUSU) continue;
2392 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2393 E = DUSU->Succs.end(); I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002394 if (I->isCtrl()) continue;
2395 SUnit *SuccSU = I->getSUnit();
Dan Gohman82016c22008-11-19 02:00:32 +00002396 if (SuccSU == SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002397 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002398 // Be conservative. Ignore if nodes aren't at roughly the same
2399 // depth and height.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002400 if (SuccSU->getHeight() < SU->getHeight() &&
2401 (SU->getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002402 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002403 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2404 // constrains whatever is using the copy, instead of the copy
2405 // itself. In the case that the copy is coalesced, this
2406 // preserves the intent of the pseudo two-address heurietics.
2407 while (SuccSU->Succs.size() == 1 &&
2408 SuccSU->getNode()->isMachineOpcode() &&
2409 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002410 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002411 SuccSU = SuccSU->Succs.front().getSUnit();
2412 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002413 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2414 continue;
2415 // Don't constrain nodes with physical register defs if the
2416 // predecessor can clobber them.
Dan Gohmanf3746cb2009-03-24 00:50:07 +00002417 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
Dan Gohman82016c22008-11-19 02:00:32 +00002418 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002419 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002420 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002421 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2422 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002423 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002424 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2425 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2426 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002427 continue;
2428 if ((!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002429 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Dan Gohman82016c22008-11-19 02:00:32 +00002430 (!SU->isCommutable && SuccSU->isCommutable)) &&
2431 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002432 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002433 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
Dan Gohman79c35162009-01-06 01:19:04 +00002434 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
Dan Gohmanbf8e5202009-01-06 01:28:56 +00002435 /*Reg=*/0, /*isNormalMemory=*/false,
2436 /*isMustAlias=*/false,
Dan Gohman2d170892008-12-09 22:54:47 +00002437 /*isArtificial=*/true));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002438 }
2439 }
2440 }
2441 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002442}
2443
Roman Levenstein30d09512008-03-27 09:44:37 +00002444/// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
Roman Levensteinbc674502008-03-27 09:14:57 +00002445/// predecessors of the successors of the SUnit SU. Stop when the provided
2446/// limit is exceeded.
Andrew Trick2085a962010-12-21 22:25:04 +00002447static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
Roman Levensteinbc674502008-03-27 09:14:57 +00002448 unsigned Limit) {
2449 unsigned Sum = 0;
2450 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2451 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002452 const SUnit *SuccSU = I->getSUnit();
Roman Levensteinbc674502008-03-27 09:14:57 +00002453 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2454 EE = SuccSU->Preds.end(); II != EE; ++II) {
Dan Gohman2d170892008-12-09 22:54:47 +00002455 SUnit *PredSU = II->getSUnit();
Evan Cheng16d72072008-03-29 18:34:22 +00002456 if (!PredSU->isScheduled)
2457 if (++Sum > Limit)
2458 return Sum;
Roman Levensteinbc674502008-03-27 09:14:57 +00002459 }
2460 }
2461 return Sum;
2462}
2463
Evan Chengd38c22b2006-05-11 23:55:42 +00002464
2465// Top down
2466bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Evan Cheng6730f032007-01-08 23:55:53 +00002467 unsigned LPriority = SPQ->getNodePriority(left);
2468 unsigned RPriority = SPQ->getNodePriority(right);
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002469 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2470 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00002471 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2472 bool RIsFloater = RIsTarget && right->NumPreds == 0;
Roman Levensteinbc674502008-03-27 09:14:57 +00002473 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2474 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00002475
2476 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2477 return false;
2478 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2479 return true;
2480
Evan Chengd38c22b2006-05-11 23:55:42 +00002481 if (LIsFloater)
2482 LBonus -= 2;
2483 if (RIsFloater)
2484 RBonus -= 2;
2485 if (left->NumSuccs == 1)
2486 LBonus += 2;
2487 if (right->NumSuccs == 1)
2488 RBonus += 2;
2489
Evan Cheng73bdf042008-03-01 00:39:47 +00002490 if (LPriority+LBonus != RPriority+RBonus)
2491 return LPriority+LBonus < RPriority+RBonus;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00002492
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002493 if (left->getDepth() != right->getDepth())
2494 return left->getDepth() < right->getDepth();
Evan Cheng73bdf042008-03-01 00:39:47 +00002495
2496 if (left->NumSuccsLeft != right->NumSuccsLeft)
2497 return left->NumSuccsLeft > right->NumSuccsLeft;
2498
Andrew Trick2085a962010-12-21 22:25:04 +00002499 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002500 "NodeQueueId cannot be zero");
2501 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002502}
2503
Evan Chengd38c22b2006-05-11 23:55:42 +00002504//===----------------------------------------------------------------------===//
2505// Public Constructor Functions
2506//===----------------------------------------------------------------------===//
2507
Dan Gohmandfaf6462009-02-11 04:27:20 +00002508llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002509llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2510 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002511 const TargetMachine &TM = IS->TM;
2512 const TargetInstrInfo *TII = TM.getInstrInfo();
2513 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002514
Evan Chenga77f3d32010-07-21 06:09:07 +00002515 BURegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002516 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002517 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002518 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002519 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002520}
2521
Dan Gohmandfaf6462009-02-11 04:27:20 +00002522llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002523llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2524 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002525 const TargetMachine &TM = IS->TM;
2526 const TargetInstrInfo *TII = TM.getInstrInfo();
2527 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002528
Evan Chenga77f3d32010-07-21 06:09:07 +00002529 TDRegReductionPriorityQueue *PQ =
2530 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002531 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Dan Gohman3f656df2008-11-20 02:45:51 +00002532 PQ->setScheduleDAG(SD);
2533 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002534}
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002535
2536llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002537llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2538 CodeGenOpt::Level OptLevel) {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002539 const TargetMachine &TM = IS->TM;
2540 const TargetInstrInfo *TII = TM.getInstrInfo();
2541 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002542
Evan Chenga77f3d32010-07-21 06:09:07 +00002543 SrcRegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002544 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002545 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002546 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002547 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002548}
2549
2550llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002551llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2552 CodeGenOpt::Level OptLevel) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002553 const TargetMachine &TM = IS->TM;
2554 const TargetInstrInfo *TII = TM.getInstrInfo();
2555 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Evan Chenga77f3d32010-07-21 06:09:07 +00002556 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002557
Evan Chenga77f3d32010-07-21 06:09:07 +00002558 HybridBURRPriorityQueue *PQ =
Evan Chengdf907f42010-07-23 22:39:59 +00002559 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002560
2561 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002562 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002563 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002564}
Evan Cheng37b740c2010-07-24 00:39:05 +00002565
2566llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002567llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2568 CodeGenOpt::Level OptLevel) {
Evan Cheng37b740c2010-07-24 00:39:05 +00002569 const TargetMachine &TM = IS->TM;
2570 const TargetInstrInfo *TII = TM.getInstrInfo();
2571 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2572 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002573
Evan Cheng37b740c2010-07-24 00:39:05 +00002574 ILPBURRPriorityQueue *PQ =
2575 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002576 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00002577 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002578 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00002579}