blob: a51595f1b06385cf37ac641dff805d4bf3720b83 [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() {
Andrew Trick5ce945c2010-12-24 07:10:19 +0000351 if (!EnableSchedCycles) {
352 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
353 return;
354 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000355
356 // If the available queue is empty, it is safe to reset MinAvailableCycle.
357 if (AvailableQueue->empty())
358 MinAvailableCycle = UINT_MAX;
359
360 // Check to see if any of the pending instructions are ready to issue. If
361 // so, add them to the available queue.
362 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
363 unsigned ReadyCycle =
364 isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDepth();
365 if (ReadyCycle < MinAvailableCycle)
366 MinAvailableCycle = ReadyCycle;
367
368 if (PendingQueue[i]->isAvailable) {
369 if (!isReady(PendingQueue[i]))
370 continue;
371 AvailableQueue->push(PendingQueue[i]);
372 }
373 PendingQueue[i]->isPending = false;
374 PendingQueue[i] = PendingQueue.back();
375 PendingQueue.pop_back();
376 --i; --e;
377 }
378}
379
380/// Move the scheduler state forward by the specified number of Cycles.
381void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
382 if (NextCycle <= CurCycle)
383 return;
384
385 AvailableQueue->setCurCycle(NextCycle);
386 if (HazardRec->getMaxLookAhead() == 0) {
387 // Bypass lots of virtual calls in case of long latency.
388 CurCycle = NextCycle;
389 }
390 else {
391 for (; CurCycle != NextCycle; ++CurCycle) {
392 if (isBottomUp)
393 HazardRec->RecedeCycle();
394 else
395 HazardRec->AdvanceCycle();
396 }
397 }
398 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
399 // available Q to release pending nodes at least once before popping.
400 ReleasePending();
401}
402
403/// Move the scheduler state forward until the specified node's dependents are
404/// ready and can be scheduled with no resource conflicts.
405void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
406 if (!EnableSchedCycles)
407 return;
408
409 unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
410
411 // Bump CurCycle to account for latency. We assume the latency of other
412 // available instructions may be hidden by the stall (not a full pipe stall).
413 // This updates the hazard recognizer's cycle before reserving resources for
414 // this instruction.
415 AdvanceToCycle(ReadyCycle);
416
417 // Calls are scheduled in their preceding cycle, so don't conflict with
418 // hazards from instructions after the call. EmitNode will reset the
419 // scoreboard state before emitting the call.
420 if (isBottomUp && SU->isCall)
421 return;
422
423 // FIXME: For resource conflicts in very long non-pipelined stages, we
424 // should probably skip ahead here to avoid useless scoreboard checks.
425 int Stalls = 0;
426 while (true) {
427 ScheduleHazardRecognizer::HazardType HT =
428 HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
429
430 if (HT == ScheduleHazardRecognizer::NoHazard)
431 break;
432
433 ++Stalls;
434 }
435 AdvanceToCycle(CurCycle + Stalls);
436}
437
438/// Record this SUnit in the HazardRecognizer.
439/// Does not update CurCycle.
440void ScheduleDAGRRList::EmitNode(SUnit *SU) {
Andrew Trickc9405662010-12-24 06:46:50 +0000441 if (!EnableSchedCycles || HazardRec->getMaxLookAhead() == 0)
442 return;
443
444 // Check for phys reg copy.
445 if (!SU->getNode())
446 return;
447
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000448 switch (SU->getNode()->getOpcode()) {
449 default:
450 assert(SU->getNode()->isMachineOpcode() &&
451 "This target-independent node should not be scheduled.");
452 break;
453 case ISD::MERGE_VALUES:
454 case ISD::TokenFactor:
455 case ISD::CopyToReg:
456 case ISD::CopyFromReg:
457 case ISD::EH_LABEL:
458 // Noops don't affect the scoreboard state. Copies are likely to be
459 // removed.
460 return;
461 case ISD::INLINEASM:
462 // For inline asm, clear the pipeline state.
463 HazardRec->Reset();
464 return;
465 }
466 if (isBottomUp && SU->isCall) {
467 // Calls are scheduled with their preceding instructions. For bottom-up
468 // scheduling, clear the pipeline state before emitting.
469 HazardRec->Reset();
470 }
471
472 HazardRec->EmitInstruction(SU);
473
474 if (!isBottomUp && SU->isCall) {
475 HazardRec->Reset();
476 }
477}
478
Dan Gohmanb9543432009-02-10 23:27:53 +0000479/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
480/// count of its predecessors. If a predecessor pending count is zero, add it to
481/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000482void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Evan Chengbdd062d2010-05-20 06:13:19 +0000483 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000484 DEBUG(SU->dump(this));
485
Evan Chengbdd062d2010-05-20 06:13:19 +0000486#ifndef NDEBUG
487 if (CurCycle < SU->getHeight())
488 DEBUG(dbgs() << " Height [" << SU->getHeight() << "] pipeline stall!\n");
489#endif
490
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000491 // FIXME: Do not modify node height. It may interfere with
492 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
493 // node it's ready cycle can aid heuristics, and after scheduling it can
494 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000495 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000496
497 // Reserve resources for the scheduled intruction.
498 EmitNode(SU);
499
Dan Gohmanb9543432009-02-10 23:27:53 +0000500 Sequence.push_back(SU);
501
Evan Cheng28590382010-07-21 23:53:58 +0000502 AvailableQueue->ScheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000503
Andrew Trick033efdf2010-12-23 03:15:51 +0000504 // Update liveness of predecessors before successors to avoid treating a
505 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000506 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000507
508 // Release all the implicit physical register defs that are live.
509 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
510 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000511 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
512 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
513 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
514 --NumLiveRegs;
515 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000516 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000517 }
518 }
519
Evan Chengd38c22b2006-05-11 23:55:42 +0000520 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000521
522 // Conditions under which the scheduler should eagerly advance the cycle:
523 // (1) No available instructions
524 // (2) All pipelines full, so available instructions must have hazards.
525 //
526 // If SchedCycles is disabled, count each inst as one cycle.
527 if (!EnableSchedCycles ||
528 AvailableQueue->empty() || HazardRec->atIssueLimit())
529 AdvanceToCycle(CurCycle + 1);
Evan Chengd38c22b2006-05-11 23:55:42 +0000530}
531
Evan Cheng5924bf72007-09-25 01:54:36 +0000532/// CapturePred - This does the opposite of ReleasePred. Since SU is being
533/// unscheduled, incrcease the succ left count of its predecessors. Remove
534/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000535void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000536 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000537 if (PredSU->isAvailable) {
538 PredSU->isAvailable = false;
539 if (!PredSU->isPending)
540 AvailableQueue->remove(PredSU);
541 }
542
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000543 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000544 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000545}
546
547/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
548/// its predecessor states to reflect the change.
549void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000550 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000551 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000552
Evan Cheng5924bf72007-09-25 01:54:36 +0000553 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
554 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000555 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000556 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000557 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000558 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000559 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000560 --NumLiveRegs;
Dan Gohman2d170892008-12-09 22:54:47 +0000561 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000562 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000563 }
564 }
565
566 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
567 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000568 if (I->isAssignedRegDep()) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000569 // This becomes the nearest def. Note that an earlier def may still be
570 // pending if this is a two-address node.
571 LiveRegDefs[I->getReg()] = SU;
Dan Gohman2d170892008-12-09 22:54:47 +0000572 if (!LiveRegDefs[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000573 ++NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000574 }
Andrew Tricka52f3252010-12-23 04:16:14 +0000575 if (LiveRegGens[I->getReg()] == NULL ||
576 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
577 LiveRegGens[I->getReg()] = I->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000578 }
579 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000580 if (SU->getHeight() < MinAvailableCycle)
581 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000582
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000583 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000584 SU->isScheduled = false;
585 SU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000586 if (EnableSchedCycles && AvailableQueue->hasReadyFilter()) {
587 // Don't make available until backtracking is complete.
588 SU->isPending = true;
589 PendingQueue.push_back(SU);
590 }
591 else {
592 AvailableQueue->push(SU);
593 }
Evan Cheng28590382010-07-21 23:53:58 +0000594 AvailableQueue->UnscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000595}
596
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000597/// After backtracking, the hazard checker needs to be restored to a state
598/// corresponding the the current cycle.
599void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
600 HazardRec->Reset();
601
602 unsigned LookAhead = std::min((unsigned)Sequence.size(),
603 HazardRec->getMaxLookAhead());
604 if (LookAhead == 0)
605 return;
606
607 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
608 unsigned HazardCycle = (*I)->getHeight();
609 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
610 SUnit *SU = *I;
611 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
612 HazardRec->RecedeCycle();
613 }
614 EmitNode(SU);
615 }
616}
617
Evan Cheng8e136a92007-09-26 21:36:17 +0000618/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000619/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000620void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
621 SUnit *OldSU = Sequence.back();
622 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000623 Sequence.pop_back();
624 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000625 // Don't try to remove SU from AvailableQueue.
626 SU->isAvailable = false;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000627 // FIXME: use ready cycle instead of height
628 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000629 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000630 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000631 if (OldSU == BtSU)
632 break;
633 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000634 }
635
Dan Gohman60d68442009-01-29 19:49:27 +0000636 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000637
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000638 RestoreHazardCheckerBottomUp();
639
Andrew Trick5ce945c2010-12-24 07:10:19 +0000640 ReleasePending();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000641
Evan Cheng1ec79b42007-09-27 07:09:03 +0000642 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000643}
644
Evan Cheng3b245872010-02-05 01:27:11 +0000645static bool isOperandOf(const SUnit *SU, SDNode *N) {
646 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000647 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000648 if (SUNode->isOperandOf(N))
649 return true;
650 }
651 return false;
652}
653
Evan Cheng5924bf72007-09-25 01:54:36 +0000654/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
655/// successors to the newly created node.
656SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000657 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000658 if (!N)
659 return NULL;
660
Andrew Trickc9405662010-12-24 06:46:50 +0000661 if (SU->getNode()->getGluedNode())
662 return NULL;
663
Evan Cheng79e97132007-10-05 01:39:18 +0000664 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000665 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000666 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000667 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000668 if (VT == MVT::Glue)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000669 return NULL;
Owen Anderson9f944592009-08-11 20:47:22 +0000670 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000671 TryUnfold = true;
672 }
Evan Cheng79e97132007-10-05 01:39:18 +0000673 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000674 const SDValue &Op = N->getOperand(i);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000675 EVT VT = Op.getNode()->getValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000676 if (VT == MVT::Glue)
Evan Cheng79e97132007-10-05 01:39:18 +0000677 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000678 }
679
680 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000681 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000682 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000683 return NULL;
684
Evan Chengbdd062d2010-05-20 06:13:19 +0000685 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000686 assert(NewNodes.size() == 2 && "Expected a load folding node!");
687
688 N = NewNodes[1];
689 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000690 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000691 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000692 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000693 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
694 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000695 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000696
Dan Gohmane52e0892008-11-11 21:34:44 +0000697 // LoadNode may already exist. This can happen when there is another
698 // load from the same location and producing the same type of value
699 // but it has different alignment or volatileness.
700 bool isNewLoad = true;
701 SUnit *LoadSU;
702 if (LoadNode->getNodeId() != -1) {
703 LoadSU = &SUnits[LoadNode->getNodeId()];
704 isNewLoad = false;
705 } else {
706 LoadSU = CreateNewSUnit(LoadNode);
707 LoadNode->setNodeId(LoadSU->NodeNum);
Dan Gohmane52e0892008-11-11 21:34:44 +0000708 ComputeLatency(LoadSU);
709 }
710
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000711 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000712 assert(N->getNodeId() == -1 && "Node already inserted!");
713 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +0000714
Dan Gohman17059682008-07-17 19:10:17 +0000715 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Dan Gohman856c0122008-02-16 00:25:40 +0000716 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000717 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000718 NewSU->isTwoAddress = true;
719 break;
720 }
721 }
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000722 if (TID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000723 NewSU->isCommutable = true;
Evan Cheng79e97132007-10-05 01:39:18 +0000724 ComputeLatency(NewSU);
725
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000726 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +0000727 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +0000728 SmallVector<SDep, 4> ChainSuccs;
729 SmallVector<SDep, 4> LoadPreds;
730 SmallVector<SDep, 4> NodePreds;
731 SmallVector<SDep, 4> NodeSuccs;
732 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
733 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000734 if (I->isCtrl())
Dan Gohman15af5522009-03-06 02:23:01 +0000735 ChainPreds.push_back(*I);
Evan Cheng3b245872010-02-05 01:27:11 +0000736 else if (isOperandOf(I->getSUnit(), LoadNode))
Dan Gohman2d170892008-12-09 22:54:47 +0000737 LoadPreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000738 else
Dan Gohman2d170892008-12-09 22:54:47 +0000739 NodePreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000740 }
741 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
742 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000743 if (I->isCtrl())
744 ChainSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000745 else
Dan Gohman2d170892008-12-09 22:54:47 +0000746 NodeSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000747 }
748
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000749 // Now assign edges to the newly-created nodes.
Dan Gohman15af5522009-03-06 02:23:01 +0000750 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
751 const SDep &Pred = ChainPreds[i];
752 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +0000753 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +0000754 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000755 }
Evan Cheng79e97132007-10-05 01:39:18 +0000756 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000757 const SDep &Pred = LoadPreds[i];
758 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +0000759 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +0000760 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000761 }
762 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000763 const SDep &Pred = NodePreds[i];
764 RemovePred(SU, Pred);
765 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000766 }
767 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000768 SDep D = NodeSuccs[i];
769 SUnit *SuccDep = D.getSUnit();
770 D.setSUnit(SU);
771 RemovePred(SuccDep, D);
772 D.setSUnit(NewSU);
773 AddPred(SuccDep, D);
Evan Cheng79e97132007-10-05 01:39:18 +0000774 }
775 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000776 SDep D = ChainSuccs[i];
777 SUnit *SuccDep = D.getSUnit();
778 D.setSUnit(SU);
779 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000780 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +0000781 D.setSUnit(LoadSU);
782 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000783 }
Andrew Trick2085a962010-12-21 22:25:04 +0000784 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000785
786 // Add a data dependency to reflect that NewSU reads the value defined
787 // by LoadSU.
788 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
Evan Cheng79e97132007-10-05 01:39:18 +0000789
Evan Cheng91e0fc92007-12-18 08:42:10 +0000790 if (isNewLoad)
791 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000792 AvailableQueue->addNode(NewSU);
793
794 ++NumUnfolds;
795
796 if (NewSU->NumSuccsLeft == 0) {
797 NewSU->isAvailable = true;
798 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +0000799 }
800 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000801 }
802
Evan Chengbdd062d2010-05-20 06:13:19 +0000803 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000804 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000805
806 // New SUnit has the exact same predecessors.
807 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
808 I != E; ++I)
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000809 if (!I->isArtificial())
Dan Gohman2d170892008-12-09 22:54:47 +0000810 AddPred(NewSU, *I);
Evan Cheng5924bf72007-09-25 01:54:36 +0000811
812 // Only copy scheduled successors. Cut them from old node's successor
813 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000814 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +0000815 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
816 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000817 if (I->isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +0000818 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000819 SUnit *SuccSU = I->getSUnit();
820 if (SuccSU->isScheduled) {
Dan Gohman2d170892008-12-09 22:54:47 +0000821 SDep D = *I;
822 D.setSUnit(NewSU);
823 AddPred(SuccSU, D);
824 D.setSUnit(SU);
825 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +0000826 }
827 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000828 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000829 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng5924bf72007-09-25 01:54:36 +0000830
831 AvailableQueue->updateNode(SU);
832 AvailableQueue->addNode(NewSU);
833
Evan Cheng1ec79b42007-09-27 07:09:03 +0000834 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000835 return NewSU;
836}
837
Evan Chengb2c42c62009-01-12 03:19:55 +0000838/// InsertCopiesAndMoveSuccs - Insert register copies and move all
839/// scheduled successors of the given SUnit to the last copy.
840void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
841 const TargetRegisterClass *DestRC,
842 const TargetRegisterClass *SrcRC,
Evan Cheng1ec79b42007-09-27 07:09:03 +0000843 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000844 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000845 CopyFromSU->CopySrcRC = SrcRC;
846 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +0000847
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000848 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000849 CopyToSU->CopySrcRC = DestRC;
850 CopyToSU->CopyDstRC = SrcRC;
851
852 // Only copy scheduled successors. Cut them from old node's successor
853 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000854 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +0000855 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
856 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000857 if (I->isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +0000858 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000859 SUnit *SuccSU = I->getSUnit();
860 if (SuccSU->isScheduled) {
861 SDep D = *I;
862 D.setSUnit(CopyToSU);
863 AddPred(SuccSU, D);
864 DelDeps.push_back(std::make_pair(SuccSU, *I));
Evan Cheng8e136a92007-09-26 21:36:17 +0000865 }
866 }
Evan Chengb2c42c62009-01-12 03:19:55 +0000867 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000868 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng8e136a92007-09-26 21:36:17 +0000869
Dan Gohman2d170892008-12-09 22:54:47 +0000870 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
871 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
Evan Cheng8e136a92007-09-26 21:36:17 +0000872
873 AvailableQueue->updateNode(SU);
874 AvailableQueue->addNode(CopyFromSU);
875 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000876 Copies.push_back(CopyFromSU);
877 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +0000878
Evan Chengb2c42c62009-01-12 03:19:55 +0000879 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +0000880}
881
882/// getPhysicalRegisterVT - Returns the ValueType of the physical register
883/// definition of the specified node.
884/// FIXME: Move to SelectionDAG?
Owen Anderson53aa7a92009-08-10 22:56:29 +0000885static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +0000886 const TargetInstrInfo *TII) {
Dan Gohman17059682008-07-17 19:10:17 +0000887 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Evan Cheng8e136a92007-09-26 21:36:17 +0000888 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
Chris Lattnerb0d06b42008-01-07 03:13:06 +0000889 unsigned NumRes = TID.getNumDefs();
890 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000891 if (Reg == *ImpDef)
892 break;
893 ++NumRes;
894 }
895 return N->getValueType(NumRes);
896}
897
Evan Chengb8905c42009-03-04 01:41:49 +0000898/// CheckForLiveRegDef - Return true and update live register vector if the
899/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000900static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Evan Chengb8905c42009-03-04 01:41:49 +0000901 std::vector<SUnit*> &LiveRegDefs,
902 SmallSet<unsigned, 4> &RegAdded,
903 SmallVector<unsigned, 4> &LRegs,
904 const TargetRegisterInfo *TRI) {
Andrew Trick12acde112010-12-23 03:43:21 +0000905 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
906
907 // Check if Ref is live.
908 if (!LiveRegDefs[Reg]) continue;
909
910 // Allow multiple uses of the same def.
911 if (LiveRegDefs[Reg] == SU) continue;
912
913 // Add Reg to the set of interfering live regs.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000914 if (RegAdded.insert(Reg))
Evan Chengb8905c42009-03-04 01:41:49 +0000915 LRegs.push_back(Reg);
Evan Chengb8905c42009-03-04 01:41:49 +0000916 }
Evan Chengb8905c42009-03-04 01:41:49 +0000917}
918
Evan Cheng5924bf72007-09-25 01:54:36 +0000919/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
920/// scheduling of the given node to satisfy live physical register dependencies.
921/// If the specific node is the last one that's available to schedule, do
922/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +0000923bool ScheduleDAGRRList::
924DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000925 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +0000926 return false;
927
Evan Chenge6f92252007-09-27 18:46:06 +0000928 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +0000929 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +0000930 //
931 // If SU is the currently live definition of the same register that it uses,
932 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +0000933 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
934 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +0000935 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Evan Chengb8905c42009-03-04 01:41:49 +0000936 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
937 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +0000938 }
939
Chris Lattner11a33812010-12-23 17:24:32 +0000940 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +0000941 if (Node->getOpcode() == ISD::INLINEASM) {
942 // Inline asm can clobber physical defs.
943 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000944 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +0000945 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +0000946
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000947 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +0000948 unsigned Flags =
949 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000950 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +0000951
952 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +0000953 if (InlineAsm::isRegDefKind(Flags) ||
954 InlineAsm::isRegDefEarlyClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +0000955 // Check for def of register or earlyclobber register.
956 for (; NumVals; --NumVals, ++i) {
957 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
958 if (TargetRegisterInfo::isPhysicalRegister(Reg))
959 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
960 }
961 } else
962 i += NumVals;
963 }
964 continue;
965 }
966
Dan Gohman072734e2008-11-13 23:24:17 +0000967 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +0000968 continue;
Dan Gohman17059682008-07-17 19:10:17 +0000969 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
Evan Cheng5924bf72007-09-25 01:54:36 +0000970 if (!TID.ImplicitDefs)
971 continue;
Evan Chengb8905c42009-03-04 01:41:49 +0000972 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
973 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +0000974 }
Andrew Trick2085a962010-12-21 22:25:04 +0000975
Evan Cheng5924bf72007-09-25 01:54:36 +0000976 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +0000977}
978
Andrew Trick528fad92010-12-23 05:42:20 +0000979/// Return a node that can be scheduled in this cycle. Requirements:
980/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000981/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +0000982/// (3) No Interferences: may unschedule to break register interferences.
983SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
984 SmallVector<SUnit*, 4> Interferences;
985 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
986
987 SUnit *CurSU = AvailableQueue->pop();
988 while (CurSU) {
989 SmallVector<unsigned, 4> LRegs;
990 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
991 break;
992 LRegsMap.insert(std::make_pair(CurSU, LRegs));
993
994 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
995 Interferences.push_back(CurSU);
996 CurSU = AvailableQueue->pop();
997 }
998 if (CurSU) {
999 // Add the nodes that aren't ready back onto the available list.
1000 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1001 Interferences[i]->isPending = false;
1002 assert(Interferences[i]->isAvailable && "must still be available");
1003 AvailableQueue->push(Interferences[i]);
1004 }
1005 return CurSU;
1006 }
1007
1008 // All candidates are delayed due to live physical reg dependencies.
1009 // Try backtracking, code duplication, or inserting cross class copies
1010 // to resolve it.
1011 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1012 SUnit *TrySU = Interferences[i];
1013 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1014
1015 // Try unscheduling up to the point where it's safe to schedule
1016 // this node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001017 SUnit *BtSU = NULL;
1018 unsigned LiveCycle = UINT_MAX;
Andrew Trick528fad92010-12-23 05:42:20 +00001019 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1020 unsigned Reg = LRegs[j];
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001021 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1022 BtSU = LiveRegGens[Reg];
1023 LiveCycle = BtSU->getHeight();
1024 }
Andrew Trick528fad92010-12-23 05:42:20 +00001025 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001026 if (!WillCreateCycle(TrySU, BtSU)) {
1027 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001028
1029 // Force the current node to be scheduled before the node that
1030 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001031 if (BtSU->isAvailable) {
1032 BtSU->isAvailable = false;
1033 if (!BtSU->isPending)
1034 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001035 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001036 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
Andrew Trick528fad92010-12-23 05:42:20 +00001037 /*Reg=*/0, /*isNormalMemory=*/false,
1038 /*isMustAlias=*/false, /*isArtificial=*/true));
1039
1040 // If one or more successors has been unscheduled, then the current
1041 // node is no longer avaialable. Schedule a successor that's now
1042 // available instead.
1043 if (!TrySU->isAvailable) {
1044 CurSU = AvailableQueue->pop();
1045 }
1046 else {
1047 CurSU = TrySU;
1048 TrySU->isPending = false;
1049 Interferences.erase(Interferences.begin()+i);
1050 }
1051 break;
1052 }
1053 }
1054
1055 if (!CurSU) {
1056 // Can't backtrack. If it's too expensive to copy the value, then try
1057 // duplicate the nodes that produces these "too expensive to copy"
1058 // values to break the dependency. In case even that doesn't work,
1059 // insert cross class copies.
1060 // If it's not too expensive, i.e. cost != -1, issue copies.
1061 SUnit *TrySU = Interferences[0];
1062 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1063 assert(LRegs.size() == 1 && "Can't handle this yet!");
1064 unsigned Reg = LRegs[0];
1065 SUnit *LRDef = LiveRegDefs[Reg];
1066 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1067 const TargetRegisterClass *RC =
1068 TRI->getMinimalPhysRegClass(Reg, VT);
1069 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1070
1071 // If cross copy register class is null, then it must be possible copy
1072 // the value directly. Do not try duplicate the def.
1073 SUnit *NewDef = 0;
1074 if (DestRC)
1075 NewDef = CopyAndMoveSuccessors(LRDef);
1076 else
1077 DestRC = RC;
1078 if (!NewDef) {
1079 // Issue copies, these can be expensive cross register class copies.
1080 SmallVector<SUnit*, 2> Copies;
1081 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1082 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1083 << " to SU #" << Copies.front()->NodeNum << "\n");
1084 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1085 /*Reg=*/0, /*isNormalMemory=*/false,
1086 /*isMustAlias=*/false,
1087 /*isArtificial=*/true));
1088 NewDef = Copies.back();
1089 }
1090
1091 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1092 << " to SU #" << TrySU->NodeNum << "\n");
1093 LiveRegDefs[Reg] = NewDef;
1094 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1095 /*Reg=*/0, /*isNormalMemory=*/false,
1096 /*isMustAlias=*/false,
1097 /*isArtificial=*/true));
1098 TrySU->isAvailable = false;
1099 CurSU = NewDef;
1100 }
1101
1102 assert(CurSU && "Unable to resolve live physical register dependencies!");
1103
1104 // Add the nodes that aren't ready back onto the available list.
1105 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1106 Interferences[i]->isPending = false;
1107 // May no longer be available due to backtracking.
1108 if (Interferences[i]->isAvailable) {
1109 AvailableQueue->push(Interferences[i]);
1110 }
1111 }
1112 return CurSU;
1113}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001114
Evan Chengd38c22b2006-05-11 23:55:42 +00001115/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1116/// schedulers.
1117void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001118 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001119 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001120
Evan Chengd38c22b2006-05-11 23:55:42 +00001121 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001122 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001123 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001124 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1125 RootSU->isAvailable = true;
1126 AvailableQueue->push(RootSU);
1127 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001128
1129 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001130 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001131 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001132 while (!AvailableQueue->empty()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001133 DEBUG(dbgs() << "\n*** Examining Available\n";
1134 AvailableQueue->dump(this));
1135
Andrew Trick528fad92010-12-23 05:42:20 +00001136 // Pick the best node to schedule taking all constraints into
1137 // consideration.
1138 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001139
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001140 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001141
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001142 ScheduleNodeBottomUp(SU);
1143
1144 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1145 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1146 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1147 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1148 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001149 }
1150
Evan Chengd38c22b2006-05-11 23:55:42 +00001151 // Reverse the order if it is bottom up.
1152 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001153
Evan Chengd38c22b2006-05-11 23:55:42 +00001154#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001155 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001156#endif
1157}
1158
1159//===----------------------------------------------------------------------===//
1160// Top-Down Scheduling
1161//===----------------------------------------------------------------------===//
1162
1163/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +00001164/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +00001165void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +00001166 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001167
Evan Chengd38c22b2006-05-11 23:55:42 +00001168#ifndef NDEBUG
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001169 if (SuccSU->NumPredsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +00001170 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +00001171 SuccSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +00001172 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +00001173 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +00001174 }
1175#endif
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001176 --SuccSU->NumPredsLeft;
1177
Dan Gohmanb9543432009-02-10 23:27:53 +00001178 // If all the node's predecessors are scheduled, this node is ready
1179 // to be scheduled. Ignore the special ExitSU node.
1180 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001181 SuccSU->isAvailable = true;
1182 AvailableQueue->push(SuccSU);
1183 }
1184}
1185
Dan Gohmanb9543432009-02-10 23:27:53 +00001186void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1187 // Top down: release successors
1188 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1189 I != E; ++I) {
1190 assert(!I->isAssignedRegDep() &&
1191 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1192
1193 ReleaseSucc(SU, &*I);
1194 }
1195}
1196
Evan Chengd38c22b2006-05-11 23:55:42 +00001197/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1198/// count of its successors. If a successor pending count is zero, add it to
1199/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +00001200void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +00001201 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +00001202 DEBUG(SU->dump(this));
Evan Chengd38c22b2006-05-11 23:55:42 +00001203
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001204 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1205 SU->setDepthToAtLeast(CurCycle);
Dan Gohman92a36d72008-11-17 21:31:02 +00001206 Sequence.push_back(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001207
Dan Gohmanb9543432009-02-10 23:27:53 +00001208 ReleaseSuccessors(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001209 SU->isScheduled = true;
Dan Gohman92a36d72008-11-17 21:31:02 +00001210 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001211}
1212
Dan Gohman54a187e2007-08-20 19:28:38 +00001213/// ListScheduleTopDown - The main loop of list scheduling for top-down
1214/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +00001215void ScheduleDAGRRList::ListScheduleTopDown() {
Evan Chengbdd062d2010-05-20 06:13:19 +00001216 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001217
Dan Gohmanb9543432009-02-10 23:27:53 +00001218 // Release any successors of the special Entry node.
1219 ReleaseSuccessors(&EntrySU);
1220
Evan Chengd38c22b2006-05-11 23:55:42 +00001221 // All leaves to Available queue.
1222 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1223 // It is available if it has no predecessors.
Dan Gohman4370f262008-04-15 01:22:18 +00001224 if (SUnits[i].Preds.empty()) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001225 AvailableQueue->push(&SUnits[i]);
1226 SUnits[i].isAvailable = true;
1227 }
1228 }
Andrew Trick2085a962010-12-21 22:25:04 +00001229
Evan Chengd38c22b2006-05-11 23:55:42 +00001230 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001231 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001232 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001233 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +00001234 SUnit *CurSU = AvailableQueue->pop();
Andrew Trick2085a962010-12-21 22:25:04 +00001235
Dan Gohmanc602dd42008-11-21 00:10:42 +00001236 if (CurSU)
Andrew Trick528fad92010-12-23 05:42:20 +00001237 ScheduleNodeTopDown(CurSU);
Dan Gohman4370f262008-04-15 01:22:18 +00001238 ++CurCycle;
Evan Chengbdd062d2010-05-20 06:13:19 +00001239 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001240 }
Andrew Trick2085a962010-12-21 22:25:04 +00001241
Evan Chengd38c22b2006-05-11 23:55:42 +00001242#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001243 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001244#endif
1245}
1246
1247
Evan Chengd38c22b2006-05-11 23:55:42 +00001248//===----------------------------------------------------------------------===//
1249// RegReductionPriorityQueue Implementation
1250//===----------------------------------------------------------------------===//
1251//
1252// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1253// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001254//
Evan Chengd38c22b2006-05-11 23:55:42 +00001255namespace {
1256 template<class SF>
1257 class RegReductionPriorityQueue;
Andrew Trick2085a962010-12-21 22:25:04 +00001258
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001259 struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1260 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1261 };
1262
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001263 /// bu_ls_rr_sort - Priority function for bottom up register pressure
1264 // reduction scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001265 struct bu_ls_rr_sort : public queue_sort {
1266 enum {
1267 IsBottomUp = true,
1268 HasReadyFilter = false
1269 };
1270
Evan Chengd38c22b2006-05-11 23:55:42 +00001271 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
1272 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
1273 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick2085a962010-12-21 22:25:04 +00001274
Evan Chengd38c22b2006-05-11 23:55:42 +00001275 bool operator()(const SUnit* left, const SUnit* right) const;
1276 };
1277
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001278 // td_ls_rr_sort - Priority function for top down register pressure reduction
1279 // scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001280 struct td_ls_rr_sort : public queue_sort {
1281 enum {
1282 IsBottomUp = false,
1283 HasReadyFilter = false
1284 };
1285
1286 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
Evan Chengd38c22b2006-05-11 23:55:42 +00001287 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
1288 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick2085a962010-12-21 22:25:04 +00001289
Evan Chengd38c22b2006-05-11 23:55:42 +00001290 bool operator()(const SUnit* left, const SUnit* right) const;
1291 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001292
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001293 // src_ls_rr_sort - Priority function for source order scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001294 struct src_ls_rr_sort : public queue_sort {
1295 enum {
1296 IsBottomUp = true,
1297 HasReadyFilter = false
1298 };
1299
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001300 RegReductionPriorityQueue<src_ls_rr_sort> *SPQ;
1301 src_ls_rr_sort(RegReductionPriorityQueue<src_ls_rr_sort> *spq)
1302 : SPQ(spq) {}
1303 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1304 : SPQ(RHS.SPQ) {}
Andrew Trick2085a962010-12-21 22:25:04 +00001305
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001306 bool operator()(const SUnit* left, const SUnit* right) const;
1307 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001308
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001309 // hybrid_ls_rr_sort - Priority function for hybrid scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001310 struct hybrid_ls_rr_sort : public queue_sort {
1311 enum {
1312 IsBottomUp = true,
1313 HasReadyFilter = false
1314 };
1315
Evan Chengbdd062d2010-05-20 06:13:19 +00001316 RegReductionPriorityQueue<hybrid_ls_rr_sort> *SPQ;
1317 hybrid_ls_rr_sort(RegReductionPriorityQueue<hybrid_ls_rr_sort> *spq)
1318 : SPQ(spq) {}
1319 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1320 : SPQ(RHS.SPQ) {}
Evan Chenga77f3d32010-07-21 06:09:07 +00001321
Evan Chengbdd062d2010-05-20 06:13:19 +00001322 bool operator()(const SUnit* left, const SUnit* right) const;
1323 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001324
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001325 // ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1326 // scheduler.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001327 struct ilp_ls_rr_sort : public queue_sort {
1328 enum {
1329 IsBottomUp = true,
1330 HasReadyFilter = true
1331 };
1332
Evan Cheng37b740c2010-07-24 00:39:05 +00001333 RegReductionPriorityQueue<ilp_ls_rr_sort> *SPQ;
1334 ilp_ls_rr_sort(RegReductionPriorityQueue<ilp_ls_rr_sort> *spq)
1335 : SPQ(spq) {}
1336 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1337 : SPQ(RHS.SPQ) {}
1338
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001339 bool isReady(SUnit *SU, unsigned CurCycle) const;
1340
Evan Cheng37b740c2010-07-24 00:39:05 +00001341 bool operator()(const SUnit* left, const SUnit* right) const;
1342 };
Evan Chengd38c22b2006-05-11 23:55:42 +00001343} // end anonymous namespace
1344
Dan Gohman186f65d2008-11-20 03:30:37 +00001345/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1346/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001347static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001348CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001349 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1350 if (SethiUllmanNumber != 0)
1351 return SethiUllmanNumber;
1352
1353 unsigned Extra = 0;
1354 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1355 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001356 if (I->isCtrl()) continue; // ignore chain preds
1357 SUnit *PredSU = I->getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001358 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001359 if (PredSethiUllman > SethiUllmanNumber) {
1360 SethiUllmanNumber = PredSethiUllman;
1361 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001362 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001363 ++Extra;
1364 }
1365
1366 SethiUllmanNumber += Extra;
1367
1368 if (SethiUllmanNumber == 0)
1369 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001370
Evan Cheng7e4abde2008-07-02 09:23:51 +00001371 return SethiUllmanNumber;
1372}
1373
Evan Chengd38c22b2006-05-11 23:55:42 +00001374namespace {
1375 template<class SF>
Nick Lewycky02d5f772009-10-25 06:33:48 +00001376 class RegReductionPriorityQueue : public SchedulingPriorityQueue {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001377 static SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker) {
1378 std::vector<SUnit *>::iterator Best = Q.begin();
1379 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1380 E = Q.end(); I != E; ++I)
1381 if (Picker(*Best, *I))
1382 Best = I;
1383 SUnit *V = *Best;
1384 if (Best != prior(Q.end()))
1385 std::swap(*Best, Q.back());
1386 Q.pop_back();
1387 return V;
1388 }
1389
Dan Gohman52c27382010-05-26 18:52:00 +00001390 std::vector<SUnit*> Queue;
1391 SF Picker;
Evan Chengbdd062d2010-05-20 06:13:19 +00001392 unsigned CurQueueId;
Evan Chengbf32e542010-07-22 06:24:48 +00001393 bool TracksRegPressure;
Evan Chengd38c22b2006-05-11 23:55:42 +00001394
Dan Gohman3f656df2008-11-20 02:45:51 +00001395 protected:
1396 // SUnits - The SUnits for the current graph.
1397 std::vector<SUnit> *SUnits;
Evan Chenga77f3d32010-07-21 06:09:07 +00001398
1399 MachineFunction &MF;
Dan Gohman3f656df2008-11-20 02:45:51 +00001400 const TargetInstrInfo *TII;
1401 const TargetRegisterInfo *TRI;
Evan Chenga77f3d32010-07-21 06:09:07 +00001402 const TargetLowering *TLI;
Dan Gohman3f656df2008-11-20 02:45:51 +00001403 ScheduleDAGRRList *scheduleDAG;
1404
Dan Gohman186f65d2008-11-20 03:30:37 +00001405 // SethiUllmanNumbers - The SethiUllman number for each node.
1406 std::vector<unsigned> SethiUllmanNumbers;
1407
Evan Chenga77f3d32010-07-21 06:09:07 +00001408 /// RegPressure - Tracking current reg pressure per register class.
1409 ///
Evan Cheng28590382010-07-21 23:53:58 +00001410 std::vector<unsigned> RegPressure;
Evan Chenga77f3d32010-07-21 06:09:07 +00001411
1412 /// RegLimit - Tracking the number of allocatable registers per register
1413 /// class.
Evan Cheng28590382010-07-21 23:53:58 +00001414 std::vector<unsigned> RegLimit;
Evan Chenga77f3d32010-07-21 06:09:07 +00001415
Dan Gohman3f656df2008-11-20 02:45:51 +00001416 public:
Evan Chenga77f3d32010-07-21 06:09:07 +00001417 RegReductionPriorityQueue(MachineFunction &mf,
Evan Chengbf32e542010-07-22 06:24:48 +00001418 bool tracksrp,
Evan Chenga77f3d32010-07-21 06:09:07 +00001419 const TargetInstrInfo *tii,
1420 const TargetRegisterInfo *tri,
1421 const TargetLowering *tli)
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001422 : SchedulingPriorityQueue(SF::HasReadyFilter), Picker(this),
1423 CurQueueId(0), TracksRegPressure(tracksrp),
Evan Chenga77f3d32010-07-21 06:09:07 +00001424 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
Evan Chengbf32e542010-07-22 06:24:48 +00001425 if (TracksRegPressure) {
1426 unsigned NumRC = TRI->getNumRegClasses();
1427 RegLimit.resize(NumRC);
1428 RegPressure.resize(NumRC);
1429 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1430 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1431 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1432 E = TRI->regclass_end(); I != E; ++I)
Evan Chengdf907f42010-07-23 22:39:59 +00001433 RegLimit[(*I)->getID()] = tli->getRegPressureLimit(*I, MF);
Evan Chengbf32e542010-07-22 06:24:48 +00001434 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001435 }
Andrew Trick2085a962010-12-21 22:25:04 +00001436
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001437 bool isBottomUp() const { return SF::IsBottomUp; }
1438
Dan Gohman3f656df2008-11-20 02:45:51 +00001439 void initNodes(std::vector<SUnit> &sunits) {
1440 SUnits = &sunits;
Dan Gohman186f65d2008-11-20 03:30:37 +00001441 // Add pseudo dependency edges for two-address nodes.
1442 AddPseudoTwoAddrDeps();
Dan Gohman9a658d72009-03-24 00:49:12 +00001443 // Reroute edges to nodes with multiple uses.
1444 PrescheduleNodesWithMultipleUses();
Dan Gohman186f65d2008-11-20 03:30:37 +00001445 // Calculate node priorities.
1446 CalculateSethiUllmanNumbers();
Dan Gohman3f656df2008-11-20 02:45:51 +00001447 }
Evan Cheng5924bf72007-09-25 01:54:36 +00001448
Dan Gohman186f65d2008-11-20 03:30:37 +00001449 void addNode(const SUnit *SU) {
1450 unsigned SUSize = SethiUllmanNumbers.size();
1451 if (SUnits->size() > SUSize)
1452 SethiUllmanNumbers.resize(SUSize*2, 0);
1453 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1454 }
Evan Cheng5924bf72007-09-25 01:54:36 +00001455
Dan Gohman186f65d2008-11-20 03:30:37 +00001456 void updateNode(const SUnit *SU) {
1457 SethiUllmanNumbers[SU->NodeNum] = 0;
1458 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1459 }
Evan Cheng5924bf72007-09-25 01:54:36 +00001460
Dan Gohman186f65d2008-11-20 03:30:37 +00001461 void releaseState() {
Dan Gohman3f656df2008-11-20 02:45:51 +00001462 SUnits = 0;
Dan Gohman186f65d2008-11-20 03:30:37 +00001463 SethiUllmanNumbers.clear();
Evan Chenga77f3d32010-07-21 06:09:07 +00001464 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Dan Gohman3f656df2008-11-20 02:45:51 +00001465 }
Dan Gohman186f65d2008-11-20 03:30:37 +00001466
1467 unsigned getNodePriority(const SUnit *SU) const {
1468 assert(SU->NodeNum < SethiUllmanNumbers.size());
1469 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
Dan Gohman261ee6b2009-01-07 22:30:55 +00001470 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
Dan Gohman186f65d2008-11-20 03:30:37 +00001471 // CopyToReg should be close to its uses to facilitate coalescing and
1472 // avoid spilling.
1473 return 0;
Chris Lattnerb06015a2010-02-09 19:54:29 +00001474 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1475 Opc == TargetOpcode::SUBREG_TO_REG ||
1476 Opc == TargetOpcode::INSERT_SUBREG)
Dan Gohman3027bb62009-04-16 20:57:10 +00001477 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1478 // close to their uses to facilitate coalescing.
Dan Gohman186f65d2008-11-20 03:30:37 +00001479 return 0;
Dan Gohman6571ef32009-02-11 21:29:39 +00001480 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1481 // If SU does not have a register use, i.e. it doesn't produce a value
1482 // that would be consumed (e.g. store), then it terminates a chain of
1483 // computation. Give it a large SethiUllman number so it will be
1484 // scheduled right before its predecessors that it doesn't lengthen
1485 // their live ranges.
Dan Gohman186f65d2008-11-20 03:30:37 +00001486 return 0xffff;
Dan Gohman6571ef32009-02-11 21:29:39 +00001487 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1488 // If SU does not have a register def, schedule it close to its uses
1489 // because it does not lengthen any live ranges.
Dan Gohman186f65d2008-11-20 03:30:37 +00001490 return 0;
Dan Gohman261ee6b2009-01-07 22:30:55 +00001491 return SethiUllmanNumbers[SU->NodeNum];
Dan Gohman186f65d2008-11-20 03:30:37 +00001492 }
Bill Wendling0a7056f2010-01-05 23:48:12 +00001493
1494 unsigned getNodeOrdering(const SUnit *SU) const {
1495 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1496 }
Evan Chengbdd062d2010-05-20 06:13:19 +00001497
Evan Chengd38c22b2006-05-11 23:55:42 +00001498 bool empty() const { return Queue.empty(); }
Andrew Trick2085a962010-12-21 22:25:04 +00001499
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001500 bool isReady(SUnit *U) const {
1501 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1502 }
1503
Evan Chengd38c22b2006-05-11 23:55:42 +00001504 void push(SUnit *U) {
Roman Levenstein6b371142008-04-29 09:07:59 +00001505 assert(!U->NodeQueueId && "Node in the queue already");
Evan Chengbdd062d2010-05-20 06:13:19 +00001506 U->NodeQueueId = ++CurQueueId;
Dan Gohman52c27382010-05-26 18:52:00 +00001507 Queue.push_back(U);
Evan Chengd38c22b2006-05-11 23:55:42 +00001508 }
Roman Levenstein6b371142008-04-29 09:07:59 +00001509
Evan Chengd38c22b2006-05-11 23:55:42 +00001510 SUnit *pop() {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001511 if (Queue.empty()) return NULL;
1512
1513 SUnit *V = popFromQueue(Queue, Picker);
Roman Levenstein6b371142008-04-29 09:07:59 +00001514 V->NodeQueueId = 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001515 return V;
1516 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001517
Evan Cheng5924bf72007-09-25 01:54:36 +00001518 void remove(SUnit *SU) {
Roman Levenstein6b371142008-04-29 09:07:59 +00001519 assert(!Queue.empty() && "Queue is empty!");
Dan Gohmana4db3352008-06-21 18:35:25 +00001520 assert(SU->NodeQueueId != 0 && "Not in queue!");
Dan Gohman52c27382010-05-26 18:52:00 +00001521 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1522 SU);
1523 if (I != prior(Queue.end()))
1524 std::swap(*I, Queue.back());
1525 Queue.pop_back();
Roman Levenstein6b371142008-04-29 09:07:59 +00001526 SU->NodeQueueId = 0;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001527 }
Dan Gohman3f656df2008-11-20 02:45:51 +00001528
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001529 bool HighRegPressure(const SUnit *SU) const {
Evan Chenga77f3d32010-07-21 06:09:07 +00001530 if (!TLI)
Evan Cheng28590382010-07-21 23:53:58 +00001531 return false;
Evan Chenga77f3d32010-07-21 06:09:07 +00001532
Evan Chenga77f3d32010-07-21 06:09:07 +00001533 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1534 I != E; ++I) {
1535 if (I->isCtrl())
1536 continue;
1537 SUnit *PredSU = I->getSUnit();
Evan Cheng28590382010-07-21 23:53:58 +00001538 const SDNode *PN = PredSU->getNode();
1539 if (!PN->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001540 if (PN->getOpcode() == ISD::CopyFromReg) {
1541 EVT VT = PN->getValueType(0);
Evan Cheng28590382010-07-21 23:53:58 +00001542 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1543 unsigned Cost = TLI->getRepRegClassCostFor(VT);
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001544 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1545 return true;
Evan Chengdf907f42010-07-23 22:39:59 +00001546 }
1547 continue;
1548 }
1549 unsigned POpc = PN->getMachineOpcode();
1550 if (POpc == TargetOpcode::IMPLICIT_DEF)
1551 continue;
1552 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1553 EVT VT = PN->getOperand(0).getValueType();
1554 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1555 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1556 // Check if this increases register pressure of the specific register
1557 // class to the point where it would cause spills.
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001558 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1559 return true;
Andrew Trick2085a962010-12-21 22:25:04 +00001560 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001561 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1562 POpc == TargetOpcode::SUBREG_TO_REG) {
1563 EVT VT = PN->getValueType(0);
1564 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1565 unsigned Cost = TLI->getRepRegClassCostFor(VT);
1566 // Check if this increases register pressure of the specific register
1567 // class to the point where it would cause spills.
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001568 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1569 return true;
Evan Chenga77f3d32010-07-21 06:09:07 +00001570 continue;
Evan Cheng28590382010-07-21 23:53:58 +00001571 }
1572 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
Evan Chenga77f3d32010-07-21 06:09:07 +00001573 for (unsigned i = 0; i != NumDefs; ++i) {
Evan Cheng28590382010-07-21 23:53:58 +00001574 EVT VT = PN->getValueType(i);
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001575 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1576 if (RegPressure[RCId] >= RegLimit[RCId])
1577 return true; // Reg pressure already high.
1578 unsigned Cost = TLI->getRepRegClassCostFor(VT);
Evan Cheng28590382010-07-21 23:53:58 +00001579 if (!PN->hasAnyUseOfValue(i))
Evan Chenga77f3d32010-07-21 06:09:07 +00001580 continue;
Evan Chenga77f3d32010-07-21 06:09:07 +00001581 // Check if this increases register pressure of the specific register
1582 // class to the point where it would cause spills.
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001583 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1584 return true;
Evan Chenga77f3d32010-07-21 06:09:07 +00001585 }
1586 }
1587
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001588 return false;
Evan Chenga77f3d32010-07-21 06:09:07 +00001589 }
1590
Evan Chengbf32e542010-07-22 06:24:48 +00001591 void ScheduledNode(SUnit *SU) {
1592 if (!TracksRegPressure)
1593 return;
1594
Evan Chenga77f3d32010-07-21 06:09:07 +00001595 const SDNode *N = SU->getNode();
Evan Chengdf907f42010-07-23 22:39:59 +00001596 if (!N->isMachineOpcode()) {
1597 if (N->getOpcode() != ISD::CopyToReg)
1598 return;
1599 } else {
1600 unsigned Opc = N->getMachineOpcode();
1601 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1602 Opc == TargetOpcode::INSERT_SUBREG ||
1603 Opc == TargetOpcode::SUBREG_TO_REG ||
1604 Opc == TargetOpcode::REG_SEQUENCE ||
1605 Opc == TargetOpcode::IMPLICIT_DEF)
1606 return;
1607 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001608
1609 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1610 I != E; ++I) {
1611 if (I->isCtrl())
1612 continue;
1613 SUnit *PredSU = I->getSUnit();
Evan Cheng28590382010-07-21 23:53:58 +00001614 if (PredSU->NumSuccsLeft != PredSU->NumSuccs)
Evan Chenga77f3d32010-07-21 06:09:07 +00001615 continue;
1616 const SDNode *PN = PredSU->getNode();
Evan Cheng28590382010-07-21 23:53:58 +00001617 if (!PN->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001618 if (PN->getOpcode() == ISD::CopyFromReg) {
1619 EVT VT = PN->getValueType(0);
Evan Cheng28590382010-07-21 23:53:58 +00001620 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1621 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1622 }
1623 continue;
1624 }
1625 unsigned POpc = PN->getMachineOpcode();
1626 if (POpc == TargetOpcode::IMPLICIT_DEF)
Evan Chenga77f3d32010-07-21 06:09:07 +00001627 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001628 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1629 EVT VT = PN->getOperand(0).getValueType();
1630 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1631 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
Andrew Trick2085a962010-12-21 22:25:04 +00001632 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001633 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1634 POpc == TargetOpcode::SUBREG_TO_REG) {
1635 EVT VT = PN->getValueType(0);
1636 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1637 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1638 continue;
1639 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001640 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1641 for (unsigned i = 0; i != NumDefs; ++i) {
1642 EVT VT = PN->getValueType(i);
1643 if (!PN->hasAnyUseOfValue(i))
1644 continue;
1645 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1646 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1647 }
1648 }
1649
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001650 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1651 // may transfer data dependencies to CopyToReg.
1652 if (SU->NumSuccs && N->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001653 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1654 for (unsigned i = 0; i != NumDefs; ++i) {
1655 EVT VT = N->getValueType(i);
1656 if (!N->hasAnyUseOfValue(i))
1657 continue;
1658 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1659 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
1660 // Register pressure tracking is imprecise. This can happen.
1661 RegPressure[RCId] = 0;
1662 else
1663 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
1664 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001665 }
Evan Chengbf32e542010-07-22 06:24:48 +00001666
1667 dumpRegPressure();
Evan Chenga77f3d32010-07-21 06:09:07 +00001668 }
1669
Evan Chengbf32e542010-07-22 06:24:48 +00001670 void UnscheduledNode(SUnit *SU) {
1671 if (!TracksRegPressure)
1672 return;
1673
Evan Chenga77f3d32010-07-21 06:09:07 +00001674 const SDNode *N = SU->getNode();
Evan Chengdf907f42010-07-23 22:39:59 +00001675 if (!N->isMachineOpcode()) {
1676 if (N->getOpcode() != ISD::CopyToReg)
1677 return;
Evan Cheng37b740c2010-07-24 00:39:05 +00001678 } else {
1679 unsigned Opc = N->getMachineOpcode();
1680 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1681 Opc == TargetOpcode::INSERT_SUBREG ||
1682 Opc == TargetOpcode::SUBREG_TO_REG ||
1683 Opc == TargetOpcode::REG_SEQUENCE ||
1684 Opc == TargetOpcode::IMPLICIT_DEF)
1685 return;
Evan Chengdf907f42010-07-23 22:39:59 +00001686 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001687
1688 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1689 I != E; ++I) {
1690 if (I->isCtrl())
1691 continue;
1692 SUnit *PredSU = I->getSUnit();
Evan Cheng28590382010-07-21 23:53:58 +00001693 if (PredSU->NumSuccsLeft != PredSU->NumSuccs)
Evan Chenga77f3d32010-07-21 06:09:07 +00001694 continue;
1695 const SDNode *PN = PredSU->getNode();
Evan Cheng28590382010-07-21 23:53:58 +00001696 if (!PN->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001697 if (PN->getOpcode() == ISD::CopyFromReg) {
1698 EVT VT = PN->getValueType(0);
Evan Cheng28590382010-07-21 23:53:58 +00001699 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1700 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1701 }
1702 continue;
1703 }
1704 unsigned POpc = PN->getMachineOpcode();
1705 if (POpc == TargetOpcode::IMPLICIT_DEF)
Evan Chenga77f3d32010-07-21 06:09:07 +00001706 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001707 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
1708 EVT VT = PN->getOperand(0).getValueType();
1709 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1710 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
Andrew Trick2085a962010-12-21 22:25:04 +00001711 continue;
Evan Chengdf907f42010-07-23 22:39:59 +00001712 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
1713 POpc == TargetOpcode::SUBREG_TO_REG) {
1714 EVT VT = PN->getValueType(0);
1715 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1716 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1717 continue;
1718 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001719 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
1720 for (unsigned i = 0; i != NumDefs; ++i) {
1721 EVT VT = PN->getValueType(i);
1722 if (!PN->hasAnyUseOfValue(i))
1723 continue;
1724 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
Evan Cheng28590382010-07-21 23:53:58 +00001725 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
Evan Chenga77f3d32010-07-21 06:09:07 +00001726 // Register pressure tracking is imprecise. This can happen.
1727 RegPressure[RCId] = 0;
Evan Cheng28590382010-07-21 23:53:58 +00001728 else
1729 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
Evan Chenga77f3d32010-07-21 06:09:07 +00001730 }
1731 }
1732
Evan Cheng8ae3eca2010-07-25 18:59:43 +00001733 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
1734 // may transfer data dependencies to CopyToReg.
1735 if (SU->NumSuccs && N->isMachineOpcode()) {
Evan Chengdf907f42010-07-23 22:39:59 +00001736 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1737 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1738 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00001739 if (VT == MVT::Glue || VT == MVT::Other)
Evan Chengdf907f42010-07-23 22:39:59 +00001740 continue;
1741 if (!N->hasAnyUseOfValue(i))
1742 continue;
1743 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1744 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
1745 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001746 }
Evan Chenga77f3d32010-07-21 06:09:07 +00001747
Evan Chenga77f3d32010-07-21 06:09:07 +00001748 dumpRegPressure();
1749 }
1750
Andrew Trick2085a962010-12-21 22:25:04 +00001751 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1752 scheduleDAG = scheduleDag;
Dan Gohman3f656df2008-11-20 02:45:51 +00001753 }
1754
Evan Chenga77f3d32010-07-21 06:09:07 +00001755 void dumpRegPressure() const {
1756 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1757 E = TRI->regclass_end(); I != E; ++I) {
1758 const TargetRegisterClass *RC = *I;
1759 unsigned Id = RC->getID();
1760 unsigned RP = RegPressure[Id];
1761 if (!RP) continue;
1762 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1763 << '\n');
1764 }
1765 }
1766
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001767 void dump(ScheduleDAG *DAG) const {
1768 // Emulate pop() without clobbering NodeQueueIds.
1769 std::vector<SUnit*> DumpQueue = Queue;
1770 SF DumpPicker = Picker;
1771 while (!DumpQueue.empty()) {
1772 SUnit *SU = popFromQueue(DumpQueue, DumpPicker);
1773 if (isBottomUp())
1774 dbgs() << "Height " << SU->getHeight() << ": ";
1775 else
1776 dbgs() << "Depth " << SU->getDepth() << ": ";
1777 SU->dump(DAG);
1778 }
1779 }
1780
Dan Gohman3f656df2008-11-20 02:45:51 +00001781 protected:
1782 bool canClobber(const SUnit *SU, const SUnit *Op);
1783 void AddPseudoTwoAddrDeps();
Dan Gohman9a658d72009-03-24 00:49:12 +00001784 void PrescheduleNodesWithMultipleUses();
Evan Cheng6730f032007-01-08 23:55:53 +00001785 void CalculateSethiUllmanNumbers();
Evan Cheng7e4abde2008-07-02 09:23:51 +00001786 };
1787
Dan Gohman186f65d2008-11-20 03:30:37 +00001788 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1789 BURegReductionPriorityQueue;
Evan Cheng7e4abde2008-07-02 09:23:51 +00001790
Dan Gohman186f65d2008-11-20 03:30:37 +00001791 typedef RegReductionPriorityQueue<td_ls_rr_sort>
1792 TDRegReductionPriorityQueue;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001793
1794 typedef RegReductionPriorityQueue<src_ls_rr_sort>
1795 SrcRegReductionPriorityQueue;
Evan Chengbdd062d2010-05-20 06:13:19 +00001796
1797 typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1798 HybridBURRPriorityQueue;
Evan Cheng37b740c2010-07-24 00:39:05 +00001799
1800 typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1801 ILPBURRPriorityQueue;
Evan Chengd38c22b2006-05-11 23:55:42 +00001802}
1803
Evan Chengb9e3db62007-03-14 22:43:40 +00001804/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00001805/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00001806static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001807 unsigned MaxHeight = 0;
Evan Cheng28748552007-03-13 23:25:11 +00001808 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00001809 I != E; ++I) {
Evan Chengce3bbe52009-02-10 08:30:11 +00001810 if (I->isCtrl()) continue; // ignore chain succs
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001811 unsigned Height = I->getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00001812 // If there are bunch of CopyToRegs stacked up, they should be considered
1813 // to be at the same position.
Dan Gohman2d170892008-12-09 22:54:47 +00001814 if (I->getSUnit()->getNode() &&
1815 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001816 Height = closestSucc(I->getSUnit())+1;
1817 if (Height > MaxHeight)
1818 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00001819 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001820 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00001821}
1822
Evan Cheng61bc51e2007-12-20 02:22:36 +00001823/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00001824/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00001825static unsigned calcMaxScratches(const SUnit *SU) {
1826 unsigned Scratches = 0;
1827 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Chengb5704992009-02-12 09:52:13 +00001828 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001829 if (I->isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00001830 Scratches++;
1831 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00001832 return Scratches;
1833}
1834
Evan Cheng6c1414f2010-10-29 18:09:28 +00001835/// hasOnlyLiveOutUse - Return true if SU has a single value successor that is a
1836/// CopyToReg to a virtual register. This SU def is probably a liveout and
1837/// it has no other use. It should be scheduled closer to the terminator.
1838static bool hasOnlyLiveOutUses(const SUnit *SU) {
1839 bool RetVal = false;
1840 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1841 I != E; ++I) {
1842 if (I->isCtrl()) continue;
1843 const SUnit *SuccSU = I->getSUnit();
1844 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
1845 unsigned Reg =
1846 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
1847 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1848 RetVal = true;
1849 continue;
1850 }
1851 }
1852 return false;
1853 }
1854 return RetVal;
1855}
1856
1857/// UnitsSharePred - Return true if the two scheduling units share a common
1858/// data predecessor.
1859static bool UnitsSharePred(const SUnit *left, const SUnit *right) {
1860 SmallSet<const SUnit*, 4> Preds;
1861 for (SUnit::const_pred_iterator I = left->Preds.begin(),E = left->Preds.end();
1862 I != E; ++I) {
1863 if (I->isCtrl()) continue; // ignore chain preds
1864 Preds.insert(I->getSUnit());
1865 }
1866 for (SUnit::const_pred_iterator I = right->Preds.begin(),E = right->Preds.end();
1867 I != E; ++I) {
1868 if (I->isCtrl()) continue; // ignore chain preds
1869 if (Preds.count(I->getSUnit()))
1870 return true;
1871 }
1872 return false;
1873}
1874
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001875template <typename RRSort>
1876static bool BURRSort(const SUnit *left, const SUnit *right,
1877 const RegReductionPriorityQueue<RRSort> *SPQ) {
Evan Cheng6730f032007-01-08 23:55:53 +00001878 unsigned LPriority = SPQ->getNodePriority(left);
1879 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng73bdf042008-03-01 00:39:47 +00001880 if (LPriority != RPriority)
1881 return LPriority > RPriority;
1882
1883 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1884 // e.g.
1885 // t1 = op t2, c1
1886 // t3 = op t4, c2
1887 //
1888 // and the following instructions are both ready.
1889 // t2 = op c3
1890 // t4 = op c4
1891 //
1892 // Then schedule t2 = op first.
1893 // i.e.
1894 // t4 = op c4
1895 // t2 = op c3
1896 // t1 = op t2, c1
1897 // t3 = op t4, c2
1898 //
1899 // This creates more short live intervals.
1900 unsigned LDist = closestSucc(left);
1901 unsigned RDist = closestSucc(right);
1902 if (LDist != RDist)
1903 return LDist < RDist;
1904
Evan Cheng3a14efa2009-02-12 08:59:45 +00001905 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00001906 unsigned LScratch = calcMaxScratches(left);
1907 unsigned RScratch = calcMaxScratches(right);
1908 if (LScratch != RScratch)
1909 return LScratch > RScratch;
1910
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001911 // Note: with a bottom-up ready filter, the height check may be redundant.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001912 if (left->getHeight() != right->getHeight())
1913 return left->getHeight() > right->getHeight();
Andrew Trick2085a962010-12-21 22:25:04 +00001914
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001915 if (left->getDepth() != right->getDepth())
1916 return left->getDepth() < right->getDepth();
Evan Cheng73bdf042008-03-01 00:39:47 +00001917
Andrew Trick2085a962010-12-21 22:25:04 +00001918 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00001919 "NodeQueueId cannot be zero");
1920 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00001921}
1922
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001923// Bottom up
1924bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1925 return BURRSort(left, right, SPQ);
1926}
1927
1928// Source order, otherwise bottom up.
Evan Chengbdd062d2010-05-20 06:13:19 +00001929bool src_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001930 unsigned LOrder = SPQ->getNodeOrdering(left);
1931 unsigned ROrder = SPQ->getNodeOrdering(right);
1932
1933 // Prefer an ordering where the lower the non-zero order number, the higher
1934 // the preference.
1935 if ((LOrder || ROrder) && LOrder != ROrder)
1936 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
1937
1938 return BURRSort(left, right, SPQ);
1939}
1940
Evan Chengbdd062d2010-05-20 06:13:19 +00001941bool hybrid_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const{
Evan Chengdebf9c52010-11-03 00:45:17 +00001942 if (left->isCall || right->isCall)
1943 // No way to compute latency of calls.
1944 return BURRSort(left, right, SPQ);
1945
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001946 bool LHigh = SPQ->HighRegPressure(left);
1947 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00001948 // Avoid causing spills. If register pressure is high, schedule for
1949 // register pressure reduction.
Evan Cheng28590382010-07-21 23:53:58 +00001950 if (LHigh && !RHigh)
1951 return true;
1952 else if (!LHigh && RHigh)
1953 return false;
Evan Chenge6d6c5d2010-07-26 21:49:07 +00001954 else if (!LHigh && !RHigh) {
Evan Cheng6c1414f2010-10-29 18:09:28 +00001955 // If the two nodes share an operand and one of them has a single
1956 // use that is a live out copy, favor the one that is live out. Otherwise
1957 // it will be difficult to eliminate the copy if the instruction is a
1958 // loop induction variable update. e.g.
1959 // BB:
1960 // sub r1, r3, #1
1961 // str r0, [r2, r3]
1962 // mov r3, r1
1963 // cmp
1964 // bne BB
1965 bool SharePred = UnitsSharePred(left, right);
1966 // FIXME: Only adjust if BB is a loop back edge.
1967 // FIXME: What's the cost of a copy?
1968 int LBonus = (SharePred && hasOnlyLiveOutUses(left)) ? 1 : 0;
1969 int RBonus = (SharePred && hasOnlyLiveOutUses(right)) ? 1 : 0;
1970 int LHeight = (int)left->getHeight() - LBonus;
1971 int RHeight = (int)right->getHeight() - RBonus;
1972
Evan Cheng28590382010-07-21 23:53:58 +00001973 // Low register pressure situation, schedule for latency if possible.
1974 bool LStall = left->SchedulingPref == Sched::Latency &&
Evan Cheng6c1414f2010-10-29 18:09:28 +00001975 (int)SPQ->getCurCycle() < LHeight;
Evan Cheng28590382010-07-21 23:53:58 +00001976 bool RStall = right->SchedulingPref == Sched::Latency &&
Evan Cheng6c1414f2010-10-29 18:09:28 +00001977 (int)SPQ->getCurCycle() < RHeight;
Evan Cheng28590382010-07-21 23:53:58 +00001978 // If scheduling one of the node will cause a pipeline stall, delay it.
1979 // If scheduling either one of the node will cause a pipeline stall, sort
1980 // them according to their height.
Evan Cheng28590382010-07-21 23:53:58 +00001981 if (LStall) {
1982 if (!RStall)
1983 return true;
Evan Cheng6c1414f2010-10-29 18:09:28 +00001984 if (LHeight != RHeight)
1985 return LHeight > RHeight;
Evan Cheng28590382010-07-21 23:53:58 +00001986 } else if (RStall)
Evan Chengbdd062d2010-05-20 06:13:19 +00001987 return false;
Evan Chengcc2efe12010-05-28 23:26:21 +00001988
Evan Cheng6c1414f2010-10-29 18:09:28 +00001989 // If either node is scheduling for latency, sort them by height
1990 // and latency.
Evan Cheng28590382010-07-21 23:53:58 +00001991 if (left->SchedulingPref == Sched::Latency ||
1992 right->SchedulingPref == Sched::Latency) {
Evan Cheng6c1414f2010-10-29 18:09:28 +00001993 if (LHeight != RHeight)
1994 return LHeight > RHeight;
Evan Cheng28590382010-07-21 23:53:58 +00001995 if (left->Latency != right->Latency)
1996 return left->Latency > right->Latency;
1997 }
Evan Chengcc2efe12010-05-28 23:26:21 +00001998 }
1999
Evan Chengbdd062d2010-05-20 06:13:19 +00002000 return BURRSort(left, right, SPQ);
2001}
2002
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002003// Schedule as many instructions in each cycle as possible. So don't make an
2004// instruction available unless it is ready in the current cycle.
2005bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2006 return SU->getHeight() <= CurCycle;
2007}
2008
Evan Cheng37b740c2010-07-24 00:39:05 +00002009bool ilp_ls_rr_sort::operator()(const SUnit *left,
2010 const SUnit *right) const {
Evan Chengdebf9c52010-11-03 00:45:17 +00002011 if (left->isCall || right->isCall)
2012 // No way to compute latency of calls.
2013 return BURRSort(left, right, SPQ);
2014
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002015 bool LHigh = SPQ->HighRegPressure(left);
2016 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002017 // Avoid causing spills. If register pressure is high, schedule for
2018 // register pressure reduction.
2019 if (LHigh && !RHigh)
2020 return true;
2021 else if (!LHigh && RHigh)
2022 return false;
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002023 else if (!LHigh && !RHigh) {
Evan Cheng8ae3eca2010-07-25 18:59:43 +00002024 // Low register pressure situation, schedule to maximize instruction level
2025 // parallelism.
Evan Cheng37b740c2010-07-24 00:39:05 +00002026 if (left->NumPreds > right->NumPreds)
2027 return false;
2028 else if (left->NumPreds < right->NumPreds)
2029 return false;
2030 }
2031
2032 return BURRSort(left, right, SPQ);
2033}
2034
Dan Gohman3f656df2008-11-20 02:45:51 +00002035template<class SF>
Evan Cheng7e4abde2008-07-02 09:23:51 +00002036bool
Dan Gohman3f656df2008-11-20 02:45:51 +00002037RegReductionPriorityQueue<SF>::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002038 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002039 unsigned Opc = SU->getNode()->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002040 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002041 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002042 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002043 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002044 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002045 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002046 if (DU->getNodeId() != -1 &&
2047 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002048 return true;
2049 }
2050 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002051 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002052 return false;
2053}
2054
Evan Chengf9891412007-12-20 09:25:31 +00002055/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002056/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002057static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002058 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002059 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002060 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002061 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2062 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002063 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002064 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002065 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002066 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002067 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002068 const unsigned *SUImpDefs =
2069 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2070 if (!SUImpDefs)
2071 return false;
2072 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002073 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002074 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002075 continue;
2076 if (!N->hasAnyUseOfValue(i))
2077 continue;
2078 unsigned Reg = ImpDefs[i - NumDefs];
2079 for (;*SUImpDefs; ++SUImpDefs) {
2080 unsigned SUReg = *SUImpDefs;
2081 if (TRI->regsOverlap(Reg, SUReg))
2082 return true;
2083 }
Evan Chengf9891412007-12-20 09:25:31 +00002084 }
2085 }
2086 return false;
2087}
2088
Dan Gohman9a658d72009-03-24 00:49:12 +00002089/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2090/// are not handled well by the general register pressure reduction
2091/// heuristics. When presented with code like this:
2092///
2093/// N
2094/// / |
2095/// / |
2096/// U store
2097/// |
2098/// ...
2099///
2100/// the heuristics tend to push the store up, but since the
2101/// operand of the store has another use (U), this would increase
2102/// the length of that other use (the U->N edge).
2103///
2104/// This function transforms code like the above to route U's
2105/// dependence through the store when possible, like this:
2106///
2107/// N
2108/// ||
2109/// ||
2110/// store
2111/// |
2112/// U
2113/// |
2114/// ...
2115///
2116/// This results in the store being scheduled immediately
2117/// after N, which shortens the U->N live range, reducing
2118/// register pressure.
2119///
2120template<class SF>
2121void RegReductionPriorityQueue<SF>::PrescheduleNodesWithMultipleUses() {
2122 // Visit all the nodes in topological order, working top-down.
2123 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2124 SUnit *SU = &(*SUnits)[i];
2125 // For now, only look at nodes with no data successors, such as stores.
2126 // These are especially important, due to the heuristics in
2127 // getNodePriority for nodes with no data successors.
2128 if (SU->NumSuccs != 0)
2129 continue;
2130 // For now, only look at nodes with exactly one data predecessor.
2131 if (SU->NumPreds != 1)
2132 continue;
2133 // Avoid prescheduling copies to virtual registers, which don't behave
2134 // like other nodes from the perspective of scheduling heuristics.
2135 if (SDNode *N = SU->getNode())
2136 if (N->getOpcode() == ISD::CopyToReg &&
2137 TargetRegisterInfo::isVirtualRegister
2138 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2139 continue;
2140
2141 // Locate the single data predecessor.
2142 SUnit *PredSU = 0;
2143 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2144 EE = SU->Preds.end(); II != EE; ++II)
2145 if (!II->isCtrl()) {
2146 PredSU = II->getSUnit();
2147 break;
2148 }
2149 assert(PredSU);
2150
2151 // Don't rewrite edges that carry physregs, because that requires additional
2152 // support infrastructure.
2153 if (PredSU->hasPhysRegDefs)
2154 continue;
2155 // Short-circuit the case where SU is PredSU's only data successor.
2156 if (PredSU->NumSuccs == 1)
2157 continue;
2158 // Avoid prescheduling to copies from virtual registers, which don't behave
2159 // like other nodes from the perspective of scheduling // heuristics.
2160 if (SDNode *N = SU->getNode())
2161 if (N->getOpcode() == ISD::CopyFromReg &&
2162 TargetRegisterInfo::isVirtualRegister
2163 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2164 continue;
2165
2166 // Perform checks on the successors of PredSU.
2167 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2168 EE = PredSU->Succs.end(); II != EE; ++II) {
2169 SUnit *PredSuccSU = II->getSUnit();
2170 if (PredSuccSU == SU) continue;
2171 // If PredSU has another successor with no data successors, for
2172 // now don't attempt to choose either over the other.
2173 if (PredSuccSU->NumSuccs == 0)
2174 goto outer_loop_continue;
2175 // Don't break physical register dependencies.
2176 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2177 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2178 goto outer_loop_continue;
2179 // Don't introduce graph cycles.
2180 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2181 goto outer_loop_continue;
2182 }
2183
2184 // Ok, the transformation is safe and the heuristics suggest it is
2185 // profitable. Update the graph.
Evan Chengbdd062d2010-05-20 06:13:19 +00002186 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2187 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002188 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002189 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2190 SDep Edge = PredSU->Succs[i];
2191 assert(!Edge.isAssignedRegDep());
2192 SUnit *SuccSU = Edge.getSUnit();
2193 if (SuccSU != SU) {
2194 Edge.setSUnit(PredSU);
2195 scheduleDAG->RemovePred(SuccSU, Edge);
2196 scheduleDAG->AddPred(SU, Edge);
2197 Edge.setSUnit(SU);
2198 scheduleDAG->AddPred(SuccSU, Edge);
2199 --i;
2200 }
2201 }
2202 outer_loop_continue:;
2203 }
2204}
2205
Evan Chengd38c22b2006-05-11 23:55:42 +00002206/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2207/// it as a def&use operand. Add a pseudo control edge from it to the other
2208/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002209/// first (lower in the schedule). If both nodes are two-address, favor the
2210/// one that has a CopyToReg use (more likely to be a loop induction update).
2211/// If both are two-address, but one is commutable while the other is not
2212/// commutable, favor the one that's not commutable.
Dan Gohman3f656df2008-11-20 02:45:51 +00002213template<class SF>
2214void RegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002215 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
Dan Gohmane955c482008-08-05 14:45:15 +00002216 SUnit *SU = &(*SUnits)[i];
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002217 if (!SU->isTwoAddress)
2218 continue;
2219
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002220 SDNode *Node = SU->getNode();
Chris Lattner11a33812010-12-23 17:24:32 +00002221 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002222 continue;
2223
Evan Cheng6c1414f2010-10-29 18:09:28 +00002224 bool isLiveOut = hasOnlyLiveOutUses(SU);
Dan Gohman17059682008-07-17 19:10:17 +00002225 unsigned Opc = Node->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002226 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002227 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002228 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002229 for (unsigned j = 0; j != NumOps; ++j) {
Dan Gohman82016c22008-11-19 02:00:32 +00002230 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2231 continue;
2232 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2233 if (DU->getNodeId() == -1)
2234 continue;
2235 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2236 if (!DUSU) continue;
2237 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2238 E = DUSU->Succs.end(); I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002239 if (I->isCtrl()) continue;
2240 SUnit *SuccSU = I->getSUnit();
Dan Gohman82016c22008-11-19 02:00:32 +00002241 if (SuccSU == SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002242 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002243 // Be conservative. Ignore if nodes aren't at roughly the same
2244 // depth and height.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002245 if (SuccSU->getHeight() < SU->getHeight() &&
2246 (SU->getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002247 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002248 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2249 // constrains whatever is using the copy, instead of the copy
2250 // itself. In the case that the copy is coalesced, this
2251 // preserves the intent of the pseudo two-address heurietics.
2252 while (SuccSU->Succs.size() == 1 &&
2253 SuccSU->getNode()->isMachineOpcode() &&
2254 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002255 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002256 SuccSU = SuccSU->Succs.front().getSUnit();
2257 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002258 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2259 continue;
2260 // Don't constrain nodes with physical register defs if the
2261 // predecessor can clobber them.
Dan Gohmanf3746cb2009-03-24 00:50:07 +00002262 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
Dan Gohman82016c22008-11-19 02:00:32 +00002263 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002264 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002265 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002266 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2267 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002268 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002269 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2270 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2271 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002272 continue;
2273 if ((!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002274 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Dan Gohman82016c22008-11-19 02:00:32 +00002275 (!SU->isCommutable && SuccSU->isCommutable)) &&
2276 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002277 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002278 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
Dan Gohman79c35162009-01-06 01:19:04 +00002279 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
Dan Gohmanbf8e5202009-01-06 01:28:56 +00002280 /*Reg=*/0, /*isNormalMemory=*/false,
2281 /*isMustAlias=*/false,
Dan Gohman2d170892008-12-09 22:54:47 +00002282 /*isArtificial=*/true));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002283 }
2284 }
2285 }
2286 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002287}
2288
Evan Cheng6730f032007-01-08 23:55:53 +00002289/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
2290/// scheduling units.
Dan Gohman186f65d2008-11-20 03:30:37 +00002291template<class SF>
2292void RegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
Evan Chengd38c22b2006-05-11 23:55:42 +00002293 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick2085a962010-12-21 22:25:04 +00002294
Evan Chengd38c22b2006-05-11 23:55:42 +00002295 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
Dan Gohman186f65d2008-11-20 03:30:37 +00002296 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002297}
Evan Chengd38c22b2006-05-11 23:55:42 +00002298
Roman Levenstein30d09512008-03-27 09:44:37 +00002299/// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
Roman Levensteinbc674502008-03-27 09:14:57 +00002300/// predecessors of the successors of the SUnit SU. Stop when the provided
2301/// limit is exceeded.
Andrew Trick2085a962010-12-21 22:25:04 +00002302static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
Roman Levensteinbc674502008-03-27 09:14:57 +00002303 unsigned Limit) {
2304 unsigned Sum = 0;
2305 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2306 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002307 const SUnit *SuccSU = I->getSUnit();
Roman Levensteinbc674502008-03-27 09:14:57 +00002308 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2309 EE = SuccSU->Preds.end(); II != EE; ++II) {
Dan Gohman2d170892008-12-09 22:54:47 +00002310 SUnit *PredSU = II->getSUnit();
Evan Cheng16d72072008-03-29 18:34:22 +00002311 if (!PredSU->isScheduled)
2312 if (++Sum > Limit)
2313 return Sum;
Roman Levensteinbc674502008-03-27 09:14:57 +00002314 }
2315 }
2316 return Sum;
2317}
2318
Evan Chengd38c22b2006-05-11 23:55:42 +00002319
2320// Top down
2321bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Evan Cheng6730f032007-01-08 23:55:53 +00002322 unsigned LPriority = SPQ->getNodePriority(left);
2323 unsigned RPriority = SPQ->getNodePriority(right);
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002324 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2325 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00002326 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2327 bool RIsFloater = RIsTarget && right->NumPreds == 0;
Roman Levensteinbc674502008-03-27 09:14:57 +00002328 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2329 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00002330
2331 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2332 return false;
2333 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2334 return true;
2335
Evan Chengd38c22b2006-05-11 23:55:42 +00002336 if (LIsFloater)
2337 LBonus -= 2;
2338 if (RIsFloater)
2339 RBonus -= 2;
2340 if (left->NumSuccs == 1)
2341 LBonus += 2;
2342 if (right->NumSuccs == 1)
2343 RBonus += 2;
2344
Evan Cheng73bdf042008-03-01 00:39:47 +00002345 if (LPriority+LBonus != RPriority+RBonus)
2346 return LPriority+LBonus < RPriority+RBonus;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00002347
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002348 if (left->getDepth() != right->getDepth())
2349 return left->getDepth() < right->getDepth();
Evan Cheng73bdf042008-03-01 00:39:47 +00002350
2351 if (left->NumSuccsLeft != right->NumSuccsLeft)
2352 return left->NumSuccsLeft > right->NumSuccsLeft;
2353
Andrew Trick2085a962010-12-21 22:25:04 +00002354 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002355 "NodeQueueId cannot be zero");
2356 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002357}
2358
Evan Chengd38c22b2006-05-11 23:55:42 +00002359//===----------------------------------------------------------------------===//
2360// Public Constructor Functions
2361//===----------------------------------------------------------------------===//
2362
Dan Gohmandfaf6462009-02-11 04:27:20 +00002363llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002364llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2365 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002366 const TargetMachine &TM = IS->TM;
2367 const TargetInstrInfo *TII = TM.getInstrInfo();
2368 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002369
Evan Chenga77f3d32010-07-21 06:09:07 +00002370 BURegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002371 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002372 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002373 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002374 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002375}
2376
Dan Gohmandfaf6462009-02-11 04:27:20 +00002377llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002378llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2379 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002380 const TargetMachine &TM = IS->TM;
2381 const TargetInstrInfo *TII = TM.getInstrInfo();
2382 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002383
Evan Chenga77f3d32010-07-21 06:09:07 +00002384 TDRegReductionPriorityQueue *PQ =
2385 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002386 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Dan Gohman3f656df2008-11-20 02:45:51 +00002387 PQ->setScheduleDAG(SD);
2388 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002389}
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002390
2391llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002392llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2393 CodeGenOpt::Level OptLevel) {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002394 const TargetMachine &TM = IS->TM;
2395 const TargetInstrInfo *TII = TM.getInstrInfo();
2396 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002397
Evan Chenga77f3d32010-07-21 06:09:07 +00002398 SrcRegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002399 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002400 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002401 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002402 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002403}
2404
2405llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002406llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2407 CodeGenOpt::Level OptLevel) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002408 const TargetMachine &TM = IS->TM;
2409 const TargetInstrInfo *TII = TM.getInstrInfo();
2410 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Evan Chenga77f3d32010-07-21 06:09:07 +00002411 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002412
Evan Chenga77f3d32010-07-21 06:09:07 +00002413 HybridBURRPriorityQueue *PQ =
Evan Chengdf907f42010-07-23 22:39:59 +00002414 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002415
2416 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002417 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002418 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002419}
Evan Cheng37b740c2010-07-24 00:39:05 +00002420
2421llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002422llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2423 CodeGenOpt::Level OptLevel) {
Evan Cheng37b740c2010-07-24 00:39:05 +00002424 const TargetMachine &TM = IS->TM;
2425 const TargetInstrInfo *TII = TM.getInstrInfo();
2426 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2427 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002428
Evan Cheng37b740c2010-07-24 00:39:05 +00002429 ILPBURRPriorityQueue *PQ =
2430 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002431 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00002432 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002433 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00002434}