blob: c93ef4dd46721d4aef8d07be83f2e6115e78981d [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
Roman Levenstein733a4d62008-03-26 11:23:38 +0000140 /// IsReachable - Checks if SU is reachable from TargetSU.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000141 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
142 return Topo.IsReachable(SU, TargetSU);
143 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000144
Dan Gohman60d68442009-01-29 19:49:27 +0000145 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000146 /// create a cycle.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000147 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
148 return Topo.WillCreateCycle(SU, TargetSU);
149 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000150
Dan Gohman2d170892008-12-09 22:54:47 +0000151 /// AddPred - adds a predecessor edge to SUnit SU.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000152 /// This returns true if this is a new predecessor.
153 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000154 void AddPred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000155 Topo.AddPred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000156 SU->addPred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000157 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000158
Dan Gohman2d170892008-12-09 22:54:47 +0000159 /// RemovePred - removes a predecessor edge from SUnit SU.
160 /// This returns true if an edge was removed.
161 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000162 void RemovePred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000163 Topo.RemovePred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000164 SU->removePred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000165 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000166
Evan Chengd38c22b2006-05-11 23:55:42 +0000167private:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000168 bool isReady(SUnit *SU) {
169 return !EnableSchedCycles || !AvailableQueue->hasReadyFilter() ||
170 AvailableQueue->isReady(SU);
171 }
172
Dan Gohman60d68442009-01-29 19:49:27 +0000173 void ReleasePred(SUnit *SU, const SDep *PredEdge);
Andrew Tricka52f3252010-12-23 04:16:14 +0000174 void ReleasePredecessors(SUnit *SU);
Dan Gohman60d68442009-01-29 19:49:27 +0000175 void ReleaseSucc(SUnit *SU, const SDep *SuccEdge);
Dan Gohmanb9543432009-02-10 23:27:53 +0000176 void ReleaseSuccessors(SUnit *SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000177 void ReleasePending();
178 void AdvanceToCycle(unsigned NextCycle);
179 void AdvancePastStalls(SUnit *SU);
180 void EmitNode(SUnit *SU);
Andrew Trick528fad92010-12-23 05:42:20 +0000181 void ScheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000182 void CapturePred(SDep *PredEdge);
Evan Cheng8e136a92007-09-26 21:36:17 +0000183 void UnscheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000184 void RestoreHazardCheckerBottomUp();
185 void BacktrackBottomUp(SUnit*, SUnit*);
Evan Cheng8e136a92007-09-26 21:36:17 +0000186 SUnit *CopyAndMoveSuccessors(SUnit*);
Evan Chengb2c42c62009-01-12 03:19:55 +0000187 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
188 const TargetRegisterClass*,
189 const TargetRegisterClass*,
190 SmallVector<SUnit*, 2>&);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000191 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000192
Andrew Trick528fad92010-12-23 05:42:20 +0000193 SUnit *PickNodeToScheduleBottomUp();
Evan Chengd38c22b2006-05-11 23:55:42 +0000194 void ListScheduleBottomUp();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000195
Andrew Trick528fad92010-12-23 05:42:20 +0000196 void ScheduleNodeTopDown(SUnit*);
197 void ListScheduleTopDown();
198
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000199
200 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000201 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000202 SUnit *CreateNewSUnit(SDNode *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000203 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000204 SUnit *NewNode = NewSUnit(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000205 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000206 if (NewNode->NodeNum >= NumSUnits)
207 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000208 return NewNode;
209 }
210
Roman Levenstein733a4d62008-03-26 11:23:38 +0000211 /// CreateClone - Creates a new SUnit from an existing one.
212 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000213 SUnit *CreateClone(SUnit *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000214 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000215 SUnit *NewNode = Clone(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000216 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000217 if (NewNode->NodeNum >= NumSUnits)
218 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000219 return NewNode;
220 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000221
Evan Chengbdd062d2010-05-20 06:13:19 +0000222 /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
223 /// need actual latency information but the hybrid scheduler does.
224 bool ForceUnitLatencies() const {
225 return !NeedLatency;
226 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000227};
228} // end anonymous namespace
229
230
231/// Schedule - Schedule the DAG using list scheduling.
232void ScheduleDAGRRList::Schedule() {
Evan Chenga77f3d32010-07-21 06:09:07 +0000233 DEBUG(dbgs()
234 << "********** List Scheduling BB#" << BB->getNumber()
Evan Cheng6c1414f2010-10-29 18:09:28 +0000235 << " '" << BB->getName() << "' **********\n");
Evan Cheng5924bf72007-09-25 01:54:36 +0000236
Andrew Trick528fad92010-12-23 05:42:20 +0000237 CurCycle = 0;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000238 MinAvailableCycle = EnableSchedCycles ? UINT_MAX : 0;
Dan Gohmanc07f6862008-09-23 18:50:48 +0000239 NumLiveRegs = 0;
Andrew Trick2085a962010-12-21 22:25:04 +0000240 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
Andrew Tricka52f3252010-12-23 04:16:14 +0000241 LiveRegGens.resize(TRI->getNumRegs(), NULL);
Evan Cheng5924bf72007-09-25 01:54:36 +0000242
Dan Gohman04543e72008-12-23 18:36:58 +0000243 // Build the scheduling graph.
Dan Gohman918ec532009-10-09 23:33:48 +0000244 BuildSchedGraph(NULL);
Evan Chengd38c22b2006-05-11 23:55:42 +0000245
Evan Chengd38c22b2006-05-11 23:55:42 +0000246 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Dan Gohman22d07b12008-11-18 02:06:40 +0000247 SUnits[su].dumpAll(this));
Dan Gohmanad2134d2008-11-25 00:52:40 +0000248 Topo.InitDAGTopologicalSorting();
Evan Chengd38c22b2006-05-11 23:55:42 +0000249
Dan Gohman46520a22008-06-21 19:18:17 +0000250 AvailableQueue->initNodes(SUnits);
Andrew Trick2085a962010-12-21 22:25:04 +0000251
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000252 HazardRec->Reset();
253
Evan Chengd38c22b2006-05-11 23:55:42 +0000254 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
255 if (isBottomUp)
256 ListScheduleBottomUp();
257 else
258 ListScheduleTopDown();
Andrew Trick2085a962010-12-21 22:25:04 +0000259
Evan Chengd38c22b2006-05-11 23:55:42 +0000260 AvailableQueue->releaseState();
Evan Chengafed73e2006-05-12 01:58:24 +0000261}
Evan Chengd38c22b2006-05-11 23:55:42 +0000262
263//===----------------------------------------------------------------------===//
264// Bottom-Up Scheduling
265//===----------------------------------------------------------------------===//
266
Evan Chengd38c22b2006-05-11 23:55:42 +0000267/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000268/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +0000269void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000270 SUnit *PredSU = PredEdge->getSUnit();
Reid Klecknercea8dab2009-09-30 20:43:07 +0000271
Evan Chengd38c22b2006-05-11 23:55:42 +0000272#ifndef NDEBUG
Reid Klecknercea8dab2009-09-30 20:43:07 +0000273 if (PredSU->NumSuccsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +0000274 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +0000275 PredSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +0000276 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +0000277 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +0000278 }
279#endif
Reid Klecknercea8dab2009-09-30 20:43:07 +0000280 --PredSU->NumSuccsLeft;
281
Evan Chengbdd062d2010-05-20 06:13:19 +0000282 if (!ForceUnitLatencies()) {
283 // Updating predecessor's height. This is now the cycle when the
284 // predecessor can be scheduled without causing a pipeline stall.
285 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
286 }
287
Dan Gohmanb9543432009-02-10 23:27:53 +0000288 // If all the node's successors are scheduled, this node is ready
289 // to be scheduled. Ignore the special EntrySU node.
290 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
Dan Gohman4370f262008-04-15 01:22:18 +0000291 PredSU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000292
293 unsigned Height = PredSU->getHeight();
294 if (Height < MinAvailableCycle)
295 MinAvailableCycle = Height;
296
297 if (isReady(SU)) {
298 AvailableQueue->push(PredSU);
299 }
300 // CapturePred and others may have left the node in the pending queue, avoid
301 // adding it twice.
302 else if (!PredSU->isPending) {
303 PredSU->isPending = true;
304 PendingQueue.push_back(PredSU);
305 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000306 }
307}
308
Andrew Trick033efdf2010-12-23 03:15:51 +0000309/// Call ReleasePred for each predecessor, then update register live def/gen.
310/// Always update LiveRegDefs for a register dependence even if the current SU
311/// also defines the register. This effectively create one large live range
312/// across a sequence of two-address node. This is important because the
313/// entire chain must be scheduled together. Example:
314///
315/// flags = (3) add
316/// flags = (2) addc flags
317/// flags = (1) addc flags
318///
319/// results in
320///
321/// LiveRegDefs[flags] = 3
Andrew Tricka52f3252010-12-23 04:16:14 +0000322/// LiveRegGens[flags] = 1
Andrew Trick033efdf2010-12-23 03:15:51 +0000323///
324/// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
325/// interference on flags.
Andrew Tricka52f3252010-12-23 04:16:14 +0000326void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000327 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000328 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000329 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000330 ReleasePred(SU, &*I);
331 if (I->isAssignedRegDep()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000332 // This is a physical register dependency and it's impossible or
Andrew Trick2085a962010-12-21 22:25:04 +0000333 // expensive to copy the register. Make sure nothing that can
Evan Cheng5924bf72007-09-25 01:54:36 +0000334 // clobber the register is scheduled between the predecessor and
335 // this node.
Andrew Tricka52f3252010-12-23 04:16:14 +0000336 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
Andrew Trick033efdf2010-12-23 03:15:51 +0000337 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
338 "interference on register dependence");
Andrew Tricka52f3252010-12-23 04:16:14 +0000339 LiveRegDefs[I->getReg()] = I->getSUnit();
340 if (!LiveRegGens[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000341 ++NumLiveRegs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000342 LiveRegGens[I->getReg()] = SU;
Evan Cheng5924bf72007-09-25 01:54:36 +0000343 }
344 }
345 }
Dan Gohmanb9543432009-02-10 23:27:53 +0000346}
347
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000348/// Check to see if any of the pending instructions are ready to issue. If
349/// so, add them to the available queue.
350void ScheduleDAGRRList::ReleasePending() {
351 assert(!EnableSchedCycles && "requires --enable-sched-cycles" );
352
353 // If the available queue is empty, it is safe to reset MinAvailableCycle.
354 if (AvailableQueue->empty())
355 MinAvailableCycle = UINT_MAX;
356
357 // Check to see if any of the pending instructions are ready to issue. If
358 // so, add them to the available queue.
359 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
360 unsigned ReadyCycle =
361 isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDepth();
362 if (ReadyCycle < MinAvailableCycle)
363 MinAvailableCycle = ReadyCycle;
364
365 if (PendingQueue[i]->isAvailable) {
366 if (!isReady(PendingQueue[i]))
367 continue;
368 AvailableQueue->push(PendingQueue[i]);
369 }
370 PendingQueue[i]->isPending = false;
371 PendingQueue[i] = PendingQueue.back();
372 PendingQueue.pop_back();
373 --i; --e;
374 }
375}
376
377/// Move the scheduler state forward by the specified number of Cycles.
378void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
379 if (NextCycle <= CurCycle)
380 return;
381
382 AvailableQueue->setCurCycle(NextCycle);
383 if (HazardRec->getMaxLookAhead() == 0) {
384 // Bypass lots of virtual calls in case of long latency.
385 CurCycle = NextCycle;
386 }
387 else {
388 for (; CurCycle != NextCycle; ++CurCycle) {
389 if (isBottomUp)
390 HazardRec->RecedeCycle();
391 else
392 HazardRec->AdvanceCycle();
393 }
394 }
395 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
396 // available Q to release pending nodes at least once before popping.
397 ReleasePending();
398}
399
400/// Move the scheduler state forward until the specified node's dependents are
401/// ready and can be scheduled with no resource conflicts.
402void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
403 if (!EnableSchedCycles)
404 return;
405
406 unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
407
408 // Bump CurCycle to account for latency. We assume the latency of other
409 // available instructions may be hidden by the stall (not a full pipe stall).
410 // This updates the hazard recognizer's cycle before reserving resources for
411 // this instruction.
412 AdvanceToCycle(ReadyCycle);
413
414 // Calls are scheduled in their preceding cycle, so don't conflict with
415 // hazards from instructions after the call. EmitNode will reset the
416 // scoreboard state before emitting the call.
417 if (isBottomUp && SU->isCall)
418 return;
419
420 // FIXME: For resource conflicts in very long non-pipelined stages, we
421 // should probably skip ahead here to avoid useless scoreboard checks.
422 int Stalls = 0;
423 while (true) {
424 ScheduleHazardRecognizer::HazardType HT =
425 HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
426
427 if (HT == ScheduleHazardRecognizer::NoHazard)
428 break;
429
430 ++Stalls;
431 }
432 AdvanceToCycle(CurCycle + Stalls);
433}
434
435/// Record this SUnit in the HazardRecognizer.
436/// Does not update CurCycle.
437void ScheduleDAGRRList::EmitNode(SUnit *SU) {
438 switch (SU->getNode()->getOpcode()) {
439 default:
440 assert(SU->getNode()->isMachineOpcode() &&
441 "This target-independent node should not be scheduled.");
442 break;
443 case ISD::MERGE_VALUES:
444 case ISD::TokenFactor:
445 case ISD::CopyToReg:
446 case ISD::CopyFromReg:
447 case ISD::EH_LABEL:
448 // Noops don't affect the scoreboard state. Copies are likely to be
449 // removed.
450 return;
451 case ISD::INLINEASM:
452 // For inline asm, clear the pipeline state.
453 HazardRec->Reset();
454 return;
455 }
456 if (isBottomUp && SU->isCall) {
457 // Calls are scheduled with their preceding instructions. For bottom-up
458 // scheduling, clear the pipeline state before emitting.
459 HazardRec->Reset();
460 }
461
462 HazardRec->EmitInstruction(SU);
463
464 if (!isBottomUp && SU->isCall) {
465 HazardRec->Reset();
466 }
467}
468
Dan Gohmanb9543432009-02-10 23:27:53 +0000469/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
470/// count of its predecessors. If a predecessor pending count is zero, add it to
471/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000472void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Evan Chengbdd062d2010-05-20 06:13:19 +0000473 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000474 DEBUG(SU->dump(this));
475
Evan Chengbdd062d2010-05-20 06:13:19 +0000476#ifndef NDEBUG
477 if (CurCycle < SU->getHeight())
478 DEBUG(dbgs() << " Height [" << SU->getHeight() << "] pipeline stall!\n");
479#endif
480
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000481 // FIXME: Do not modify node height. It may interfere with
482 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
483 // node it's ready cycle can aid heuristics, and after scheduling it can
484 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000485 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000486
487 // Reserve resources for the scheduled intruction.
488 EmitNode(SU);
489
Dan Gohmanb9543432009-02-10 23:27:53 +0000490 Sequence.push_back(SU);
491
Evan Cheng28590382010-07-21 23:53:58 +0000492 AvailableQueue->ScheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000493
Andrew Trick033efdf2010-12-23 03:15:51 +0000494 // Update liveness of predecessors before successors to avoid treating a
495 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000496 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000497
498 // Release all the implicit physical register defs that are live.
499 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
500 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000501 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
502 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
503 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
504 --NumLiveRegs;
505 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000506 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000507 }
508 }
509
Evan Chengd38c22b2006-05-11 23:55:42 +0000510 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000511
512 // Conditions under which the scheduler should eagerly advance the cycle:
513 // (1) No available instructions
514 // (2) All pipelines full, so available instructions must have hazards.
515 //
516 // If SchedCycles is disabled, count each inst as one cycle.
517 if (!EnableSchedCycles ||
518 AvailableQueue->empty() || HazardRec->atIssueLimit())
519 AdvanceToCycle(CurCycle + 1);
Evan Chengd38c22b2006-05-11 23:55:42 +0000520}
521
Evan Cheng5924bf72007-09-25 01:54:36 +0000522/// CapturePred - This does the opposite of ReleasePred. Since SU is being
523/// unscheduled, incrcease the succ left count of its predecessors. Remove
524/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000525void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000526 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000527 if (PredSU->isAvailable) {
528 PredSU->isAvailable = false;
529 if (!PredSU->isPending)
530 AvailableQueue->remove(PredSU);
531 }
532
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000533 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000534 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000535}
536
537/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
538/// its predecessor states to reflect the change.
539void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000540 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000541 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000542
Evan Cheng5924bf72007-09-25 01:54:36 +0000543 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
544 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000545 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000546 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000547 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000548 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000549 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000550 --NumLiveRegs;
Dan Gohman2d170892008-12-09 22:54:47 +0000551 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000552 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000553 }
554 }
555
556 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
557 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000558 if (I->isAssignedRegDep()) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000559 // This becomes the nearest def. Note that an earlier def may still be
560 // pending if this is a two-address node.
561 LiveRegDefs[I->getReg()] = SU;
Dan Gohman2d170892008-12-09 22:54:47 +0000562 if (!LiveRegDefs[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000563 ++NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000564 }
Andrew Tricka52f3252010-12-23 04:16:14 +0000565 if (LiveRegGens[I->getReg()] == NULL ||
566 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
567 LiveRegGens[I->getReg()] = I->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000568 }
569 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000570 if (SU->getHeight() < MinAvailableCycle)
571 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000572
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000573 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000574 SU->isScheduled = false;
575 SU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000576 if (EnableSchedCycles && AvailableQueue->hasReadyFilter()) {
577 // Don't make available until backtracking is complete.
578 SU->isPending = true;
579 PendingQueue.push_back(SU);
580 }
581 else {
582 AvailableQueue->push(SU);
583 }
Evan Cheng28590382010-07-21 23:53:58 +0000584 AvailableQueue->UnscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000585}
586
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000587/// After backtracking, the hazard checker needs to be restored to a state
588/// corresponding the the current cycle.
589void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
590 HazardRec->Reset();
591
592 unsigned LookAhead = std::min((unsigned)Sequence.size(),
593 HazardRec->getMaxLookAhead());
594 if (LookAhead == 0)
595 return;
596
597 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
598 unsigned HazardCycle = (*I)->getHeight();
599 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
600 SUnit *SU = *I;
601 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
602 HazardRec->RecedeCycle();
603 }
604 EmitNode(SU);
605 }
606}
607
Evan Cheng8e136a92007-09-26 21:36:17 +0000608/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000609/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000610void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
611 SUnit *OldSU = Sequence.back();
612 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000613 Sequence.pop_back();
614 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000615 // Don't try to remove SU from AvailableQueue.
616 SU->isAvailable = false;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000617 // FIXME: use ready cycle instead of height
618 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000619 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000620 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000621 if (OldSU == BtSU)
622 break;
623 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000624 }
625
Dan Gohman60d68442009-01-29 19:49:27 +0000626 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000627
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000628 RestoreHazardCheckerBottomUp();
629
630 if (EnableSchedCycles)
631 ReleasePending();
632
Evan Cheng1ec79b42007-09-27 07:09:03 +0000633 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000634}
635
Evan Cheng3b245872010-02-05 01:27:11 +0000636static bool isOperandOf(const SUnit *SU, SDNode *N) {
637 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000638 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000639 if (SUNode->isOperandOf(N))
640 return true;
641 }
642 return false;
643}
644
Evan Cheng5924bf72007-09-25 01:54:36 +0000645/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
646/// successors to the newly created node.
647SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Chris Lattner11a33812010-12-23 17:24:32 +0000648 if (SU->getNode()->getGluedNode())
Evan Cheng79e97132007-10-05 01:39:18 +0000649 return NULL;
Evan Cheng8e136a92007-09-26 21:36:17 +0000650
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000651 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000652 if (!N)
653 return NULL;
654
655 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000656 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000657 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000658 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000659 if (VT == MVT::Glue)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000660 return NULL;
Owen Anderson9f944592009-08-11 20:47:22 +0000661 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000662 TryUnfold = true;
663 }
Evan Cheng79e97132007-10-05 01:39:18 +0000664 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000665 const SDValue &Op = N->getOperand(i);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000666 EVT VT = Op.getNode()->getValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000667 if (VT == MVT::Glue)
Evan Cheng79e97132007-10-05 01:39:18 +0000668 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000669 }
670
671 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000672 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000673 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000674 return NULL;
675
Evan Chengbdd062d2010-05-20 06:13:19 +0000676 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000677 assert(NewNodes.size() == 2 && "Expected a load folding node!");
678
679 N = NewNodes[1];
680 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000681 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000682 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000683 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000684 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
685 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000686 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000687
Dan Gohmane52e0892008-11-11 21:34:44 +0000688 // LoadNode may already exist. This can happen when there is another
689 // load from the same location and producing the same type of value
690 // but it has different alignment or volatileness.
691 bool isNewLoad = true;
692 SUnit *LoadSU;
693 if (LoadNode->getNodeId() != -1) {
694 LoadSU = &SUnits[LoadNode->getNodeId()];
695 isNewLoad = false;
696 } else {
697 LoadSU = CreateNewSUnit(LoadNode);
698 LoadNode->setNodeId(LoadSU->NodeNum);
Dan Gohmane52e0892008-11-11 21:34:44 +0000699 ComputeLatency(LoadSU);
700 }
701
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000702 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000703 assert(N->getNodeId() == -1 && "Node already inserted!");
704 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +0000705
Dan Gohman17059682008-07-17 19:10:17 +0000706 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Dan Gohman856c0122008-02-16 00:25:40 +0000707 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000708 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000709 NewSU->isTwoAddress = true;
710 break;
711 }
712 }
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000713 if (TID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000714 NewSU->isCommutable = true;
Evan Cheng79e97132007-10-05 01:39:18 +0000715 ComputeLatency(NewSU);
716
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000717 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +0000718 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +0000719 SmallVector<SDep, 4> ChainSuccs;
720 SmallVector<SDep, 4> LoadPreds;
721 SmallVector<SDep, 4> NodePreds;
722 SmallVector<SDep, 4> NodeSuccs;
723 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
724 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000725 if (I->isCtrl())
Dan Gohman15af5522009-03-06 02:23:01 +0000726 ChainPreds.push_back(*I);
Evan Cheng3b245872010-02-05 01:27:11 +0000727 else if (isOperandOf(I->getSUnit(), LoadNode))
Dan Gohman2d170892008-12-09 22:54:47 +0000728 LoadPreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000729 else
Dan Gohman2d170892008-12-09 22:54:47 +0000730 NodePreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000731 }
732 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
733 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000734 if (I->isCtrl())
735 ChainSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000736 else
Dan Gohman2d170892008-12-09 22:54:47 +0000737 NodeSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000738 }
739
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000740 // Now assign edges to the newly-created nodes.
Dan Gohman15af5522009-03-06 02:23:01 +0000741 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
742 const SDep &Pred = ChainPreds[i];
743 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +0000744 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +0000745 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000746 }
Evan Cheng79e97132007-10-05 01:39:18 +0000747 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000748 const SDep &Pred = LoadPreds[i];
749 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +0000750 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +0000751 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000752 }
753 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000754 const SDep &Pred = NodePreds[i];
755 RemovePred(SU, Pred);
756 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000757 }
758 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000759 SDep D = NodeSuccs[i];
760 SUnit *SuccDep = D.getSUnit();
761 D.setSUnit(SU);
762 RemovePred(SuccDep, D);
763 D.setSUnit(NewSU);
764 AddPred(SuccDep, D);
Evan Cheng79e97132007-10-05 01:39:18 +0000765 }
766 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000767 SDep D = ChainSuccs[i];
768 SUnit *SuccDep = D.getSUnit();
769 D.setSUnit(SU);
770 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000771 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +0000772 D.setSUnit(LoadSU);
773 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000774 }
Andrew Trick2085a962010-12-21 22:25:04 +0000775 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000776
777 // Add a data dependency to reflect that NewSU reads the value defined
778 // by LoadSU.
779 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
Evan Cheng79e97132007-10-05 01:39:18 +0000780
Evan Cheng91e0fc92007-12-18 08:42:10 +0000781 if (isNewLoad)
782 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000783 AvailableQueue->addNode(NewSU);
784
785 ++NumUnfolds;
786
787 if (NewSU->NumSuccsLeft == 0) {
788 NewSU->isAvailable = true;
789 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +0000790 }
791 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000792 }
793
Evan Chengbdd062d2010-05-20 06:13:19 +0000794 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000795 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000796
797 // New SUnit has the exact same predecessors.
798 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
799 I != E; ++I)
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000800 if (!I->isArtificial())
Dan Gohman2d170892008-12-09 22:54:47 +0000801 AddPred(NewSU, *I);
Evan Cheng5924bf72007-09-25 01:54:36 +0000802
803 // Only copy scheduled successors. Cut them from old node's successor
804 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000805 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +0000806 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
807 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000808 if (I->isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +0000809 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000810 SUnit *SuccSU = I->getSUnit();
811 if (SuccSU->isScheduled) {
Dan Gohman2d170892008-12-09 22:54:47 +0000812 SDep D = *I;
813 D.setSUnit(NewSU);
814 AddPred(SuccSU, D);
815 D.setSUnit(SU);
816 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +0000817 }
818 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000819 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000820 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng5924bf72007-09-25 01:54:36 +0000821
822 AvailableQueue->updateNode(SU);
823 AvailableQueue->addNode(NewSU);
824
Evan Cheng1ec79b42007-09-27 07:09:03 +0000825 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000826 return NewSU;
827}
828
Evan Chengb2c42c62009-01-12 03:19:55 +0000829/// InsertCopiesAndMoveSuccs - Insert register copies and move all
830/// scheduled successors of the given SUnit to the last copy.
831void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
832 const TargetRegisterClass *DestRC,
833 const TargetRegisterClass *SrcRC,
Evan Cheng1ec79b42007-09-27 07:09:03 +0000834 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000835 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000836 CopyFromSU->CopySrcRC = SrcRC;
837 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +0000838
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000839 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000840 CopyToSU->CopySrcRC = DestRC;
841 CopyToSU->CopyDstRC = SrcRC;
842
843 // Only copy scheduled successors. Cut them from old node's successor
844 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000845 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +0000846 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
847 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000848 if (I->isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +0000849 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000850 SUnit *SuccSU = I->getSUnit();
851 if (SuccSU->isScheduled) {
852 SDep D = *I;
853 D.setSUnit(CopyToSU);
854 AddPred(SuccSU, D);
855 DelDeps.push_back(std::make_pair(SuccSU, *I));
Evan Cheng8e136a92007-09-26 21:36:17 +0000856 }
857 }
Evan Chengb2c42c62009-01-12 03:19:55 +0000858 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000859 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng8e136a92007-09-26 21:36:17 +0000860
Dan Gohman2d170892008-12-09 22:54:47 +0000861 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
862 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
Evan Cheng8e136a92007-09-26 21:36:17 +0000863
864 AvailableQueue->updateNode(SU);
865 AvailableQueue->addNode(CopyFromSU);
866 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000867 Copies.push_back(CopyFromSU);
868 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +0000869
Evan Chengb2c42c62009-01-12 03:19:55 +0000870 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +0000871}
872
873/// getPhysicalRegisterVT - Returns the ValueType of the physical register
874/// definition of the specified node.
875/// FIXME: Move to SelectionDAG?
Owen Anderson53aa7a92009-08-10 22:56:29 +0000876static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +0000877 const TargetInstrInfo *TII) {
Dan Gohman17059682008-07-17 19:10:17 +0000878 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Evan Cheng8e136a92007-09-26 21:36:17 +0000879 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
Chris Lattnerb0d06b42008-01-07 03:13:06 +0000880 unsigned NumRes = TID.getNumDefs();
881 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000882 if (Reg == *ImpDef)
883 break;
884 ++NumRes;
885 }
886 return N->getValueType(NumRes);
887}
888
Evan Chengb8905c42009-03-04 01:41:49 +0000889/// CheckForLiveRegDef - Return true and update live register vector if the
890/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000891static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Evan Chengb8905c42009-03-04 01:41:49 +0000892 std::vector<SUnit*> &LiveRegDefs,
893 SmallSet<unsigned, 4> &RegAdded,
894 SmallVector<unsigned, 4> &LRegs,
895 const TargetRegisterInfo *TRI) {
Andrew Trick12acde112010-12-23 03:43:21 +0000896 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
897
898 // Check if Ref is live.
899 if (!LiveRegDefs[Reg]) continue;
900
901 // Allow multiple uses of the same def.
902 if (LiveRegDefs[Reg] == SU) continue;
903
904 // Add Reg to the set of interfering live regs.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000905 if (RegAdded.insert(Reg))
Evan Chengb8905c42009-03-04 01:41:49 +0000906 LRegs.push_back(Reg);
Evan Chengb8905c42009-03-04 01:41:49 +0000907 }
Evan Chengb8905c42009-03-04 01:41:49 +0000908}
909
Evan Cheng5924bf72007-09-25 01:54:36 +0000910/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
911/// scheduling of the given node to satisfy live physical register dependencies.
912/// If the specific node is the last one that's available to schedule, do
913/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000914bool ScheduleDAGRRList::
915DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000916 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +0000917 return false;
918
Evan Chenge6f92252007-09-27 18:46:06 +0000919 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +0000920 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +0000921 //
922 // If SU is the currently live definition of the same register that it uses,
923 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +0000924 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
925 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +0000926 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Evan Chengb8905c42009-03-04 01:41:49 +0000927 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
928 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +0000929 }
930
Chris Lattner11a33812010-12-23 17:24:32 +0000931 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +0000932 if (Node->getOpcode() == ISD::INLINEASM) {
933 // Inline asm can clobber physical defs.
934 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000935 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +0000936 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +0000937
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000938 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +0000939 unsigned Flags =
940 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000941 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +0000942
943 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000944 if (InlineAsm::isRegDefKind(Flags) ||
945 InlineAsm::isRegDefEarlyClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +0000946 // Check for def of register or earlyclobber register.
947 for (; NumVals; --NumVals, ++i) {
948 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
949 if (TargetRegisterInfo::isPhysicalRegister(Reg))
950 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
951 }
952 } else
953 i += NumVals;
954 }
955 continue;
956 }
957
Dan Gohman072734e2008-11-13 23:24:17 +0000958 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +0000959 continue;
Dan Gohman17059682008-07-17 19:10:17 +0000960 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
Evan Cheng5924bf72007-09-25 01:54:36 +0000961 if (!TID.ImplicitDefs)
962 continue;
Evan Chengb8905c42009-03-04 01:41:49 +0000963 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
964 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +0000965 }
Andrew Trick2085a962010-12-21 22:25:04 +0000966
Evan Cheng5924bf72007-09-25 01:54:36 +0000967 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +0000968}
969
Andrew Trick528fad92010-12-23 05:42:20 +0000970/// Return a node that can be scheduled in this cycle. Requirements:
971/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000972/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +0000973/// (3) No Interferences: may unschedule to break register interferences.
974SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
975 SmallVector<SUnit*, 4> Interferences;
976 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
977
978 SUnit *CurSU = AvailableQueue->pop();
979 while (CurSU) {
980 SmallVector<unsigned, 4> LRegs;
981 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
982 break;
983 LRegsMap.insert(std::make_pair(CurSU, LRegs));
984
985 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
986 Interferences.push_back(CurSU);
987 CurSU = AvailableQueue->pop();
988 }
989 if (CurSU) {
990 // Add the nodes that aren't ready back onto the available list.
991 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
992 Interferences[i]->isPending = false;
993 assert(Interferences[i]->isAvailable && "must still be available");
994 AvailableQueue->push(Interferences[i]);
995 }
996 return CurSU;
997 }
998
999 // All candidates are delayed due to live physical reg dependencies.
1000 // Try backtracking, code duplication, or inserting cross class copies
1001 // to resolve it.
1002 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1003 SUnit *TrySU = Interferences[i];
1004 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1005
1006 // Try unscheduling up to the point where it's safe to schedule
1007 // this node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001008 SUnit *BtSU = NULL;
1009 unsigned LiveCycle = UINT_MAX;
Andrew Trick528fad92010-12-23 05:42:20 +00001010 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1011 unsigned Reg = LRegs[j];
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001012 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1013 BtSU = LiveRegGens[Reg];
1014 LiveCycle = BtSU->getHeight();
1015 }
Andrew Trick528fad92010-12-23 05:42:20 +00001016 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001017 if (!WillCreateCycle(TrySU, BtSU)) {
1018 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001019
1020 // Force the current node to be scheduled before the node that
1021 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001022 if (BtSU->isAvailable) {
1023 BtSU->isAvailable = false;
1024 if (!BtSU->isPending)
1025 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001026 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001027 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
Andrew Trick528fad92010-12-23 05:42:20 +00001028 /*Reg=*/0, /*isNormalMemory=*/false,
1029 /*isMustAlias=*/false, /*isArtificial=*/true));
1030
1031 // If one or more successors has been unscheduled, then the current
1032 // node is no longer avaialable. Schedule a successor that's now
1033 // available instead.
1034 if (!TrySU->isAvailable) {
1035 CurSU = AvailableQueue->pop();
1036 }
1037 else {
1038 CurSU = TrySU;
1039 TrySU->isPending = false;
1040 Interferences.erase(Interferences.begin()+i);
1041 }
1042 break;
1043 }
1044 }
1045
1046 if (!CurSU) {
1047 // Can't backtrack. If it's too expensive to copy the value, then try
1048 // duplicate the nodes that produces these "too expensive to copy"
1049 // values to break the dependency. In case even that doesn't work,
1050 // insert cross class copies.
1051 // If it's not too expensive, i.e. cost != -1, issue copies.
1052 SUnit *TrySU = Interferences[0];
1053 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1054 assert(LRegs.size() == 1 && "Can't handle this yet!");
1055 unsigned Reg = LRegs[0];
1056 SUnit *LRDef = LiveRegDefs[Reg];
1057 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1058 const TargetRegisterClass *RC =
1059 TRI->getMinimalPhysRegClass(Reg, VT);
1060 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1061
1062 // If cross copy register class is null, then it must be possible copy
1063 // the value directly. Do not try duplicate the def.
1064 SUnit *NewDef = 0;
1065 if (DestRC)
1066 NewDef = CopyAndMoveSuccessors(LRDef);
1067 else
1068 DestRC = RC;
1069 if (!NewDef) {
1070 // Issue copies, these can be expensive cross register class copies.
1071 SmallVector<SUnit*, 2> Copies;
1072 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1073 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1074 << " to SU #" << Copies.front()->NodeNum << "\n");
1075 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1076 /*Reg=*/0, /*isNormalMemory=*/false,
1077 /*isMustAlias=*/false,
1078 /*isArtificial=*/true));
1079 NewDef = Copies.back();
1080 }
1081
1082 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1083 << " to SU #" << TrySU->NodeNum << "\n");
1084 LiveRegDefs[Reg] = NewDef;
1085 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1086 /*Reg=*/0, /*isNormalMemory=*/false,
1087 /*isMustAlias=*/false,
1088 /*isArtificial=*/true));
1089 TrySU->isAvailable = false;
1090 CurSU = NewDef;
1091 }
1092
1093 assert(CurSU && "Unable to resolve live physical register dependencies!");
1094
1095 // Add the nodes that aren't ready back onto the available list.
1096 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1097 Interferences[i]->isPending = false;
1098 // May no longer be available due to backtracking.
1099 if (Interferences[i]->isAvailable) {
1100 AvailableQueue->push(Interferences[i]);
1101 }
1102 }
1103 return CurSU;
1104}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001105
Evan Chengd38c22b2006-05-11 23:55:42 +00001106/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1107/// schedulers.
1108void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001109 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001110 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001111
Evan Chengd38c22b2006-05-11 23:55:42 +00001112 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001113 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001114 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001115 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1116 RootSU->isAvailable = true;
1117 AvailableQueue->push(RootSU);
1118 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001119
1120 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001121 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001122 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001123 while (!AvailableQueue->empty()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001124 DEBUG(dbgs() << "\n*** Examining Available\n";
1125 AvailableQueue->dump(this));
1126
Andrew Trick528fad92010-12-23 05:42:20 +00001127 // Pick the best node to schedule taking all constraints into
1128 // consideration.
1129 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001130
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001131 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001132
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001133 ScheduleNodeBottomUp(SU);
1134
1135 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1136 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1137 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1138 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1139 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001140 }
1141
Evan Chengd38c22b2006-05-11 23:55:42 +00001142 // Reverse the order if it is bottom up.
1143 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001144
Evan Chengd38c22b2006-05-11 23:55:42 +00001145#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001146 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001147#endif
1148}
1149
1150//===----------------------------------------------------------------------===//
1151// Top-Down Scheduling
1152//===----------------------------------------------------------------------===//
1153
1154/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +00001155/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +00001156void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +00001157 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001158
Evan Chengd38c22b2006-05-11 23:55:42 +00001159#ifndef NDEBUG
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001160 if (SuccSU->NumPredsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +00001161 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +00001162 SuccSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +00001163 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +00001164 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +00001165 }
1166#endif
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001167 --SuccSU->NumPredsLeft;
1168
Dan Gohmanb9543432009-02-10 23:27:53 +00001169 // If all the node's predecessors are scheduled, this node is ready
1170 // to be scheduled. Ignore the special ExitSU node.
1171 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001172 SuccSU->isAvailable = true;
1173 AvailableQueue->push(SuccSU);
1174 }
1175}
1176
Dan Gohmanb9543432009-02-10 23:27:53 +00001177void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1178 // Top down: release successors
1179 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1180 I != E; ++I) {
1181 assert(!I->isAssignedRegDep() &&
1182 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1183
1184 ReleaseSucc(SU, &*I);
1185 }
1186}
1187
Evan Chengd38c22b2006-05-11 23:55:42 +00001188/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1189/// count of its successors. If a successor pending count is zero, add it to
1190/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +00001191void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +00001192 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +00001193 DEBUG(SU->dump(this));
Evan Chengd38c22b2006-05-11 23:55:42 +00001194
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001195 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1196 SU->setDepthToAtLeast(CurCycle);
Dan Gohman92a36d72008-11-17 21:31:02 +00001197 Sequence.push_back(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001198
Dan Gohmanb9543432009-02-10 23:27:53 +00001199 ReleaseSuccessors(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001200 SU->isScheduled = true;
Dan Gohman92a36d72008-11-17 21:31:02 +00001201 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001202}
1203
Dan Gohman54a187e2007-08-20 19:28:38 +00001204/// ListScheduleTopDown - The main loop of list scheduling for top-down
1205/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +00001206void ScheduleDAGRRList::ListScheduleTopDown() {
Evan Chengbdd062d2010-05-20 06:13:19 +00001207 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001208
Dan Gohmanb9543432009-02-10 23:27:53 +00001209 // Release any successors of the special Entry node.
1210 ReleaseSuccessors(&EntrySU);
1211
Evan Chengd38c22b2006-05-11 23:55:42 +00001212 // All leaves to Available queue.
1213 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1214 // It is available if it has no predecessors.
Dan Gohman4370f262008-04-15 01:22:18 +00001215 if (SUnits[i].Preds.empty()) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001216 AvailableQueue->push(&SUnits[i]);
1217 SUnits[i].isAvailable = true;
1218 }
1219 }
Andrew Trick2085a962010-12-21 22:25:04 +00001220
Evan Chengd38c22b2006-05-11 23:55:42 +00001221 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001222 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001223 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001224 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +00001225 SUnit *CurSU = AvailableQueue->pop();
Andrew Trick2085a962010-12-21 22:25:04 +00001226
Dan Gohmanc602dd42008-11-21 00:10:42 +00001227 if (CurSU)
Andrew Trick528fad92010-12-23 05:42:20 +00001228 ScheduleNodeTopDown(CurSU);
Dan Gohman4370f262008-04-15 01:22:18 +00001229 ++CurCycle;
Evan Chengbdd062d2010-05-20 06:13:19 +00001230 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001231 }
Andrew Trick2085a962010-12-21 22:25:04 +00001232
Evan Chengd38c22b2006-05-11 23:55:42 +00001233#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001234 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001235#endif
1236}
1237
1238
Evan Chengd38c22b2006-05-11 23:55:42 +00001239//===----------------------------------------------------------------------===//
1240// RegReductionPriorityQueue Implementation
1241//===----------------------------------------------------------------------===//
1242//
1243// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1244// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001245//
Evan Chengd38c22b2006-05-11 23:55:42 +00001246namespace {
1247 template<class SF>
1248 class RegReductionPriorityQueue;
Andrew Trick2085a962010-12-21 22:25:04 +00001249
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001250 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1251 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1252 };
1253
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001254 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1255 // reduction scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001256 struct bu_ls_rr_sort : public queue_sort {
1257 enum {
1258 IsBottomUp = true,
1259 HasReadyFilter = false
1260 };
1261
Evan Chengd38c22b2006-05-11 23:55:42 +00001262 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
1263 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
1264 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick2085a962010-12-21 22:25:04 +00001265
Evan Chengd38c22b2006-05-11 23:55:42 +00001266 bool operator()(const SUnit* left, const SUnit* right) const;
1267 };
1268
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001269 // td_ls_rr_sort - Priority function for top down register pressure reduction
1270 // scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001271 struct td_ls_rr_sort : public queue_sort {
1272 enum {
1273 IsBottomUp = false,
1274 HasReadyFilter = false
1275 };
1276
1277 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
Evan Chengd38c22b2006-05-11 23:55:42 +00001278 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
1279 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick2085a962010-12-21 22:25:04 +00001280
Evan Chengd38c22b2006-05-11 23:55:42 +00001281 bool operator()(const SUnit* left, const SUnit* right) const;
1282 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001283
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001284 // src_ls_rr_sort - Priority function for source order scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001285 struct src_ls_rr_sort : public queue_sort {
1286 enum {
1287 IsBottomUp = true,
1288 HasReadyFilter = false
1289 };
1290
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001291 RegReductionPriorityQueue<src_ls_rr_sort> *SPQ;
1292 src_ls_rr_sort(RegReductionPriorityQueue<src_ls_rr_sort> *spq)
1293 : SPQ(spq) {}
1294 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1295 : SPQ(RHS.SPQ) {}
Andrew Trick2085a962010-12-21 22:25:04 +00001296
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001297 bool operator()(const SUnit* left, const SUnit* right) const;
1298 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001299
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001300 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001301 struct hybrid_ls_rr_sort : public queue_sort {
1302 enum {
1303 IsBottomUp = true,
1304 HasReadyFilter = false
1305 };
1306
Evan Chengbdd062d2010-05-20 06:13:19 +00001307 RegReductionPriorityQueue<hybrid_ls_rr_sort> *SPQ;
1308 hybrid_ls_rr_sort(RegReductionPriorityQueue<hybrid_ls_rr_sort> *spq)
1309 : SPQ(spq) {}
1310 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1311 : SPQ(RHS.SPQ) {}
Evan Chenga77f3d32010-07-21 06:09:07 +00001312
Evan Chengbdd062d2010-05-20 06:13:19 +00001313 bool operator()(const SUnit* left, const SUnit* right) const;
1314 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001315
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001316 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1317 // scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001318 struct ilp_ls_rr_sort : public queue_sort {
1319 enum {
1320 IsBottomUp = true,
1321 HasReadyFilter = true
1322 };
1323
Evan Cheng37b740c2010-07-24 00:39:05 +00001324 RegReductionPriorityQueue<ilp_ls_rr_sort> *SPQ;
1325 ilp_ls_rr_sort(RegReductionPriorityQueue<ilp_ls_rr_sort> *spq)
1326 : SPQ(spq) {}
1327 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1328 : SPQ(RHS.SPQ) {}
1329
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001330 bool isReady(SUnit *SU, unsigned CurCycle) const;
1331
Evan Cheng37b740c2010-07-24 00:39:05 +00001332 bool operator()(const SUnit* left, const SUnit* right) const;
1333 };
Evan Chengd38c22b2006-05-11 23:55:42 +00001334} // end anonymous namespace
1335
Dan Gohman186f65d2008-11-20 03:30:37 +00001336/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1337/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001338static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001339CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001340 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1341 if (SethiUllmanNumber != 0)
1342 return SethiUllmanNumber;
1343
1344 unsigned Extra = 0;
1345 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1346 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001347 if (I->isCtrl()) continue; // ignore chain preds
1348 SUnit *PredSU = I->getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001349 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001350 if (PredSethiUllman > SethiUllmanNumber) {
1351 SethiUllmanNumber = PredSethiUllman;
1352 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001353 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001354 ++Extra;
1355 }
1356
1357 SethiUllmanNumber += Extra;
1358
1359 if (SethiUllmanNumber == 0)
1360 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001361
Evan Cheng7e4abde2008-07-02 09:23:51 +00001362 return SethiUllmanNumber;
1363}
1364
Evan Chengd38c22b2006-05-11 23:55:42 +00001365namespace {
1366 template<class SF>
Nick Lewycky02d5f772009-10-25 06:33:48 +00001367 class RegReductionPriorityQueue : public SchedulingPriorityQueue {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001368 static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1369 std::vector<SUnit *>::iterator Best = Q.begin();
1370 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1371 E = Q.end(); I != E; ++I)
1372 if (Picker(*Best, *I))
1373 Best = I;
1374 SUnit *V = *Best;
1375 if (Best != prior(Q.end()))
1376 std::swap(*Best, Q.back());
1377 Q.pop_back();
1378 return V;
1379 }
1380
Dan Gohman52c27382010-05-26 18:52:00 +00001381 std::vector<SUnit*> Queue;
1382 SF Picker;
Evan Chengbdd062d2010-05-20 06:13:19 +00001383 unsigned CurQueueId;
Evan Chengbf32e542010-07-22 06:24:48 +00001384 bool TracksRegPressure;
Evan Chengd38c22b2006-05-11 23:55:42 +00001385
Dan Gohman3f656df2008-11-20 02:45:51 +00001386 protected:
1387 // SUnits - The SUnits for the current graph.
1388 std::vector<SUnit> *SUnits;
Evan Chenga77f3d32010-07-21 06:09:07 +00001389
1390 MachineFunction &MF;
Dan Gohman3f656df2008-11-20 02:45:51 +00001391 const TargetInstrInfo *TII;
1392 const TargetRegisterInfo *TRI;
Evan Chenga77f3d32010-07-21 06:09:07 +00001393 const TargetLowering *TLI;
Dan Gohman3f656df2008-11-20 02:45:51 +00001394 ScheduleDAGRRList *scheduleDAG;
1395
Dan Gohman186f65d2008-11-20 03:30:37 +00001396 // SethiUllmanNumbers - The SethiUllman number for each node.
1397 std::vector<unsigned> SethiUllmanNumbers;
1398
Evan Chenga77f3d32010-07-21 06:09:07 +00001399 /// RegPressure - Tracking current reg pressure per register class.
1400 ///
Evan Cheng28590382010-07-21 23:53:58 +00001401 std::vector<unsigned> RegPressure;
Evan Chenga77f3d32010-07-21 06:09:07 +00001402
1403 /// RegLimit - Tracking the number of allocatable registers per register
1404 /// class.
Evan Cheng28590382010-07-21 23:53:58 +00001405 std::vector<unsigned> RegLimit;
Evan Chenga77f3d32010-07-21 06:09:07 +00001406
Dan Gohman3f656df2008-11-20 02:45:51 +00001407 public:
Evan Chenga77f3d32010-07-21 06:09:07 +00001408 RegReductionPriorityQueue(MachineFunction &mf,
Evan Chengbf32e542010-07-22 06:24:48 +00001409 bool tracksrp,
Evan Chenga77f3d32010-07-21 06:09:07 +00001410 const TargetInstrInfo *tii,
1411 const TargetRegisterInfo *tri,
1412 const TargetLowering *tli)
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001413 : SchedulingPriorityQueue(SF::HasReadyFilter), Picker(this),
1414 CurQueueId(0), TracksRegPressure(tracksrp),
Evan Chenga77f3d32010-07-21 06:09:07 +00001415 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
Evan Chengbf32e542010-07-22 06:24:48 +00001416 if (TracksRegPressure) {
1417 unsigned NumRC = TRI->getNumRegClasses();
1418 RegLimit.resize(NumRC);
1419 RegPressure.resize(NumRC);
1420 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1421 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1422 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1423 E = TRI->regclass_end(); I != E; ++I)
Evan Chengdf907f42010-07-23 22:39:59 +00001424 RegLimit[(*I)->getID()] = tli->getRegPressureLimit(*I, MF);
Evan Chengbf32e542010-07-22 06:24:48 +00001425 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001426 }
Andrew Trick2085a962010-12-21 22:25:04 +00001427
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001428 bool isBottomUp() const { return SF::IsBottomUp; }
1429
Dan Gohman3f656df2008-11-20 02:45:51 +00001430 void initNodes(std::vector<SUnit> &sunits) {
1431 SUnits = &sunits;
Dan Gohman186f65d2008-11-20 03:30:37 +00001432 // Add pseudo dependency edges for two-address nodes.
1433 AddPseudoTwoAddrDeps();
Dan Gohman9a658d72009-03-24 00:49:12 +00001434 // Reroute edges to nodes with multiple uses.
1435 PrescheduleNodesWithMultipleUses();
Dan Gohman186f65d2008-11-20 03:30:37 +00001436 // Calculate node priorities.
1437 CalculateSethiUllmanNumbers();
Dan Gohman3f656df2008-11-20 02:45:51 +00001438 }
Evan Cheng5924bf72007-09-25 01:54:36 +00001439
Dan Gohman186f65d2008-11-20 03:30:37 +00001440 void addNode(const SUnit *SU) {
1441 unsigned SUSize = SethiUllmanNumbers.size();
1442 if (SUnits->size() > SUSize)
1443 SethiUllmanNumbers.resize(SUSize*2, 0);
1444 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1445 }
Evan Cheng5924bf72007-09-25 01:54:36 +00001446
Dan Gohman186f65d2008-11-20 03:30:37 +00001447 void updateNode(const SUnit *SU) {
1448 SethiUllmanNumbers[SU->NodeNum] = 0;
1449 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1450 }
Evan Cheng5924bf72007-09-25 01:54:36 +00001451
Dan Gohman186f65d2008-11-20 03:30:37 +00001452 void releaseState() {
Dan Gohman3f656df2008-11-20 02:45:51 +00001453 SUnits = 0;
Dan Gohman186f65d2008-11-20 03:30:37 +00001454 SethiUllmanNumbers.clear();
Evan Chenga77f3d32010-07-21 06:09:07 +00001455 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Dan Gohman3f656df2008-11-20 02:45:51 +00001456 }
Dan Gohman186f65d2008-11-20 03:30:37 +00001457
1458 unsigned getNodePriority(const SUnit *SU) const {
1459 assert(SU->NodeNum < SethiUllmanNumbers.size());
1460 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
Dan Gohman261ee6b2009-01-07 22:30:55 +00001461 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
Dan Gohman186f65d2008-11-20 03:30:37 +00001462 // CopyToReg should be close to its uses to facilitate coalescing and
1463 // avoid spilling.
1464 return 0;
Chris Lattnerb06015a2010-02-09 19:54:29 +00001465 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1466 Opc == TargetOpcode::SUBREG_TO_REG ||
1467 Opc == TargetOpcode::INSERT_SUBREG)
Dan Gohman3027bb62009-04-16 20:57:10 +00001468 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1469 // close to their uses to facilitate coalescing.
Dan Gohman186f65d2008-11-20 03:30:37 +00001470 return 0;
Dan Gohman6571ef32009-02-11 21:29:39 +00001471 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1472 // If SU does not have a register use, i.e. it doesn't produce a value
1473 // that would be consumed (e.g. store), then it terminates a chain of
1474 // computation. Give it a large SethiUllman number so it will be
1475 // scheduled right before its predecessors that it doesn't lengthen
1476 // their live ranges.
Dan Gohman186f65d2008-11-20 03:30:37 +00001477 return 0xffff;
Dan Gohman6571ef32009-02-11 21:29:39 +00001478 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1479 // If SU does not have a register def, schedule it close to its uses
1480 // because it does not lengthen any live ranges.
Dan Gohman186f65d2008-11-20 03:30:37 +00001481 return 0;
Dan Gohman261ee6b2009-01-07 22:30:55 +00001482 return SethiUllmanNumbers[SU->NodeNum];
Dan Gohman186f65d2008-11-20 03:30:37 +00001483 }
Bill Wendling0a7056f2010-01-05 23:48:12 +00001484
1485 unsigned getNodeOrdering(const SUnit *SU) const {
1486 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1487 }
Evan Chengbdd062d2010-05-20 06:13:19 +00001488
Evan Chengd38c22b2006-05-11 23:55:42 +00001489 bool empty() const { return Queue.empty(); }
Andrew Trick2085a962010-12-21 22:25:04 +00001490
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001491 bool isReady(SUnit *U) const {
1492 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1493 }
1494
Evan Chengd38c22b2006-05-11 23:55:42 +00001495 void push(SUnit *U) {
Roman Levenstein6b371142008-04-29 09:07:59 +00001496 assert(!U->NodeQueueId && "Node in the queue already");
Evan Chengbdd062d2010-05-20 06:13:19 +00001497 U->NodeQueueId = ++CurQueueId;
Dan Gohman52c27382010-05-26 18:52:00 +00001498 Queue.push_back(U);
Evan Chengd38c22b2006-05-11 23:55:42 +00001499 }
Roman Levenstein6b371142008-04-29 09:07:59 +00001500
Evan Chengd38c22b2006-05-11 23:55:42 +00001501 SUnit *pop() {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001502 if (Queue.empty()) return NULL;
1503
1504 SUnit *V = popFromQueue(Queue, Picker);
Roman Levenstein6b371142008-04-29 09:07:59 +00001505 V->NodeQueueId = 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001506 return V;
1507 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001508
Evan Cheng5924bf72007-09-25 01:54:36 +00001509 void remove(SUnit *SU) {
Roman Levenstein6b371142008-04-29 09:07:59 +00001510 assert(!Queue.empty() && "Queue is empty!");
Dan Gohmana4db3352008-06-21 18:35:25 +00001511 assert(SU->NodeQueueId != 0 && "Not in queue!");
Dan Gohman52c27382010-05-26 18:52:00 +00001512 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1513 SU);
1514 if (I != prior(Queue.end()))
1515 std::swap(*I, Queue.back());
1516 Queue.pop_back();
Roman Levenstein6b371142008-04-29 09:07:59 +00001517 SU->NodeQueueId = 0;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001518 }
Dan Gohman3f656df2008-11-20 02:45:51 +00001519
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001520 bool HighRegPressure(const SUnit *SU) const {
Evan Chenga77f3d32010-07-21 06:09:07 +00001521 if (!TLI)
Evan Cheng28590382010-07-21 23:53:58 +00001522 return false;
Evan Chenga77f3d32010-07-21 06:09:07 +00001523
Evan Chenga77f3d32010-07-21 06:09:07 +00001524 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1525 I != E; ++I) {
1526 if (I->isCtrl())
1527 continue;
1528 SUnit *PredSU = I->getSUnit();
Evan Cheng28590382010-07-21 23:53:58 +00001529 const SDNode *PN = PredSU->getNode();
1530 if (!PN->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001531 if (PN->getOpcode() == ISD::CopyFromReg) {
1532 EVT VT = PN->getValueType(0);
Evan Cheng28590382010-07-21 23:53:58 +00001533 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1534 unsigned Cost = TLI->getRepRegClassCostFor(VT);
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001535 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1536 return true;
Evan Chengdf907f42010-07-23 22:39:59 +00001537 }
1538 continue;
1539 }
1540 unsigned POpc = PN->getMachineOpcode();
1541 if (POpc == TargetOpcode::IMPLICIT_DEF)
1542 continue;
1543 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1544 EVT VT = PN->getOperand(0).getValueType();
1545 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1546 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1547 // Check if this increases register pressure of the specific register
1548 // class to the point where it would cause spills.
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001549 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1550 return true;
Andrew Trick2085a962010-12-21 22:25:04 +00001551 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001552 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1553 POpc == TargetOpcode::SUBREG_TO_REG) {
1554 EVT VT = PN->getValueType(0);
1555 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1556 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1557 // Check if this increases register pressure of the specific register
1558 // class to the point where it would cause spills.
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001559 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1560 return true;
Evan Chenga77f3d32010-07-21 06:09:07 +00001561 continue;
Evan Cheng28590382010-07-21 23:53:58 +00001562 }
1563 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
Evan Chenga77f3d32010-07-21 06:09:07 +00001564 for (unsigned i = 0; i != NumDefs; ++i) {
Evan Cheng28590382010-07-21 23:53:58 +00001565 EVT VT = PN->getValueType(i);
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001566 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1567 if (RegPressure[RCId] >= RegLimit[RCId])
1568 return true; // Reg pressure already high.
1569 unsigned Cost = TLI->getRepRegClassCostFor(VT);
Evan Cheng28590382010-07-21 23:53:58 +00001570 if (!PN->hasAnyUseOfValue(i))
Evan Chenga77f3d32010-07-21 06:09:07 +00001571 continue;
Evan Chenga77f3d32010-07-21 06:09:07 +00001572 // Check if this increases register pressure of the specific register
1573 // class to the point where it would cause spills.
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001574 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1575 return true;
Evan Chenga77f3d32010-07-21 06:09:07 +00001576 }
1577 }
1578
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001579 return false;
Evan Chenga77f3d32010-07-21 06:09:07 +00001580 }
1581
Evan Chengbf32e542010-07-22 06:24:48 +00001582 void ScheduledNode(SUnit *SU) {
1583 if (!TracksRegPressure)
1584 return;
1585
Evan Chenga77f3d32010-07-21 06:09:07 +00001586 const SDNode *N = SU->getNode();
Evan Chengdf907f42010-07-23 22:39:59 +00001587 if (!N->isMachineOpcode()) {
1588 if (N->getOpcode() != ISD::CopyToReg)
1589 return;
1590 } else {
1591 unsigned Opc = N->getMachineOpcode();
1592 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1593 Opc == TargetOpcode::INSERT_SUBREG ||
1594 Opc == TargetOpcode::SUBREG_TO_REG ||
1595 Opc == TargetOpcode::REG_SEQUENCE ||
1596 Opc == TargetOpcode::IMPLICIT_DEF)
1597 return;
1598 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001599
1600 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1601 I != E; ++I) {
1602 if (I->isCtrl())
1603 continue;
1604 SUnit *PredSU = I->getSUnit();
Evan Cheng28590382010-07-21 23:53:58 +00001605 if (PredSU->NumSuccsLeft != PredSU->NumSuccs)
Evan Chenga77f3d32010-07-21 06:09:07 +00001606 continue;
1607 const SDNode *PN = PredSU->getNode();
Evan Cheng28590382010-07-21 23:53:58 +00001608 if (!PN->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001609 if (PN->getOpcode() == ISD::CopyFromReg) {
1610 EVT VT = PN->getValueType(0);
Evan Cheng28590382010-07-21 23:53:58 +00001611 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1612 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1613 }
1614 continue;
1615 }
1616 unsigned POpc = PN->getMachineOpcode();
1617 if (POpc == TargetOpcode::IMPLICIT_DEF)
Evan Chenga77f3d32010-07-21 06:09:07 +00001618 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001619 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1620 EVT VT = PN->getOperand(0).getValueType();
1621 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1622 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
Andrew Trick2085a962010-12-21 22:25:04 +00001623 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001624 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1625 POpc == TargetOpcode::SUBREG_TO_REG) {
1626 EVT VT = PN->getValueType(0);
1627 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1628 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1629 continue;
1630 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001631 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1632 for (unsigned i = 0; i != NumDefs; ++i) {
1633 EVT VT = PN->getValueType(i);
1634 if (!PN->hasAnyUseOfValue(i))
1635 continue;
1636 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1637 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1638 }
1639 }
1640
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001641 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1642 // may transfer data dependencies to CopyToReg.
1643 if (SU->NumSuccs && N->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001644 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1645 for (unsigned i = 0; i != NumDefs; ++i) {
1646 EVT VT = N->getValueType(i);
1647 if (!N->hasAnyUseOfValue(i))
1648 continue;
1649 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1650 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1651 // Register pressure tracking is imprecise. This can happen.
1652 RegPressure[RCId] = 0;
1653 else
1654 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1655 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001656 }
Evan Chengbf32e542010-07-22 06:24:48 +00001657
1658 dumpRegPressure();
Evan Chenga77f3d32010-07-21 06:09:07 +00001659 }
1660
Evan Chengbf32e542010-07-22 06:24:48 +00001661 void UnscheduledNode(SUnit *SU) {
1662 if (!TracksRegPressure)
1663 return;
1664
Evan Chenga77f3d32010-07-21 06:09:07 +00001665 const SDNode *N = SU->getNode();
Evan Chengdf907f42010-07-23 22:39:59 +00001666 if (!N->isMachineOpcode()) {
1667 if (N->getOpcode() != ISD::CopyToReg)
1668 return;
Evan Cheng37b740c2010-07-24 00:39:05 +00001669 } else {
1670 unsigned Opc = N->getMachineOpcode();
1671 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1672 Opc == TargetOpcode::INSERT_SUBREG ||
1673 Opc == TargetOpcode::SUBREG_TO_REG ||
1674 Opc == TargetOpcode::REG_SEQUENCE ||
1675 Opc == TargetOpcode::IMPLICIT_DEF)
1676 return;
Evan Chengdf907f42010-07-23 22:39:59 +00001677 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001678
1679 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1680 I != E; ++I) {
1681 if (I->isCtrl())
1682 continue;
1683 SUnit *PredSU = I->getSUnit();
Evan Cheng28590382010-07-21 23:53:58 +00001684 if (PredSU->NumSuccsLeft != PredSU->NumSuccs)
Evan Chenga77f3d32010-07-21 06:09:07 +00001685 continue;
1686 const SDNode *PN = PredSU->getNode();
Evan Cheng28590382010-07-21 23:53:58 +00001687 if (!PN->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001688 if (PN->getOpcode() == ISD::CopyFromReg) {
1689 EVT VT = PN->getValueType(0);
Evan Cheng28590382010-07-21 23:53:58 +00001690 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1691 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1692 }
1693 continue;
1694 }
1695 unsigned POpc = PN->getMachineOpcode();
1696 if (POpc == TargetOpcode::IMPLICIT_DEF)
Evan Chenga77f3d32010-07-21 06:09:07 +00001697 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001698 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1699 EVT VT = PN->getOperand(0).getValueType();
1700 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1701 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
Andrew Trick2085a962010-12-21 22:25:04 +00001702 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001703 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1704 POpc == TargetOpcode::SUBREG_TO_REG) {
1705 EVT VT = PN->getValueType(0);
1706 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1707 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1708 continue;
1709 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001710 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1711 for (unsigned i = 0; i != NumDefs; ++i) {
1712 EVT VT = PN->getValueType(i);
1713 if (!PN->hasAnyUseOfValue(i))
1714 continue;
1715 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
Evan Cheng28590382010-07-21 23:53:58 +00001716 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
Evan Chenga77f3d32010-07-21 06:09:07 +00001717 // Register pressure tracking is imprecise. This can happen.
1718 RegPressure[RCId] = 0;
Evan Cheng28590382010-07-21 23:53:58 +00001719 else
1720 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
Evan Chenga77f3d32010-07-21 06:09:07 +00001721 }
1722 }
1723
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001724 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1725 // may transfer data dependencies to CopyToReg.
1726 if (SU->NumSuccs && N->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001727 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1728 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1729 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00001730 if (VT == MVT::Glue || VT == MVT::Other)
Evan Chengdf907f42010-07-23 22:39:59 +00001731 continue;
1732 if (!N->hasAnyUseOfValue(i))
1733 continue;
1734 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1735 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1736 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001737 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001738
Evan Chenga77f3d32010-07-21 06:09:07 +00001739 dumpRegPressure();
1740 }
1741
Andrew Trick2085a962010-12-21 22:25:04 +00001742 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1743 scheduleDAG = scheduleDag;
Dan Gohman3f656df2008-11-20 02:45:51 +00001744 }
1745
Evan Chenga77f3d32010-07-21 06:09:07 +00001746 void dumpRegPressure() const {
1747 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1748 E = TRI->regclass_end(); I != E; ++I) {
1749 const TargetRegisterClass *RC = *I;
1750 unsigned Id = RC->getID();
1751 unsigned RP = RegPressure[Id];
1752 if (!RP) continue;
1753 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1754 << '\n');
1755 }
1756 }
1757
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001758 void dump(ScheduleDAG *DAG) const {
1759 // Emulate pop() without clobbering NodeQueueIds.
1760 std::vector<SUnit*> DumpQueue = Queue;
1761 SF DumpPicker = Picker;
1762 while (!DumpQueue.empty()) {
1763 SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1764 if (isBottomUp())
1765 dbgs() << "Height " << SU->getHeight() << ": ";
1766 else
1767 dbgs() << "Depth " << SU->getDepth() << ": ";
1768 SU->dump(DAG);
1769 }
1770 }
1771
Dan Gohman3f656df2008-11-20 02:45:51 +00001772 protected:
1773 bool canClobber(const SUnit *SU, const SUnit *Op);
1774 void AddPseudoTwoAddrDeps();
Dan Gohman9a658d72009-03-24 00:49:12 +00001775 void PrescheduleNodesWithMultipleUses();
Evan Cheng6730f032007-01-08 23:55:53 +00001776 void CalculateSethiUllmanNumbers();
Evan Cheng7e4abde2008-07-02 09:23:51 +00001777 };
1778
Dan Gohman186f65d2008-11-20 03:30:37 +00001779 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1780 BURegReductionPriorityQueue;
Evan Cheng7e4abde2008-07-02 09:23:51 +00001781
Dan Gohman186f65d2008-11-20 03:30:37 +00001782 typedef RegReductionPriorityQueue<td_ls_rr_sort>
1783 TDRegReductionPriorityQueue;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001784
1785 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1786 SrcRegReductionPriorityQueue;
Evan Chengbdd062d2010-05-20 06:13:19 +00001787
1788 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1789 HybridBURRPriorityQueue;
Evan Cheng37b740c2010-07-24 00:39:05 +00001790
1791 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1792 ILPBURRPriorityQueue;
Evan Chengd38c22b2006-05-11 23:55:42 +00001793}
1794
Evan Chengb9e3db62007-03-14 22:43:40 +00001795/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00001796/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00001797static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001798 unsigned MaxHeight = 0;
Evan Cheng28748552007-03-13 23:25:11 +00001799 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00001800 I != E; ++I) {
Evan Chengce3bbe52009-02-10 08:30:11 +00001801 if (I->isCtrl()) continue; // ignore chain succs
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001802 unsigned Height = I->getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00001803 // If there are bunch of CopyToRegs stacked up, they should be considered
1804 // to be at the same position.
Dan Gohman2d170892008-12-09 22:54:47 +00001805 if (I->getSUnit()->getNode() &&
1806 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001807 Height = closestSucc(I->getSUnit())+1;
1808 if (Height > MaxHeight)
1809 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00001810 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001811 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00001812}
1813
Evan Cheng61bc51e2007-12-20 02:22:36 +00001814/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00001815/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00001816static unsigned calcMaxScratches(const SUnit *SU) {
1817 unsigned Scratches = 0;
1818 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Chengb5704992009-02-12 09:52:13 +00001819 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001820 if (I->isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00001821 Scratches++;
1822 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00001823 return Scratches;
1824}
1825
Evan Cheng6c1414f2010-10-29 18:09:28 +00001826/// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
1827/// CopyToReg to a virtual register. This SU def is probably a liveout and
1828/// it has no other use. It should be scheduled closer to the terminator.
1829static bool hasOnlyLiveOutUses(const SUnit *SU) {
1830 bool RetVal = false;
1831 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1832 I != E; ++I) {
1833 if (I->isCtrl()) continue;
1834 const SUnit *SuccSU = I->getSUnit();
1835 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
1836 unsigned Reg =
1837 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
1838 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1839 RetVal = true;
1840 continue;
1841 }
1842 }
1843 return false;
1844 }
1845 return RetVal;
1846}
1847
1848/// UnitsSharePred - Return true if the two scheduling units share a common
1849/// data predecessor.
1850static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
1851 SmallSet<const SUnit*, 4> Preds;
1852 for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
1853 I != E; ++I) {
1854 if (I->isCtrl()) continue; // ignore chain preds
1855 Preds.insert(I->getSUnit());
1856 }
1857 for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
1858 I != E; ++I) {
1859 if (I->isCtrl()) continue; // ignore chain preds
1860 if (Preds.count(I->getSUnit()))
1861 return true;
1862 }
1863 return false;
1864}
1865
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001866template <typename RRSort>
1867static bool BURRSort(const SUnit *left, const SUnit *right,
1868 const RegReductionPriorityQueue<RRSort> *SPQ) {
Evan Cheng6730f032007-01-08 23:55:53 +00001869 unsigned LPriority = SPQ->getNodePriority(left);
1870 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng73bdf042008-03-01 00:39:47 +00001871 if (LPriority != RPriority)
1872 return LPriority > RPriority;
1873
1874 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1875 // e.g.
1876 // t1 = op t2, c1
1877 // t3 = op t4, c2
1878 //
1879 // and the following instructions are both ready.
1880 // t2 = op c3
1881 // t4 = op c4
1882 //
1883 // Then schedule t2 = op first.
1884 // i.e.
1885 // t4 = op c4
1886 // t2 = op c3
1887 // t1 = op t2, c1
1888 // t3 = op t4, c2
1889 //
1890 // This creates more short live intervals.
1891 unsigned LDist = closestSucc(left);
1892 unsigned RDist = closestSucc(right);
1893 if (LDist != RDist)
1894 return LDist < RDist;
1895
Evan Cheng3a14efa2009-02-12 08:59:45 +00001896 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00001897 unsigned LScratch = calcMaxScratches(left);
1898 unsigned RScratch = calcMaxScratches(right);
1899 if (LScratch != RScratch)
1900 return LScratch > RScratch;
1901
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001902 // Note: with a bottom-up ready filter, the height check may be redundant.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001903 if (left->getHeight() != right->getHeight())
1904 return left->getHeight() > right->getHeight();
Andrew Trick2085a962010-12-21 22:25:04 +00001905
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001906 if (left->getDepth() != right->getDepth())
1907 return left->getDepth() < right->getDepth();
Evan Cheng73bdf042008-03-01 00:39:47 +00001908
Andrew Trick2085a962010-12-21 22:25:04 +00001909 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00001910 "NodeQueueId cannot be zero");
1911 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00001912}
1913
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001914// Bottom up
1915bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1916 return BURRSort(left, right, SPQ);
1917}
1918
1919// Source order, otherwise bottom up.
Evan Chengbdd062d2010-05-20 06:13:19 +00001920bool src_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001921 unsigned LOrder = SPQ->getNodeOrdering(left);
1922 unsigned ROrder = SPQ->getNodeOrdering(right);
1923
1924 // Prefer an ordering where the lower the non-zero order number, the higher
1925 // the preference.
1926 if ((LOrder || ROrder) && LOrder != ROrder)
1927 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
1928
1929 return BURRSort(left, right, SPQ);
1930}
1931
Evan Chengbdd062d2010-05-20 06:13:19 +00001932bool hybrid_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const{
Evan Chengdebf9c52010-11-03 00:45:17 +00001933 if (left->isCall || right->isCall)
1934 // No way to compute latency of calls.
1935 return BURRSort(left, right, SPQ);
1936
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001937 bool LHigh = SPQ->HighRegPressure(left);
1938 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00001939 // Avoid causing spills. If register pressure is high, schedule for
1940 // register pressure reduction.
Evan Cheng28590382010-07-21 23:53:58 +00001941 if (LHigh && !RHigh)
1942 return true;
1943 else if (!LHigh && RHigh)
1944 return false;
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001945 else if (!LHigh && !RHigh) {
Evan Cheng6c1414f2010-10-29 18:09:28 +00001946 // If the two nodes share an operand and one of them has a single
1947 // use that is a live out copy, favor the one that is live out. Otherwise
1948 // it will be difficult to eliminate the copy if the instruction is a
1949 // loop induction variable update. e.g.
1950 // BB:
1951 // sub r1, r3, #1
1952 // str r0, [r2, r3]
1953 // mov r3, r1
1954 // cmp
1955 // bne BB
1956 bool SharePred = UnitsSharePred(left, right);
1957 // FIXME: Only adjust if BB is a loop back edge.
1958 // FIXME: What's the cost of a copy?
1959 int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
1960 int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
1961 int LHeight = (int)left->getHeight() - LBonus;
1962 int RHeight = (int)right->getHeight() - RBonus;
1963
Evan Cheng28590382010-07-21 23:53:58 +00001964 // Low register pressure situation, schedule for latency if possible.
1965 bool LStall = left->SchedulingPref == Sched::Latency &&
Evan Cheng6c1414f2010-10-29 18:09:28 +00001966 (int)SPQ->getCurCycle() < LHeight;
Evan Cheng28590382010-07-21 23:53:58 +00001967 bool RStall = right->SchedulingPref == Sched::Latency &&
Evan Cheng6c1414f2010-10-29 18:09:28 +00001968 (int)SPQ->getCurCycle() < RHeight;
Evan Cheng28590382010-07-21 23:53:58 +00001969 // If scheduling one of the node will cause a pipeline stall, delay it.
1970 // If scheduling either one of the node will cause a pipeline stall, sort
1971 // them according to their height.
Evan Cheng28590382010-07-21 23:53:58 +00001972 if (LStall) {
1973 if (!RStall)
1974 return true;
Evan Cheng6c1414f2010-10-29 18:09:28 +00001975 if (LHeight != RHeight)
1976 return LHeight > RHeight;
Evan Cheng28590382010-07-21 23:53:58 +00001977 } else if (RStall)
Evan Chengbdd062d2010-05-20 06:13:19 +00001978 return false;
Evan Chengcc2efe12010-05-28 23:26:21 +00001979
Evan Cheng6c1414f2010-10-29 18:09:28 +00001980 // If either node is scheduling for latency, sort them by height
1981 // and latency.
Evan Cheng28590382010-07-21 23:53:58 +00001982 if (left->SchedulingPref == Sched::Latency ||
1983 right->SchedulingPref == Sched::Latency) {
Evan Cheng6c1414f2010-10-29 18:09:28 +00001984 if (LHeight != RHeight)
1985 return LHeight > RHeight;
Evan Cheng28590382010-07-21 23:53:58 +00001986 if (left->Latency != right->Latency)
1987 return left->Latency > right->Latency;
1988 }
Evan Chengcc2efe12010-05-28 23:26:21 +00001989 }
1990
Evan Chengbdd062d2010-05-20 06:13:19 +00001991 return BURRSort(left, right, SPQ);
1992}
1993
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001994// Schedule as many instructions in each cycle as possible. So don't make an
1995// instruction available unless it is ready in the current cycle.
1996bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
1997 return SU->getHeight() <= CurCycle;
1998}
1999
Evan Cheng37b740c2010-07-24 00:39:05 +00002000bool ilp_ls_rr_sort::operator()(const SUnit *left,
2001 const SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002002 if (left->isCall || right->isCall)
2003 // No way to compute latency of calls.
2004 return BURRSort(left, right, SPQ);
2005
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002006 bool LHigh = SPQ->HighRegPressure(left);
2007 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002008 // Avoid causing spills. If register pressure is high, schedule for
2009 // register pressure reduction.
2010 if (LHigh && !RHigh)
2011 return true;
2012 else if (!LHigh && RHigh)
2013 return false;
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002014 else if (!LHigh && !RHigh) {
Evan Cheng8ae3eca2010-07-25 18:59:43 +00002015 // Low register pressure situation, schedule to maximize instruction level
2016 // parallelism.
Evan Cheng37b740c2010-07-24 00:39:05 +00002017 if (left->NumPreds > right->NumPreds)
2018 return false;
2019 else if (left->NumPreds < right->NumPreds)
2020 return false;
2021 }
2022
2023 return BURRSort(left, right, SPQ);
2024}
2025
Dan Gohman3f656df2008-11-20 02:45:51 +00002026template<class SF>
Evan Cheng7e4abde2008-07-02 09:23:51 +00002027bool
Dan Gohman3f656df2008-11-20 02:45:51 +00002028RegReductionPriorityQueue<SF>::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002029 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002030 unsigned Opc = SU->getNode()->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002031 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002032 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002033 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002034 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002035 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002036 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002037 if (DU->getNodeId() != -1 &&
2038 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002039 return true;
2040 }
2041 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002042 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002043 return false;
2044}
2045
Evan Chengf9891412007-12-20 09:25:31 +00002046/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002047/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002048static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002049 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002050 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002051 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002052 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2053 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002054 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002055 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002056 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002057 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002058 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002059 const unsigned *SUImpDefs =
2060 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2061 if (!SUImpDefs)
2062 return false;
2063 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002064 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002065 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002066 continue;
2067 if (!N->hasAnyUseOfValue(i))
2068 continue;
2069 unsigned Reg = ImpDefs[i - NumDefs];
2070 for (;*SUImpDefs; ++SUImpDefs) {
2071 unsigned SUReg = *SUImpDefs;
2072 if (TRI->regsOverlap(Reg, SUReg))
2073 return true;
2074 }
Evan Chengf9891412007-12-20 09:25:31 +00002075 }
2076 }
2077 return false;
2078}
2079
Dan Gohman9a658d72009-03-24 00:49:12 +00002080/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2081/// are not handled well by the general register pressure reduction
2082/// heuristics. When presented with code like this:
2083///
2084/// N
2085/// / |
2086/// / |
2087/// U store
2088/// |
2089/// ...
2090///
2091/// the heuristics tend to push the store up, but since the
2092/// operand of the store has another use (U), this would increase
2093/// the length of that other use (the U->N edge).
2094///
2095/// This function transforms code like the above to route U's
2096/// dependence through the store when possible, like this:
2097///
2098/// N
2099/// ||
2100/// ||
2101/// store
2102/// |
2103/// U
2104/// |
2105/// ...
2106///
2107/// This results in the store being scheduled immediately
2108/// after N, which shortens the U->N live range, reducing
2109/// register pressure.
2110///
2111template<class SF>
2112void RegReductionPriorityQueue<SF>::PrescheduleNodesWithMultipleUses() {
2113 // Visit all the nodes in topological order, working top-down.
2114 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2115 SUnit *SU = &(*SUnits)[i];
2116 // For now, only look at nodes with no data successors, such as stores.
2117 // These are especially important, due to the heuristics in
2118 // getNodePriority for nodes with no data successors.
2119 if (SU->NumSuccs != 0)
2120 continue;
2121 // For now, only look at nodes with exactly one data predecessor.
2122 if (SU->NumPreds != 1)
2123 continue;
2124 // Avoid prescheduling copies to virtual registers, which don't behave
2125 // like other nodes from the perspective of scheduling heuristics.
2126 if (SDNode *N = SU->getNode())
2127 if (N->getOpcode() == ISD::CopyToReg &&
2128 TargetRegisterInfo::isVirtualRegister
2129 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2130 continue;
2131
2132 // Locate the single data predecessor.
2133 SUnit *PredSU = 0;
2134 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2135 EE = SU->Preds.end(); II != EE; ++II)
2136 if (!II->isCtrl()) {
2137 PredSU = II->getSUnit();
2138 break;
2139 }
2140 assert(PredSU);
2141
2142 // Don't rewrite edges that carry physregs, because that requires additional
2143 // support infrastructure.
2144 if (PredSU->hasPhysRegDefs)
2145 continue;
2146 // Short-circuit the case where SU is PredSU's only data successor.
2147 if (PredSU->NumSuccs == 1)
2148 continue;
2149 // Avoid prescheduling to copies from virtual registers, which don't behave
2150 // like other nodes from the perspective of scheduling // heuristics.
2151 if (SDNode *N = SU->getNode())
2152 if (N->getOpcode() == ISD::CopyFromReg &&
2153 TargetRegisterInfo::isVirtualRegister
2154 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2155 continue;
2156
2157 // Perform checks on the successors of PredSU.
2158 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2159 EE = PredSU->Succs.end(); II != EE; ++II) {
2160 SUnit *PredSuccSU = II->getSUnit();
2161 if (PredSuccSU == SU) continue;
2162 // If PredSU has another successor with no data successors, for
2163 // now don't attempt to choose either over the other.
2164 if (PredSuccSU->NumSuccs == 0)
2165 goto outer_loop_continue;
2166 // Don't break physical register dependencies.
2167 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2168 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2169 goto outer_loop_continue;
2170 // Don't introduce graph cycles.
2171 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2172 goto outer_loop_continue;
2173 }
2174
2175 // Ok, the transformation is safe and the heuristics suggest it is
2176 // profitable. Update the graph.
Evan Chengbdd062d2010-05-20 06:13:19 +00002177 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2178 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002179 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002180 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2181 SDep Edge = PredSU->Succs[i];
2182 assert(!Edge.isAssignedRegDep());
2183 SUnit *SuccSU = Edge.getSUnit();
2184 if (SuccSU != SU) {
2185 Edge.setSUnit(PredSU);
2186 scheduleDAG->RemovePred(SuccSU, Edge);
2187 scheduleDAG->AddPred(SU, Edge);
2188 Edge.setSUnit(SU);
2189 scheduleDAG->AddPred(SuccSU, Edge);
2190 --i;
2191 }
2192 }
2193 outer_loop_continue:;
2194 }
2195}
2196
Evan Chengd38c22b2006-05-11 23:55:42 +00002197/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2198/// it as a def&use operand. Add a pseudo control edge from it to the other
2199/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002200/// first (lower in the schedule). If both nodes are two-address, favor the
2201/// one that has a CopyToReg use (more likely to be a loop induction update).
2202/// If both are two-address, but one is commutable while the other is not
2203/// commutable, favor the one that's not commutable.
Dan Gohman3f656df2008-11-20 02:45:51 +00002204template<class SF>
2205void RegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002206 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
Dan Gohmane955c482008-08-05 14:45:15 +00002207 SUnit *SU = &(*SUnits)[i];
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002208 if (!SU->isTwoAddress)
2209 continue;
2210
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002211 SDNode *Node = SU->getNode();
Chris Lattner11a33812010-12-23 17:24:32 +00002212 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002213 continue;
2214
Evan Cheng6c1414f2010-10-29 18:09:28 +00002215 bool isLiveOut = hasOnlyLiveOutUses(SU);
Dan Gohman17059682008-07-17 19:10:17 +00002216 unsigned Opc = Node->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002217 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002218 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002219 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002220 for (unsigned j = 0; j != NumOps; ++j) {
Dan Gohman82016c22008-11-19 02:00:32 +00002221 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2222 continue;
2223 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2224 if (DU->getNodeId() == -1)
2225 continue;
2226 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2227 if (!DUSU) continue;
2228 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2229 E = DUSU->Succs.end(); I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002230 if (I->isCtrl()) continue;
2231 SUnit *SuccSU = I->getSUnit();
Dan Gohman82016c22008-11-19 02:00:32 +00002232 if (SuccSU == SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002233 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002234 // Be conservative. Ignore if nodes aren't at roughly the same
2235 // depth and height.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002236 if (SuccSU->getHeight() < SU->getHeight() &&
2237 (SU->getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002238 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002239 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2240 // constrains whatever is using the copy, instead of the copy
2241 // itself. In the case that the copy is coalesced, this
2242 // preserves the intent of the pseudo two-address heurietics.
2243 while (SuccSU->Succs.size() == 1 &&
2244 SuccSU->getNode()->isMachineOpcode() &&
2245 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002246 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002247 SuccSU = SuccSU->Succs.front().getSUnit();
2248 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002249 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2250 continue;
2251 // Don't constrain nodes with physical register defs if the
2252 // predecessor can clobber them.
Dan Gohmanf3746cb2009-03-24 00:50:07 +00002253 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
Dan Gohman82016c22008-11-19 02:00:32 +00002254 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002255 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002256 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002257 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2258 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002259 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002260 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2261 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2262 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002263 continue;
2264 if ((!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002265 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Dan Gohman82016c22008-11-19 02:00:32 +00002266 (!SU->isCommutable && SuccSU->isCommutable)) &&
2267 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002268 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002269 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
Dan Gohman79c35162009-01-06 01:19:04 +00002270 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
Dan Gohmanbf8e5202009-01-06 01:28:56 +00002271 /*Reg=*/0, /*isNormalMemory=*/false,
2272 /*isMustAlias=*/false,
Dan Gohman2d170892008-12-09 22:54:47 +00002273 /*isArtificial=*/true));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002274 }
2275 }
2276 }
2277 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002278}
2279
Evan Cheng6730f032007-01-08 23:55:53 +00002280/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
2281/// scheduling units.
Dan Gohman186f65d2008-11-20 03:30:37 +00002282template<class SF>
2283void RegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
Evan Chengd38c22b2006-05-11 23:55:42 +00002284 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick2085a962010-12-21 22:25:04 +00002285
Evan Chengd38c22b2006-05-11 23:55:42 +00002286 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
Dan Gohman186f65d2008-11-20 03:30:37 +00002287 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002288}
Evan Chengd38c22b2006-05-11 23:55:42 +00002289
Roman Levenstein30d09512008-03-27 09:44:37 +00002290/// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
Roman Levensteinbc674502008-03-27 09:14:57 +00002291/// predecessors of the successors of the SUnit SU. Stop when the provided
2292/// limit is exceeded.
Andrew Trick2085a962010-12-21 22:25:04 +00002293static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
Roman Levensteinbc674502008-03-27 09:14:57 +00002294 unsigned Limit) {
2295 unsigned Sum = 0;
2296 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2297 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002298 const SUnit *SuccSU = I->getSUnit();
Roman Levensteinbc674502008-03-27 09:14:57 +00002299 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2300 EE = SuccSU->Preds.end(); II != EE; ++II) {
Dan Gohman2d170892008-12-09 22:54:47 +00002301 SUnit *PredSU = II->getSUnit();
Evan Cheng16d72072008-03-29 18:34:22 +00002302 if (!PredSU->isScheduled)
2303 if (++Sum > Limit)
2304 return Sum;
Roman Levensteinbc674502008-03-27 09:14:57 +00002305 }
2306 }
2307 return Sum;
2308}
2309
Evan Chengd38c22b2006-05-11 23:55:42 +00002310
2311// Top down
2312bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Evan Cheng6730f032007-01-08 23:55:53 +00002313 unsigned LPriority = SPQ->getNodePriority(left);
2314 unsigned RPriority = SPQ->getNodePriority(right);
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002315 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2316 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00002317 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2318 bool RIsFloater = RIsTarget && right->NumPreds == 0;
Roman Levensteinbc674502008-03-27 09:14:57 +00002319 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2320 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00002321
2322 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2323 return false;
2324 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2325 return true;
2326
Evan Chengd38c22b2006-05-11 23:55:42 +00002327 if (LIsFloater)
2328 LBonus -= 2;
2329 if (RIsFloater)
2330 RBonus -= 2;
2331 if (left->NumSuccs == 1)
2332 LBonus += 2;
2333 if (right->NumSuccs == 1)
2334 RBonus += 2;
2335
Evan Cheng73bdf042008-03-01 00:39:47 +00002336 if (LPriority+LBonus != RPriority+RBonus)
2337 return LPriority+LBonus < RPriority+RBonus;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00002338
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002339 if (left->getDepth() != right->getDepth())
2340 return left->getDepth() < right->getDepth();
Evan Cheng73bdf042008-03-01 00:39:47 +00002341
2342 if (left->NumSuccsLeft != right->NumSuccsLeft)
2343 return left->NumSuccsLeft > right->NumSuccsLeft;
2344
Andrew Trick2085a962010-12-21 22:25:04 +00002345 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002346 "NodeQueueId cannot be zero");
2347 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002348}
2349
Evan Chengd38c22b2006-05-11 23:55:42 +00002350//===----------------------------------------------------------------------===//
2351// Public Constructor Functions
2352//===----------------------------------------------------------------------===//
2353
Dan Gohmandfaf6462009-02-11 04:27:20 +00002354llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002355llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2356 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002357 const TargetMachine &TM = IS->TM;
2358 const TargetInstrInfo *TII = TM.getInstrInfo();
2359 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002360
Evan Chenga77f3d32010-07-21 06:09:07 +00002361 BURegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002362 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002363 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002364 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002365 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002366}
2367
Dan Gohmandfaf6462009-02-11 04:27:20 +00002368llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002369llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2370 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002371 const TargetMachine &TM = IS->TM;
2372 const TargetInstrInfo *TII = TM.getInstrInfo();
2373 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002374
Evan Chenga77f3d32010-07-21 06:09:07 +00002375 TDRegReductionPriorityQueue *PQ =
2376 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002377 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Dan Gohman3f656df2008-11-20 02:45:51 +00002378 PQ->setScheduleDAG(SD);
2379 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002380}
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002381
2382llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002383llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2384 CodeGenOpt::Level OptLevel) {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002385 const TargetMachine &TM = IS->TM;
2386 const TargetInstrInfo *TII = TM.getInstrInfo();
2387 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002388
Evan Chenga77f3d32010-07-21 06:09:07 +00002389 SrcRegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002390 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002391 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002392 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002393 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002394}
2395
2396llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002397llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2398 CodeGenOpt::Level OptLevel) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002399 const TargetMachine &TM = IS->TM;
2400 const TargetInstrInfo *TII = TM.getInstrInfo();
2401 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Evan Chenga77f3d32010-07-21 06:09:07 +00002402 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002403
Evan Chenga77f3d32010-07-21 06:09:07 +00002404 HybridBURRPriorityQueue *PQ =
Evan Chengdf907f42010-07-23 22:39:59 +00002405 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002406
2407 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002408 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002409 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002410}
Evan Cheng37b740c2010-07-24 00:39:05 +00002411
2412llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002413llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2414 CodeGenOpt::Level OptLevel) {
Evan Cheng37b740c2010-07-24 00:39:05 +00002415 const TargetMachine &TM = IS->TM;
2416 const TargetInstrInfo *TII = TM.getInstrInfo();
2417 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2418 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002419
Evan Cheng37b740c2010-07-24 00:39:05 +00002420 ILPBURRPriorityQueue *PQ =
2421 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002422 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00002423 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002424 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00002425}