blob: d6368047bcd1966d33a982d8acdfb4a5b71d69e4 [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) {
Andrew Trickc9405662010-12-24 06:46:50 +0000438 if (!EnableSchedCycles || HazardRec->getMaxLookAhead() == 0)
439 return;
440
441 // Check for phys reg copy.
442 if (!SU->getNode())
443 return;
444
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000445 switch (SU->getNode()->getOpcode()) {
446 default:
447 assert(SU->getNode()->isMachineOpcode() &&
448 "This target-independent node should not be scheduled.");
449 break;
450 case ISD::MERGE_VALUES:
451 case ISD::TokenFactor:
452 case ISD::CopyToReg:
453 case ISD::CopyFromReg:
454 case ISD::EH_LABEL:
455 // Noops don't affect the scoreboard state. Copies are likely to be
456 // removed.
457 return;
458 case ISD::INLINEASM:
459 // For inline asm, clear the pipeline state.
460 HazardRec->Reset();
461 return;
462 }
463 if (isBottomUp && SU->isCall) {
464 // Calls are scheduled with their preceding instructions. For bottom-up
465 // scheduling, clear the pipeline state before emitting.
466 HazardRec->Reset();
467 }
468
469 HazardRec->EmitInstruction(SU);
470
471 if (!isBottomUp && SU->isCall) {
472 HazardRec->Reset();
473 }
474}
475
Dan Gohmanb9543432009-02-10 23:27:53 +0000476/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
477/// count of its predecessors. If a predecessor pending count is zero, add it to
478/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000479void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Evan Chengbdd062d2010-05-20 06:13:19 +0000480 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000481 DEBUG(SU->dump(this));
482
Evan Chengbdd062d2010-05-20 06:13:19 +0000483#ifndef NDEBUG
484 if (CurCycle < SU->getHeight())
485 DEBUG(dbgs() << " Height [" << SU->getHeight() << "] pipeline stall!\n");
486#endif
487
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000488 // FIXME: Do not modify node height. It may interfere with
489 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
490 // node it's ready cycle can aid heuristics, and after scheduling it can
491 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000492 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000493
494 // Reserve resources for the scheduled intruction.
495 EmitNode(SU);
496
Dan Gohmanb9543432009-02-10 23:27:53 +0000497 Sequence.push_back(SU);
498
Evan Cheng28590382010-07-21 23:53:58 +0000499 AvailableQueue->ScheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000500
Andrew Trick033efdf2010-12-23 03:15:51 +0000501 // Update liveness of predecessors before successors to avoid treating a
502 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000503 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000504
505 // Release all the implicit physical register defs that are live.
506 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
507 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000508 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
509 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
510 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
511 --NumLiveRegs;
512 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000513 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000514 }
515 }
516
Evan Chengd38c22b2006-05-11 23:55:42 +0000517 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000518
519 // Conditions under which the scheduler should eagerly advance the cycle:
520 // (1) No available instructions
521 // (2) All pipelines full, so available instructions must have hazards.
522 //
523 // If SchedCycles is disabled, count each inst as one cycle.
524 if (!EnableSchedCycles ||
525 AvailableQueue->empty() || HazardRec->atIssueLimit())
526 AdvanceToCycle(CurCycle + 1);
Evan Chengd38c22b2006-05-11 23:55:42 +0000527}
528
Evan Cheng5924bf72007-09-25 01:54:36 +0000529/// CapturePred - This does the opposite of ReleasePred. Since SU is being
530/// unscheduled, incrcease the succ left count of its predecessors. Remove
531/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000532void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000533 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000534 if (PredSU->isAvailable) {
535 PredSU->isAvailable = false;
536 if (!PredSU->isPending)
537 AvailableQueue->remove(PredSU);
538 }
539
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000540 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000541 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000542}
543
544/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
545/// its predecessor states to reflect the change.
546void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000547 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000548 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000549
Evan Cheng5924bf72007-09-25 01:54:36 +0000550 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
551 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000552 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000553 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000554 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000555 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000556 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000557 --NumLiveRegs;
Dan Gohman2d170892008-12-09 22:54:47 +0000558 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000559 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000560 }
561 }
562
563 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
564 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000565 if (I->isAssignedRegDep()) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000566 // This becomes the nearest def. Note that an earlier def may still be
567 // pending if this is a two-address node.
568 LiveRegDefs[I->getReg()] = SU;
Dan Gohman2d170892008-12-09 22:54:47 +0000569 if (!LiveRegDefs[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000570 ++NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000571 }
Andrew Tricka52f3252010-12-23 04:16:14 +0000572 if (LiveRegGens[I->getReg()] == NULL ||
573 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
574 LiveRegGens[I->getReg()] = I->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000575 }
576 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000577 if (SU->getHeight() < MinAvailableCycle)
578 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000579
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000580 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000581 SU->isScheduled = false;
582 SU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000583 if (EnableSchedCycles && AvailableQueue->hasReadyFilter()) {
584 // Don't make available until backtracking is complete.
585 SU->isPending = true;
586 PendingQueue.push_back(SU);
587 }
588 else {
589 AvailableQueue->push(SU);
590 }
Evan Cheng28590382010-07-21 23:53:58 +0000591 AvailableQueue->UnscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000592}
593
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000594/// After backtracking, the hazard checker needs to be restored to a state
595/// corresponding the the current cycle.
596void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
597 HazardRec->Reset();
598
599 unsigned LookAhead = std::min((unsigned)Sequence.size(),
600 HazardRec->getMaxLookAhead());
601 if (LookAhead == 0)
602 return;
603
604 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
605 unsigned HazardCycle = (*I)->getHeight();
606 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
607 SUnit *SU = *I;
608 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
609 HazardRec->RecedeCycle();
610 }
611 EmitNode(SU);
612 }
613}
614
Evan Cheng8e136a92007-09-26 21:36:17 +0000615/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000616/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000617void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
618 SUnit *OldSU = Sequence.back();
619 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000620 Sequence.pop_back();
621 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000622 // Don't try to remove SU from AvailableQueue.
623 SU->isAvailable = false;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000624 // FIXME: use ready cycle instead of height
625 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000626 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000627 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000628 if (OldSU == BtSU)
629 break;
630 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000631 }
632
Dan Gohman60d68442009-01-29 19:49:27 +0000633 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000634
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000635 RestoreHazardCheckerBottomUp();
636
637 if (EnableSchedCycles)
638 ReleasePending();
639
Evan Cheng1ec79b42007-09-27 07:09:03 +0000640 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000641}
642
Evan Cheng3b245872010-02-05 01:27:11 +0000643static bool isOperandOf(const SUnit *SU, SDNode *N) {
644 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000645 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000646 if (SUNode->isOperandOf(N))
647 return true;
648 }
649 return false;
650}
651
Evan Cheng5924bf72007-09-25 01:54:36 +0000652/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
653/// successors to the newly created node.
654SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000655 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000656 if (!N)
657 return NULL;
658
Andrew Trickc9405662010-12-24 06:46:50 +0000659 if (SU->getNode()->getGluedNode())
660 return NULL;
661
Evan Cheng79e97132007-10-05 01:39:18 +0000662 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000663 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000664 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000665 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000666 if (VT == MVT::Glue)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000667 return NULL;
Owen Anderson9f944592009-08-11 20:47:22 +0000668 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000669 TryUnfold = true;
670 }
Evan Cheng79e97132007-10-05 01:39:18 +0000671 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000672 const SDValue &Op = N->getOperand(i);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000673 EVT VT = Op.getNode()->getValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000674 if (VT == MVT::Glue)
Evan Cheng79e97132007-10-05 01:39:18 +0000675 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000676 }
677
678 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000679 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000680 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000681 return NULL;
682
Evan Chengbdd062d2010-05-20 06:13:19 +0000683 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000684 assert(NewNodes.size() == 2 && "Expected a load folding node!");
685
686 N = NewNodes[1];
687 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000688 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000689 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000690 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000691 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
692 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000693 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000694
Dan Gohmane52e0892008-11-11 21:34:44 +0000695 // LoadNode may already exist. This can happen when there is another
696 // load from the same location and producing the same type of value
697 // but it has different alignment or volatileness.
698 bool isNewLoad = true;
699 SUnit *LoadSU;
700 if (LoadNode->getNodeId() != -1) {
701 LoadSU = &SUnits[LoadNode->getNodeId()];
702 isNewLoad = false;
703 } else {
704 LoadSU = CreateNewSUnit(LoadNode);
705 LoadNode->setNodeId(LoadSU->NodeNum);
Dan Gohmane52e0892008-11-11 21:34:44 +0000706 ComputeLatency(LoadSU);
707 }
708
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000709 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000710 assert(N->getNodeId() == -1 && "Node already inserted!");
711 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +0000712
Dan Gohman17059682008-07-17 19:10:17 +0000713 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Dan Gohman856c0122008-02-16 00:25:40 +0000714 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000715 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000716 NewSU->isTwoAddress = true;
717 break;
718 }
719 }
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000720 if (TID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000721 NewSU->isCommutable = true;
Evan Cheng79e97132007-10-05 01:39:18 +0000722 ComputeLatency(NewSU);
723
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000724 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +0000725 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +0000726 SmallVector<SDep, 4> ChainSuccs;
727 SmallVector<SDep, 4> LoadPreds;
728 SmallVector<SDep, 4> NodePreds;
729 SmallVector<SDep, 4> NodeSuccs;
730 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
731 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000732 if (I->isCtrl())
Dan Gohman15af5522009-03-06 02:23:01 +0000733 ChainPreds.push_back(*I);
Evan Cheng3b245872010-02-05 01:27:11 +0000734 else if (isOperandOf(I->getSUnit(), LoadNode))
Dan Gohman2d170892008-12-09 22:54:47 +0000735 LoadPreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000736 else
Dan Gohman2d170892008-12-09 22:54:47 +0000737 NodePreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000738 }
739 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
740 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000741 if (I->isCtrl())
742 ChainSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000743 else
Dan Gohman2d170892008-12-09 22:54:47 +0000744 NodeSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000745 }
746
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000747 // Now assign edges to the newly-created nodes.
Dan Gohman15af5522009-03-06 02:23:01 +0000748 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
749 const SDep &Pred = ChainPreds[i];
750 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +0000751 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +0000752 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000753 }
Evan Cheng79e97132007-10-05 01:39:18 +0000754 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000755 const SDep &Pred = LoadPreds[i];
756 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +0000757 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +0000758 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000759 }
760 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000761 const SDep &Pred = NodePreds[i];
762 RemovePred(SU, Pred);
763 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000764 }
765 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000766 SDep D = NodeSuccs[i];
767 SUnit *SuccDep = D.getSUnit();
768 D.setSUnit(SU);
769 RemovePred(SuccDep, D);
770 D.setSUnit(NewSU);
771 AddPred(SuccDep, D);
Evan Cheng79e97132007-10-05 01:39:18 +0000772 }
773 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000774 SDep D = ChainSuccs[i];
775 SUnit *SuccDep = D.getSUnit();
776 D.setSUnit(SU);
777 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000778 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +0000779 D.setSUnit(LoadSU);
780 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000781 }
Andrew Trick2085a962010-12-21 22:25:04 +0000782 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000783
784 // Add a data dependency to reflect that NewSU reads the value defined
785 // by LoadSU.
786 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
Evan Cheng79e97132007-10-05 01:39:18 +0000787
Evan Cheng91e0fc92007-12-18 08:42:10 +0000788 if (isNewLoad)
789 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000790 AvailableQueue->addNode(NewSU);
791
792 ++NumUnfolds;
793
794 if (NewSU->NumSuccsLeft == 0) {
795 NewSU->isAvailable = true;
796 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +0000797 }
798 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000799 }
800
Evan Chengbdd062d2010-05-20 06:13:19 +0000801 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000802 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000803
804 // New SUnit has the exact same predecessors.
805 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
806 I != E; ++I)
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000807 if (!I->isArtificial())
Dan Gohman2d170892008-12-09 22:54:47 +0000808 AddPred(NewSU, *I);
Evan Cheng5924bf72007-09-25 01:54:36 +0000809
810 // Only copy scheduled successors. Cut them from old node's successor
811 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000812 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +0000813 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
814 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000815 if (I->isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +0000816 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000817 SUnit *SuccSU = I->getSUnit();
818 if (SuccSU->isScheduled) {
Dan Gohman2d170892008-12-09 22:54:47 +0000819 SDep D = *I;
820 D.setSUnit(NewSU);
821 AddPred(SuccSU, D);
822 D.setSUnit(SU);
823 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +0000824 }
825 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000826 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000827 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng5924bf72007-09-25 01:54:36 +0000828
829 AvailableQueue->updateNode(SU);
830 AvailableQueue->addNode(NewSU);
831
Evan Cheng1ec79b42007-09-27 07:09:03 +0000832 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000833 return NewSU;
834}
835
Evan Chengb2c42c62009-01-12 03:19:55 +0000836/// InsertCopiesAndMoveSuccs - Insert register copies and move all
837/// scheduled successors of the given SUnit to the last copy.
838void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
839 const TargetRegisterClass *DestRC,
840 const TargetRegisterClass *SrcRC,
Evan Cheng1ec79b42007-09-27 07:09:03 +0000841 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000842 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000843 CopyFromSU->CopySrcRC = SrcRC;
844 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +0000845
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000846 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000847 CopyToSU->CopySrcRC = DestRC;
848 CopyToSU->CopyDstRC = SrcRC;
849
850 // Only copy scheduled successors. Cut them from old node's successor
851 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000852 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +0000853 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
854 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000855 if (I->isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +0000856 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000857 SUnit *SuccSU = I->getSUnit();
858 if (SuccSU->isScheduled) {
859 SDep D = *I;
860 D.setSUnit(CopyToSU);
861 AddPred(SuccSU, D);
862 DelDeps.push_back(std::make_pair(SuccSU, *I));
Evan Cheng8e136a92007-09-26 21:36:17 +0000863 }
864 }
Evan Chengb2c42c62009-01-12 03:19:55 +0000865 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000866 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng8e136a92007-09-26 21:36:17 +0000867
Dan Gohman2d170892008-12-09 22:54:47 +0000868 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
869 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
Evan Cheng8e136a92007-09-26 21:36:17 +0000870
871 AvailableQueue->updateNode(SU);
872 AvailableQueue->addNode(CopyFromSU);
873 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000874 Copies.push_back(CopyFromSU);
875 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +0000876
Evan Chengb2c42c62009-01-12 03:19:55 +0000877 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +0000878}
879
880/// getPhysicalRegisterVT - Returns the ValueType of the physical register
881/// definition of the specified node.
882/// FIXME: Move to SelectionDAG?
Owen Anderson53aa7a92009-08-10 22:56:29 +0000883static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +0000884 const TargetInstrInfo *TII) {
Dan Gohman17059682008-07-17 19:10:17 +0000885 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Evan Cheng8e136a92007-09-26 21:36:17 +0000886 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
Chris Lattnerb0d06b42008-01-07 03:13:06 +0000887 unsigned NumRes = TID.getNumDefs();
888 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000889 if (Reg == *ImpDef)
890 break;
891 ++NumRes;
892 }
893 return N->getValueType(NumRes);
894}
895
Evan Chengb8905c42009-03-04 01:41:49 +0000896/// CheckForLiveRegDef - Return true and update live register vector if the
897/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000898static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Evan Chengb8905c42009-03-04 01:41:49 +0000899 std::vector<SUnit*> &LiveRegDefs,
900 SmallSet<unsigned, 4> &RegAdded,
901 SmallVector<unsigned, 4> &LRegs,
902 const TargetRegisterInfo *TRI) {
Andrew Trick12acde112010-12-23 03:43:21 +0000903 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
904
905 // Check if Ref is live.
906 if (!LiveRegDefs[Reg]) continue;
907
908 // Allow multiple uses of the same def.
909 if (LiveRegDefs[Reg] == SU) continue;
910
911 // Add Reg to the set of interfering live regs.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000912 if (RegAdded.insert(Reg))
Evan Chengb8905c42009-03-04 01:41:49 +0000913 LRegs.push_back(Reg);
Evan Chengb8905c42009-03-04 01:41:49 +0000914 }
Evan Chengb8905c42009-03-04 01:41:49 +0000915}
916
Evan Cheng5924bf72007-09-25 01:54:36 +0000917/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
918/// scheduling of the given node to satisfy live physical register dependencies.
919/// If the specific node is the last one that's available to schedule, do
920/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000921bool ScheduleDAGRRList::
922DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000923 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +0000924 return false;
925
Evan Chenge6f92252007-09-27 18:46:06 +0000926 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +0000927 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +0000928 //
929 // If SU is the currently live definition of the same register that it uses,
930 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +0000931 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
932 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +0000933 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Evan Chengb8905c42009-03-04 01:41:49 +0000934 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
935 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +0000936 }
937
Chris Lattner11a33812010-12-23 17:24:32 +0000938 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +0000939 if (Node->getOpcode() == ISD::INLINEASM) {
940 // Inline asm can clobber physical defs.
941 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000942 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +0000943 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +0000944
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000945 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +0000946 unsigned Flags =
947 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000948 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +0000949
950 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000951 if (InlineAsm::isRegDefKind(Flags) ||
952 InlineAsm::isRegDefEarlyClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +0000953 // Check for def of register or earlyclobber register.
954 for (; NumVals; --NumVals, ++i) {
955 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
956 if (TargetRegisterInfo::isPhysicalRegister(Reg))
957 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
958 }
959 } else
960 i += NumVals;
961 }
962 continue;
963 }
964
Dan Gohman072734e2008-11-13 23:24:17 +0000965 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +0000966 continue;
Dan Gohman17059682008-07-17 19:10:17 +0000967 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
Evan Cheng5924bf72007-09-25 01:54:36 +0000968 if (!TID.ImplicitDefs)
969 continue;
Evan Chengb8905c42009-03-04 01:41:49 +0000970 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
971 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +0000972 }
Andrew Trick2085a962010-12-21 22:25:04 +0000973
Evan Cheng5924bf72007-09-25 01:54:36 +0000974 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +0000975}
976
Andrew Trick528fad92010-12-23 05:42:20 +0000977/// Return a node that can be scheduled in this cycle. Requirements:
978/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000979/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +0000980/// (3) No Interferences: may unschedule to break register interferences.
981SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
982 SmallVector<SUnit*, 4> Interferences;
983 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
984
985 SUnit *CurSU = AvailableQueue->pop();
986 while (CurSU) {
987 SmallVector<unsigned, 4> LRegs;
988 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
989 break;
990 LRegsMap.insert(std::make_pair(CurSU, LRegs));
991
992 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
993 Interferences.push_back(CurSU);
994 CurSU = AvailableQueue->pop();
995 }
996 if (CurSU) {
997 // Add the nodes that aren't ready back onto the available list.
998 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
999 Interferences[i]->isPending = false;
1000 assert(Interferences[i]->isAvailable && "must still be available");
1001 AvailableQueue->push(Interferences[i]);
1002 }
1003 return CurSU;
1004 }
1005
1006 // All candidates are delayed due to live physical reg dependencies.
1007 // Try backtracking, code duplication, or inserting cross class copies
1008 // to resolve it.
1009 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1010 SUnit *TrySU = Interferences[i];
1011 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1012
1013 // Try unscheduling up to the point where it's safe to schedule
1014 // this node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001015 SUnit *BtSU = NULL;
1016 unsigned LiveCycle = UINT_MAX;
Andrew Trick528fad92010-12-23 05:42:20 +00001017 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1018 unsigned Reg = LRegs[j];
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001019 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1020 BtSU = LiveRegGens[Reg];
1021 LiveCycle = BtSU->getHeight();
1022 }
Andrew Trick528fad92010-12-23 05:42:20 +00001023 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001024 if (!WillCreateCycle(TrySU, BtSU)) {
1025 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001026
1027 // Force the current node to be scheduled before the node that
1028 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001029 if (BtSU->isAvailable) {
1030 BtSU->isAvailable = false;
1031 if (!BtSU->isPending)
1032 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001033 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001034 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
Andrew Trick528fad92010-12-23 05:42:20 +00001035 /*Reg=*/0, /*isNormalMemory=*/false,
1036 /*isMustAlias=*/false, /*isArtificial=*/true));
1037
1038 // If one or more successors has been unscheduled, then the current
1039 // node is no longer avaialable. Schedule a successor that's now
1040 // available instead.
1041 if (!TrySU->isAvailable) {
1042 CurSU = AvailableQueue->pop();
1043 }
1044 else {
1045 CurSU = TrySU;
1046 TrySU->isPending = false;
1047 Interferences.erase(Interferences.begin()+i);
1048 }
1049 break;
1050 }
1051 }
1052
1053 if (!CurSU) {
1054 // Can't backtrack. If it's too expensive to copy the value, then try
1055 // duplicate the nodes that produces these "too expensive to copy"
1056 // values to break the dependency. In case even that doesn't work,
1057 // insert cross class copies.
1058 // If it's not too expensive, i.e. cost != -1, issue copies.
1059 SUnit *TrySU = Interferences[0];
1060 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1061 assert(LRegs.size() == 1 && "Can't handle this yet!");
1062 unsigned Reg = LRegs[0];
1063 SUnit *LRDef = LiveRegDefs[Reg];
1064 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1065 const TargetRegisterClass *RC =
1066 TRI->getMinimalPhysRegClass(Reg, VT);
1067 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1068
1069 // If cross copy register class is null, then it must be possible copy
1070 // the value directly. Do not try duplicate the def.
1071 SUnit *NewDef = 0;
1072 if (DestRC)
1073 NewDef = CopyAndMoveSuccessors(LRDef);
1074 else
1075 DestRC = RC;
1076 if (!NewDef) {
1077 // Issue copies, these can be expensive cross register class copies.
1078 SmallVector<SUnit*, 2> Copies;
1079 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1080 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1081 << " to SU #" << Copies.front()->NodeNum << "\n");
1082 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1083 /*Reg=*/0, /*isNormalMemory=*/false,
1084 /*isMustAlias=*/false,
1085 /*isArtificial=*/true));
1086 NewDef = Copies.back();
1087 }
1088
1089 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1090 << " to SU #" << TrySU->NodeNum << "\n");
1091 LiveRegDefs[Reg] = NewDef;
1092 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1093 /*Reg=*/0, /*isNormalMemory=*/false,
1094 /*isMustAlias=*/false,
1095 /*isArtificial=*/true));
1096 TrySU->isAvailable = false;
1097 CurSU = NewDef;
1098 }
1099
1100 assert(CurSU && "Unable to resolve live physical register dependencies!");
1101
1102 // Add the nodes that aren't ready back onto the available list.
1103 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1104 Interferences[i]->isPending = false;
1105 // May no longer be available due to backtracking.
1106 if (Interferences[i]->isAvailable) {
1107 AvailableQueue->push(Interferences[i]);
1108 }
1109 }
1110 return CurSU;
1111}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001112
Evan Chengd38c22b2006-05-11 23:55:42 +00001113/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1114/// schedulers.
1115void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001116 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001117 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001118
Evan Chengd38c22b2006-05-11 23:55:42 +00001119 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001120 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001121 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001122 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1123 RootSU->isAvailable = true;
1124 AvailableQueue->push(RootSU);
1125 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001126
1127 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001128 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001129 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001130 while (!AvailableQueue->empty()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001131 DEBUG(dbgs() << "\n*** Examining Available\n";
1132 AvailableQueue->dump(this));
1133
Andrew Trick528fad92010-12-23 05:42:20 +00001134 // Pick the best node to schedule taking all constraints into
1135 // consideration.
1136 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001137
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001138 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001139
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001140 ScheduleNodeBottomUp(SU);
1141
1142 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1143 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1144 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1145 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1146 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001147 }
1148
Evan Chengd38c22b2006-05-11 23:55:42 +00001149 // Reverse the order if it is bottom up.
1150 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001151
Evan Chengd38c22b2006-05-11 23:55:42 +00001152#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001153 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001154#endif
1155}
1156
1157//===----------------------------------------------------------------------===//
1158// Top-Down Scheduling
1159//===----------------------------------------------------------------------===//
1160
1161/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +00001162/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +00001163void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +00001164 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001165
Evan Chengd38c22b2006-05-11 23:55:42 +00001166#ifndef NDEBUG
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001167 if (SuccSU->NumPredsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +00001168 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +00001169 SuccSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +00001170 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +00001171 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +00001172 }
1173#endif
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001174 --SuccSU->NumPredsLeft;
1175
Dan Gohmanb9543432009-02-10 23:27:53 +00001176 // If all the node's predecessors are scheduled, this node is ready
1177 // to be scheduled. Ignore the special ExitSU node.
1178 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001179 SuccSU->isAvailable = true;
1180 AvailableQueue->push(SuccSU);
1181 }
1182}
1183
Dan Gohmanb9543432009-02-10 23:27:53 +00001184void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1185 // Top down: release successors
1186 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1187 I != E; ++I) {
1188 assert(!I->isAssignedRegDep() &&
1189 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1190
1191 ReleaseSucc(SU, &*I);
1192 }
1193}
1194
Evan Chengd38c22b2006-05-11 23:55:42 +00001195/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1196/// count of its successors. If a successor pending count is zero, add it to
1197/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +00001198void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +00001199 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +00001200 DEBUG(SU->dump(this));
Evan Chengd38c22b2006-05-11 23:55:42 +00001201
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001202 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1203 SU->setDepthToAtLeast(CurCycle);
Dan Gohman92a36d72008-11-17 21:31:02 +00001204 Sequence.push_back(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001205
Dan Gohmanb9543432009-02-10 23:27:53 +00001206 ReleaseSuccessors(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001207 SU->isScheduled = true;
Dan Gohman92a36d72008-11-17 21:31:02 +00001208 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001209}
1210
Dan Gohman54a187e2007-08-20 19:28:38 +00001211/// ListScheduleTopDown - The main loop of list scheduling for top-down
1212/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +00001213void ScheduleDAGRRList::ListScheduleTopDown() {
Evan Chengbdd062d2010-05-20 06:13:19 +00001214 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001215
Dan Gohmanb9543432009-02-10 23:27:53 +00001216 // Release any successors of the special Entry node.
1217 ReleaseSuccessors(&EntrySU);
1218
Evan Chengd38c22b2006-05-11 23:55:42 +00001219 // All leaves to Available queue.
1220 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1221 // It is available if it has no predecessors.
Dan Gohman4370f262008-04-15 01:22:18 +00001222 if (SUnits[i].Preds.empty()) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001223 AvailableQueue->push(&SUnits[i]);
1224 SUnits[i].isAvailable = true;
1225 }
1226 }
Andrew Trick2085a962010-12-21 22:25:04 +00001227
Evan Chengd38c22b2006-05-11 23:55:42 +00001228 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001229 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001230 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001231 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +00001232 SUnit *CurSU = AvailableQueue->pop();
Andrew Trick2085a962010-12-21 22:25:04 +00001233
Dan Gohmanc602dd42008-11-21 00:10:42 +00001234 if (CurSU)
Andrew Trick528fad92010-12-23 05:42:20 +00001235 ScheduleNodeTopDown(CurSU);
Dan Gohman4370f262008-04-15 01:22:18 +00001236 ++CurCycle;
Evan Chengbdd062d2010-05-20 06:13:19 +00001237 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001238 }
Andrew Trick2085a962010-12-21 22:25:04 +00001239
Evan Chengd38c22b2006-05-11 23:55:42 +00001240#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001241 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001242#endif
1243}
1244
1245
Evan Chengd38c22b2006-05-11 23:55:42 +00001246//===----------------------------------------------------------------------===//
1247// RegReductionPriorityQueue Implementation
1248//===----------------------------------------------------------------------===//
1249//
1250// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1251// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001252//
Evan Chengd38c22b2006-05-11 23:55:42 +00001253namespace {
1254 template<class SF>
1255 class RegReductionPriorityQueue;
Andrew Trick2085a962010-12-21 22:25:04 +00001256
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001257 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1258 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1259 };
1260
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001261 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1262 // reduction scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001263 struct bu_ls_rr_sort : public queue_sort {
1264 enum {
1265 IsBottomUp = true,
1266 HasReadyFilter = false
1267 };
1268
Evan Chengd38c22b2006-05-11 23:55:42 +00001269 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
1270 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
1271 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick2085a962010-12-21 22:25:04 +00001272
Evan Chengd38c22b2006-05-11 23:55:42 +00001273 bool operator()(const SUnit* left, const SUnit* right) const;
1274 };
1275
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001276 // td_ls_rr_sort - Priority function for top down register pressure reduction
1277 // scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001278 struct td_ls_rr_sort : public queue_sort {
1279 enum {
1280 IsBottomUp = false,
1281 HasReadyFilter = false
1282 };
1283
1284 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
Evan Chengd38c22b2006-05-11 23:55:42 +00001285 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
1286 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick2085a962010-12-21 22:25:04 +00001287
Evan Chengd38c22b2006-05-11 23:55:42 +00001288 bool operator()(const SUnit* left, const SUnit* right) const;
1289 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001290
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001291 // src_ls_rr_sort - Priority function for source order scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001292 struct src_ls_rr_sort : public queue_sort {
1293 enum {
1294 IsBottomUp = true,
1295 HasReadyFilter = false
1296 };
1297
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001298 RegReductionPriorityQueue<src_ls_rr_sort> *SPQ;
1299 src_ls_rr_sort(RegReductionPriorityQueue<src_ls_rr_sort> *spq)
1300 : SPQ(spq) {}
1301 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1302 : SPQ(RHS.SPQ) {}
Andrew Trick2085a962010-12-21 22:25:04 +00001303
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001304 bool operator()(const SUnit* left, const SUnit* right) const;
1305 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001306
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001307 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001308 struct hybrid_ls_rr_sort : public queue_sort {
1309 enum {
1310 IsBottomUp = true,
1311 HasReadyFilter = false
1312 };
1313
Evan Chengbdd062d2010-05-20 06:13:19 +00001314 RegReductionPriorityQueue<hybrid_ls_rr_sort> *SPQ;
1315 hybrid_ls_rr_sort(RegReductionPriorityQueue<hybrid_ls_rr_sort> *spq)
1316 : SPQ(spq) {}
1317 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1318 : SPQ(RHS.SPQ) {}
Evan Chenga77f3d32010-07-21 06:09:07 +00001319
Evan Chengbdd062d2010-05-20 06:13:19 +00001320 bool operator()(const SUnit* left, const SUnit* right) const;
1321 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001322
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001323 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1324 // scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001325 struct ilp_ls_rr_sort : public queue_sort {
1326 enum {
1327 IsBottomUp = true,
1328 HasReadyFilter = true
1329 };
1330
Evan Cheng37b740c2010-07-24 00:39:05 +00001331 RegReductionPriorityQueue<ilp_ls_rr_sort> *SPQ;
1332 ilp_ls_rr_sort(RegReductionPriorityQueue<ilp_ls_rr_sort> *spq)
1333 : SPQ(spq) {}
1334 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1335 : SPQ(RHS.SPQ) {}
1336
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001337 bool isReady(SUnit *SU, unsigned CurCycle) const;
1338
Evan Cheng37b740c2010-07-24 00:39:05 +00001339 bool operator()(const SUnit* left, const SUnit* right) const;
1340 };
Evan Chengd38c22b2006-05-11 23:55:42 +00001341} // end anonymous namespace
1342
Dan Gohman186f65d2008-11-20 03:30:37 +00001343/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1344/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001345static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001346CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001347 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1348 if (SethiUllmanNumber != 0)
1349 return SethiUllmanNumber;
1350
1351 unsigned Extra = 0;
1352 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1353 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001354 if (I->isCtrl()) continue; // ignore chain preds
1355 SUnit *PredSU = I->getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001356 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001357 if (PredSethiUllman > SethiUllmanNumber) {
1358 SethiUllmanNumber = PredSethiUllman;
1359 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001360 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001361 ++Extra;
1362 }
1363
1364 SethiUllmanNumber += Extra;
1365
1366 if (SethiUllmanNumber == 0)
1367 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001368
Evan Cheng7e4abde2008-07-02 09:23:51 +00001369 return SethiUllmanNumber;
1370}
1371
Evan Chengd38c22b2006-05-11 23:55:42 +00001372namespace {
1373 template<class SF>
Nick Lewycky02d5f772009-10-25 06:33:48 +00001374 class RegReductionPriorityQueue : public SchedulingPriorityQueue {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001375 static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1376 std::vector<SUnit *>::iterator Best = Q.begin();
1377 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1378 E = Q.end(); I != E; ++I)
1379 if (Picker(*Best, *I))
1380 Best = I;
1381 SUnit *V = *Best;
1382 if (Best != prior(Q.end()))
1383 std::swap(*Best, Q.back());
1384 Q.pop_back();
1385 return V;
1386 }
1387
Dan Gohman52c27382010-05-26 18:52:00 +00001388 std::vector<SUnit*> Queue;
1389 SF Picker;
Evan Chengbdd062d2010-05-20 06:13:19 +00001390 unsigned CurQueueId;
Evan Chengbf32e542010-07-22 06:24:48 +00001391 bool TracksRegPressure;
Evan Chengd38c22b2006-05-11 23:55:42 +00001392
Dan Gohman3f656df2008-11-20 02:45:51 +00001393 protected:
1394 // SUnits - The SUnits for the current graph.
1395 std::vector<SUnit> *SUnits;
Evan Chenga77f3d32010-07-21 06:09:07 +00001396
1397 MachineFunction &MF;
Dan Gohman3f656df2008-11-20 02:45:51 +00001398 const TargetInstrInfo *TII;
1399 const TargetRegisterInfo *TRI;
Evan Chenga77f3d32010-07-21 06:09:07 +00001400 const TargetLowering *TLI;
Dan Gohman3f656df2008-11-20 02:45:51 +00001401 ScheduleDAGRRList *scheduleDAG;
1402
Dan Gohman186f65d2008-11-20 03:30:37 +00001403 // SethiUllmanNumbers - The SethiUllman number for each node.
1404 std::vector<unsigned> SethiUllmanNumbers;
1405
Evan Chenga77f3d32010-07-21 06:09:07 +00001406 /// RegPressure - Tracking current reg pressure per register class.
1407 ///
Evan Cheng28590382010-07-21 23:53:58 +00001408 std::vector<unsigned> RegPressure;
Evan Chenga77f3d32010-07-21 06:09:07 +00001409
1410 /// RegLimit - Tracking the number of allocatable registers per register
1411 /// class.
Evan Cheng28590382010-07-21 23:53:58 +00001412 std::vector<unsigned> RegLimit;
Evan Chenga77f3d32010-07-21 06:09:07 +00001413
Dan Gohman3f656df2008-11-20 02:45:51 +00001414 public:
Evan Chenga77f3d32010-07-21 06:09:07 +00001415 RegReductionPriorityQueue(MachineFunction &mf,
Evan Chengbf32e542010-07-22 06:24:48 +00001416 bool tracksrp,
Evan Chenga77f3d32010-07-21 06:09:07 +00001417 const TargetInstrInfo *tii,
1418 const TargetRegisterInfo *tri,
1419 const TargetLowering *tli)
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001420 : SchedulingPriorityQueue(SF::HasReadyFilter), Picker(this),
1421 CurQueueId(0), TracksRegPressure(tracksrp),
Evan Chenga77f3d32010-07-21 06:09:07 +00001422 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
Evan Chengbf32e542010-07-22 06:24:48 +00001423 if (TracksRegPressure) {
1424 unsigned NumRC = TRI->getNumRegClasses();
1425 RegLimit.resize(NumRC);
1426 RegPressure.resize(NumRC);
1427 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1428 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1429 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1430 E = TRI->regclass_end(); I != E; ++I)
Evan Chengdf907f42010-07-23 22:39:59 +00001431 RegLimit[(*I)->getID()] = tli->getRegPressureLimit(*I, MF);
Evan Chengbf32e542010-07-22 06:24:48 +00001432 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001433 }
Andrew Trick2085a962010-12-21 22:25:04 +00001434
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001435 bool isBottomUp() const { return SF::IsBottomUp; }
1436
Dan Gohman3f656df2008-11-20 02:45:51 +00001437 void initNodes(std::vector<SUnit> &sunits) {
1438 SUnits = &sunits;
Dan Gohman186f65d2008-11-20 03:30:37 +00001439 // Add pseudo dependency edges for two-address nodes.
1440 AddPseudoTwoAddrDeps();
Dan Gohman9a658d72009-03-24 00:49:12 +00001441 // Reroute edges to nodes with multiple uses.
1442 PrescheduleNodesWithMultipleUses();
Dan Gohman186f65d2008-11-20 03:30:37 +00001443 // Calculate node priorities.
1444 CalculateSethiUllmanNumbers();
Dan Gohman3f656df2008-11-20 02:45:51 +00001445 }
Evan Cheng5924bf72007-09-25 01:54:36 +00001446
Dan Gohman186f65d2008-11-20 03:30:37 +00001447 void addNode(const SUnit *SU) {
1448 unsigned SUSize = SethiUllmanNumbers.size();
1449 if (SUnits->size() > SUSize)
1450 SethiUllmanNumbers.resize(SUSize*2, 0);
1451 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1452 }
Evan Cheng5924bf72007-09-25 01:54:36 +00001453
Dan Gohman186f65d2008-11-20 03:30:37 +00001454 void updateNode(const SUnit *SU) {
1455 SethiUllmanNumbers[SU->NodeNum] = 0;
1456 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1457 }
Evan Cheng5924bf72007-09-25 01:54:36 +00001458
Dan Gohman186f65d2008-11-20 03:30:37 +00001459 void releaseState() {
Dan Gohman3f656df2008-11-20 02:45:51 +00001460 SUnits = 0;
Dan Gohman186f65d2008-11-20 03:30:37 +00001461 SethiUllmanNumbers.clear();
Evan Chenga77f3d32010-07-21 06:09:07 +00001462 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Dan Gohman3f656df2008-11-20 02:45:51 +00001463 }
Dan Gohman186f65d2008-11-20 03:30:37 +00001464
1465 unsigned getNodePriority(const SUnit *SU) const {
1466 assert(SU->NodeNum < SethiUllmanNumbers.size());
1467 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
Dan Gohman261ee6b2009-01-07 22:30:55 +00001468 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
Dan Gohman186f65d2008-11-20 03:30:37 +00001469 // CopyToReg should be close to its uses to facilitate coalescing and
1470 // avoid spilling.
1471 return 0;
Chris Lattnerb06015a2010-02-09 19:54:29 +00001472 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1473 Opc == TargetOpcode::SUBREG_TO_REG ||
1474 Opc == TargetOpcode::INSERT_SUBREG)
Dan Gohman3027bb62009-04-16 20:57:10 +00001475 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1476 // close to their uses to facilitate coalescing.
Dan Gohman186f65d2008-11-20 03:30:37 +00001477 return 0;
Dan Gohman6571ef32009-02-11 21:29:39 +00001478 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1479 // If SU does not have a register use, i.e. it doesn't produce a value
1480 // that would be consumed (e.g. store), then it terminates a chain of
1481 // computation. Give it a large SethiUllman number so it will be
1482 // scheduled right before its predecessors that it doesn't lengthen
1483 // their live ranges.
Dan Gohman186f65d2008-11-20 03:30:37 +00001484 return 0xffff;
Dan Gohman6571ef32009-02-11 21:29:39 +00001485 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1486 // If SU does not have a register def, schedule it close to its uses
1487 // because it does not lengthen any live ranges.
Dan Gohman186f65d2008-11-20 03:30:37 +00001488 return 0;
Dan Gohman261ee6b2009-01-07 22:30:55 +00001489 return SethiUllmanNumbers[SU->NodeNum];
Dan Gohman186f65d2008-11-20 03:30:37 +00001490 }
Bill Wendling0a7056f2010-01-05 23:48:12 +00001491
1492 unsigned getNodeOrdering(const SUnit *SU) const {
1493 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1494 }
Evan Chengbdd062d2010-05-20 06:13:19 +00001495
Evan Chengd38c22b2006-05-11 23:55:42 +00001496 bool empty() const { return Queue.empty(); }
Andrew Trick2085a962010-12-21 22:25:04 +00001497
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001498 bool isReady(SUnit *U) const {
1499 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1500 }
1501
Evan Chengd38c22b2006-05-11 23:55:42 +00001502 void push(SUnit *U) {
Roman Levenstein6b371142008-04-29 09:07:59 +00001503 assert(!U->NodeQueueId && "Node in the queue already");
Evan Chengbdd062d2010-05-20 06:13:19 +00001504 U->NodeQueueId = ++CurQueueId;
Dan Gohman52c27382010-05-26 18:52:00 +00001505 Queue.push_back(U);
Evan Chengd38c22b2006-05-11 23:55:42 +00001506 }
Roman Levenstein6b371142008-04-29 09:07:59 +00001507
Evan Chengd38c22b2006-05-11 23:55:42 +00001508 SUnit *pop() {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001509 if (Queue.empty()) return NULL;
1510
1511 SUnit *V = popFromQueue(Queue, Picker);
Roman Levenstein6b371142008-04-29 09:07:59 +00001512 V->NodeQueueId = 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001513 return V;
1514 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001515
Evan Cheng5924bf72007-09-25 01:54:36 +00001516 void remove(SUnit *SU) {
Roman Levenstein6b371142008-04-29 09:07:59 +00001517 assert(!Queue.empty() && "Queue is empty!");
Dan Gohmana4db3352008-06-21 18:35:25 +00001518 assert(SU->NodeQueueId != 0 && "Not in queue!");
Dan Gohman52c27382010-05-26 18:52:00 +00001519 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1520 SU);
1521 if (I != prior(Queue.end()))
1522 std::swap(*I, Queue.back());
1523 Queue.pop_back();
Roman Levenstein6b371142008-04-29 09:07:59 +00001524 SU->NodeQueueId = 0;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001525 }
Dan Gohman3f656df2008-11-20 02:45:51 +00001526
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001527 bool HighRegPressure(const SUnit *SU) const {
Evan Chenga77f3d32010-07-21 06:09:07 +00001528 if (!TLI)
Evan Cheng28590382010-07-21 23:53:58 +00001529 return false;
Evan Chenga77f3d32010-07-21 06:09:07 +00001530
Evan Chenga77f3d32010-07-21 06:09:07 +00001531 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1532 I != E; ++I) {
1533 if (I->isCtrl())
1534 continue;
1535 SUnit *PredSU = I->getSUnit();
Evan Cheng28590382010-07-21 23:53:58 +00001536 const SDNode *PN = PredSU->getNode();
1537 if (!PN->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001538 if (PN->getOpcode() == ISD::CopyFromReg) {
1539 EVT VT = PN->getValueType(0);
Evan Cheng28590382010-07-21 23:53:58 +00001540 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1541 unsigned Cost = TLI->getRepRegClassCostFor(VT);
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001542 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1543 return true;
Evan Chengdf907f42010-07-23 22:39:59 +00001544 }
1545 continue;
1546 }
1547 unsigned POpc = PN->getMachineOpcode();
1548 if (POpc == TargetOpcode::IMPLICIT_DEF)
1549 continue;
1550 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1551 EVT VT = PN->getOperand(0).getValueType();
1552 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1553 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1554 // Check if this increases register pressure of the specific register
1555 // class to the point where it would cause spills.
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001556 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1557 return true;
Andrew Trick2085a962010-12-21 22:25:04 +00001558 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001559 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1560 POpc == TargetOpcode::SUBREG_TO_REG) {
1561 EVT VT = PN->getValueType(0);
1562 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1563 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1564 // Check if this increases register pressure of the specific register
1565 // class to the point where it would cause spills.
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001566 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1567 return true;
Evan Chenga77f3d32010-07-21 06:09:07 +00001568 continue;
Evan Cheng28590382010-07-21 23:53:58 +00001569 }
1570 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
Evan Chenga77f3d32010-07-21 06:09:07 +00001571 for (unsigned i = 0; i != NumDefs; ++i) {
Evan Cheng28590382010-07-21 23:53:58 +00001572 EVT VT = PN->getValueType(i);
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001573 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1574 if (RegPressure[RCId] >= RegLimit[RCId])
1575 return true; // Reg pressure already high.
1576 unsigned Cost = TLI->getRepRegClassCostFor(VT);
Evan Cheng28590382010-07-21 23:53:58 +00001577 if (!PN->hasAnyUseOfValue(i))
Evan Chenga77f3d32010-07-21 06:09:07 +00001578 continue;
Evan Chenga77f3d32010-07-21 06:09:07 +00001579 // Check if this increases register pressure of the specific register
1580 // class to the point where it would cause spills.
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001581 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1582 return true;
Evan Chenga77f3d32010-07-21 06:09:07 +00001583 }
1584 }
1585
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001586 return false;
Evan Chenga77f3d32010-07-21 06:09:07 +00001587 }
1588
Evan Chengbf32e542010-07-22 06:24:48 +00001589 void ScheduledNode(SUnit *SU) {
1590 if (!TracksRegPressure)
1591 return;
1592
Evan Chenga77f3d32010-07-21 06:09:07 +00001593 const SDNode *N = SU->getNode();
Evan Chengdf907f42010-07-23 22:39:59 +00001594 if (!N->isMachineOpcode()) {
1595 if (N->getOpcode() != ISD::CopyToReg)
1596 return;
1597 } else {
1598 unsigned Opc = N->getMachineOpcode();
1599 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1600 Opc == TargetOpcode::INSERT_SUBREG ||
1601 Opc == TargetOpcode::SUBREG_TO_REG ||
1602 Opc == TargetOpcode::REG_SEQUENCE ||
1603 Opc == TargetOpcode::IMPLICIT_DEF)
1604 return;
1605 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001606
1607 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1608 I != E; ++I) {
1609 if (I->isCtrl())
1610 continue;
1611 SUnit *PredSU = I->getSUnit();
Evan Cheng28590382010-07-21 23:53:58 +00001612 if (PredSU->NumSuccsLeft != PredSU->NumSuccs)
Evan Chenga77f3d32010-07-21 06:09:07 +00001613 continue;
1614 const SDNode *PN = PredSU->getNode();
Evan Cheng28590382010-07-21 23:53:58 +00001615 if (!PN->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001616 if (PN->getOpcode() == ISD::CopyFromReg) {
1617 EVT VT = PN->getValueType(0);
Evan Cheng28590382010-07-21 23:53:58 +00001618 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1619 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1620 }
1621 continue;
1622 }
1623 unsigned POpc = PN->getMachineOpcode();
1624 if (POpc == TargetOpcode::IMPLICIT_DEF)
Evan Chenga77f3d32010-07-21 06:09:07 +00001625 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001626 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1627 EVT VT = PN->getOperand(0).getValueType();
1628 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1629 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
Andrew Trick2085a962010-12-21 22:25:04 +00001630 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001631 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1632 POpc == TargetOpcode::SUBREG_TO_REG) {
1633 EVT VT = PN->getValueType(0);
1634 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1635 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1636 continue;
1637 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001638 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1639 for (unsigned i = 0; i != NumDefs; ++i) {
1640 EVT VT = PN->getValueType(i);
1641 if (!PN->hasAnyUseOfValue(i))
1642 continue;
1643 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1644 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1645 }
1646 }
1647
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001648 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1649 // may transfer data dependencies to CopyToReg.
1650 if (SU->NumSuccs && N->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001651 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1652 for (unsigned i = 0; i != NumDefs; ++i) {
1653 EVT VT = N->getValueType(i);
1654 if (!N->hasAnyUseOfValue(i))
1655 continue;
1656 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1657 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1658 // Register pressure tracking is imprecise. This can happen.
1659 RegPressure[RCId] = 0;
1660 else
1661 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1662 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001663 }
Evan Chengbf32e542010-07-22 06:24:48 +00001664
1665 dumpRegPressure();
Evan Chenga77f3d32010-07-21 06:09:07 +00001666 }
1667
Evan Chengbf32e542010-07-22 06:24:48 +00001668 void UnscheduledNode(SUnit *SU) {
1669 if (!TracksRegPressure)
1670 return;
1671
Evan Chenga77f3d32010-07-21 06:09:07 +00001672 const SDNode *N = SU->getNode();
Evan Chengdf907f42010-07-23 22:39:59 +00001673 if (!N->isMachineOpcode()) {
1674 if (N->getOpcode() != ISD::CopyToReg)
1675 return;
Evan Cheng37b740c2010-07-24 00:39:05 +00001676 } else {
1677 unsigned Opc = N->getMachineOpcode();
1678 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1679 Opc == TargetOpcode::INSERT_SUBREG ||
1680 Opc == TargetOpcode::SUBREG_TO_REG ||
1681 Opc == TargetOpcode::REG_SEQUENCE ||
1682 Opc == TargetOpcode::IMPLICIT_DEF)
1683 return;
Evan Chengdf907f42010-07-23 22:39:59 +00001684 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001685
1686 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1687 I != E; ++I) {
1688 if (I->isCtrl())
1689 continue;
1690 SUnit *PredSU = I->getSUnit();
Evan Cheng28590382010-07-21 23:53:58 +00001691 if (PredSU->NumSuccsLeft != PredSU->NumSuccs)
Evan Chenga77f3d32010-07-21 06:09:07 +00001692 continue;
1693 const SDNode *PN = PredSU->getNode();
Evan Cheng28590382010-07-21 23:53:58 +00001694 if (!PN->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001695 if (PN->getOpcode() == ISD::CopyFromReg) {
1696 EVT VT = PN->getValueType(0);
Evan Cheng28590382010-07-21 23:53:58 +00001697 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1698 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1699 }
1700 continue;
1701 }
1702 unsigned POpc = PN->getMachineOpcode();
1703 if (POpc == TargetOpcode::IMPLICIT_DEF)
Evan Chenga77f3d32010-07-21 06:09:07 +00001704 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001705 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1706 EVT VT = PN->getOperand(0).getValueType();
1707 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1708 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
Andrew Trick2085a962010-12-21 22:25:04 +00001709 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001710 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1711 POpc == TargetOpcode::SUBREG_TO_REG) {
1712 EVT VT = PN->getValueType(0);
1713 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1714 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1715 continue;
1716 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001717 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1718 for (unsigned i = 0; i != NumDefs; ++i) {
1719 EVT VT = PN->getValueType(i);
1720 if (!PN->hasAnyUseOfValue(i))
1721 continue;
1722 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
Evan Cheng28590382010-07-21 23:53:58 +00001723 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
Evan Chenga77f3d32010-07-21 06:09:07 +00001724 // Register pressure tracking is imprecise. This can happen.
1725 RegPressure[RCId] = 0;
Evan Cheng28590382010-07-21 23:53:58 +00001726 else
1727 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
Evan Chenga77f3d32010-07-21 06:09:07 +00001728 }
1729 }
1730
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001731 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1732 // may transfer data dependencies to CopyToReg.
1733 if (SU->NumSuccs && N->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001734 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1735 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1736 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00001737 if (VT == MVT::Glue || VT == MVT::Other)
Evan Chengdf907f42010-07-23 22:39:59 +00001738 continue;
1739 if (!N->hasAnyUseOfValue(i))
1740 continue;
1741 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1742 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1743 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001744 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001745
Evan Chenga77f3d32010-07-21 06:09:07 +00001746 dumpRegPressure();
1747 }
1748
Andrew Trick2085a962010-12-21 22:25:04 +00001749 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1750 scheduleDAG = scheduleDag;
Dan Gohman3f656df2008-11-20 02:45:51 +00001751 }
1752
Evan Chenga77f3d32010-07-21 06:09:07 +00001753 void dumpRegPressure() const {
1754 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1755 E = TRI->regclass_end(); I != E; ++I) {
1756 const TargetRegisterClass *RC = *I;
1757 unsigned Id = RC->getID();
1758 unsigned RP = RegPressure[Id];
1759 if (!RP) continue;
1760 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1761 << '\n');
1762 }
1763 }
1764
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001765 void dump(ScheduleDAG *DAG) const {
1766 // Emulate pop() without clobbering NodeQueueIds.
1767 std::vector<SUnit*> DumpQueue = Queue;
1768 SF DumpPicker = Picker;
1769 while (!DumpQueue.empty()) {
1770 SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1771 if (isBottomUp())
1772 dbgs() << "Height " << SU->getHeight() << ": ";
1773 else
1774 dbgs() << "Depth " << SU->getDepth() << ": ";
1775 SU->dump(DAG);
1776 }
1777 }
1778
Dan Gohman3f656df2008-11-20 02:45:51 +00001779 protected:
1780 bool canClobber(const SUnit *SU, const SUnit *Op);
1781 void AddPseudoTwoAddrDeps();
Dan Gohman9a658d72009-03-24 00:49:12 +00001782 void PrescheduleNodesWithMultipleUses();
Evan Cheng6730f032007-01-08 23:55:53 +00001783 void CalculateSethiUllmanNumbers();
Evan Cheng7e4abde2008-07-02 09:23:51 +00001784 };
1785
Dan Gohman186f65d2008-11-20 03:30:37 +00001786 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1787 BURegReductionPriorityQueue;
Evan Cheng7e4abde2008-07-02 09:23:51 +00001788
Dan Gohman186f65d2008-11-20 03:30:37 +00001789 typedef RegReductionPriorityQueue<td_ls_rr_sort>
1790 TDRegReductionPriorityQueue;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001791
1792 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1793 SrcRegReductionPriorityQueue;
Evan Chengbdd062d2010-05-20 06:13:19 +00001794
1795 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1796 HybridBURRPriorityQueue;
Evan Cheng37b740c2010-07-24 00:39:05 +00001797
1798 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1799 ILPBURRPriorityQueue;
Evan Chengd38c22b2006-05-11 23:55:42 +00001800}
1801
Evan Chengb9e3db62007-03-14 22:43:40 +00001802/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00001803/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00001804static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001805 unsigned MaxHeight = 0;
Evan Cheng28748552007-03-13 23:25:11 +00001806 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00001807 I != E; ++I) {
Evan Chengce3bbe52009-02-10 08:30:11 +00001808 if (I->isCtrl()) continue; // ignore chain succs
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001809 unsigned Height = I->getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00001810 // If there are bunch of CopyToRegs stacked up, they should be considered
1811 // to be at the same position.
Dan Gohman2d170892008-12-09 22:54:47 +00001812 if (I->getSUnit()->getNode() &&
1813 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001814 Height = closestSucc(I->getSUnit())+1;
1815 if (Height > MaxHeight)
1816 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00001817 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001818 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00001819}
1820
Evan Cheng61bc51e2007-12-20 02:22:36 +00001821/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00001822/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00001823static unsigned calcMaxScratches(const SUnit *SU) {
1824 unsigned Scratches = 0;
1825 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Chengb5704992009-02-12 09:52:13 +00001826 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001827 if (I->isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00001828 Scratches++;
1829 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00001830 return Scratches;
1831}
1832
Evan Cheng6c1414f2010-10-29 18:09:28 +00001833/// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
1834/// CopyToReg to a virtual register. This SU def is probably a liveout and
1835/// it has no other use. It should be scheduled closer to the terminator.
1836static bool hasOnlyLiveOutUses(const SUnit *SU) {
1837 bool RetVal = false;
1838 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1839 I != E; ++I) {
1840 if (I->isCtrl()) continue;
1841 const SUnit *SuccSU = I->getSUnit();
1842 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
1843 unsigned Reg =
1844 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
1845 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1846 RetVal = true;
1847 continue;
1848 }
1849 }
1850 return false;
1851 }
1852 return RetVal;
1853}
1854
1855/// UnitsSharePred - Return true if the two scheduling units share a common
1856/// data predecessor.
1857static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
1858 SmallSet<const SUnit*, 4> Preds;
1859 for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
1860 I != E; ++I) {
1861 if (I->isCtrl()) continue; // ignore chain preds
1862 Preds.insert(I->getSUnit());
1863 }
1864 for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
1865 I != E; ++I) {
1866 if (I->isCtrl()) continue; // ignore chain preds
1867 if (Preds.count(I->getSUnit()))
1868 return true;
1869 }
1870 return false;
1871}
1872
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001873template <typename RRSort>
1874static bool BURRSort(const SUnit *left, const SUnit *right,
1875 const RegReductionPriorityQueue<RRSort> *SPQ) {
Evan Cheng6730f032007-01-08 23:55:53 +00001876 unsigned LPriority = SPQ->getNodePriority(left);
1877 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng73bdf042008-03-01 00:39:47 +00001878 if (LPriority != RPriority)
1879 return LPriority > RPriority;
1880
1881 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1882 // e.g.
1883 // t1 = op t2, c1
1884 // t3 = op t4, c2
1885 //
1886 // and the following instructions are both ready.
1887 // t2 = op c3
1888 // t4 = op c4
1889 //
1890 // Then schedule t2 = op first.
1891 // i.e.
1892 // t4 = op c4
1893 // t2 = op c3
1894 // t1 = op t2, c1
1895 // t3 = op t4, c2
1896 //
1897 // This creates more short live intervals.
1898 unsigned LDist = closestSucc(left);
1899 unsigned RDist = closestSucc(right);
1900 if (LDist != RDist)
1901 return LDist < RDist;
1902
Evan Cheng3a14efa2009-02-12 08:59:45 +00001903 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00001904 unsigned LScratch = calcMaxScratches(left);
1905 unsigned RScratch = calcMaxScratches(right);
1906 if (LScratch != RScratch)
1907 return LScratch > RScratch;
1908
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001909 // Note: with a bottom-up ready filter, the height check may be redundant.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001910 if (left->getHeight() != right->getHeight())
1911 return left->getHeight() > right->getHeight();
Andrew Trick2085a962010-12-21 22:25:04 +00001912
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001913 if (left->getDepth() != right->getDepth())
1914 return left->getDepth() < right->getDepth();
Evan Cheng73bdf042008-03-01 00:39:47 +00001915
Andrew Trick2085a962010-12-21 22:25:04 +00001916 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00001917 "NodeQueueId cannot be zero");
1918 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00001919}
1920
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001921// Bottom up
1922bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1923 return BURRSort(left, right, SPQ);
1924}
1925
1926// Source order, otherwise bottom up.
Evan Chengbdd062d2010-05-20 06:13:19 +00001927bool src_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001928 unsigned LOrder = SPQ->getNodeOrdering(left);
1929 unsigned ROrder = SPQ->getNodeOrdering(right);
1930
1931 // Prefer an ordering where the lower the non-zero order number, the higher
1932 // the preference.
1933 if ((LOrder || ROrder) && LOrder != ROrder)
1934 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
1935
1936 return BURRSort(left, right, SPQ);
1937}
1938
Evan Chengbdd062d2010-05-20 06:13:19 +00001939bool hybrid_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const{
Evan Chengdebf9c52010-11-03 00:45:17 +00001940 if (left->isCall || right->isCall)
1941 // No way to compute latency of calls.
1942 return BURRSort(left, right, SPQ);
1943
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001944 bool LHigh = SPQ->HighRegPressure(left);
1945 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00001946 // Avoid causing spills. If register pressure is high, schedule for
1947 // register pressure reduction.
Evan Cheng28590382010-07-21 23:53:58 +00001948 if (LHigh && !RHigh)
1949 return true;
1950 else if (!LHigh && RHigh)
1951 return false;
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001952 else if (!LHigh && !RHigh) {
Evan Cheng6c1414f2010-10-29 18:09:28 +00001953 // If the two nodes share an operand and one of them has a single
1954 // use that is a live out copy, favor the one that is live out. Otherwise
1955 // it will be difficult to eliminate the copy if the instruction is a
1956 // loop induction variable update. e.g.
1957 // BB:
1958 // sub r1, r3, #1
1959 // str r0, [r2, r3]
1960 // mov r3, r1
1961 // cmp
1962 // bne BB
1963 bool SharePred = UnitsSharePred(left, right);
1964 // FIXME: Only adjust if BB is a loop back edge.
1965 // FIXME: What's the cost of a copy?
1966 int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
1967 int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
1968 int LHeight = (int)left->getHeight() - LBonus;
1969 int RHeight = (int)right->getHeight() - RBonus;
1970
Evan Cheng28590382010-07-21 23:53:58 +00001971 // Low register pressure situation, schedule for latency if possible.
1972 bool LStall = left->SchedulingPref == Sched::Latency &&
Evan Cheng6c1414f2010-10-29 18:09:28 +00001973 (int)SPQ->getCurCycle() < LHeight;
Evan Cheng28590382010-07-21 23:53:58 +00001974 bool RStall = right->SchedulingPref == Sched::Latency &&
Evan Cheng6c1414f2010-10-29 18:09:28 +00001975 (int)SPQ->getCurCycle() < RHeight;
Evan Cheng28590382010-07-21 23:53:58 +00001976 // If scheduling one of the node will cause a pipeline stall, delay it.
1977 // If scheduling either one of the node will cause a pipeline stall, sort
1978 // them according to their height.
Evan Cheng28590382010-07-21 23:53:58 +00001979 if (LStall) {
1980 if (!RStall)
1981 return true;
Evan Cheng6c1414f2010-10-29 18:09:28 +00001982 if (LHeight != RHeight)
1983 return LHeight > RHeight;
Evan Cheng28590382010-07-21 23:53:58 +00001984 } else if (RStall)
Evan Chengbdd062d2010-05-20 06:13:19 +00001985 return false;
Evan Chengcc2efe12010-05-28 23:26:21 +00001986
Evan Cheng6c1414f2010-10-29 18:09:28 +00001987 // If either node is scheduling for latency, sort them by height
1988 // and latency.
Evan Cheng28590382010-07-21 23:53:58 +00001989 if (left->SchedulingPref == Sched::Latency ||
1990 right->SchedulingPref == Sched::Latency) {
Evan Cheng6c1414f2010-10-29 18:09:28 +00001991 if (LHeight != RHeight)
1992 return LHeight > RHeight;
Evan Cheng28590382010-07-21 23:53:58 +00001993 if (left->Latency != right->Latency)
1994 return left->Latency > right->Latency;
1995 }
Evan Chengcc2efe12010-05-28 23:26:21 +00001996 }
1997
Evan Chengbdd062d2010-05-20 06:13:19 +00001998 return BURRSort(left, right, SPQ);
1999}
2000
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002001// Schedule as many instructions in each cycle as possible. So don't make an
2002// instruction available unless it is ready in the current cycle.
2003bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2004 return SU->getHeight() <= CurCycle;
2005}
2006
Evan Cheng37b740c2010-07-24 00:39:05 +00002007bool ilp_ls_rr_sort::operator()(const SUnit *left,
2008 const SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002009 if (left->isCall || right->isCall)
2010 // No way to compute latency of calls.
2011 return BURRSort(left, right, SPQ);
2012
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002013 bool LHigh = SPQ->HighRegPressure(left);
2014 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002015 // Avoid causing spills. If register pressure is high, schedule for
2016 // register pressure reduction.
2017 if (LHigh && !RHigh)
2018 return true;
2019 else if (!LHigh && RHigh)
2020 return false;
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002021 else if (!LHigh && !RHigh) {
Evan Cheng8ae3eca2010-07-25 18:59:43 +00002022 // Low register pressure situation, schedule to maximize instruction level
2023 // parallelism.
Evan Cheng37b740c2010-07-24 00:39:05 +00002024 if (left->NumPreds > right->NumPreds)
2025 return false;
2026 else if (left->NumPreds < right->NumPreds)
2027 return false;
2028 }
2029
2030 return BURRSort(left, right, SPQ);
2031}
2032
Dan Gohman3f656df2008-11-20 02:45:51 +00002033template<class SF>
Evan Cheng7e4abde2008-07-02 09:23:51 +00002034bool
Dan Gohman3f656df2008-11-20 02:45:51 +00002035RegReductionPriorityQueue<SF>::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002036 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002037 unsigned Opc = SU->getNode()->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002038 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002039 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002040 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002041 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002042 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002043 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002044 if (DU->getNodeId() != -1 &&
2045 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002046 return true;
2047 }
2048 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002049 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002050 return false;
2051}
2052
Evan Chengf9891412007-12-20 09:25:31 +00002053/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002054/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002055static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002056 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002057 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002058 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002059 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2060 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002061 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002062 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002063 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002064 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002065 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002066 const unsigned *SUImpDefs =
2067 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2068 if (!SUImpDefs)
2069 return false;
2070 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002071 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002072 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002073 continue;
2074 if (!N->hasAnyUseOfValue(i))
2075 continue;
2076 unsigned Reg = ImpDefs[i - NumDefs];
2077 for (;*SUImpDefs; ++SUImpDefs) {
2078 unsigned SUReg = *SUImpDefs;
2079 if (TRI->regsOverlap(Reg, SUReg))
2080 return true;
2081 }
Evan Chengf9891412007-12-20 09:25:31 +00002082 }
2083 }
2084 return false;
2085}
2086
Dan Gohman9a658d72009-03-24 00:49:12 +00002087/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2088/// are not handled well by the general register pressure reduction
2089/// heuristics. When presented with code like this:
2090///
2091/// N
2092/// / |
2093/// / |
2094/// U store
2095/// |
2096/// ...
2097///
2098/// the heuristics tend to push the store up, but since the
2099/// operand of the store has another use (U), this would increase
2100/// the length of that other use (the U->N edge).
2101///
2102/// This function transforms code like the above to route U's
2103/// dependence through the store when possible, like this:
2104///
2105/// N
2106/// ||
2107/// ||
2108/// store
2109/// |
2110/// U
2111/// |
2112/// ...
2113///
2114/// This results in the store being scheduled immediately
2115/// after N, which shortens the U->N live range, reducing
2116/// register pressure.
2117///
2118template<class SF>
2119void RegReductionPriorityQueue<SF>::PrescheduleNodesWithMultipleUses() {
2120 // Visit all the nodes in topological order, working top-down.
2121 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2122 SUnit *SU = &(*SUnits)[i];
2123 // For now, only look at nodes with no data successors, such as stores.
2124 // These are especially important, due to the heuristics in
2125 // getNodePriority for nodes with no data successors.
2126 if (SU->NumSuccs != 0)
2127 continue;
2128 // For now, only look at nodes with exactly one data predecessor.
2129 if (SU->NumPreds != 1)
2130 continue;
2131 // Avoid prescheduling copies to virtual registers, which don't behave
2132 // like other nodes from the perspective of scheduling heuristics.
2133 if (SDNode *N = SU->getNode())
2134 if (N->getOpcode() == ISD::CopyToReg &&
2135 TargetRegisterInfo::isVirtualRegister
2136 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2137 continue;
2138
2139 // Locate the single data predecessor.
2140 SUnit *PredSU = 0;
2141 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2142 EE = SU->Preds.end(); II != EE; ++II)
2143 if (!II->isCtrl()) {
2144 PredSU = II->getSUnit();
2145 break;
2146 }
2147 assert(PredSU);
2148
2149 // Don't rewrite edges that carry physregs, because that requires additional
2150 // support infrastructure.
2151 if (PredSU->hasPhysRegDefs)
2152 continue;
2153 // Short-circuit the case where SU is PredSU's only data successor.
2154 if (PredSU->NumSuccs == 1)
2155 continue;
2156 // Avoid prescheduling to copies from virtual registers, which don't behave
2157 // like other nodes from the perspective of scheduling // heuristics.
2158 if (SDNode *N = SU->getNode())
2159 if (N->getOpcode() == ISD::CopyFromReg &&
2160 TargetRegisterInfo::isVirtualRegister
2161 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2162 continue;
2163
2164 // Perform checks on the successors of PredSU.
2165 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2166 EE = PredSU->Succs.end(); II != EE; ++II) {
2167 SUnit *PredSuccSU = II->getSUnit();
2168 if (PredSuccSU == SU) continue;
2169 // If PredSU has another successor with no data successors, for
2170 // now don't attempt to choose either over the other.
2171 if (PredSuccSU->NumSuccs == 0)
2172 goto outer_loop_continue;
2173 // Don't break physical register dependencies.
2174 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2175 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2176 goto outer_loop_continue;
2177 // Don't introduce graph cycles.
2178 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2179 goto outer_loop_continue;
2180 }
2181
2182 // Ok, the transformation is safe and the heuristics suggest it is
2183 // profitable. Update the graph.
Evan Chengbdd062d2010-05-20 06:13:19 +00002184 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2185 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002186 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002187 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2188 SDep Edge = PredSU->Succs[i];
2189 assert(!Edge.isAssignedRegDep());
2190 SUnit *SuccSU = Edge.getSUnit();
2191 if (SuccSU != SU) {
2192 Edge.setSUnit(PredSU);
2193 scheduleDAG->RemovePred(SuccSU, Edge);
2194 scheduleDAG->AddPred(SU, Edge);
2195 Edge.setSUnit(SU);
2196 scheduleDAG->AddPred(SuccSU, Edge);
2197 --i;
2198 }
2199 }
2200 outer_loop_continue:;
2201 }
2202}
2203
Evan Chengd38c22b2006-05-11 23:55:42 +00002204/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2205/// it as a def&use operand. Add a pseudo control edge from it to the other
2206/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002207/// first (lower in the schedule). If both nodes are two-address, favor the
2208/// one that has a CopyToReg use (more likely to be a loop induction update).
2209/// If both are two-address, but one is commutable while the other is not
2210/// commutable, favor the one that's not commutable.
Dan Gohman3f656df2008-11-20 02:45:51 +00002211template<class SF>
2212void RegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002213 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
Dan Gohmane955c482008-08-05 14:45:15 +00002214 SUnit *SU = &(*SUnits)[i];
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002215 if (!SU->isTwoAddress)
2216 continue;
2217
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002218 SDNode *Node = SU->getNode();
Chris Lattner11a33812010-12-23 17:24:32 +00002219 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002220 continue;
2221
Evan Cheng6c1414f2010-10-29 18:09:28 +00002222 bool isLiveOut = hasOnlyLiveOutUses(SU);
Dan Gohman17059682008-07-17 19:10:17 +00002223 unsigned Opc = Node->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002224 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002225 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002226 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002227 for (unsigned j = 0; j != NumOps; ++j) {
Dan Gohman82016c22008-11-19 02:00:32 +00002228 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2229 continue;
2230 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2231 if (DU->getNodeId() == -1)
2232 continue;
2233 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2234 if (!DUSU) continue;
2235 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2236 E = DUSU->Succs.end(); I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002237 if (I->isCtrl()) continue;
2238 SUnit *SuccSU = I->getSUnit();
Dan Gohman82016c22008-11-19 02:00:32 +00002239 if (SuccSU == SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002240 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002241 // Be conservative. Ignore if nodes aren't at roughly the same
2242 // depth and height.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002243 if (SuccSU->getHeight() < SU->getHeight() &&
2244 (SU->getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002245 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002246 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2247 // constrains whatever is using the copy, instead of the copy
2248 // itself. In the case that the copy is coalesced, this
2249 // preserves the intent of the pseudo two-address heurietics.
2250 while (SuccSU->Succs.size() == 1 &&
2251 SuccSU->getNode()->isMachineOpcode() &&
2252 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002253 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002254 SuccSU = SuccSU->Succs.front().getSUnit();
2255 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002256 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2257 continue;
2258 // Don't constrain nodes with physical register defs if the
2259 // predecessor can clobber them.
Dan Gohmanf3746cb2009-03-24 00:50:07 +00002260 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
Dan Gohman82016c22008-11-19 02:00:32 +00002261 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002262 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002263 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002264 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2265 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002266 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002267 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2268 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2269 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002270 continue;
2271 if ((!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002272 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Dan Gohman82016c22008-11-19 02:00:32 +00002273 (!SU->isCommutable && SuccSU->isCommutable)) &&
2274 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002275 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002276 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
Dan Gohman79c35162009-01-06 01:19:04 +00002277 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
Dan Gohmanbf8e5202009-01-06 01:28:56 +00002278 /*Reg=*/0, /*isNormalMemory=*/false,
2279 /*isMustAlias=*/false,
Dan Gohman2d170892008-12-09 22:54:47 +00002280 /*isArtificial=*/true));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002281 }
2282 }
2283 }
2284 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002285}
2286
Evan Cheng6730f032007-01-08 23:55:53 +00002287/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
2288/// scheduling units.
Dan Gohman186f65d2008-11-20 03:30:37 +00002289template<class SF>
2290void RegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
Evan Chengd38c22b2006-05-11 23:55:42 +00002291 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick2085a962010-12-21 22:25:04 +00002292
Evan Chengd38c22b2006-05-11 23:55:42 +00002293 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
Dan Gohman186f65d2008-11-20 03:30:37 +00002294 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002295}
Evan Chengd38c22b2006-05-11 23:55:42 +00002296
Roman Levenstein30d09512008-03-27 09:44:37 +00002297/// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
Roman Levensteinbc674502008-03-27 09:14:57 +00002298/// predecessors of the successors of the SUnit SU. Stop when the provided
2299/// limit is exceeded.
Andrew Trick2085a962010-12-21 22:25:04 +00002300static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
Roman Levensteinbc674502008-03-27 09:14:57 +00002301 unsigned Limit) {
2302 unsigned Sum = 0;
2303 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2304 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002305 const SUnit *SuccSU = I->getSUnit();
Roman Levensteinbc674502008-03-27 09:14:57 +00002306 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2307 EE = SuccSU->Preds.end(); II != EE; ++II) {
Dan Gohman2d170892008-12-09 22:54:47 +00002308 SUnit *PredSU = II->getSUnit();
Evan Cheng16d72072008-03-29 18:34:22 +00002309 if (!PredSU->isScheduled)
2310 if (++Sum > Limit)
2311 return Sum;
Roman Levensteinbc674502008-03-27 09:14:57 +00002312 }
2313 }
2314 return Sum;
2315}
2316
Evan Chengd38c22b2006-05-11 23:55:42 +00002317
2318// Top down
2319bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Evan Cheng6730f032007-01-08 23:55:53 +00002320 unsigned LPriority = SPQ->getNodePriority(left);
2321 unsigned RPriority = SPQ->getNodePriority(right);
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002322 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2323 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00002324 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2325 bool RIsFloater = RIsTarget && right->NumPreds == 0;
Roman Levensteinbc674502008-03-27 09:14:57 +00002326 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2327 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00002328
2329 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2330 return false;
2331 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2332 return true;
2333
Evan Chengd38c22b2006-05-11 23:55:42 +00002334 if (LIsFloater)
2335 LBonus -= 2;
2336 if (RIsFloater)
2337 RBonus -= 2;
2338 if (left->NumSuccs == 1)
2339 LBonus += 2;
2340 if (right->NumSuccs == 1)
2341 RBonus += 2;
2342
Evan Cheng73bdf042008-03-01 00:39:47 +00002343 if (LPriority+LBonus != RPriority+RBonus)
2344 return LPriority+LBonus < RPriority+RBonus;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00002345
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002346 if (left->getDepth() != right->getDepth())
2347 return left->getDepth() < right->getDepth();
Evan Cheng73bdf042008-03-01 00:39:47 +00002348
2349 if (left->NumSuccsLeft != right->NumSuccsLeft)
2350 return left->NumSuccsLeft > right->NumSuccsLeft;
2351
Andrew Trick2085a962010-12-21 22:25:04 +00002352 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002353 "NodeQueueId cannot be zero");
2354 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002355}
2356
Evan Chengd38c22b2006-05-11 23:55:42 +00002357//===----------------------------------------------------------------------===//
2358// Public Constructor Functions
2359//===----------------------------------------------------------------------===//
2360
Dan Gohmandfaf6462009-02-11 04:27:20 +00002361llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002362llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2363 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002364 const TargetMachine &TM = IS->TM;
2365 const TargetInstrInfo *TII = TM.getInstrInfo();
2366 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002367
Evan Chenga77f3d32010-07-21 06:09:07 +00002368 BURegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002369 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002370 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002371 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002372 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002373}
2374
Dan Gohmandfaf6462009-02-11 04:27:20 +00002375llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002376llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2377 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002378 const TargetMachine &TM = IS->TM;
2379 const TargetInstrInfo *TII = TM.getInstrInfo();
2380 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002381
Evan Chenga77f3d32010-07-21 06:09:07 +00002382 TDRegReductionPriorityQueue *PQ =
2383 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002384 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Dan Gohman3f656df2008-11-20 02:45:51 +00002385 PQ->setScheduleDAG(SD);
2386 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002387}
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002388
2389llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002390llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2391 CodeGenOpt::Level OptLevel) {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002392 const TargetMachine &TM = IS->TM;
2393 const TargetInstrInfo *TII = TM.getInstrInfo();
2394 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002395
Evan Chenga77f3d32010-07-21 06:09:07 +00002396 SrcRegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002397 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002398 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002399 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002400 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002401}
2402
2403llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002404llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2405 CodeGenOpt::Level OptLevel) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002406 const TargetMachine &TM = IS->TM;
2407 const TargetInstrInfo *TII = TM.getInstrInfo();
2408 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Evan Chenga77f3d32010-07-21 06:09:07 +00002409 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002410
Evan Chenga77f3d32010-07-21 06:09:07 +00002411 HybridBURRPriorityQueue *PQ =
Evan Chengdf907f42010-07-23 22:39:59 +00002412 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002413
2414 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002415 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002416 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002417}
Evan Cheng37b740c2010-07-24 00:39:05 +00002418
2419llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002420llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2421 CodeGenOpt::Level OptLevel) {
Evan Cheng37b740c2010-07-24 00:39:05 +00002422 const TargetMachine &TM = IS->TM;
2423 const TargetInstrInfo *TII = TM.getInstrInfo();
2424 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2425 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002426
Evan Cheng37b740c2010-07-24 00:39:05 +00002427 ILPBURRPriorityQueue *PQ =
2428 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002429 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00002430 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002431 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00002432}