blob: 6175bc275ea6ddcaeed8ddc458d32df0426932a4 [file] [log] [blame]
Evan Chengd38c22b2006-05-11 23:55:42 +00001//===----- ScheduleDAGList.cpp - Reg pressure reduction list scheduler ----===//
2//
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"
Evan Chengd38c22b2006-05-11 23:55:42 +000019#include "llvm/CodeGen/ScheduleDAG.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000020#include "llvm/CodeGen/SchedulerRegistry.h"
Dan Gohman3a4be0f2008-02-10 18:45:23 +000021#include "llvm/Target/TargetRegisterInfo.h"
Owen Anderson8c2c1e92006-05-12 06:33:49 +000022#include "llvm/Target/TargetData.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000023#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetInstrInfo.h"
25#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000026#include "llvm/Support/Compiler.h"
Dan Gohmana4db3352008-06-21 18:35:25 +000027#include "llvm/ADT/BitVector.h"
28#include "llvm/ADT/PriorityQueue.h"
Evan Chenge6f92252007-09-27 18:46:06 +000029#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng5924bf72007-09-25 01:54:36 +000030#include "llvm/ADT/SmallSet.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000031#include "llvm/ADT/Statistic.h"
Roman Levenstein6b371142008-04-29 09:07:59 +000032#include "llvm/ADT/STLExtras.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000033#include <climits>
Evan Chengd38c22b2006-05-11 23:55:42 +000034#include "llvm/Support/CommandLine.h"
35using namespace llvm;
36
Dan Gohmanfd227e92008-03-25 17:10:29 +000037STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
Evan Cheng79e97132007-10-05 01:39:18 +000038STATISTIC(NumUnfolds, "Number of nodes unfolded");
Evan Cheng1ec79b42007-09-27 07:09:03 +000039STATISTIC(NumDups, "Number of duplicated nodes");
40STATISTIC(NumCCCopies, "Number of cross class copies");
41
Jim Laskey95eda5b2006-08-01 14:21:23 +000042static RegisterScheduler
43 burrListDAGScheduler("list-burr",
44 " Bottom-up register reduction list scheduling",
45 createBURRListDAGScheduler);
46static RegisterScheduler
47 tdrListrDAGScheduler("list-tdrr",
48 " Top-down register reduction list scheduling",
49 createTDRRListDAGScheduler);
50
Evan Chengd38c22b2006-05-11 23:55:42 +000051namespace {
Evan Chengd38c22b2006-05-11 23:55:42 +000052//===----------------------------------------------------------------------===//
53/// ScheduleDAGRRList - The actual register reduction list scheduler
54/// implementation. This supports both top-down and bottom-up scheduling.
55///
Chris Lattnere097e6f2006-06-28 22:17:39 +000056class VISIBILITY_HIDDEN ScheduleDAGRRList : public ScheduleDAG {
Evan Chengd38c22b2006-05-11 23:55:42 +000057private:
58 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
59 /// it is top-down.
60 bool isBottomUp;
61
62 /// AvailableQueue - The priority queue to use for the available SUnits.
Evan Chengd38c22b2006-05-11 23:55:42 +000063 SchedulingPriorityQueue *AvailableQueue;
64
Evan Cheng5924bf72007-09-25 01:54:36 +000065 /// LiveRegs / LiveRegDefs - A set of physical registers and their definition
66 /// that are "live". These nodes must be scheduled before any other nodes that
67 /// modifies the registers can be scheduled.
68 SmallSet<unsigned, 4> LiveRegs;
69 std::vector<SUnit*> LiveRegDefs;
70 std::vector<unsigned> LiveRegCycles;
71
Evan Chengd38c22b2006-05-11 23:55:42 +000072public:
73 ScheduleDAGRRList(SelectionDAG &dag, MachineBasicBlock *bb,
74 const TargetMachine &tm, bool isbottomup,
75 SchedulingPriorityQueue *availqueue)
76 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
77 AvailableQueue(availqueue) {
78 }
79
80 ~ScheduleDAGRRList() {
81 delete AvailableQueue;
82 }
83
84 void Schedule();
85
Roman Levenstein733a4d62008-03-26 11:23:38 +000086 /// IsReachable - Checks if SU is reachable from TargetSU.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +000087 bool IsReachable(SUnit *SU, SUnit *TargetSU);
88
89 /// willCreateCycle - Returns true if adding an edge from SU to TargetSU will
90 /// create a cycle.
91 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU);
92
93 /// AddPred - This adds the specified node X as a predecessor of
94 /// the current node Y if not already.
Roman Levenstein733a4d62008-03-26 11:23:38 +000095 /// This returns true if this is a new predecessor.
96 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +000097 bool AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
Roman Levenstein733a4d62008-03-26 11:23:38 +000098 unsigned PhyReg = 0, int Cost = 1);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +000099
Roman Levenstein733a4d62008-03-26 11:23:38 +0000100 /// RemovePred - This removes the specified node N from the predecessors of
101 /// the current node M. Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000102 bool RemovePred(SUnit *M, SUnit *N, bool isCtrl, bool isSpecial);
103
Evan Chengd38c22b2006-05-11 23:55:42 +0000104private:
Evan Cheng8e136a92007-09-26 21:36:17 +0000105 void ReleasePred(SUnit*, bool, unsigned);
106 void ReleaseSucc(SUnit*, bool isChain, unsigned);
107 void CapturePred(SUnit*, SUnit*, bool);
108 void ScheduleNodeBottomUp(SUnit*, unsigned);
109 void ScheduleNodeTopDown(SUnit*, unsigned);
110 void UnscheduleNodeBottomUp(SUnit*);
111 void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
112 SUnit *CopyAndMoveSuccessors(SUnit*);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000113 void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
Evan Cheng8e136a92007-09-26 21:36:17 +0000114 const TargetRegisterClass*,
Evan Cheng1ec79b42007-09-27 07:09:03 +0000115 const TargetRegisterClass*,
116 SmallVector<SUnit*, 2>&);
117 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
Evan Chengd38c22b2006-05-11 23:55:42 +0000118 void ListScheduleTopDown();
119 void ListScheduleBottomUp();
Evan Chengafed73e2006-05-12 01:58:24 +0000120 void CommuteNodesToReducePressure();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000121
122
123 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000124 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000125 SUnit *CreateNewSUnit(SDNode *N) {
126 SUnit *NewNode = NewSUnit(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000127 // Update the topological ordering.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000128 if (NewNode->NodeNum >= Node2Index.size())
129 InitDAGTopologicalSorting();
130 return NewNode;
131 }
132
Roman Levenstein733a4d62008-03-26 11:23:38 +0000133 /// CreateClone - Creates a new SUnit from an existing one.
134 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000135 SUnit *CreateClone(SUnit *N) {
136 SUnit *NewNode = Clone(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000137 // Update the topological ordering.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000138 if (NewNode->NodeNum >= Node2Index.size())
139 InitDAGTopologicalSorting();
140 return NewNode;
141 }
142
143 /// Functions for preserving the topological ordering
144 /// even after dynamic insertions of new edges.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000145 /// This allows a very fast implementation of IsReachable.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000146
147
148 /**
149 The idea of the algorithm is taken from
150 "Online algorithms for managing the topological order of
Roman Levenstein733a4d62008-03-26 11:23:38 +0000151 a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
152 This is the MNR algorithm, which was first introduced by
153 A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000154 "Maintaining a topological order under edge insertions".
155
156 Short description of the algorithm:
157
158 Topological ordering, ord, of a DAG maps each node to a topological
Roman Levenstein733a4d62008-03-26 11:23:38 +0000159 index so that for all edges X->Y it is the case that ord(X) < ord(Y).
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000160
161 This means that if there is a path from the node X to the node Z,
162 then ord(X) < ord(Z).
163
164 This property can be used to check for reachability of nodes:
165 if Z is reachable from X, then an insertion of the edge Z->X would
166 create a cycle.
167
Roman Levenstein733a4d62008-03-26 11:23:38 +0000168 The algorithm first computes a topological ordering for the DAG by initializing
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000169 the Index2Node and Node2Index arrays and then tries to keep the ordering
170 up-to-date after edge insertions by reordering the DAG.
171
172 On insertion of the edge X->Y, the algorithm first marks by calling DFS the
173 nodes reachable from Y, and then shifts them using Shift to lie immediately
174 after X in Index2Node.
175 */
176
Roman Levenstein733a4d62008-03-26 11:23:38 +0000177 /// InitDAGTopologicalSorting - create the initial topological
178 /// ordering from the DAG to be scheduled.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000179 void InitDAGTopologicalSorting();
180
181 /// DFS - make a DFS traversal and mark all nodes affected by the
Roman Levenstein733a4d62008-03-26 11:23:38 +0000182 /// edge insertion. These nodes will later get new topological indexes
183 /// by means of the Shift method.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000184 void DFS(SUnit *SU, int UpperBound, bool& HasLoop);
185
186 /// Shift - reassign topological indexes for the nodes in the DAG
Roman Levenstein733a4d62008-03-26 11:23:38 +0000187 /// to preserve the topological ordering.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000188 void Shift(BitVector& Visited, int LowerBound, int UpperBound);
189
Roman Levenstein733a4d62008-03-26 11:23:38 +0000190 /// Allocate - assign the topological index to the node n.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000191 void Allocate(int n, int index);
192
Roman Levenstein733a4d62008-03-26 11:23:38 +0000193 /// Index2Node - Maps topological index to the node number.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000194 std::vector<int> Index2Node;
Roman Levenstein733a4d62008-03-26 11:23:38 +0000195 /// Node2Index - Maps the node number to its topological index.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000196 std::vector<int> Node2Index;
Roman Levenstein733a4d62008-03-26 11:23:38 +0000197 /// Visited - a set of nodes visited during a DFS traversal.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000198 BitVector Visited;
Evan Chengd38c22b2006-05-11 23:55:42 +0000199};
200} // end anonymous namespace
201
202
203/// Schedule - Schedule the DAG using list scheduling.
204void ScheduleDAGRRList::Schedule() {
Bill Wendling22e978a2006-12-07 20:04:42 +0000205 DOUT << "********** List Scheduling **********\n";
Evan Cheng5924bf72007-09-25 01:54:36 +0000206
Dan Gohman3a4be0f2008-02-10 18:45:23 +0000207 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
208 LiveRegCycles.resize(TRI->getNumRegs(), 0);
Evan Cheng5924bf72007-09-25 01:54:36 +0000209
Evan Chengd38c22b2006-05-11 23:55:42 +0000210 // Build scheduling units.
211 BuildSchedUnits();
212
Evan Chengd38c22b2006-05-11 23:55:42 +0000213 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Chris Lattnerd86418a2006-08-17 00:09:56 +0000214 SUnits[su].dumpAll(&DAG));
Evan Cheng47fbeda2006-10-14 08:34:06 +0000215 CalculateDepths();
216 CalculateHeights();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000217 InitDAGTopologicalSorting();
Evan Chengd38c22b2006-05-11 23:55:42 +0000218
Dan Gohman46520a22008-06-21 19:18:17 +0000219 AvailableQueue->initNodes(SUnits);
Dan Gohman54a187e2007-08-20 19:28:38 +0000220
Evan Chengd38c22b2006-05-11 23:55:42 +0000221 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
222 if (isBottomUp)
223 ListScheduleBottomUp();
224 else
225 ListScheduleTopDown();
226
227 AvailableQueue->releaseState();
Dan Gohman54a187e2007-08-20 19:28:38 +0000228
Evan Cheng009f5f52006-05-25 08:37:31 +0000229 CommuteNodesToReducePressure();
Evan Chengd38c22b2006-05-11 23:55:42 +0000230
Bill Wendling22e978a2006-12-07 20:04:42 +0000231 DOUT << "*** Final schedule ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000232 DEBUG(dumpSchedule());
Bill Wendling22e978a2006-12-07 20:04:42 +0000233 DOUT << "\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000234
235 // Emit in scheduled order
236 EmitSchedule();
237}
238
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000239/// CommuteNodesToReducePressure - If a node is two-address and commutable, and
Evan Chengafed73e2006-05-12 01:58:24 +0000240/// it is not the last use of its first operand, add it to the CommuteSet if
241/// possible. It will be commuted when it is translated to a MI.
242void ScheduleDAGRRList::CommuteNodesToReducePressure() {
Evan Chenge3c44192007-06-22 01:35:51 +0000243 SmallPtrSet<SUnit*, 4> OperandSeen;
Dan Gohman4370f262008-04-15 01:22:18 +0000244 for (unsigned i = Sequence.size(); i != 0; ) {
245 --i;
Evan Chengafed73e2006-05-12 01:58:24 +0000246 SUnit *SU = Sequence[i];
Evan Cheng8e136a92007-09-26 21:36:17 +0000247 if (!SU || !SU->Node) continue;
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000248 if (SU->isCommutable) {
249 unsigned Opc = SU->Node->getTargetOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +0000250 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000251 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +0000252 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000253 for (unsigned j = 0; j != NumOps; ++j) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000254 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000255 continue;
256
257 SDNode *OpN = SU->Node->getOperand(j).Val;
Dan Gohman46520a22008-06-21 19:18:17 +0000258 SUnit *OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000259 if (OpSU && OperandSeen.count(OpSU) == 1) {
260 // Ok, so SU is not the last use of OpSU, but SU is two-address so
261 // it will clobber OpSU. Try to commute SU if no other source operands
262 // are live below.
263 bool DoCommute = true;
264 for (unsigned k = 0; k < NumOps; ++k) {
265 if (k != j) {
266 OpN = SU->Node->getOperand(k).Val;
Dan Gohman46520a22008-06-21 19:18:17 +0000267 OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000268 if (OpSU && OperandSeen.count(OpSU) == 1) {
269 DoCommute = false;
270 break;
271 }
272 }
Evan Chengafed73e2006-05-12 01:58:24 +0000273 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000274 if (DoCommute)
275 CommuteSet.insert(SU->Node);
Evan Chengafed73e2006-05-12 01:58:24 +0000276 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +0000277
278 // Only look at the first use&def node for now.
279 break;
Evan Chengafed73e2006-05-12 01:58:24 +0000280 }
281 }
282
Chris Lattnerd86418a2006-08-17 00:09:56 +0000283 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
284 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +0000285 if (!I->isCtrl)
Dan Gohmane6e13482008-06-21 15:52:51 +0000286 OperandSeen.insert(I->Dep->OrigNode);
Evan Chengafed73e2006-05-12 01:58:24 +0000287 }
288 }
289}
Evan Chengd38c22b2006-05-11 23:55:42 +0000290
291//===----------------------------------------------------------------------===//
292// Bottom-Up Scheduling
293//===----------------------------------------------------------------------===//
294
Evan Chengd38c22b2006-05-11 23:55:42 +0000295/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000296/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Evan Chengd38c22b2006-05-11 23:55:42 +0000297void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain,
298 unsigned CurCycle) {
299 // FIXME: the distance between two nodes is not always == the predecessor's
300 // latency. For example, the reader can very well read the register written
301 // by the predecessor later than the issue cycle. It also depends on the
302 // interrupt model (drain vs. freeze).
303 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
304
Evan Cheng038dcc52007-09-28 19:24:24 +0000305 --PredSU->NumSuccsLeft;
Evan Chengd38c22b2006-05-11 23:55:42 +0000306
307#ifndef NDEBUG
Evan Cheng038dcc52007-09-28 19:24:24 +0000308 if (PredSU->NumSuccsLeft < 0) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000309 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000310 PredSU->dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +0000311 cerr << " has been released too many times!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +0000312 assert(0);
313 }
314#endif
315
Evan Cheng038dcc52007-09-28 19:24:24 +0000316 if (PredSU->NumSuccsLeft == 0) {
Dan Gohman4370f262008-04-15 01:22:18 +0000317 PredSU->isAvailable = true;
318 AvailableQueue->push(PredSU);
Evan Chengd38c22b2006-05-11 23:55:42 +0000319 }
320}
321
322/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
323/// count of its predecessors. If a predecessor pending count is zero, add it to
324/// the Available queue.
Evan Chengd12c97d2006-05-30 18:05:39 +0000325void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
Bill Wendling22e978a2006-12-07 20:04:42 +0000326 DOUT << "*** Scheduling [" << CurCycle << "]: ";
Evan Chengd38c22b2006-05-11 23:55:42 +0000327 DEBUG(SU->dump(&DAG));
328 SU->Cycle = CurCycle;
329
330 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +0000331
332 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000333 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000334 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +0000335 ReleasePred(I->Dep, I->isCtrl, CurCycle);
Evan Cheng5924bf72007-09-25 01:54:36 +0000336 if (I->Cost < 0) {
337 // This is a physical register dependency and it's impossible or
338 // expensive to copy the register. Make sure nothing that can
339 // clobber the register is scheduled between the predecessor and
340 // this node.
341 if (LiveRegs.insert(I->Reg)) {
342 LiveRegDefs[I->Reg] = I->Dep;
343 LiveRegCycles[I->Reg] = CurCycle;
344 }
345 }
346 }
347
348 // Release all the implicit physical register defs that are live.
349 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
350 I != E; ++I) {
351 if (I->Cost < 0) {
352 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
353 LiveRegs.erase(I->Reg);
354 assert(LiveRegDefs[I->Reg] == SU &&
355 "Physical register dependency violated?");
356 LiveRegDefs[I->Reg] = NULL;
357 LiveRegCycles[I->Reg] = 0;
358 }
359 }
360 }
361
Evan Chengd38c22b2006-05-11 23:55:42 +0000362 SU->isScheduled = true;
Evan Chengd38c22b2006-05-11 23:55:42 +0000363}
364
Evan Cheng5924bf72007-09-25 01:54:36 +0000365/// CapturePred - This does the opposite of ReleasePred. Since SU is being
366/// unscheduled, incrcease the succ left count of its predecessors. Remove
367/// them from AvailableQueue if necessary.
Roman Levenstein6b371142008-04-29 09:07:59 +0000368void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {
369 unsigned CycleBound = 0;
Evan Cheng5924bf72007-09-25 01:54:36 +0000370 for (SUnit::succ_iterator I = PredSU->Succs.begin(), E = PredSU->Succs.end();
371 I != E; ++I) {
372 if (I->Dep == SU)
373 continue;
Roman Levenstein6b371142008-04-29 09:07:59 +0000374 CycleBound = std::max(CycleBound,
375 I->Dep->Cycle + PredSU->Latency);
Evan Cheng5924bf72007-09-25 01:54:36 +0000376 }
377
378 if (PredSU->isAvailable) {
379 PredSU->isAvailable = false;
380 if (!PredSU->isPending)
381 AvailableQueue->remove(PredSU);
382 }
383
Roman Levenstein6b371142008-04-29 09:07:59 +0000384 PredSU->CycleBound = CycleBound;
Evan Cheng038dcc52007-09-28 19:24:24 +0000385 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000386}
387
388/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
389/// its predecessor states to reflect the change.
390void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
391 DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
392 DEBUG(SU->dump(&DAG));
393
394 AvailableQueue->UnscheduledNode(SU);
395
396 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
397 I != E; ++I) {
398 CapturePred(I->Dep, SU, I->isCtrl);
399 if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg]) {
400 LiveRegs.erase(I->Reg);
401 assert(LiveRegDefs[I->Reg] == I->Dep &&
402 "Physical register dependency violated?");
403 LiveRegDefs[I->Reg] = NULL;
404 LiveRegCycles[I->Reg] = 0;
405 }
406 }
407
408 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
409 I != E; ++I) {
410 if (I->Cost < 0) {
411 if (LiveRegs.insert(I->Reg)) {
412 assert(!LiveRegDefs[I->Reg] &&
413 "Physical register dependency violated?");
414 LiveRegDefs[I->Reg] = SU;
415 }
416 if (I->Dep->Cycle < LiveRegCycles[I->Reg])
417 LiveRegCycles[I->Reg] = I->Dep->Cycle;
418 }
419 }
420
421 SU->Cycle = 0;
422 SU->isScheduled = false;
423 SU->isAvailable = true;
424 AvailableQueue->push(SU);
425}
426
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000427/// IsReachable - Checks if SU is reachable from TargetSU.
428bool ScheduleDAGRRList::IsReachable(SUnit *SU, SUnit *TargetSU) {
Roman Levenstein733a4d62008-03-26 11:23:38 +0000429 // If insertion of the edge SU->TargetSU would create a cycle
430 // then there is a path from TargetSU to SU.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000431 int UpperBound, LowerBound;
432 LowerBound = Node2Index[TargetSU->NodeNum];
433 UpperBound = Node2Index[SU->NodeNum];
434 bool HasLoop = false;
435 // Is Ord(TargetSU) < Ord(SU) ?
436 if (LowerBound < UpperBound) {
437 Visited.reset();
438 // There may be a path from TargetSU to SU. Check for it.
439 DFS(TargetSU, UpperBound, HasLoop);
Evan Chengcfd5f822007-09-27 00:25:29 +0000440 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000441 return HasLoop;
Evan Chengcfd5f822007-09-27 00:25:29 +0000442}
443
Roman Levenstein733a4d62008-03-26 11:23:38 +0000444/// Allocate - assign the topological index to the node n.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000445inline void ScheduleDAGRRList::Allocate(int n, int index) {
446 Node2Index[n] = index;
447 Index2Node[index] = n;
Evan Chengcfd5f822007-09-27 00:25:29 +0000448}
449
Roman Levenstein733a4d62008-03-26 11:23:38 +0000450/// InitDAGTopologicalSorting - create the initial topological
451/// ordering from the DAG to be scheduled.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000452void ScheduleDAGRRList::InitDAGTopologicalSorting() {
453 unsigned DAGSize = SUnits.size();
454 std::vector<unsigned> InDegree(DAGSize);
455 std::vector<SUnit*> WorkList;
456 WorkList.reserve(DAGSize);
457 std::vector<SUnit*> TopOrder;
458 TopOrder.reserve(DAGSize);
459
Roman Levenstein733a4d62008-03-26 11:23:38 +0000460 // Initialize the data structures.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000461 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
462 SUnit *SU = &SUnits[i];
463 int NodeNum = SU->NodeNum;
464 unsigned Degree = SU->Succs.size();
465 InDegree[NodeNum] = Degree;
466
467 // Is it a node without dependencies?
468 if (Degree == 0) {
469 assert(SU->Succs.empty() && "SUnit should have no successors");
Roman Levenstein733a4d62008-03-26 11:23:38 +0000470 // Collect leaf nodes.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000471 WorkList.push_back(SU);
472 }
473 }
474
475 while (!WorkList.empty()) {
476 SUnit *SU = WorkList.back();
477 WorkList.pop_back();
478 TopOrder.push_back(SU);
479 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
480 I != E; ++I) {
481 SUnit *SU = I->Dep;
482 if (!--InDegree[SU->NodeNum])
483 // If all dependencies of the node are processed already,
Roman Levenstein733a4d62008-03-26 11:23:38 +0000484 // then the node can be computed now.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000485 WorkList.push_back(SU);
486 }
487 }
488
489 // Second pass, assign the actual topological order as node ids.
490 int Id = 0;
491
492 Index2Node.clear();
493 Node2Index.clear();
494 Index2Node.resize(DAGSize);
495 Node2Index.resize(DAGSize);
496 Visited.resize(DAGSize);
497
498 for (std::vector<SUnit*>::reverse_iterator TI = TopOrder.rbegin(),
499 TE = TopOrder.rend();TI != TE; ++TI) {
500 Allocate((*TI)->NodeNum, Id);
501 Id++;
502 }
503
504#ifndef NDEBUG
505 // Check correctness of the ordering
506 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
507 SUnit *SU = &SUnits[i];
508 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
509 I != E; ++I) {
510 assert(Node2Index[SU->NodeNum] > Node2Index[I->Dep->NodeNum] &&
511 "Wrong topological sorting");
512 }
513 }
514#endif
515}
516
Roman Levenstein733a4d62008-03-26 11:23:38 +0000517/// AddPred - adds an edge from SUnit X to SUnit Y.
518/// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000519bool ScheduleDAGRRList::AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
520 unsigned PhyReg, int Cost) {
521 int UpperBound, LowerBound;
522 LowerBound = Node2Index[Y->NodeNum];
523 UpperBound = Node2Index[X->NodeNum];
524 bool HasLoop = false;
525 // Is Ord(X) < Ord(Y) ?
526 if (LowerBound < UpperBound) {
Roman Levenstein733a4d62008-03-26 11:23:38 +0000527 // Update the topological order.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000528 Visited.reset();
529 DFS(Y, UpperBound, HasLoop);
530 assert(!HasLoop && "Inserted edge creates a loop!");
Roman Levenstein733a4d62008-03-26 11:23:38 +0000531 // Recompute topological indexes.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000532 Shift(Visited, LowerBound, UpperBound);
533 }
Roman Levenstein733a4d62008-03-26 11:23:38 +0000534 // Now really insert the edge.
535 return Y->addPred(X, isCtrl, isSpecial, PhyReg, Cost);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000536}
537
Roman Levenstein733a4d62008-03-26 11:23:38 +0000538/// RemovePred - This removes the specified node N from the predecessors of
539/// the current node M. Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000540bool ScheduleDAGRRList::RemovePred(SUnit *M, SUnit *N,
541 bool isCtrl, bool isSpecial) {
542 // InitDAGTopologicalSorting();
543 return M->removePred(N, isCtrl, isSpecial);
544}
545
Roman Levenstein733a4d62008-03-26 11:23:38 +0000546/// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
547/// all nodes affected by the edge insertion. These nodes will later get new
548/// topological indexes by means of the Shift method.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000549void ScheduleDAGRRList::DFS(SUnit *SU, int UpperBound, bool& HasLoop) {
550 std::vector<SUnit*> WorkList;
551 WorkList.reserve(SUnits.size());
552
553 WorkList.push_back(SU);
554 while (!WorkList.empty()) {
555 SU = WorkList.back();
556 WorkList.pop_back();
557 Visited.set(SU->NodeNum);
558 for (int I = SU->Succs.size()-1; I >= 0; --I) {
559 int s = SU->Succs[I].Dep->NodeNum;
560 if (Node2Index[s] == UpperBound) {
561 HasLoop = true;
562 return;
563 }
Roman Levenstein733a4d62008-03-26 11:23:38 +0000564 // Visit successors if not already and in affected region.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000565 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
566 WorkList.push_back(SU->Succs[I].Dep);
567 }
568 }
569 }
570}
571
Roman Levenstein733a4d62008-03-26 11:23:38 +0000572/// Shift - Renumber the nodes so that the topological ordering is
573/// preserved.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000574void ScheduleDAGRRList::Shift(BitVector& Visited, int LowerBound,
575 int UpperBound) {
576 std::vector<int> L;
577 int shift = 0;
578 int i;
579
580 for (i = LowerBound; i <= UpperBound; ++i) {
Roman Levenstein733a4d62008-03-26 11:23:38 +0000581 // w is node at topological index i.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000582 int w = Index2Node[i];
583 if (Visited.test(w)) {
Roman Levenstein733a4d62008-03-26 11:23:38 +0000584 // Unmark.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000585 Visited.reset(w);
586 L.push_back(w);
587 shift = shift + 1;
588 } else {
589 Allocate(w, i - shift);
590 }
591 }
592
593 for (unsigned j = 0; j < L.size(); ++j) {
594 Allocate(L[j], i - shift);
595 i = i + 1;
596 }
597}
598
599
Dan Gohmanfd227e92008-03-25 17:10:29 +0000600/// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
Evan Chengcfd5f822007-09-27 00:25:29 +0000601/// create a cycle.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000602bool ScheduleDAGRRList::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
603 if (IsReachable(TargetSU, SU))
Evan Chengcfd5f822007-09-27 00:25:29 +0000604 return true;
605 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
606 I != E; ++I)
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000607 if (I->Cost < 0 && IsReachable(TargetSU, I->Dep))
Evan Chengcfd5f822007-09-27 00:25:29 +0000608 return true;
609 return false;
610}
611
Evan Cheng8e136a92007-09-26 21:36:17 +0000612/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Evan Cheng5924bf72007-09-25 01:54:36 +0000613/// BTCycle in order to schedule a specific node. Returns the last unscheduled
614/// SUnit. Also returns if a successor is unscheduled in the process.
Evan Cheng8e136a92007-09-26 21:36:17 +0000615void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
616 unsigned &CurCycle) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000617 SUnit *OldSU = NULL;
Evan Cheng8e136a92007-09-26 21:36:17 +0000618 while (CurCycle > BtCycle) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000619 OldSU = Sequence.back();
620 Sequence.pop_back();
621 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000622 // Don't try to remove SU from AvailableQueue.
623 SU->isAvailable = false;
Evan Cheng5924bf72007-09-25 01:54:36 +0000624 UnscheduleNodeBottomUp(OldSU);
625 --CurCycle;
626 }
627
628
629 if (SU->isSucc(OldSU)) {
630 assert(false && "Something is wrong!");
631 abort();
632 }
Evan Cheng1ec79b42007-09-27 07:09:03 +0000633
634 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000635}
636
Evan Cheng5924bf72007-09-25 01:54:36 +0000637/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
638/// successors to the newly created node.
639SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Evan Cheng79e97132007-10-05 01:39:18 +0000640 if (SU->FlaggedNodes.size())
641 return NULL;
Evan Cheng8e136a92007-09-26 21:36:17 +0000642
Evan Cheng79e97132007-10-05 01:39:18 +0000643 SDNode *N = SU->Node;
644 if (!N)
645 return NULL;
646
647 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000648 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000649 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Duncan Sands13237ac2008-06-06 12:08:01 +0000650 MVT VT = N->getValueType(i);
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000651 if (VT == MVT::Flag)
652 return NULL;
653 else if (VT == MVT::Other)
654 TryUnfold = true;
655 }
Evan Cheng79e97132007-10-05 01:39:18 +0000656 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
657 const SDOperand &Op = N->getOperand(i);
Duncan Sands13237ac2008-06-06 12:08:01 +0000658 MVT VT = Op.Val->getValueType(Op.ResNo);
Evan Cheng79e97132007-10-05 01:39:18 +0000659 if (VT == MVT::Flag)
660 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000661 }
662
663 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000664 SmallVector<SDNode*, 2> NewNodes;
Owen Anderson0ec92e92008-01-07 01:35:56 +0000665 if (!TII->unfoldMemoryOperand(DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000666 return NULL;
667
668 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
669 assert(NewNodes.size() == 2 && "Expected a load folding node!");
670
671 N = NewNodes[1];
672 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000673 unsigned NumVals = N->getNumValues();
674 unsigned OldNumVals = SU->Node->getNumValues();
675 for (unsigned i = 0; i != NumVals; ++i)
Chris Lattner3cfb56d2007-10-15 06:10:22 +0000676 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, i), SDOperand(N, i));
Evan Cheng79e97132007-10-05 01:39:18 +0000677 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, OldNumVals-1),
Chris Lattner3cfb56d2007-10-15 06:10:22 +0000678 SDOperand(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000679
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000680 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000681 assert(N->getNodeId() == -1 && "Node already inserted!");
682 N->setNodeId(NewSU->NodeNum);
Dan Gohmane6e13482008-06-21 15:52:51 +0000683
Chris Lattner03ad8852008-01-07 07:27:27 +0000684 const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
Dan Gohman856c0122008-02-16 00:25:40 +0000685 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000686 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000687 NewSU->isTwoAddress = true;
688 break;
689 }
690 }
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000691 if (TID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000692 NewSU->isCommutable = true;
Evan Cheng79e97132007-10-05 01:39:18 +0000693 // FIXME: Calculate height / depth and propagate the changes?
Evan Cheng91e0fc92007-12-18 08:42:10 +0000694 NewSU->Depth = SU->Depth;
695 NewSU->Height = SU->Height;
Evan Cheng79e97132007-10-05 01:39:18 +0000696 ComputeLatency(NewSU);
697
Evan Cheng91e0fc92007-12-18 08:42:10 +0000698 // LoadNode may already exist. This can happen when there is another
699 // load from the same location and producing the same type of value
700 // but it has different alignment or volatileness.
701 bool isNewLoad = true;
702 SUnit *LoadSU;
Dan Gohman46520a22008-06-21 19:18:17 +0000703 if (LoadNode->getNodeId() != -1) {
704 LoadSU = &SUnits[LoadNode->getNodeId()];
Evan Cheng91e0fc92007-12-18 08:42:10 +0000705 isNewLoad = false;
706 } else {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000707 LoadSU = CreateNewSUnit(LoadNode);
Dan Gohman46520a22008-06-21 19:18:17 +0000708 LoadNode->setNodeId(LoadSU->NodeNum);
Evan Cheng91e0fc92007-12-18 08:42:10 +0000709
710 LoadSU->Depth = SU->Depth;
711 LoadSU->Height = SU->Height;
712 ComputeLatency(LoadSU);
713 }
714
Evan Cheng79e97132007-10-05 01:39:18 +0000715 SUnit *ChainPred = NULL;
716 SmallVector<SDep, 4> ChainSuccs;
717 SmallVector<SDep, 4> LoadPreds;
718 SmallVector<SDep, 4> NodePreds;
719 SmallVector<SDep, 4> NodeSuccs;
720 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
721 I != E; ++I) {
722 if (I->isCtrl)
723 ChainPred = I->Dep;
Evan Cheng567d2e52008-03-04 00:41:45 +0000724 else if (I->Dep->Node && I->Dep->Node->isOperandOf(LoadNode))
Evan Cheng79e97132007-10-05 01:39:18 +0000725 LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
726 else
727 NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
728 }
729 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
730 I != E; ++I) {
731 if (I->isCtrl)
732 ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
733 I->isCtrl, I->isSpecial));
734 else
735 NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
736 I->isCtrl, I->isSpecial));
737 }
738
Dan Gohman4370f262008-04-15 01:22:18 +0000739 if (ChainPred) {
740 RemovePred(SU, ChainPred, true, false);
741 if (isNewLoad)
742 AddPred(LoadSU, ChainPred, true, false);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000743 }
Evan Cheng79e97132007-10-05 01:39:18 +0000744 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
745 SDep *Pred = &LoadPreds[i];
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000746 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
747 if (isNewLoad) {
748 AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
Roman Levenstein733a4d62008-03-26 11:23:38 +0000749 Pred->Reg, Pred->Cost);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000750 }
Evan Cheng79e97132007-10-05 01:39:18 +0000751 }
752 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
753 SDep *Pred = &NodePreds[i];
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000754 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
755 AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
Roman Levenstein733a4d62008-03-26 11:23:38 +0000756 Pred->Reg, Pred->Cost);
Evan Cheng79e97132007-10-05 01:39:18 +0000757 }
758 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
759 SDep *Succ = &NodeSuccs[i];
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000760 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
761 AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isSpecial,
Roman Levenstein733a4d62008-03-26 11:23:38 +0000762 Succ->Reg, Succ->Cost);
Evan Cheng79e97132007-10-05 01:39:18 +0000763 }
764 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
765 SDep *Succ = &ChainSuccs[i];
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000766 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
767 if (isNewLoad) {
768 AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isSpecial,
Roman Levenstein733a4d62008-03-26 11:23:38 +0000769 Succ->Reg, Succ->Cost);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000770 }
Evan Cheng79e97132007-10-05 01:39:18 +0000771 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000772 if (isNewLoad) {
773 AddPred(NewSU, LoadSU, false, false);
774 }
Evan Cheng79e97132007-10-05 01:39:18 +0000775
Evan Cheng91e0fc92007-12-18 08:42:10 +0000776 if (isNewLoad)
777 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000778 AvailableQueue->addNode(NewSU);
779
780 ++NumUnfolds;
781
782 if (NewSU->NumSuccsLeft == 0) {
783 NewSU->isAvailable = true;
784 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +0000785 }
786 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000787 }
788
789 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000790 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000791
792 // New SUnit has the exact same predecessors.
793 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
794 I != E; ++I)
795 if (!I->isSpecial) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000796 AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
Evan Cheng5924bf72007-09-25 01:54:36 +0000797 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
798 }
799
800 // Only copy scheduled successors. Cut them from old node's successor
801 // list and move them over.
Evan Chengbde499b2007-09-27 07:29:27 +0000802 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +0000803 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
804 I != E; ++I) {
805 if (I->isSpecial)
806 continue;
Evan Cheng5924bf72007-09-25 01:54:36 +0000807 if (I->Dep->isScheduled) {
Evan Chengbde499b2007-09-27 07:29:27 +0000808 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000809 AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
Evan Chengbde499b2007-09-27 07:29:27 +0000810 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
Evan Cheng5924bf72007-09-25 01:54:36 +0000811 }
812 }
813 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
Evan Chengbde499b2007-09-27 07:29:27 +0000814 SUnit *Succ = DelDeps[i].first;
815 bool isCtrl = DelDeps[i].second;
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000816 RemovePred(Succ, SU, isCtrl, false);
Evan Cheng5924bf72007-09-25 01:54:36 +0000817 }
818
819 AvailableQueue->updateNode(SU);
820 AvailableQueue->addNode(NewSU);
821
Evan Cheng1ec79b42007-09-27 07:09:03 +0000822 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000823 return NewSU;
824}
825
Evan Cheng1ec79b42007-09-27 07:09:03 +0000826/// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
827/// and move all scheduled successors of the given SUnit to the last copy.
828void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
829 const TargetRegisterClass *DestRC,
830 const TargetRegisterClass *SrcRC,
831 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000832 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000833 CopyFromSU->CopySrcRC = SrcRC;
834 CopyFromSU->CopyDstRC = DestRC;
835 CopyFromSU->Depth = SU->Depth;
836 CopyFromSU->Height = SU->Height;
837
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000838 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000839 CopyToSU->CopySrcRC = DestRC;
840 CopyToSU->CopyDstRC = SrcRC;
841
842 // Only copy scheduled successors. Cut them from old node's successor
843 // list and move them over.
Evan Chengbde499b2007-09-27 07:29:27 +0000844 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +0000845 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
846 I != E; ++I) {
847 if (I->isSpecial)
848 continue;
Evan Cheng8e136a92007-09-26 21:36:17 +0000849 if (I->Dep->isScheduled) {
Evan Chengbde499b2007-09-27 07:29:27 +0000850 CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000851 AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
Evan Chengbde499b2007-09-27 07:29:27 +0000852 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
Evan Cheng8e136a92007-09-26 21:36:17 +0000853 }
854 }
855 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
Evan Chengbde499b2007-09-27 07:29:27 +0000856 SUnit *Succ = DelDeps[i].first;
857 bool isCtrl = DelDeps[i].second;
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000858 RemovePred(Succ, SU, isCtrl, false);
Evan Cheng8e136a92007-09-26 21:36:17 +0000859 }
860
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000861 AddPred(CopyFromSU, SU, false, false, Reg, -1);
862 AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
Evan Cheng8e136a92007-09-26 21:36:17 +0000863
864 AvailableQueue->updateNode(SU);
865 AvailableQueue->addNode(CopyFromSU);
866 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000867 Copies.push_back(CopyFromSU);
868 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +0000869
Evan Cheng1ec79b42007-09-27 07:09:03 +0000870 ++NumCCCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +0000871}
872
873/// getPhysicalRegisterVT - Returns the ValueType of the physical register
874/// definition of the specified node.
875/// FIXME: Move to SelectionDAG?
Duncan Sands13237ac2008-06-06 12:08:01 +0000876static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
877 const TargetInstrInfo *TII) {
Chris Lattner03ad8852008-01-07 07:27:27 +0000878 const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
Evan Cheng8e136a92007-09-26 21:36:17 +0000879 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
Chris Lattnerb0d06b42008-01-07 03:13:06 +0000880 unsigned NumRes = TID.getNumDefs();
881 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +0000882 if (Reg == *ImpDef)
883 break;
884 ++NumRes;
885 }
886 return N->getValueType(NumRes);
887}
888
Evan Cheng5924bf72007-09-25 01:54:36 +0000889/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
890/// scheduling of the given node to satisfy live physical register dependencies.
891/// If the specific node is the last one that's available to schedule, do
892/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Evan Cheng1ec79b42007-09-27 07:09:03 +0000893bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
894 SmallVector<unsigned, 4> &LRegs){
Evan Cheng5924bf72007-09-25 01:54:36 +0000895 if (LiveRegs.empty())
896 return false;
897
Evan Chenge6f92252007-09-27 18:46:06 +0000898 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +0000899 // If this node would clobber any "live" register, then it's not ready.
Evan Cheng5924bf72007-09-25 01:54:36 +0000900 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
901 I != E; ++I) {
902 if (I->Cost < 0) {
903 unsigned Reg = I->Reg;
Evan Chenge6f92252007-09-27 18:46:06 +0000904 if (LiveRegs.count(Reg) && LiveRegDefs[Reg] != I->Dep) {
905 if (RegAdded.insert(Reg))
906 LRegs.push_back(Reg);
907 }
Dan Gohman3a4be0f2008-02-10 18:45:23 +0000908 for (const unsigned *Alias = TRI->getAliasSet(Reg);
Evan Cheng5924bf72007-09-25 01:54:36 +0000909 *Alias; ++Alias)
Evan Chenge6f92252007-09-27 18:46:06 +0000910 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != I->Dep) {
911 if (RegAdded.insert(*Alias))
912 LRegs.push_back(*Alias);
913 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000914 }
915 }
916
917 for (unsigned i = 0, e = SU->FlaggedNodes.size()+1; i != e; ++i) {
918 SDNode *Node = (i == 0) ? SU->Node : SU->FlaggedNodes[i-1];
Evan Cheng8e136a92007-09-26 21:36:17 +0000919 if (!Node || !Node->isTargetOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +0000920 continue;
Chris Lattner03ad8852008-01-07 07:27:27 +0000921 const TargetInstrDesc &TID = TII->get(Node->getTargetOpcode());
Evan Cheng5924bf72007-09-25 01:54:36 +0000922 if (!TID.ImplicitDefs)
923 continue;
924 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
Evan Chenge6f92252007-09-27 18:46:06 +0000925 if (LiveRegs.count(*Reg) && LiveRegDefs[*Reg] != SU) {
926 if (RegAdded.insert(*Reg))
927 LRegs.push_back(*Reg);
928 }
Dan Gohman3a4be0f2008-02-10 18:45:23 +0000929 for (const unsigned *Alias = TRI->getAliasSet(*Reg);
Evan Cheng5924bf72007-09-25 01:54:36 +0000930 *Alias; ++Alias)
Evan Chenge6f92252007-09-27 18:46:06 +0000931 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != SU) {
932 if (RegAdded.insert(*Alias))
933 LRegs.push_back(*Alias);
934 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000935 }
936 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000937 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +0000938}
939
Evan Cheng1ec79b42007-09-27 07:09:03 +0000940
Evan Chengd38c22b2006-05-11 23:55:42 +0000941/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
942/// schedulers.
943void ScheduleDAGRRList::ListScheduleBottomUp() {
944 unsigned CurCycle = 0;
945 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +0000946 if (!SUnits.empty()) {
Dan Gohman46520a22008-06-21 19:18:17 +0000947 SUnit *RootSU = &SUnits[DAG.getRoot().Val->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +0000948 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
949 RootSU->isAvailable = true;
950 AvailableQueue->push(RootSU);
951 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000952
953 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +0000954 // priority. If it is not ready put it back. Schedule the node.
Evan Cheng5924bf72007-09-25 01:54:36 +0000955 SmallVector<SUnit*, 4> NotReady;
Dan Gohmane6e13482008-06-21 15:52:51 +0000956 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +0000957 while (!AvailableQueue->empty()) {
Evan Cheng1ec79b42007-09-27 07:09:03 +0000958 bool Delayed = false;
959 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
Evan Cheng5924bf72007-09-25 01:54:36 +0000960 SUnit *CurSU = AvailableQueue->pop();
961 while (CurSU) {
Evan Cheng1ec79b42007-09-27 07:09:03 +0000962 if (CurSU->CycleBound <= CurCycle) {
963 SmallVector<unsigned, 4> LRegs;
964 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
Evan Cheng5924bf72007-09-25 01:54:36 +0000965 break;
Evan Cheng1ec79b42007-09-27 07:09:03 +0000966 Delayed = true;
967 LRegsMap.insert(std::make_pair(CurSU, LRegs));
Evan Cheng5924bf72007-09-25 01:54:36 +0000968 }
Evan Cheng1ec79b42007-09-27 07:09:03 +0000969
970 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
971 NotReady.push_back(CurSU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000972 CurSU = AvailableQueue->pop();
Evan Chengd38c22b2006-05-11 23:55:42 +0000973 }
Evan Cheng1ec79b42007-09-27 07:09:03 +0000974
975 // All candidates are delayed due to live physical reg dependencies.
976 // Try backtracking, code duplication, or inserting cross class copies
977 // to resolve it.
978 if (Delayed && !CurSU) {
979 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
980 SUnit *TrySU = NotReady[i];
981 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
982
983 // Try unscheduling up to the point where it's safe to schedule
984 // this node.
985 unsigned LiveCycle = CurCycle;
986 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
987 unsigned Reg = LRegs[j];
988 unsigned LCycle = LiveRegCycles[Reg];
989 LiveCycle = std::min(LiveCycle, LCycle);
990 }
991 SUnit *OldSU = Sequence[LiveCycle];
992 if (!WillCreateCycle(TrySU, OldSU)) {
993 BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
994 // Force the current node to be scheduled before the node that
995 // requires the physical reg dep.
996 if (OldSU->isAvailable) {
997 OldSU->isAvailable = false;
998 AvailableQueue->remove(OldSU);
999 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001000 AddPred(TrySU, OldSU, true, true);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001001 // If one or more successors has been unscheduled, then the current
1002 // node is no longer avaialable. Schedule a successor that's now
1003 // available instead.
1004 if (!TrySU->isAvailable)
1005 CurSU = AvailableQueue->pop();
1006 else {
1007 CurSU = TrySU;
1008 TrySU->isPending = false;
1009 NotReady.erase(NotReady.begin()+i);
1010 }
1011 break;
1012 }
1013 }
1014
1015 if (!CurSU) {
Dan Gohmanfd227e92008-03-25 17:10:29 +00001016 // Can't backtrack. Try duplicating the nodes that produces these
Evan Cheng1ec79b42007-09-27 07:09:03 +00001017 // "expensive to copy" values to break the dependency. In case even
1018 // that doesn't work, insert cross class copies.
1019 SUnit *TrySU = NotReady[0];
1020 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1021 assert(LRegs.size() == 1 && "Can't handle this yet!");
1022 unsigned Reg = LRegs[0];
1023 SUnit *LRDef = LiveRegDefs[Reg];
Evan Cheng79e97132007-10-05 01:39:18 +00001024 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
1025 if (!NewDef) {
Evan Cheng1ec79b42007-09-27 07:09:03 +00001026 // Issue expensive cross register class copies.
Duncan Sands13237ac2008-06-06 12:08:01 +00001027 MVT VT = getPhysicalRegisterVT(LRDef->Node, Reg, TII);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001028 const TargetRegisterClass *RC =
Evan Chenge88a6252008-03-11 07:19:34 +00001029 TRI->getPhysicalRegisterRegClass(Reg, VT);
Dan Gohman3a4be0f2008-02-10 18:45:23 +00001030 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001031 if (!DestRC) {
1032 assert(false && "Don't know how to copy this physical register!");
1033 abort();
1034 }
1035 SmallVector<SUnit*, 2> Copies;
1036 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1037 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
1038 << " to SU #" << Copies.front()->NodeNum << "\n";
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001039 AddPred(TrySU, Copies.front(), true, true);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001040 NewDef = Copies.back();
1041 }
1042
1043 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
1044 << " to SU #" << TrySU->NodeNum << "\n";
1045 LiveRegDefs[Reg] = NewDef;
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001046 AddPred(NewDef, TrySU, true, true);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001047 TrySU->isAvailable = false;
1048 CurSU = NewDef;
1049 }
1050
1051 if (!CurSU) {
1052 assert(false && "Unable to resolve live physical register dependencies!");
1053 abort();
1054 }
1055 }
1056
Evan Chengd38c22b2006-05-11 23:55:42 +00001057 // Add the nodes that aren't ready back onto the available list.
Evan Cheng5924bf72007-09-25 01:54:36 +00001058 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
1059 NotReady[i]->isPending = false;
Evan Cheng1ec79b42007-09-27 07:09:03 +00001060 // May no longer be available due to backtracking.
Evan Cheng5924bf72007-09-25 01:54:36 +00001061 if (NotReady[i]->isAvailable)
1062 AvailableQueue->push(NotReady[i]);
1063 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001064 NotReady.clear();
1065
Evan Cheng5924bf72007-09-25 01:54:36 +00001066 if (!CurSU)
1067 Sequence.push_back(0);
1068 else {
1069 ScheduleNodeBottomUp(CurSU, CurCycle);
1070 Sequence.push_back(CurSU);
1071 }
1072 ++CurCycle;
Evan Chengd38c22b2006-05-11 23:55:42 +00001073 }
1074
Evan Chengd38c22b2006-05-11 23:55:42 +00001075 // Reverse the order if it is bottom up.
1076 std::reverse(Sequence.begin(), Sequence.end());
1077
1078
1079#ifndef NDEBUG
1080 // Verify that all SUnits were scheduled.
1081 bool AnyNotSched = false;
Dan Gohman4370f262008-04-15 01:22:18 +00001082 unsigned DeadNodes = 0;
Dan Gohman82b66732008-04-15 22:40:14 +00001083 unsigned Noops = 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001084 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
Dan Gohman4370f262008-04-15 01:22:18 +00001085 if (!SUnits[i].isScheduled) {
1086 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1087 ++DeadNodes;
1088 continue;
1089 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001090 if (!AnyNotSched)
Bill Wendling22e978a2006-12-07 20:04:42 +00001091 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +00001092 SUnits[i].dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +00001093 cerr << "has not been scheduled!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +00001094 AnyNotSched = true;
1095 }
Dan Gohman4370f262008-04-15 01:22:18 +00001096 if (SUnits[i].NumSuccsLeft != 0) {
1097 if (!AnyNotSched)
1098 cerr << "*** List scheduling failed! ***\n";
1099 SUnits[i].dump(&DAG);
1100 cerr << "has successors left!\n";
1101 AnyNotSched = true;
1102 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001103 }
Dan Gohman82b66732008-04-15 22:40:14 +00001104 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1105 if (!Sequence[i])
1106 ++Noops;
Evan Chengd38c22b2006-05-11 23:55:42 +00001107 assert(!AnyNotSched);
Dan Gohman82b66732008-04-15 22:40:14 +00001108 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
Dan Gohman4370f262008-04-15 01:22:18 +00001109 "The number of nodes scheduled doesn't match the expected number!");
Evan Chengd38c22b2006-05-11 23:55:42 +00001110#endif
1111}
1112
1113//===----------------------------------------------------------------------===//
1114// Top-Down Scheduling
1115//===----------------------------------------------------------------------===//
1116
1117/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +00001118/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Evan Chengd38c22b2006-05-11 23:55:42 +00001119void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain,
1120 unsigned CurCycle) {
1121 // FIXME: the distance between two nodes is not always == the predecessor's
1122 // latency. For example, the reader can very well read the register written
1123 // by the predecessor later than the issue cycle. It also depends on the
1124 // interrupt model (drain vs. freeze).
1125 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
1126
Evan Cheng038dcc52007-09-28 19:24:24 +00001127 --SuccSU->NumPredsLeft;
Evan Chengd38c22b2006-05-11 23:55:42 +00001128
1129#ifndef NDEBUG
Evan Cheng038dcc52007-09-28 19:24:24 +00001130 if (SuccSU->NumPredsLeft < 0) {
Bill Wendling22e978a2006-12-07 20:04:42 +00001131 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +00001132 SuccSU->dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +00001133 cerr << " has been released too many times!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +00001134 assert(0);
1135 }
1136#endif
1137
Evan Cheng038dcc52007-09-28 19:24:24 +00001138 if (SuccSU->NumPredsLeft == 0) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001139 SuccSU->isAvailable = true;
1140 AvailableQueue->push(SuccSU);
1141 }
1142}
1143
1144
1145/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1146/// count of its successors. If a successor pending count is zero, add it to
1147/// the Available queue.
Evan Chengd12c97d2006-05-30 18:05:39 +00001148void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
Bill Wendling22e978a2006-12-07 20:04:42 +00001149 DOUT << "*** Scheduling [" << CurCycle << "]: ";
Evan Chengd38c22b2006-05-11 23:55:42 +00001150 DEBUG(SU->dump(&DAG));
1151 SU->Cycle = CurCycle;
1152
1153 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001154
1155 // Top down: release successors
Chris Lattnerd86418a2006-08-17 00:09:56 +00001156 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1157 I != E; ++I)
Evan Cheng0effc3a2007-09-19 01:38:40 +00001158 ReleaseSucc(I->Dep, I->isCtrl, CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001159 SU->isScheduled = true;
Evan Chengd38c22b2006-05-11 23:55:42 +00001160}
1161
Dan Gohman54a187e2007-08-20 19:28:38 +00001162/// ListScheduleTopDown - The main loop of list scheduling for top-down
1163/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +00001164void ScheduleDAGRRList::ListScheduleTopDown() {
1165 unsigned CurCycle = 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001166
1167 // All leaves to Available queue.
1168 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1169 // It is available if it has no predecessors.
Dan Gohman4370f262008-04-15 01:22:18 +00001170 if (SUnits[i].Preds.empty()) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001171 AvailableQueue->push(&SUnits[i]);
1172 SUnits[i].isAvailable = true;
1173 }
1174 }
1175
Evan Chengd38c22b2006-05-11 23:55:42 +00001176 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001177 // priority. If it is not ready put it back. Schedule the node.
Evan Chengd38c22b2006-05-11 23:55:42 +00001178 std::vector<SUnit*> NotReady;
Dan Gohmane6e13482008-06-21 15:52:51 +00001179 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001180 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +00001181 SUnit *CurSU = AvailableQueue->pop();
1182 while (CurSU && CurSU->CycleBound > CurCycle) {
1183 NotReady.push_back(CurSU);
1184 CurSU = AvailableQueue->pop();
Evan Chengd38c22b2006-05-11 23:55:42 +00001185 }
1186
1187 // Add the nodes that aren't ready back onto the available list.
1188 AvailableQueue->push_all(NotReady);
1189 NotReady.clear();
1190
Evan Cheng5924bf72007-09-25 01:54:36 +00001191 if (!CurSU)
1192 Sequence.push_back(0);
1193 else {
1194 ScheduleNodeTopDown(CurSU, CurCycle);
1195 Sequence.push_back(CurSU);
1196 }
Dan Gohman4370f262008-04-15 01:22:18 +00001197 ++CurCycle;
Evan Chengd38c22b2006-05-11 23:55:42 +00001198 }
1199
1200
1201#ifndef NDEBUG
1202 // Verify that all SUnits were scheduled.
1203 bool AnyNotSched = false;
Dan Gohman4370f262008-04-15 01:22:18 +00001204 unsigned DeadNodes = 0;
Dan Gohman82b66732008-04-15 22:40:14 +00001205 unsigned Noops = 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001206 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1207 if (!SUnits[i].isScheduled) {
Dan Gohman4370f262008-04-15 01:22:18 +00001208 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
1209 ++DeadNodes;
1210 continue;
1211 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001212 if (!AnyNotSched)
Bill Wendling22e978a2006-12-07 20:04:42 +00001213 cerr << "*** List scheduling failed! ***\n";
Evan Chengd38c22b2006-05-11 23:55:42 +00001214 SUnits[i].dump(&DAG);
Bill Wendling22e978a2006-12-07 20:04:42 +00001215 cerr << "has not been scheduled!\n";
Evan Chengd38c22b2006-05-11 23:55:42 +00001216 AnyNotSched = true;
1217 }
Dan Gohman4370f262008-04-15 01:22:18 +00001218 if (SUnits[i].NumPredsLeft != 0) {
1219 if (!AnyNotSched)
1220 cerr << "*** List scheduling failed! ***\n";
1221 SUnits[i].dump(&DAG);
1222 cerr << "has predecessors left!\n";
1223 AnyNotSched = true;
1224 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001225 }
Dan Gohman82b66732008-04-15 22:40:14 +00001226 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
1227 if (!Sequence[i])
1228 ++Noops;
Evan Chengd38c22b2006-05-11 23:55:42 +00001229 assert(!AnyNotSched);
Dan Gohman82b66732008-04-15 22:40:14 +00001230 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
Dan Gohman4370f262008-04-15 01:22:18 +00001231 "The number of nodes scheduled doesn't match the expected number!");
Evan Chengd38c22b2006-05-11 23:55:42 +00001232#endif
1233}
1234
1235
1236
1237//===----------------------------------------------------------------------===//
1238// RegReductionPriorityQueue Implementation
1239//===----------------------------------------------------------------------===//
1240//
1241// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1242// to reduce register pressure.
1243//
1244namespace {
1245 template<class SF>
1246 class RegReductionPriorityQueue;
1247
1248 /// Sorting functions for the Available queue.
1249 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1250 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
1251 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
1252 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1253
1254 bool operator()(const SUnit* left, const SUnit* right) const;
1255 };
1256
1257 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1258 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
1259 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
1260 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1261
1262 bool operator()(const SUnit* left, const SUnit* right) const;
1263 };
1264} // end anonymous namespace
1265
Evan Cheng961bbd32007-01-08 23:50:38 +00001266static inline bool isCopyFromLiveIn(const SUnit *SU) {
1267 SDNode *N = SU->Node;
Evan Cheng8e136a92007-09-26 21:36:17 +00001268 return N && N->getOpcode() == ISD::CopyFromReg &&
Evan Cheng961bbd32007-01-08 23:50:38 +00001269 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
1270}
1271
Evan Chengd38c22b2006-05-11 23:55:42 +00001272namespace {
1273 template<class SF>
Chris Lattner996795b2006-06-28 23:17:24 +00001274 class VISIBILITY_HIDDEN RegReductionPriorityQueue
1275 : public SchedulingPriorityQueue {
Dan Gohmana4db3352008-06-21 18:35:25 +00001276 PriorityQueue<SUnit*, std::vector<SUnit*>, SF> Queue;
Roman Levenstein6b371142008-04-29 09:07:59 +00001277 unsigned currentQueueId;
Evan Chengd38c22b2006-05-11 23:55:42 +00001278
1279 public:
1280 RegReductionPriorityQueue() :
Roman Levenstein6b371142008-04-29 09:07:59 +00001281 Queue(SF(this)), currentQueueId(0) {}
Evan Chengd38c22b2006-05-11 23:55:42 +00001282
Dan Gohman46520a22008-06-21 19:18:17 +00001283 virtual void initNodes(std::vector<SUnit> &sunits) {}
Evan Cheng5924bf72007-09-25 01:54:36 +00001284
1285 virtual void addNode(const SUnit *SU) {}
1286
1287 virtual void updateNode(const SUnit *SU) {}
1288
Evan Chengd38c22b2006-05-11 23:55:42 +00001289 virtual void releaseState() {}
1290
Evan Cheng6730f032007-01-08 23:55:53 +00001291 virtual unsigned getNodePriority(const SUnit *SU) const {
Evan Chengd38c22b2006-05-11 23:55:42 +00001292 return 0;
1293 }
1294
Evan Cheng5924bf72007-09-25 01:54:36 +00001295 unsigned size() const { return Queue.size(); }
1296
Evan Chengd38c22b2006-05-11 23:55:42 +00001297 bool empty() const { return Queue.empty(); }
1298
1299 void push(SUnit *U) {
Roman Levenstein6b371142008-04-29 09:07:59 +00001300 assert(!U->NodeQueueId && "Node in the queue already");
1301 U->NodeQueueId = ++currentQueueId;
Dan Gohmana4db3352008-06-21 18:35:25 +00001302 Queue.push(U);
Evan Chengd38c22b2006-05-11 23:55:42 +00001303 }
Roman Levenstein6b371142008-04-29 09:07:59 +00001304
Evan Chengd38c22b2006-05-11 23:55:42 +00001305 void push_all(const std::vector<SUnit *> &Nodes) {
1306 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Roman Levenstein6b371142008-04-29 09:07:59 +00001307 push(Nodes[i]);
Evan Chengd38c22b2006-05-11 23:55:42 +00001308 }
1309
1310 SUnit *pop() {
Evan Chengd12c97d2006-05-30 18:05:39 +00001311 if (empty()) return NULL;
Dan Gohmana4db3352008-06-21 18:35:25 +00001312 SUnit *V = Queue.top();
1313 Queue.pop();
Roman Levenstein6b371142008-04-29 09:07:59 +00001314 V->NodeQueueId = 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001315 return V;
1316 }
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001317
Evan Cheng5924bf72007-09-25 01:54:36 +00001318 void remove(SUnit *SU) {
Roman Levenstein6b371142008-04-29 09:07:59 +00001319 assert(!Queue.empty() && "Queue is empty!");
Dan Gohmana4db3352008-06-21 18:35:25 +00001320 assert(SU->NodeQueueId != 0 && "Not in queue!");
1321 Queue.erase_one(SU);
Roman Levenstein6b371142008-04-29 09:07:59 +00001322 SU->NodeQueueId = 0;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001323 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001324 };
1325
Chris Lattner996795b2006-06-28 23:17:24 +00001326 class VISIBILITY_HIDDEN BURegReductionPriorityQueue
Dan Gohman4b49be12008-06-21 01:08:22 +00001327 : public RegReductionPriorityQueue<bu_ls_rr_sort> {
Evan Chengd38c22b2006-05-11 23:55:42 +00001328 // SUnits - The SUnits for the current graph.
1329 const std::vector<SUnit> *SUnits;
1330
1331 // SethiUllmanNumbers - The SethiUllman number for each node.
Evan Cheng961bbd32007-01-08 23:50:38 +00001332 std::vector<unsigned> SethiUllmanNumbers;
Evan Chengd38c22b2006-05-11 23:55:42 +00001333
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001334 const TargetInstrInfo *TII;
Dan Gohman3a4be0f2008-02-10 18:45:23 +00001335 const TargetRegisterInfo *TRI;
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001336 ScheduleDAGRRList *scheduleDAG;
Evan Chengd38c22b2006-05-11 23:55:42 +00001337 public:
Evan Chengf9891412007-12-20 09:25:31 +00001338 explicit BURegReductionPriorityQueue(const TargetInstrInfo *tii,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00001339 const TargetRegisterInfo *tri)
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001340 : TII(tii), TRI(tri), scheduleDAG(NULL) {}
Evan Chengd38c22b2006-05-11 23:55:42 +00001341
Dan Gohman46520a22008-06-21 19:18:17 +00001342 void initNodes(std::vector<SUnit> &sunits) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001343 SUnits = &sunits;
1344 // Add pseudo dependency edges for two-address nodes.
Evan Chengafed73e2006-05-12 01:58:24 +00001345 AddPseudoTwoAddrDeps();
Evan Chengd38c22b2006-05-11 23:55:42 +00001346 // Calculate node priorities.
Evan Cheng6730f032007-01-08 23:55:53 +00001347 CalculateSethiUllmanNumbers();
Evan Chengd38c22b2006-05-11 23:55:42 +00001348 }
1349
Evan Cheng5924bf72007-09-25 01:54:36 +00001350 void addNode(const SUnit *SU) {
1351 SethiUllmanNumbers.resize(SUnits->size(), 0);
1352 CalcNodeSethiUllmanNumber(SU);
1353 }
1354
1355 void updateNode(const SUnit *SU) {
1356 SethiUllmanNumbers[SU->NodeNum] = 0;
1357 CalcNodeSethiUllmanNumber(SU);
1358 }
1359
Evan Chengd38c22b2006-05-11 23:55:42 +00001360 void releaseState() {
1361 SUnits = 0;
1362 SethiUllmanNumbers.clear();
1363 }
1364
Evan Cheng6730f032007-01-08 23:55:53 +00001365 unsigned getNodePriority(const SUnit *SU) const {
Evan Cheng961bbd32007-01-08 23:50:38 +00001366 assert(SU->NodeNum < SethiUllmanNumbers.size());
Evan Cheng8e136a92007-09-26 21:36:17 +00001367 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
Evan Cheng961bbd32007-01-08 23:50:38 +00001368 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
1369 // CopyFromReg should be close to its def because it restricts
1370 // allocation choices. But if it is a livein then perhaps we want it
1371 // closer to its uses so it can be coalesced.
1372 return 0xffff;
1373 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1374 // CopyToReg should be close to its uses to facilitate coalescing and
1375 // avoid spilling.
1376 return 0;
Evan Chengaa2d6ef2007-10-12 08:50:34 +00001377 else if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
1378 Opc == TargetInstrInfo::INSERT_SUBREG)
1379 // EXTRACT_SUBREG / INSERT_SUBREG should be close to its use to
1380 // facilitate coalescing.
1381 return 0;
Evan Cheng961bbd32007-01-08 23:50:38 +00001382 else if (SU->NumSuccs == 0)
1383 // If SU does not have a use, i.e. it doesn't produce a value that would
1384 // be consumed (e.g. store), then it terminates a chain of computation.
1385 // Give it a large SethiUllman number so it will be scheduled right
1386 // before its predecessors that it doesn't lengthen their live ranges.
1387 return 0xffff;
1388 else if (SU->NumPreds == 0)
1389 // If SU does not have a def, schedule it close to its uses because it
1390 // does not lengthen any live ranges.
1391 return 0;
1392 else
1393 return SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +00001394 }
1395
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001396 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1397 scheduleDAG = scheduleDag;
1398 }
1399
Evan Chengd38c22b2006-05-11 23:55:42 +00001400 private:
Evan Cheng73bdf042008-03-01 00:39:47 +00001401 bool canClobber(const SUnit *SU, const SUnit *Op);
Evan Chengd38c22b2006-05-11 23:55:42 +00001402 void AddPseudoTwoAddrDeps();
Evan Cheng6730f032007-01-08 23:55:53 +00001403 void CalculateSethiUllmanNumbers();
1404 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001405 };
1406
1407
Dan Gohman54a187e2007-08-20 19:28:38 +00001408 class VISIBILITY_HIDDEN TDRegReductionPriorityQueue
Dan Gohman4b49be12008-06-21 01:08:22 +00001409 : public RegReductionPriorityQueue<td_ls_rr_sort> {
Evan Chengd38c22b2006-05-11 23:55:42 +00001410 // SUnits - The SUnits for the current graph.
1411 const std::vector<SUnit> *SUnits;
1412
1413 // SethiUllmanNumbers - The SethiUllman number for each node.
Evan Cheng961bbd32007-01-08 23:50:38 +00001414 std::vector<unsigned> SethiUllmanNumbers;
Evan Chengd38c22b2006-05-11 23:55:42 +00001415
1416 public:
1417 TDRegReductionPriorityQueue() {}
1418
Dan Gohman46520a22008-06-21 19:18:17 +00001419 void initNodes(std::vector<SUnit> &sunits) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001420 SUnits = &sunits;
1421 // Calculate node priorities.
Evan Cheng6730f032007-01-08 23:55:53 +00001422 CalculateSethiUllmanNumbers();
Evan Chengd38c22b2006-05-11 23:55:42 +00001423 }
1424
Evan Cheng5924bf72007-09-25 01:54:36 +00001425 void addNode(const SUnit *SU) {
1426 SethiUllmanNumbers.resize(SUnits->size(), 0);
1427 CalcNodeSethiUllmanNumber(SU);
1428 }
1429
1430 void updateNode(const SUnit *SU) {
1431 SethiUllmanNumbers[SU->NodeNum] = 0;
1432 CalcNodeSethiUllmanNumber(SU);
1433 }
1434
Evan Chengd38c22b2006-05-11 23:55:42 +00001435 void releaseState() {
1436 SUnits = 0;
1437 SethiUllmanNumbers.clear();
1438 }
1439
Evan Cheng6730f032007-01-08 23:55:53 +00001440 unsigned getNodePriority(const SUnit *SU) const {
Evan Cheng961bbd32007-01-08 23:50:38 +00001441 assert(SU->NodeNum < SethiUllmanNumbers.size());
1442 return SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +00001443 }
1444
1445 private:
Evan Cheng6730f032007-01-08 23:55:53 +00001446 void CalculateSethiUllmanNumbers();
1447 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001448 };
1449}
1450
Evan Chengb9e3db62007-03-14 22:43:40 +00001451/// closestSucc - Returns the scheduled cycle of the successor which is
1452/// closet to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00001453static unsigned closestSucc(const SUnit *SU) {
1454 unsigned MaxCycle = 0;
1455 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00001456 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001457 unsigned Cycle = I->Dep->Cycle;
Evan Chengb9e3db62007-03-14 22:43:40 +00001458 // If there are bunch of CopyToRegs stacked up, they should be considered
1459 // to be at the same position.
Evan Cheng8e136a92007-09-26 21:36:17 +00001460 if (I->Dep->Node && I->Dep->Node->getOpcode() == ISD::CopyToReg)
Evan Cheng0effc3a2007-09-19 01:38:40 +00001461 Cycle = closestSucc(I->Dep)+1;
Evan Chengb9e3db62007-03-14 22:43:40 +00001462 if (Cycle > MaxCycle)
1463 MaxCycle = Cycle;
1464 }
Evan Cheng28748552007-03-13 23:25:11 +00001465 return MaxCycle;
1466}
1467
Evan Cheng61bc51e2007-12-20 02:22:36 +00001468/// calcMaxScratches - Returns an cost estimate of the worse case requirement
1469/// for scratch registers. Live-in operands and live-out results don't count
1470/// since they are "fixed".
1471static unsigned calcMaxScratches(const SUnit *SU) {
1472 unsigned Scratches = 0;
1473 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1474 I != E; ++I) {
1475 if (I->isCtrl) continue; // ignore chain preds
Evan Cheng0e400d42008-01-09 23:01:55 +00001476 if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyFromReg)
Evan Cheng61bc51e2007-12-20 02:22:36 +00001477 Scratches++;
1478 }
1479 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1480 I != E; ++I) {
1481 if (I->isCtrl) continue; // ignore chain succs
Evan Cheng0e400d42008-01-09 23:01:55 +00001482 if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyToReg)
Evan Cheng61bc51e2007-12-20 02:22:36 +00001483 Scratches += 10;
1484 }
1485 return Scratches;
1486}
1487
Evan Chengd38c22b2006-05-11 23:55:42 +00001488// Bottom up
1489bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Evan Cheng99f2f792006-05-13 08:22:24 +00001490
Evan Cheng6730f032007-01-08 23:55:53 +00001491 unsigned LPriority = SPQ->getNodePriority(left);
1492 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng73bdf042008-03-01 00:39:47 +00001493 if (LPriority != RPriority)
1494 return LPriority > RPriority;
1495
1496 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1497 // e.g.
1498 // t1 = op t2, c1
1499 // t3 = op t4, c2
1500 //
1501 // and the following instructions are both ready.
1502 // t2 = op c3
1503 // t4 = op c4
1504 //
1505 // Then schedule t2 = op first.
1506 // i.e.
1507 // t4 = op c4
1508 // t2 = op c3
1509 // t1 = op t2, c1
1510 // t3 = op t4, c2
1511 //
1512 // This creates more short live intervals.
1513 unsigned LDist = closestSucc(left);
1514 unsigned RDist = closestSucc(right);
1515 if (LDist != RDist)
1516 return LDist < RDist;
1517
1518 // Intuitively, it's good to push down instructions whose results are
1519 // liveout so their long live ranges won't conflict with other values
1520 // which are needed inside the BB. Further prioritize liveout instructions
1521 // by the number of operands which are calculated within the BB.
1522 unsigned LScratch = calcMaxScratches(left);
1523 unsigned RScratch = calcMaxScratches(right);
1524 if (LScratch != RScratch)
1525 return LScratch > RScratch;
1526
1527 if (left->Height != right->Height)
1528 return left->Height > right->Height;
1529
1530 if (left->Depth != right->Depth)
1531 return left->Depth < right->Depth;
1532
1533 if (left->CycleBound != right->CycleBound)
1534 return left->CycleBound > right->CycleBound;
1535
Roman Levenstein6b371142008-04-29 09:07:59 +00001536 assert(left->NodeQueueId && right->NodeQueueId &&
1537 "NodeQueueId cannot be zero");
1538 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00001539}
1540
Dan Gohman4b49be12008-06-21 01:08:22 +00001541bool
1542BURegReductionPriorityQueue::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001543 if (SU->isTwoAddress) {
1544 unsigned Opc = SU->Node->getTargetOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00001545 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00001546 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00001547 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001548 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +00001549 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001550 SDNode *DU = SU->Node->getOperand(i).Val;
Dan Gohman46520a22008-06-21 19:18:17 +00001551 if (DU->getNodeId() != -1 &&
1552 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001553 return true;
1554 }
1555 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001556 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001557 return false;
1558}
1559
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001560
Evan Chenga5e595d2007-09-28 22:32:30 +00001561/// hasCopyToRegUse - Return true if SU has a value successor that is a
1562/// CopyToReg node.
1563static bool hasCopyToRegUse(SUnit *SU) {
1564 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1565 I != E; ++I) {
1566 if (I->isCtrl) continue;
1567 SUnit *SuccSU = I->Dep;
1568 if (SuccSU->Node && SuccSU->Node->getOpcode() == ISD::CopyToReg)
1569 return true;
1570 }
1571 return false;
1572}
1573
Evan Chengf9891412007-12-20 09:25:31 +00001574/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1575/// physical register def.
1576static bool canClobberPhysRegDefs(SUnit *SuccSU, SUnit *SU,
1577 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00001578 const TargetRegisterInfo *TRI) {
Evan Chengf9891412007-12-20 09:25:31 +00001579 SDNode *N = SuccSU->Node;
Chris Lattnerb0d06b42008-01-07 03:13:06 +00001580 unsigned NumDefs = TII->get(N->getTargetOpcode()).getNumDefs();
1581 const unsigned *ImpDefs = TII->get(N->getTargetOpcode()).getImplicitDefs();
Evan Chengf9891412007-12-20 09:25:31 +00001582 if (!ImpDefs)
1583 return false;
Chris Lattnerb0d06b42008-01-07 03:13:06 +00001584 const unsigned *SUImpDefs =
1585 TII->get(SU->Node->getTargetOpcode()).getImplicitDefs();
Evan Chengf9891412007-12-20 09:25:31 +00001586 if (!SUImpDefs)
1587 return false;
1588 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Duncan Sands13237ac2008-06-06 12:08:01 +00001589 MVT VT = N->getValueType(i);
Evan Chengf9891412007-12-20 09:25:31 +00001590 if (VT == MVT::Flag || VT == MVT::Other)
1591 continue;
1592 unsigned Reg = ImpDefs[i - NumDefs];
1593 for (;*SUImpDefs; ++SUImpDefs) {
1594 unsigned SUReg = *SUImpDefs;
Dan Gohman3a4be0f2008-02-10 18:45:23 +00001595 if (TRI->regsOverlap(Reg, SUReg))
Evan Chengf9891412007-12-20 09:25:31 +00001596 return true;
1597 }
1598 }
1599 return false;
1600}
1601
Evan Chengd38c22b2006-05-11 23:55:42 +00001602/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1603/// it as a def&use operand. Add a pseudo control edge from it to the other
1604/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00001605/// first (lower in the schedule). If both nodes are two-address, favor the
1606/// one that has a CopyToReg use (more likely to be a loop induction update).
1607/// If both are two-address, but one is commutable while the other is not
1608/// commutable, favor the one that's not commutable.
Dan Gohman4b49be12008-06-21 01:08:22 +00001609void BURegReductionPriorityQueue::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001610 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1611 SUnit *SU = (SUnit *)&((*SUnits)[i]);
1612 if (!SU->isTwoAddress)
1613 continue;
1614
1615 SDNode *Node = SU->Node;
Evan Chenga5e595d2007-09-28 22:32:30 +00001616 if (!Node || !Node->isTargetOpcode() || SU->FlaggedNodes.size() > 0)
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001617 continue;
1618
1619 unsigned Opc = Node->getTargetOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00001620 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00001621 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00001622 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001623 for (unsigned j = 0; j != NumOps; ++j) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +00001624 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) != -1) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001625 SDNode *DU = SU->Node->getOperand(j).Val;
Dan Gohman46520a22008-06-21 19:18:17 +00001626 if (DU->getNodeId() == -1)
Evan Cheng1bf166312007-11-09 01:27:11 +00001627 continue;
Dan Gohman46520a22008-06-21 19:18:17 +00001628 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
Evan Chengf24d15f2006-11-06 21:33:46 +00001629 if (!DUSU) continue;
Dan Gohman46520a22008-06-21 19:18:17 +00001630 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
1631 E = DUSU->Succs.end(); I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001632 if (I->isCtrl) continue;
1633 SUnit *SuccSU = I->Dep;
Evan Chengf9891412007-12-20 09:25:31 +00001634 if (SuccSU == SU)
Evan Cheng5924bf72007-09-25 01:54:36 +00001635 continue;
Evan Cheng2dbffa42007-11-06 08:44:59 +00001636 // Be conservative. Ignore if nodes aren't at roughly the same
1637 // depth and height.
1638 if (SuccSU->Height < SU->Height && (SU->Height - SuccSU->Height) > 1)
1639 continue;
Evan Chengaa2d6ef2007-10-12 08:50:34 +00001640 if (!SuccSU->Node || !SuccSU->Node->isTargetOpcode())
1641 continue;
Evan Chengf9891412007-12-20 09:25:31 +00001642 // Don't constrain nodes with physical register defs if the
Dan Gohmancf8827a2008-01-29 12:43:50 +00001643 // predecessor can clobber them.
Evan Chengf9891412007-12-20 09:25:31 +00001644 if (SuccSU->hasPhysRegDefs) {
Dan Gohman3a4be0f2008-02-10 18:45:23 +00001645 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Chengf9891412007-12-20 09:25:31 +00001646 continue;
1647 }
Evan Chengaa2d6ef2007-10-12 08:50:34 +00001648 // Don't constraint extract_subreg / insert_subreg these may be
1649 // coalesced away. We don't them close to their uses.
1650 unsigned SuccOpc = SuccSU->Node->getTargetOpcode();
1651 if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1652 SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1653 continue;
Evan Cheng5924bf72007-09-25 01:54:36 +00001654 if ((!canClobber(SuccSU, DUSU) ||
Evan Chenga5e595d2007-09-28 22:32:30 +00001655 (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
Evan Cheng5924bf72007-09-25 01:54:36 +00001656 (!SU->isCommutable && SuccSU->isCommutable)) &&
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001657 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Cheng5924bf72007-09-25 01:54:36 +00001658 DOUT << "Adding an edge from SU # " << SU->NodeNum
1659 << " to SU #" << SuccSU->NodeNum << "\n";
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001660 scheduleDAG->AddPred(SU, SuccSU, true, true);
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001661 }
1662 }
1663 }
1664 }
1665 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001666}
1667
Evan Cheng6730f032007-01-08 23:55:53 +00001668/// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
Evan Chengd38c22b2006-05-11 23:55:42 +00001669/// Smaller number is the higher priority.
Dan Gohman4b49be12008-06-21 01:08:22 +00001670unsigned BURegReductionPriorityQueue::
Chris Lattner296a83c2007-02-01 04:55:59 +00001671CalcNodeSethiUllmanNumber(const SUnit *SU) {
Evan Cheng961bbd32007-01-08 23:50:38 +00001672 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +00001673 if (SethiUllmanNumber != 0)
1674 return SethiUllmanNumber;
1675
Evan Cheng961bbd32007-01-08 23:50:38 +00001676 unsigned Extra = 0;
1677 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1678 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001679 if (I->isCtrl) continue; // ignore chain preds
1680 SUnit *PredSU = I->Dep;
Evan Cheng6730f032007-01-08 23:55:53 +00001681 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
Evan Cheng961bbd32007-01-08 23:50:38 +00001682 if (PredSethiUllman > SethiUllmanNumber) {
1683 SethiUllmanNumber = PredSethiUllman;
1684 Extra = 0;
Evan Cheng0effc3a2007-09-19 01:38:40 +00001685 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
Evan Cheng5924bf72007-09-25 01:54:36 +00001686 ++Extra;
Evan Chengd38c22b2006-05-11 23:55:42 +00001687 }
Evan Cheng961bbd32007-01-08 23:50:38 +00001688
1689 SethiUllmanNumber += Extra;
1690
1691 if (SethiUllmanNumber == 0)
1692 SethiUllmanNumber = 1;
Evan Chengd38c22b2006-05-11 23:55:42 +00001693
1694 return SethiUllmanNumber;
1695}
1696
Evan Cheng6730f032007-01-08 23:55:53 +00001697/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1698/// scheduling units.
Dan Gohman4b49be12008-06-21 01:08:22 +00001699void BURegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
Evan Chengd38c22b2006-05-11 23:55:42 +00001700 SethiUllmanNumbers.assign(SUnits->size(), 0);
1701
1702 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
Evan Cheng6730f032007-01-08 23:55:53 +00001703 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
Evan Chengd38c22b2006-05-11 23:55:42 +00001704}
1705
Roman Levenstein30d09512008-03-27 09:44:37 +00001706/// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
Roman Levensteinbc674502008-03-27 09:14:57 +00001707/// predecessors of the successors of the SUnit SU. Stop when the provided
1708/// limit is exceeded.
Roman Levensteinbc674502008-03-27 09:14:57 +00001709static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
1710 unsigned Limit) {
1711 unsigned Sum = 0;
1712 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1713 I != E; ++I) {
1714 SUnit *SuccSU = I->Dep;
1715 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1716 EE = SuccSU->Preds.end(); II != EE; ++II) {
1717 SUnit *PredSU = II->Dep;
Evan Cheng16d72072008-03-29 18:34:22 +00001718 if (!PredSU->isScheduled)
1719 if (++Sum > Limit)
1720 return Sum;
Roman Levensteinbc674502008-03-27 09:14:57 +00001721 }
1722 }
1723 return Sum;
1724}
1725
Evan Chengd38c22b2006-05-11 23:55:42 +00001726
1727// Top down
1728bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Evan Cheng6730f032007-01-08 23:55:53 +00001729 unsigned LPriority = SPQ->getNodePriority(left);
1730 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng8e136a92007-09-26 21:36:17 +00001731 bool LIsTarget = left->Node && left->Node->isTargetOpcode();
1732 bool RIsTarget = right->Node && right->Node->isTargetOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00001733 bool LIsFloater = LIsTarget && left->NumPreds == 0;
1734 bool RIsFloater = RIsTarget && right->NumPreds == 0;
Roman Levensteinbc674502008-03-27 09:14:57 +00001735 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
1736 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001737
1738 if (left->NumSuccs == 0 && right->NumSuccs != 0)
1739 return false;
1740 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1741 return true;
1742
Evan Chengd38c22b2006-05-11 23:55:42 +00001743 if (LIsFloater)
1744 LBonus -= 2;
1745 if (RIsFloater)
1746 RBonus -= 2;
1747 if (left->NumSuccs == 1)
1748 LBonus += 2;
1749 if (right->NumSuccs == 1)
1750 RBonus += 2;
1751
Evan Cheng73bdf042008-03-01 00:39:47 +00001752 if (LPriority+LBonus != RPriority+RBonus)
1753 return LPriority+LBonus < RPriority+RBonus;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00001754
Evan Cheng73bdf042008-03-01 00:39:47 +00001755 if (left->Depth != right->Depth)
1756 return left->Depth < right->Depth;
1757
1758 if (left->NumSuccsLeft != right->NumSuccsLeft)
1759 return left->NumSuccsLeft > right->NumSuccsLeft;
1760
1761 if (left->CycleBound != right->CycleBound)
1762 return left->CycleBound > right->CycleBound;
1763
Roman Levenstein6b371142008-04-29 09:07:59 +00001764 assert(left->NodeQueueId && right->NodeQueueId &&
1765 "NodeQueueId cannot be zero");
1766 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00001767}
1768
Evan Cheng6730f032007-01-08 23:55:53 +00001769/// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
Evan Chengd38c22b2006-05-11 23:55:42 +00001770/// Smaller number is the higher priority.
Dan Gohman4b49be12008-06-21 01:08:22 +00001771unsigned TDRegReductionPriorityQueue::
Chris Lattner296a83c2007-02-01 04:55:59 +00001772CalcNodeSethiUllmanNumber(const SUnit *SU) {
Evan Cheng961bbd32007-01-08 23:50:38 +00001773 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
Evan Chengd38c22b2006-05-11 23:55:42 +00001774 if (SethiUllmanNumber != 0)
1775 return SethiUllmanNumber;
1776
Evan Cheng8e136a92007-09-26 21:36:17 +00001777 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001778 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
Evan Cheng961bbd32007-01-08 23:50:38 +00001779 SethiUllmanNumber = 0xffff;
Evan Chengd38c22b2006-05-11 23:55:42 +00001780 else if (SU->NumSuccsLeft == 0)
1781 // If SU does not have a use, i.e. it doesn't produce a value that would
1782 // be consumed (e.g. store), then it terminates a chain of computation.
Chris Lattner296a83c2007-02-01 04:55:59 +00001783 // Give it a small SethiUllman number so it will be scheduled right before
1784 // its predecessors that it doesn't lengthen their live ranges.
Evan Cheng961bbd32007-01-08 23:50:38 +00001785 SethiUllmanNumber = 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00001786 else if (SU->NumPredsLeft == 0 &&
1787 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
Evan Cheng961bbd32007-01-08 23:50:38 +00001788 SethiUllmanNumber = 0xffff;
Evan Chengd38c22b2006-05-11 23:55:42 +00001789 else {
1790 int Extra = 0;
Chris Lattnerd86418a2006-08-17 00:09:56 +00001791 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1792 I != E; ++I) {
Evan Cheng0effc3a2007-09-19 01:38:40 +00001793 if (I->isCtrl) continue; // ignore chain preds
1794 SUnit *PredSU = I->Dep;
Evan Cheng6730f032007-01-08 23:55:53 +00001795 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001796 if (PredSethiUllman > SethiUllmanNumber) {
1797 SethiUllmanNumber = PredSethiUllman;
1798 Extra = 0;
Evan Cheng0effc3a2007-09-19 01:38:40 +00001799 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
Evan Cheng5924bf72007-09-25 01:54:36 +00001800 ++Extra;
Evan Chengd38c22b2006-05-11 23:55:42 +00001801 }
1802
1803 SethiUllmanNumber += Extra;
1804 }
1805
1806 return SethiUllmanNumber;
1807}
1808
Evan Cheng6730f032007-01-08 23:55:53 +00001809/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1810/// scheduling units.
Dan Gohman4b49be12008-06-21 01:08:22 +00001811void TDRegReductionPriorityQueue::CalculateSethiUllmanNumbers() {
Evan Chengd38c22b2006-05-11 23:55:42 +00001812 SethiUllmanNumbers.assign(SUnits->size(), 0);
1813
1814 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
Evan Cheng6730f032007-01-08 23:55:53 +00001815 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
Evan Chengd38c22b2006-05-11 23:55:42 +00001816}
1817
1818//===----------------------------------------------------------------------===//
1819// Public Constructor Functions
1820//===----------------------------------------------------------------------===//
1821
Jim Laskey03593f72006-08-01 18:29:48 +00001822llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1823 SelectionDAG *DAG,
Evan Chengd38c22b2006-05-11 23:55:42 +00001824 MachineBasicBlock *BB) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00001825 const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
Dan Gohman3a4be0f2008-02-10 18:45:23 +00001826 const TargetRegisterInfo *TRI = DAG->getTarget().getRegisterInfo();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001827
Dan Gohman4b49be12008-06-21 01:08:22 +00001828 BURegReductionPriorityQueue *priorityQueue =
1829 new BURegReductionPriorityQueue(TII, TRI);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001830
1831 ScheduleDAGRRList * scheduleDAG =
1832 new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true, priorityQueue);
1833 priorityQueue->setScheduleDAG(scheduleDAG);
1834 return scheduleDAG;
Evan Chengd38c22b2006-05-11 23:55:42 +00001835}
1836
Jim Laskey03593f72006-08-01 18:29:48 +00001837llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1838 SelectionDAG *DAG,
Evan Chengd38c22b2006-05-11 23:55:42 +00001839 MachineBasicBlock *BB) {
Jim Laskey95eda5b2006-08-01 14:21:23 +00001840 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false,
Dan Gohman4b49be12008-06-21 01:08:22 +00001841 new TDRegReductionPriorityQueue());
Evan Chengd38c22b2006-05-11 23:55:42 +00001842}
1843