blob: 1053b888a0dc881d968d03b64fc3f10a64275e75 [file] [log] [blame]
Dan Gohman23785a12008-08-12 17:42:33 +00001//===----- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler --===//
Evan Chengd38c22b2006-05-11 23:55:42 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Chengd38c22b2006-05-11 23:55:42 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This implements bottom-up and top-down register pressure reduction list
11// schedulers, using standard algorithms. The basic approach uses a priority
12// queue of available nodes to schedule. One at a time, nodes are taken from
13// the priority queue (thus in priority order), checked for legality to
14// schedule, and emitted if legal.
15//
16//===----------------------------------------------------------------------===//
17
Dale Johannesen2182f062007-07-13 17:13:54 +000018#define DEBUG_TYPE "pre-RA-sched"
Dan Gohman483377c2009-02-06 17:22:58 +000019#include "ScheduleDAGSDNodes.h"
Chris Lattner3b9f02a2010-04-07 05:20:54 +000020#include "llvm/InlineAsm.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000021#include "llvm/CodeGen/SchedulerRegistry.h"
Dan Gohman619ef482009-01-15 19:20:50 +000022#include "llvm/CodeGen/SelectionDAGISel.h"
Andrew Trick10ffc2b2010-12-24 05:03:26 +000023#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Dan Gohman3a4be0f2008-02-10 18:45:23 +000024#include "llvm/Target/TargetRegisterInfo.h"
Owen Anderson8c2c1e92006-05-12 06:33:49 +000025#include "llvm/Target/TargetData.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000026#include "llvm/Target/TargetMachine.h"
27#include "llvm/Target/TargetInstrInfo.h"
Evan Chenga77f3d32010-07-21 06:09:07 +000028#include "llvm/Target/TargetLowering.h"
Evan Cheng5924bf72007-09-25 01:54:36 +000029#include "llvm/ADT/SmallSet.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000030#include "llvm/ADT/Statistic.h"
Roman Levenstein6b371142008-04-29 09:07:59 +000031#include "llvm/ADT/STLExtras.h"
Chris Lattner3b9f02a2010-04-07 05:20:54 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000034#include "llvm/Support/raw_ostream.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000035#include <climits>
Evan Chengd38c22b2006-05-11 23:55:42 +000036using namespace llvm;
37
Dan Gohmanfd227e92008-03-25 17:10:29 +000038STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
Evan Cheng79e97132007-10-05 01:39:18 +000039STATISTIC(NumUnfolds, "Number of nodes unfolded");
Evan Cheng1ec79b42007-09-27 07:09:03 +000040STATISTIC(NumDups, "Number of duplicated nodes");
Evan Chengb2c42c62009-01-12 03:19:55 +000041STATISTIC(NumPRCopies, "Number of physical register copies");
Evan Cheng1ec79b42007-09-27 07:09:03 +000042
Jim Laskey95eda5b2006-08-01 14:21:23 +000043static RegisterScheduler
44 burrListDAGScheduler("list-burr",
Dan Gohman9c4b7d52008-10-14 20:25:08 +000045 "Bottom-up register reduction list scheduling",
Jim Laskey95eda5b2006-08-01 14:21:23 +000046 createBURRListDAGScheduler);
47static RegisterScheduler
48 tdrListrDAGScheduler("list-tdrr",
Dan Gohman9c4b7d52008-10-14 20:25:08 +000049 "Top-down register reduction list scheduling",
Jim Laskey95eda5b2006-08-01 14:21:23 +000050 createTDRRListDAGScheduler);
Bill Wendling8cbc25d2010-01-23 10:26:57 +000051static RegisterScheduler
52 sourceListDAGScheduler("source",
53 "Similar to list-burr but schedules in source "
54 "order when possible",
55 createSourceListDAGScheduler);
Jim Laskey95eda5b2006-08-01 14:21:23 +000056
Evan Chengbdd062d2010-05-20 06:13:19 +000057static RegisterScheduler
Evan Cheng725211e2010-05-21 00:42:32 +000058 hybridListDAGScheduler("list-hybrid",
Evan Cheng37b740c2010-07-24 00:39:05 +000059 "Bottom-up register pressure aware list scheduling "
60 "which tries to balance latency and register pressure",
Evan Chengbdd062d2010-05-20 06:13:19 +000061 createHybridListDAGScheduler);
62
Evan Cheng37b740c2010-07-24 00:39:05 +000063static RegisterScheduler
64 ILPListDAGScheduler("list-ilp",
65 "Bottom-up register pressure aware list scheduling "
66 "which tries to balance ILP and register pressure",
67 createILPListDAGScheduler);
68
Andrew Trick47ff14b2011-01-21 05:51:33 +000069static cl::opt<bool> DisableSchedCycles(
Andrew Trickbd428ec2011-01-21 06:19:05 +000070 "disable-sched-cycles", cl::Hidden, cl::init(false),
Andrew Trick47ff14b2011-01-21 05:51:33 +000071 cl::desc("Disable cycle-level precision during preRA scheduling"));
Andrew Trick10ffc2b2010-12-24 05:03:26 +000072
Andrew Trick641e2d42011-03-05 08:00:22 +000073// Temporary sched=list-ilp flags until the heuristics are robust.
Andrew Trickbfbd9722011-04-14 05:15:06 +000074// Some options are also available under sched=list-hybrid.
Andrew Trick641e2d42011-03-05 08:00:22 +000075static cl::opt<bool> DisableSchedRegPressure(
76 "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
77 cl::desc("Disable regpressure priority in sched=list-ilp"));
78static cl::opt<bool> DisableSchedLiveUses(
Andrew Trickdd017322011-03-06 00:03:32 +000079 "disable-sched-live-uses", cl::Hidden, cl::init(true),
Andrew Trick641e2d42011-03-05 08:00:22 +000080 cl::desc("Disable live use priority in sched=list-ilp"));
Andrew Trick2ad0b372011-04-07 19:54:57 +000081static cl::opt<bool> DisableSchedVRegCycle(
82 "disable-sched-vrcycle", cl::Hidden, cl::init(false),
83 cl::desc("Disable virtual register cycle interference checks"));
Andrew Trickbfbd9722011-04-14 05:15:06 +000084static cl::opt<bool> DisableSchedPhysRegJoin(
85 "disable-sched-physreg-join", cl::Hidden, cl::init(false),
86 cl::desc("Disable physreg def-use affinity"));
Andrew Trick641e2d42011-03-05 08:00:22 +000087static cl::opt<bool> DisableSchedStalls(
Andrew Trickdd017322011-03-06 00:03:32 +000088 "disable-sched-stalls", cl::Hidden, cl::init(true),
Andrew Trick641e2d42011-03-05 08:00:22 +000089 cl::desc("Disable no-stall priority in sched=list-ilp"));
90static cl::opt<bool> DisableSchedCriticalPath(
91 "disable-sched-critical-path", cl::Hidden, cl::init(false),
92 cl::desc("Disable critical path priority in sched=list-ilp"));
93static cl::opt<bool> DisableSchedHeight(
94 "disable-sched-height", cl::Hidden, cl::init(false),
95 cl::desc("Disable scheduled-height priority in sched=list-ilp"));
96
97static cl::opt<int> MaxReorderWindow(
98 "max-sched-reorder", cl::Hidden, cl::init(6),
99 cl::desc("Number of instructions to allow ahead of the critical path "
100 "in sched=list-ilp"));
101
102static cl::opt<unsigned> AvgIPC(
103 "sched-avg-ipc", cl::Hidden, cl::init(1),
104 cl::desc("Average inst/cycle whan no target itinerary exists."));
105
106#ifndef NDEBUG
107namespace {
108 // For sched=list-ilp, Count the number of times each factor comes into play.
Andrew Trickb53a00d2011-04-13 00:38:32 +0000109 enum { FactPressureDiff, FactRegUses, FactStall, FactHeight, FactDepth,
110 FactStatic, FactOther, NumFactors };
Andrew Trick641e2d42011-03-05 08:00:22 +0000111}
112static const char *FactorName[NumFactors] =
Andrew Trickb53a00d2011-04-13 00:38:32 +0000113{"PressureDiff", "RegUses", "Stall", "Height", "Depth","Static", "Other"};
Andrew Trick641e2d42011-03-05 08:00:22 +0000114static int FactorCount[NumFactors];
115#endif //!NDEBUG
116
Evan Chengd38c22b2006-05-11 23:55:42 +0000117namespace {
Evan Chengd38c22b2006-05-11 23:55:42 +0000118//===----------------------------------------------------------------------===//
119/// ScheduleDAGRRList - The actual register reduction list scheduler
120/// implementation. This supports both top-down and bottom-up scheduling.
121///
Nick Lewycky02d5f772009-10-25 06:33:48 +0000122class ScheduleDAGRRList : public ScheduleDAGSDNodes {
Evan Chengd38c22b2006-05-11 23:55:42 +0000123private:
124 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
125 /// it is top-down.
126 bool isBottomUp;
Evan Cheng2c977312008-07-01 18:05:03 +0000127
Evan Chengbdd062d2010-05-20 06:13:19 +0000128 /// NeedLatency - True if the scheduler will make use of latency information.
129 ///
130 bool NeedLatency;
131
Evan Chengd38c22b2006-05-11 23:55:42 +0000132 /// AvailableQueue - The priority queue to use for the available SUnits.
Evan Chengd38c22b2006-05-11 23:55:42 +0000133 SchedulingPriorityQueue *AvailableQueue;
134
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000135 /// PendingQueue - This contains all of the instructions whose operands have
136 /// been issued, but their results are not ready yet (due to the latency of
137 /// the operation). Once the operands becomes available, the instruction is
138 /// added to the AvailableQueue.
139 std::vector<SUnit*> PendingQueue;
140
141 /// HazardRec - The hazard recognizer to use.
142 ScheduleHazardRecognizer *HazardRec;
143
Andrew Trick528fad92010-12-23 05:42:20 +0000144 /// CurCycle - The current scheduler state corresponds to this cycle.
145 unsigned CurCycle;
146
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000147 /// MinAvailableCycle - Cycle of the soonest available instruction.
148 unsigned MinAvailableCycle;
149
Andrew Trick641e2d42011-03-05 08:00:22 +0000150 /// IssueCount - Count instructions issued in this cycle
151 /// Currently valid only for bottom-up scheduling.
152 unsigned IssueCount;
153
Dan Gohmanc07f6862008-09-23 18:50:48 +0000154 /// LiveRegDefs - A set of physical registers and their definition
Evan Cheng5924bf72007-09-25 01:54:36 +0000155 /// that are "live". These nodes must be scheduled before any other nodes that
156 /// modifies the registers can be scheduled.
Dan Gohmanc07f6862008-09-23 18:50:48 +0000157 unsigned NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000158 std::vector<SUnit*> LiveRegDefs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000159 std::vector<SUnit*> LiveRegGens;
Evan Cheng5924bf72007-09-25 01:54:36 +0000160
Dan Gohmanad2134d2008-11-25 00:52:40 +0000161 /// Topo - A topological ordering for SUnits which permits fast IsReachable
162 /// and similar queries.
163 ScheduleDAGTopologicalSort Topo;
164
Evan Chengd38c22b2006-05-11 23:55:42 +0000165public:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000166 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
167 SchedulingPriorityQueue *availqueue,
168 CodeGenOpt::Level OptLevel)
169 : ScheduleDAGSDNodes(mf), isBottomUp(availqueue->isBottomUp()),
170 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
171 Topo(SUnits) {
172
173 const TargetMachine &tm = mf.getTarget();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000174 if (DisableSchedCycles || !NeedLatency)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000175 HazardRec = new ScheduleHazardRecognizer();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000176 else
177 HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000178 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000179
180 ~ScheduleDAGRRList() {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000181 delete HazardRec;
Evan Chengd38c22b2006-05-11 23:55:42 +0000182 delete AvailableQueue;
183 }
184
185 void Schedule();
186
Andrew Trick9ccce772011-01-14 21:11:41 +0000187 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
188
Roman Levenstein733a4d62008-03-26 11:23:38 +0000189 /// IsReachable - Checks if SU is reachable from TargetSU.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000190 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
191 return Topo.IsReachable(SU, TargetSU);
192 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000193
Dan Gohman60d68442009-01-29 19:49:27 +0000194 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000195 /// create a cycle.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000196 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
197 return Topo.WillCreateCycle(SU, TargetSU);
198 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000199
Dan Gohman2d170892008-12-09 22:54:47 +0000200 /// AddPred - adds a predecessor edge to SUnit SU.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000201 /// This returns true if this is a new predecessor.
202 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000203 void AddPred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000204 Topo.AddPred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000205 SU->addPred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000206 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000207
Dan Gohman2d170892008-12-09 22:54:47 +0000208 /// RemovePred - removes a predecessor edge from SUnit SU.
209 /// This returns true if an edge was removed.
210 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000211 void RemovePred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000212 Topo.RemovePred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000213 SU->removePred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000214 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000215
Evan Chengd38c22b2006-05-11 23:55:42 +0000216private:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000217 bool isReady(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000218 return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000219 AvailableQueue->isReady(SU);
220 }
221
Dan Gohman60d68442009-01-29 19:49:27 +0000222 void ReleasePred(SUnit *SU, const SDep *PredEdge);
Andrew Tricka52f3252010-12-23 04:16:14 +0000223 void ReleasePredecessors(SUnit *SU);
Dan Gohman60d68442009-01-29 19:49:27 +0000224 void ReleaseSucc(SUnit *SU, const SDep *SuccEdge);
Dan Gohmanb9543432009-02-10 23:27:53 +0000225 void ReleaseSuccessors(SUnit *SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000226 void ReleasePending();
227 void AdvanceToCycle(unsigned NextCycle);
228 void AdvancePastStalls(SUnit *SU);
229 void EmitNode(SUnit *SU);
Andrew Trick528fad92010-12-23 05:42:20 +0000230 void ScheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000231 void CapturePred(SDep *PredEdge);
Evan Cheng8e136a92007-09-26 21:36:17 +0000232 void UnscheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000233 void RestoreHazardCheckerBottomUp();
234 void BacktrackBottomUp(SUnit*, SUnit*);
Evan Cheng8e136a92007-09-26 21:36:17 +0000235 SUnit *CopyAndMoveSuccessors(SUnit*);
Evan Chengb2c42c62009-01-12 03:19:55 +0000236 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
237 const TargetRegisterClass*,
238 const TargetRegisterClass*,
239 SmallVector<SUnit*, 2>&);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000240 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000241
Andrew Trick528fad92010-12-23 05:42:20 +0000242 SUnit *PickNodeToScheduleBottomUp();
Evan Chengd38c22b2006-05-11 23:55:42 +0000243 void ListScheduleBottomUp();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000244
Andrew Trick528fad92010-12-23 05:42:20 +0000245 void ScheduleNodeTopDown(SUnit*);
246 void ListScheduleTopDown();
247
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000248
249 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000250 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000251 SUnit *CreateNewSUnit(SDNode *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000252 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000253 SUnit *NewNode = NewSUnit(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000254 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000255 if (NewNode->NodeNum >= NumSUnits)
256 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000257 return NewNode;
258 }
259
Roman Levenstein733a4d62008-03-26 11:23:38 +0000260 /// CreateClone - Creates a new SUnit from an existing one.
261 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000262 SUnit *CreateClone(SUnit *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000263 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000264 SUnit *NewNode = Clone(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000265 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000266 if (NewNode->NodeNum >= NumSUnits)
267 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000268 return NewNode;
269 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000270
Evan Chengbdd062d2010-05-20 06:13:19 +0000271 /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
272 /// need actual latency information but the hybrid scheduler does.
273 bool ForceUnitLatencies() const {
274 return !NeedLatency;
275 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000276};
277} // end anonymous namespace
278
Owen Anderson96adc4a2011-06-15 23:35:18 +0000279/// GetCostForDef - Looks up the register class and cost for a given definition.
280/// Typically this just means looking up the representative register class,
281/// but for untyped values (MVT::untyped) it means inspecting the node's
282/// opcode to determine what register class is being generated.
283static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos,
284 const TargetLowering *TLI,
285 const TargetInstrInfo *TII,
286 const TargetRegisterInfo *TRI,
287 unsigned &RegClass, unsigned &Cost) {
288 EVT VT = RegDefPos.GetValue();
289
290 // Special handling for untyped values. These values can only come from
291 // the expansion of custom DAG-to-DAG patterns.
292 if (VT == MVT::untyped) {
Owen Andersond1955e72011-06-21 22:54:23 +0000293 const SDNode *Node = RegDefPos.GetNode();
294 unsigned Opcode = Node->getMachineOpcode();
295
296 if (Opcode == TargetOpcode::REG_SEQUENCE) {
297 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
298 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
299 RegClass = RC->getID();
300 Cost = 1;
301 return;
302 }
303
Owen Anderson96adc4a2011-06-15 23:35:18 +0000304 unsigned Idx = RegDefPos.GetIdx();
305 const TargetInstrDesc Desc = TII->get(Opcode);
306 const TargetRegisterClass *RC = Desc.getRegClass(Idx, TRI);
307 RegClass = RC->getID();
308 // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
309 // better way to determine it.
310 Cost = 1;
311 } else {
312 RegClass = TLI->getRepRegClassFor(VT)->getID();
313 Cost = TLI->getRepRegClassCostFor(VT);
314 }
315}
Evan Chengd38c22b2006-05-11 23:55:42 +0000316
317/// Schedule - Schedule the DAG using list scheduling.
318void ScheduleDAGRRList::Schedule() {
Evan Chenga77f3d32010-07-21 06:09:07 +0000319 DEBUG(dbgs()
320 << "********** List Scheduling BB#" << BB->getNumber()
Evan Cheng6c1414f2010-10-29 18:09:28 +0000321 << " '" << BB->getName() << "' **********\n");
Andrew Trick641e2d42011-03-05 08:00:22 +0000322#ifndef NDEBUG
323 for (int i = 0; i < NumFactors; ++i) {
324 FactorCount[i] = 0;
325 }
326#endif //!NDEBUG
Evan Cheng5924bf72007-09-25 01:54:36 +0000327
Andrew Trick528fad92010-12-23 05:42:20 +0000328 CurCycle = 0;
Andrew Trick641e2d42011-03-05 08:00:22 +0000329 IssueCount = 0;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000330 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
Dan Gohmanc07f6862008-09-23 18:50:48 +0000331 NumLiveRegs = 0;
Andrew Trick2085a962010-12-21 22:25:04 +0000332 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
Andrew Tricka52f3252010-12-23 04:16:14 +0000333 LiveRegGens.resize(TRI->getNumRegs(), NULL);
Evan Cheng5924bf72007-09-25 01:54:36 +0000334
Dan Gohman04543e72008-12-23 18:36:58 +0000335 // Build the scheduling graph.
Dan Gohman918ec532009-10-09 23:33:48 +0000336 BuildSchedGraph(NULL);
Evan Chengd38c22b2006-05-11 23:55:42 +0000337
Evan Chengd38c22b2006-05-11 23:55:42 +0000338 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Dan Gohman22d07b12008-11-18 02:06:40 +0000339 SUnits[su].dumpAll(this));
Dan Gohmanad2134d2008-11-25 00:52:40 +0000340 Topo.InitDAGTopologicalSorting();
Evan Chengd38c22b2006-05-11 23:55:42 +0000341
Dan Gohman46520a22008-06-21 19:18:17 +0000342 AvailableQueue->initNodes(SUnits);
Andrew Trick2085a962010-12-21 22:25:04 +0000343
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000344 HazardRec->Reset();
345
Evan Chengd38c22b2006-05-11 23:55:42 +0000346 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
347 if (isBottomUp)
348 ListScheduleBottomUp();
349 else
350 ListScheduleTopDown();
Andrew Trick2085a962010-12-21 22:25:04 +0000351
Andrew Trick641e2d42011-03-05 08:00:22 +0000352#ifndef NDEBUG
353 for (int i = 0; i < NumFactors; ++i) {
354 DEBUG(dbgs() << FactorName[i] << "\t" << FactorCount[i] << "\n");
355 }
356#endif // !NDEBUG
Evan Chengd38c22b2006-05-11 23:55:42 +0000357 AvailableQueue->releaseState();
Evan Chengafed73e2006-05-12 01:58:24 +0000358}
Evan Chengd38c22b2006-05-11 23:55:42 +0000359
360//===----------------------------------------------------------------------===//
361// Bottom-Up Scheduling
362//===----------------------------------------------------------------------===//
363
Evan Chengd38c22b2006-05-11 23:55:42 +0000364/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000365/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +0000366void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000367 SUnit *PredSU = PredEdge->getSUnit();
Reid Klecknercea8dab2009-09-30 20:43:07 +0000368
Evan Chengd38c22b2006-05-11 23:55:42 +0000369#ifndef NDEBUG
Reid Klecknercea8dab2009-09-30 20:43:07 +0000370 if (PredSU->NumSuccsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +0000371 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +0000372 PredSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +0000373 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +0000374 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +0000375 }
376#endif
Reid Klecknercea8dab2009-09-30 20:43:07 +0000377 --PredSU->NumSuccsLeft;
378
Evan Chengbdd062d2010-05-20 06:13:19 +0000379 if (!ForceUnitLatencies()) {
380 // Updating predecessor's height. This is now the cycle when the
381 // predecessor can be scheduled without causing a pipeline stall.
382 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
383 }
384
Dan Gohmanb9543432009-02-10 23:27:53 +0000385 // If all the node's successors are scheduled, this node is ready
386 // to be scheduled. Ignore the special EntrySU node.
387 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
Dan Gohman4370f262008-04-15 01:22:18 +0000388 PredSU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000389
390 unsigned Height = PredSU->getHeight();
391 if (Height < MinAvailableCycle)
392 MinAvailableCycle = Height;
393
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000394 if (isReady(PredSU)) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000395 AvailableQueue->push(PredSU);
396 }
397 // CapturePred and others may have left the node in the pending queue, avoid
398 // adding it twice.
399 else if (!PredSU->isPending) {
400 PredSU->isPending = true;
401 PendingQueue.push_back(PredSU);
402 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000403 }
404}
405
Andrew Trick033efdf2010-12-23 03:15:51 +0000406/// Call ReleasePred for each predecessor, then update register live def/gen.
407/// Always update LiveRegDefs for a register dependence even if the current SU
408/// also defines the register. This effectively create one large live range
409/// across a sequence of two-address node. This is important because the
410/// entire chain must be scheduled together. Example:
411///
412/// flags = (3) add
413/// flags = (2) addc flags
414/// flags = (1) addc flags
415///
416/// results in
417///
418/// LiveRegDefs[flags] = 3
Andrew Tricka52f3252010-12-23 04:16:14 +0000419/// LiveRegGens[flags] = 1
Andrew Trick033efdf2010-12-23 03:15:51 +0000420///
421/// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
422/// interference on flags.
Andrew Tricka52f3252010-12-23 04:16:14 +0000423void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000424 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000425 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000426 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000427 ReleasePred(SU, &*I);
428 if (I->isAssignedRegDep()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000429 // This is a physical register dependency and it's impossible or
Andrew Trick2085a962010-12-21 22:25:04 +0000430 // expensive to copy the register. Make sure nothing that can
Evan Cheng5924bf72007-09-25 01:54:36 +0000431 // clobber the register is scheduled between the predecessor and
432 // this node.
Andrew Tricka52f3252010-12-23 04:16:14 +0000433 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
Andrew Trick033efdf2010-12-23 03:15:51 +0000434 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
435 "interference on register dependence");
Andrew Tricka52f3252010-12-23 04:16:14 +0000436 LiveRegDefs[I->getReg()] = I->getSUnit();
437 if (!LiveRegGens[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000438 ++NumLiveRegs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000439 LiveRegGens[I->getReg()] = SU;
Evan Cheng5924bf72007-09-25 01:54:36 +0000440 }
441 }
442 }
Dan Gohmanb9543432009-02-10 23:27:53 +0000443}
444
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000445/// Check to see if any of the pending instructions are ready to issue. If
446/// so, add them to the available queue.
447void ScheduleDAGRRList::ReleasePending() {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000448 if (DisableSchedCycles) {
Andrew Trick5ce945c2010-12-24 07:10:19 +0000449 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
450 return;
451 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000452
453 // If the available queue is empty, it is safe to reset MinAvailableCycle.
454 if (AvailableQueue->empty())
455 MinAvailableCycle = UINT_MAX;
456
457 // Check to see if any of the pending instructions are ready to issue. If
458 // so, add them to the available queue.
459 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
460 unsigned ReadyCycle =
461 isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDepth();
462 if (ReadyCycle < MinAvailableCycle)
463 MinAvailableCycle = ReadyCycle;
464
465 if (PendingQueue[i]->isAvailable) {
466 if (!isReady(PendingQueue[i]))
467 continue;
468 AvailableQueue->push(PendingQueue[i]);
469 }
470 PendingQueue[i]->isPending = false;
471 PendingQueue[i] = PendingQueue.back();
472 PendingQueue.pop_back();
473 --i; --e;
474 }
475}
476
477/// Move the scheduler state forward by the specified number of Cycles.
478void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
479 if (NextCycle <= CurCycle)
480 return;
481
Andrew Trick641e2d42011-03-05 08:00:22 +0000482 IssueCount = 0;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000483 AvailableQueue->setCurCycle(NextCycle);
Andrew Trick47ff14b2011-01-21 05:51:33 +0000484 if (!HazardRec->isEnabled()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000485 // Bypass lots of virtual calls in case of long latency.
486 CurCycle = NextCycle;
487 }
488 else {
489 for (; CurCycle != NextCycle; ++CurCycle) {
490 if (isBottomUp)
491 HazardRec->RecedeCycle();
492 else
493 HazardRec->AdvanceCycle();
494 }
495 }
496 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
497 // available Q to release pending nodes at least once before popping.
498 ReleasePending();
499}
500
501/// Move the scheduler state forward until the specified node's dependents are
502/// ready and can be scheduled with no resource conflicts.
503void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000504 if (DisableSchedCycles)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000505 return;
506
Andrew Trickb53a00d2011-04-13 00:38:32 +0000507 // FIXME: Nodes such as CopyFromReg probably should not advance the current
508 // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
509 // has predecessors the cycle will be advanced when they are scheduled.
510 // But given the crude nature of modeling latency though such nodes, we
511 // currently need to treat these nodes like real instructions.
512 // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
513
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000514 unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
515
516 // Bump CurCycle to account for latency. We assume the latency of other
517 // available instructions may be hidden by the stall (not a full pipe stall).
518 // This updates the hazard recognizer's cycle before reserving resources for
519 // this instruction.
520 AdvanceToCycle(ReadyCycle);
521
522 // Calls are scheduled in their preceding cycle, so don't conflict with
523 // hazards from instructions after the call. EmitNode will reset the
524 // scoreboard state before emitting the call.
525 if (isBottomUp && SU->isCall)
526 return;
527
528 // FIXME: For resource conflicts in very long non-pipelined stages, we
529 // should probably skip ahead here to avoid useless scoreboard checks.
530 int Stalls = 0;
531 while (true) {
532 ScheduleHazardRecognizer::HazardType HT =
533 HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
534
535 if (HT == ScheduleHazardRecognizer::NoHazard)
536 break;
537
538 ++Stalls;
539 }
540 AdvanceToCycle(CurCycle + Stalls);
541}
542
543/// Record this SUnit in the HazardRecognizer.
544/// Does not update CurCycle.
545void ScheduleDAGRRList::EmitNode(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000546 if (!HazardRec->isEnabled())
Andrew Trickc9405662010-12-24 06:46:50 +0000547 return;
548
549 // Check for phys reg copy.
550 if (!SU->getNode())
551 return;
552
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000553 switch (SU->getNode()->getOpcode()) {
554 default:
555 assert(SU->getNode()->isMachineOpcode() &&
556 "This target-independent node should not be scheduled.");
557 break;
558 case ISD::MERGE_VALUES:
559 case ISD::TokenFactor:
560 case ISD::CopyToReg:
561 case ISD::CopyFromReg:
562 case ISD::EH_LABEL:
563 // Noops don't affect the scoreboard state. Copies are likely to be
564 // removed.
565 return;
566 case ISD::INLINEASM:
567 // For inline asm, clear the pipeline state.
568 HazardRec->Reset();
569 return;
570 }
571 if (isBottomUp && SU->isCall) {
572 // Calls are scheduled with their preceding instructions. For bottom-up
573 // scheduling, clear the pipeline state before emitting.
574 HazardRec->Reset();
575 }
576
577 HazardRec->EmitInstruction(SU);
578
579 if (!isBottomUp && SU->isCall) {
580 HazardRec->Reset();
581 }
582}
583
Andrew Trickb53a00d2011-04-13 00:38:32 +0000584static void resetVRegCycle(SUnit *SU);
585
Dan Gohmanb9543432009-02-10 23:27:53 +0000586/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
587/// count of its predecessors. If a predecessor pending count is zero, add it to
588/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000589void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Andrew Trick1b60ad62011-04-12 20:14:07 +0000590 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000591 DEBUG(SU->dump(this));
592
Evan Chengbdd062d2010-05-20 06:13:19 +0000593#ifndef NDEBUG
594 if (CurCycle < SU->getHeight())
Andrew Trickb53a00d2011-04-13 00:38:32 +0000595 DEBUG(dbgs() << " Height [" << SU->getHeight()
596 << "] pipeline stall!\n");
Evan Chengbdd062d2010-05-20 06:13:19 +0000597#endif
598
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000599 // FIXME: Do not modify node height. It may interfere with
600 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
Eric Christopher1b4b1e52011-03-21 18:06:21 +0000601 // node its ready cycle can aid heuristics, and after scheduling it can
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000602 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000603 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000604
605 // Reserve resources for the scheduled intruction.
606 EmitNode(SU);
607
Dan Gohmanb9543432009-02-10 23:27:53 +0000608 Sequence.push_back(SU);
609
Evan Cheng28590382010-07-21 23:53:58 +0000610 AvailableQueue->ScheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000611
Andrew Trick641e2d42011-03-05 08:00:22 +0000612 // If HazardRec is disabled, and each inst counts as one cycle, then
Andrew Trickb53a00d2011-04-13 00:38:32 +0000613 // advance CurCycle before ReleasePredecessors to avoid useless pushes to
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000614 // PendingQueue for schedulers that implement HasReadyFilter.
Andrew Trick641e2d42011-03-05 08:00:22 +0000615 if (!HazardRec->isEnabled() && AvgIPC < 2)
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000616 AdvanceToCycle(CurCycle + 1);
617
Andrew Trick033efdf2010-12-23 03:15:51 +0000618 // Update liveness of predecessors before successors to avoid treating a
619 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000620 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000621
622 // Release all the implicit physical register defs that are live.
623 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
624 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000625 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
626 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
627 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
628 --NumLiveRegs;
629 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000630 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000631 }
632 }
633
Andrew Trickb53a00d2011-04-13 00:38:32 +0000634 resetVRegCycle(SU);
635
Evan Chengd38c22b2006-05-11 23:55:42 +0000636 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000637
638 // Conditions under which the scheduler should eagerly advance the cycle:
639 // (1) No available instructions
640 // (2) All pipelines full, so available instructions must have hazards.
641 //
Andrew Trickb53a00d2011-04-13 00:38:32 +0000642 // If HazardRec is disabled, the cycle was pre-advanced before calling
643 // ReleasePredecessors. In that case, IssueCount should remain 0.
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000644 //
645 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
Andrew Trickb53a00d2011-04-13 00:38:32 +0000646 if (HazardRec->isEnabled() || AvgIPC > 1) {
647 if (SU->getNode() && SU->getNode()->isMachineOpcode())
648 ++IssueCount;
649 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
650 || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
651 AdvanceToCycle(CurCycle + 1);
652 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000653}
654
Evan Cheng5924bf72007-09-25 01:54:36 +0000655/// CapturePred - This does the opposite of ReleasePred. Since SU is being
656/// unscheduled, incrcease the succ left count of its predecessors. Remove
657/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000658void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000659 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000660 if (PredSU->isAvailable) {
661 PredSU->isAvailable = false;
662 if (!PredSU->isPending)
663 AvailableQueue->remove(PredSU);
664 }
665
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000666 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000667 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000668}
669
670/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
671/// its predecessor states to reflect the change.
672void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000673 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000674 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000675
Evan Cheng5924bf72007-09-25 01:54:36 +0000676 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
677 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000678 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000679 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000680 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000681 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000682 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000683 --NumLiveRegs;
Dan Gohman2d170892008-12-09 22:54:47 +0000684 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000685 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000686 }
687 }
688
689 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
690 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000691 if (I->isAssignedRegDep()) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000692 // This becomes the nearest def. Note that an earlier def may still be
693 // pending if this is a two-address node.
694 LiveRegDefs[I->getReg()] = SU;
Dan Gohman2d170892008-12-09 22:54:47 +0000695 if (!LiveRegDefs[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000696 ++NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000697 }
Andrew Tricka52f3252010-12-23 04:16:14 +0000698 if (LiveRegGens[I->getReg()] == NULL ||
699 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
700 LiveRegGens[I->getReg()] = I->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000701 }
702 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000703 if (SU->getHeight() < MinAvailableCycle)
704 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000705
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000706 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000707 SU->isScheduled = false;
708 SU->isAvailable = true;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000709 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000710 // Don't make available until backtracking is complete.
711 SU->isPending = true;
712 PendingQueue.push_back(SU);
713 }
714 else {
715 AvailableQueue->push(SU);
716 }
Evan Cheng28590382010-07-21 23:53:58 +0000717 AvailableQueue->UnscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000718}
719
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000720/// After backtracking, the hazard checker needs to be restored to a state
721/// corresponding the the current cycle.
722void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
723 HazardRec->Reset();
724
725 unsigned LookAhead = std::min((unsigned)Sequence.size(),
726 HazardRec->getMaxLookAhead());
727 if (LookAhead == 0)
728 return;
729
730 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
731 unsigned HazardCycle = (*I)->getHeight();
732 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
733 SUnit *SU = *I;
734 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
735 HazardRec->RecedeCycle();
736 }
737 EmitNode(SU);
738 }
739}
740
Evan Cheng8e136a92007-09-26 21:36:17 +0000741/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000742/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000743void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
744 SUnit *OldSU = Sequence.back();
745 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000746 Sequence.pop_back();
747 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000748 // Don't try to remove SU from AvailableQueue.
749 SU->isAvailable = false;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000750 // FIXME: use ready cycle instead of height
751 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000752 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000753 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000754 if (OldSU == BtSU)
755 break;
756 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000757 }
758
Dan Gohman60d68442009-01-29 19:49:27 +0000759 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000760
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000761 RestoreHazardCheckerBottomUp();
762
Andrew Trick5ce945c2010-12-24 07:10:19 +0000763 ReleasePending();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000764
Evan Cheng1ec79b42007-09-27 07:09:03 +0000765 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000766}
767
Evan Cheng3b245872010-02-05 01:27:11 +0000768static bool isOperandOf(const SUnit *SU, SDNode *N) {
769 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000770 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000771 if (SUNode->isOperandOf(N))
772 return true;
773 }
774 return false;
775}
776
Evan Cheng5924bf72007-09-25 01:54:36 +0000777/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
778/// successors to the newly created node.
779SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000780 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000781 if (!N)
782 return NULL;
783
Andrew Trickc9405662010-12-24 06:46:50 +0000784 if (SU->getNode()->getGluedNode())
785 return NULL;
786
Evan Cheng79e97132007-10-05 01:39:18 +0000787 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000788 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000789 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000790 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000791 if (VT == MVT::Glue)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000792 return NULL;
Owen Anderson9f944592009-08-11 20:47:22 +0000793 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000794 TryUnfold = true;
795 }
Evan Cheng79e97132007-10-05 01:39:18 +0000796 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000797 const SDValue &Op = N->getOperand(i);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000798 EVT VT = Op.getNode()->getValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000799 if (VT == MVT::Glue)
Evan Cheng79e97132007-10-05 01:39:18 +0000800 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000801 }
802
803 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000804 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000805 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000806 return NULL;
807
Evan Chengbdd062d2010-05-20 06:13:19 +0000808 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000809 assert(NewNodes.size() == 2 && "Expected a load folding node!");
810
811 N = NewNodes[1];
812 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000813 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000814 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000815 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000816 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
817 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000818 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000819
Dan Gohmane52e0892008-11-11 21:34:44 +0000820 // LoadNode may already exist. This can happen when there is another
821 // load from the same location and producing the same type of value
822 // but it has different alignment or volatileness.
823 bool isNewLoad = true;
824 SUnit *LoadSU;
825 if (LoadNode->getNodeId() != -1) {
826 LoadSU = &SUnits[LoadNode->getNodeId()];
827 isNewLoad = false;
828 } else {
829 LoadSU = CreateNewSUnit(LoadNode);
830 LoadNode->setNodeId(LoadSU->NodeNum);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000831
832 InitNumRegDefsLeft(LoadSU);
Dan Gohmane52e0892008-11-11 21:34:44 +0000833 ComputeLatency(LoadSU);
834 }
835
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000836 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000837 assert(N->getNodeId() == -1 && "Node already inserted!");
838 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +0000839
Dan Gohman17059682008-07-17 19:10:17 +0000840 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Dan Gohman856c0122008-02-16 00:25:40 +0000841 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000842 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000843 NewSU->isTwoAddress = true;
844 break;
845 }
846 }
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000847 if (TID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000848 NewSU->isCommutable = true;
Andrew Trickd0548ae2011-02-04 03:18:17 +0000849
850 InitNumRegDefsLeft(NewSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000851 ComputeLatency(NewSU);
852
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000853 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +0000854 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +0000855 SmallVector<SDep, 4> ChainSuccs;
856 SmallVector<SDep, 4> LoadPreds;
857 SmallVector<SDep, 4> NodePreds;
858 SmallVector<SDep, 4> NodeSuccs;
859 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
860 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000861 if (I->isCtrl())
Dan Gohman15af5522009-03-06 02:23:01 +0000862 ChainPreds.push_back(*I);
Evan Cheng3b245872010-02-05 01:27:11 +0000863 else if (isOperandOf(I->getSUnit(), LoadNode))
Dan Gohman2d170892008-12-09 22:54:47 +0000864 LoadPreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000865 else
Dan Gohman2d170892008-12-09 22:54:47 +0000866 NodePreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000867 }
868 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
869 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000870 if (I->isCtrl())
871 ChainSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000872 else
Dan Gohman2d170892008-12-09 22:54:47 +0000873 NodeSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000874 }
875
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000876 // Now assign edges to the newly-created nodes.
Dan Gohman15af5522009-03-06 02:23:01 +0000877 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
878 const SDep &Pred = ChainPreds[i];
879 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +0000880 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +0000881 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000882 }
Evan Cheng79e97132007-10-05 01:39:18 +0000883 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000884 const SDep &Pred = LoadPreds[i];
885 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +0000886 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +0000887 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000888 }
889 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000890 const SDep &Pred = NodePreds[i];
891 RemovePred(SU, Pred);
892 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000893 }
894 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000895 SDep D = NodeSuccs[i];
896 SUnit *SuccDep = D.getSUnit();
897 D.setSUnit(SU);
898 RemovePred(SuccDep, D);
899 D.setSUnit(NewSU);
900 AddPred(SuccDep, D);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000901 // Balance register pressure.
902 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
903 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
904 --NewSU->NumRegDefsLeft;
Evan Cheng79e97132007-10-05 01:39:18 +0000905 }
906 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000907 SDep D = ChainSuccs[i];
908 SUnit *SuccDep = D.getSUnit();
909 D.setSUnit(SU);
910 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000911 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +0000912 D.setSUnit(LoadSU);
913 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000914 }
Andrew Trick2085a962010-12-21 22:25:04 +0000915 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000916
917 // Add a data dependency to reflect that NewSU reads the value defined
918 // by LoadSU.
919 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
Evan Cheng79e97132007-10-05 01:39:18 +0000920
Evan Cheng91e0fc92007-12-18 08:42:10 +0000921 if (isNewLoad)
922 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000923 AvailableQueue->addNode(NewSU);
924
925 ++NumUnfolds;
926
927 if (NewSU->NumSuccsLeft == 0) {
928 NewSU->isAvailable = true;
929 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +0000930 }
931 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000932 }
933
Evan Chengbdd062d2010-05-20 06:13:19 +0000934 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000935 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000936
937 // New SUnit has the exact same predecessors.
938 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
939 I != E; ++I)
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000940 if (!I->isArtificial())
Dan Gohman2d170892008-12-09 22:54:47 +0000941 AddPred(NewSU, *I);
Evan Cheng5924bf72007-09-25 01:54:36 +0000942
943 // Only copy scheduled successors. Cut them from old node's successor
944 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000945 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +0000946 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
947 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000948 if (I->isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +0000949 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000950 SUnit *SuccSU = I->getSUnit();
951 if (SuccSU->isScheduled) {
Dan Gohman2d170892008-12-09 22:54:47 +0000952 SDep D = *I;
953 D.setSUnit(NewSU);
954 AddPred(SuccSU, D);
955 D.setSUnit(SU);
956 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +0000957 }
958 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000959 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000960 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng5924bf72007-09-25 01:54:36 +0000961
962 AvailableQueue->updateNode(SU);
963 AvailableQueue->addNode(NewSU);
964
Evan Cheng1ec79b42007-09-27 07:09:03 +0000965 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000966 return NewSU;
967}
968
Evan Chengb2c42c62009-01-12 03:19:55 +0000969/// InsertCopiesAndMoveSuccs - Insert register copies and move all
970/// scheduled successors of the given SUnit to the last copy.
971void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
972 const TargetRegisterClass *DestRC,
973 const TargetRegisterClass *SrcRC,
Evan Cheng1ec79b42007-09-27 07:09:03 +0000974 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000975 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000976 CopyFromSU->CopySrcRC = SrcRC;
977 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +0000978
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000979 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000980 CopyToSU->CopySrcRC = DestRC;
981 CopyToSU->CopyDstRC = SrcRC;
982
983 // Only copy scheduled successors. Cut them from old node's successor
984 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000985 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +0000986 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
987 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000988 if (I->isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +0000989 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000990 SUnit *SuccSU = I->getSUnit();
991 if (SuccSU->isScheduled) {
992 SDep D = *I;
993 D.setSUnit(CopyToSU);
994 AddPred(SuccSU, D);
995 DelDeps.push_back(std::make_pair(SuccSU, *I));
Evan Cheng8e136a92007-09-26 21:36:17 +0000996 }
Andrew Trick13acae02011-03-23 20:42:39 +0000997 else {
998 // Avoid scheduling the def-side copy before other successors. Otherwise
999 // we could introduce another physreg interference on the copy and
1000 // continue inserting copies indefinitely.
1001 SDep D(CopyFromSU, SDep::Order, /*Latency=*/0,
1002 /*Reg=*/0, /*isNormalMemory=*/false,
1003 /*isMustAlias=*/false, /*isArtificial=*/true);
1004 AddPred(SuccSU, D);
1005 }
Evan Cheng8e136a92007-09-26 21:36:17 +00001006 }
Evan Chengb2c42c62009-01-12 03:19:55 +00001007 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +00001008 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng8e136a92007-09-26 21:36:17 +00001009
Dan Gohman2d170892008-12-09 22:54:47 +00001010 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
1011 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
Evan Cheng8e136a92007-09-26 21:36:17 +00001012
1013 AvailableQueue->updateNode(SU);
1014 AvailableQueue->addNode(CopyFromSU);
1015 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001016 Copies.push_back(CopyFromSU);
1017 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +00001018
Evan Chengb2c42c62009-01-12 03:19:55 +00001019 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +00001020}
1021
1022/// getPhysicalRegisterVT - Returns the ValueType of the physical register
1023/// definition of the specified node.
1024/// FIXME: Move to SelectionDAG?
Owen Anderson53aa7a92009-08-10 22:56:29 +00001025static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +00001026 const TargetInstrInfo *TII) {
Dan Gohman17059682008-07-17 19:10:17 +00001027 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Evan Cheng8e136a92007-09-26 21:36:17 +00001028 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
Chris Lattnerb0d06b42008-01-07 03:13:06 +00001029 unsigned NumRes = TID.getNumDefs();
1030 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +00001031 if (Reg == *ImpDef)
1032 break;
1033 ++NumRes;
1034 }
1035 return N->getValueType(NumRes);
1036}
1037
Evan Chengb8905c42009-03-04 01:41:49 +00001038/// CheckForLiveRegDef - Return true and update live register vector if the
1039/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001040static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Evan Chengb8905c42009-03-04 01:41:49 +00001041 std::vector<SUnit*> &LiveRegDefs,
1042 SmallSet<unsigned, 4> &RegAdded,
1043 SmallVector<unsigned, 4> &LRegs,
1044 const TargetRegisterInfo *TRI) {
Andrew Trick12acde112010-12-23 03:43:21 +00001045 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
1046
1047 // Check if Ref is live.
Andrew Trick0af2e472011-06-07 00:38:12 +00001048 if (!LiveRegDefs[*AliasI]) continue;
Andrew Trick12acde112010-12-23 03:43:21 +00001049
1050 // Allow multiple uses of the same def.
Andrew Trick0af2e472011-06-07 00:38:12 +00001051 if (LiveRegDefs[*AliasI] == SU) continue;
Andrew Trick12acde112010-12-23 03:43:21 +00001052
1053 // Add Reg to the set of interfering live regs.
Andrew Trick0af2e472011-06-07 00:38:12 +00001054 if (RegAdded.insert(*AliasI)) {
Andrew Trick0af2e472011-06-07 00:38:12 +00001055 LRegs.push_back(*AliasI);
1056 }
Evan Chengb8905c42009-03-04 01:41:49 +00001057 }
Evan Chengb8905c42009-03-04 01:41:49 +00001058}
1059
Evan Cheng5924bf72007-09-25 01:54:36 +00001060/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1061/// scheduling of the given node to satisfy live physical register dependencies.
1062/// If the specific node is the last one that's available to schedule, do
1063/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001064bool ScheduleDAGRRList::
1065DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +00001066 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +00001067 return false;
1068
Evan Chenge6f92252007-09-27 18:46:06 +00001069 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +00001070 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001071 //
1072 // If SU is the currently live definition of the same register that it uses,
1073 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +00001074 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1075 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001076 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Evan Chengb8905c42009-03-04 01:41:49 +00001077 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
1078 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001079 }
1080
Chris Lattner11a33812010-12-23 17:24:32 +00001081 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +00001082 if (Node->getOpcode() == ISD::INLINEASM) {
1083 // Inline asm can clobber physical defs.
1084 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +00001085 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +00001086 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +00001087
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001088 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +00001089 unsigned Flags =
1090 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001091 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +00001092
1093 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001094 if (InlineAsm::isRegDefKind(Flags) ||
Jakob Stoklund Olesen537a3022011-06-27 04:08:33 +00001095 InlineAsm::isRegDefEarlyClobberKind(Flags) ||
1096 InlineAsm::isClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +00001097 // Check for def of register or earlyclobber register.
1098 for (; NumVals; --NumVals, ++i) {
1099 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1100 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1101 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1102 }
1103 } else
1104 i += NumVals;
1105 }
1106 continue;
1107 }
1108
Dan Gohman072734e2008-11-13 23:24:17 +00001109 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +00001110 continue;
Dan Gohman17059682008-07-17 19:10:17 +00001111 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
Evan Cheng5924bf72007-09-25 01:54:36 +00001112 if (!TID.ImplicitDefs)
1113 continue;
Evan Chengb8905c42009-03-04 01:41:49 +00001114 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
1115 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001116 }
Andrew Trick2085a962010-12-21 22:25:04 +00001117
Evan Cheng5924bf72007-09-25 01:54:36 +00001118 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +00001119}
1120
Andrew Trick528fad92010-12-23 05:42:20 +00001121/// Return a node that can be scheduled in this cycle. Requirements:
1122/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001123/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +00001124/// (3) No Interferences: may unschedule to break register interferences.
1125SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1126 SmallVector<SUnit*, 4> Interferences;
1127 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1128
1129 SUnit *CurSU = AvailableQueue->pop();
1130 while (CurSU) {
1131 SmallVector<unsigned, 4> LRegs;
1132 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1133 break;
1134 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1135
1136 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1137 Interferences.push_back(CurSU);
1138 CurSU = AvailableQueue->pop();
1139 }
1140 if (CurSU) {
1141 // Add the nodes that aren't ready back onto the available list.
1142 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1143 Interferences[i]->isPending = false;
1144 assert(Interferences[i]->isAvailable && "must still be available");
1145 AvailableQueue->push(Interferences[i]);
1146 }
1147 return CurSU;
1148 }
1149
1150 // All candidates are delayed due to live physical reg dependencies.
1151 // Try backtracking, code duplication, or inserting cross class copies
1152 // to resolve it.
1153 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1154 SUnit *TrySU = Interferences[i];
1155 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1156
1157 // Try unscheduling up to the point where it's safe to schedule
1158 // this node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001159 SUnit *BtSU = NULL;
1160 unsigned LiveCycle = UINT_MAX;
Andrew Trick528fad92010-12-23 05:42:20 +00001161 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1162 unsigned Reg = LRegs[j];
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001163 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1164 BtSU = LiveRegGens[Reg];
1165 LiveCycle = BtSU->getHeight();
1166 }
Andrew Trick528fad92010-12-23 05:42:20 +00001167 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001168 if (!WillCreateCycle(TrySU, BtSU)) {
1169 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001170
1171 // Force the current node to be scheduled before the node that
1172 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001173 if (BtSU->isAvailable) {
1174 BtSU->isAvailable = false;
1175 if (!BtSU->isPending)
1176 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001177 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001178 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
Andrew Trick528fad92010-12-23 05:42:20 +00001179 /*Reg=*/0, /*isNormalMemory=*/false,
1180 /*isMustAlias=*/false, /*isArtificial=*/true));
1181
1182 // If one or more successors has been unscheduled, then the current
1183 // node is no longer avaialable. Schedule a successor that's now
1184 // available instead.
1185 if (!TrySU->isAvailable) {
1186 CurSU = AvailableQueue->pop();
1187 }
1188 else {
1189 CurSU = TrySU;
1190 TrySU->isPending = false;
1191 Interferences.erase(Interferences.begin()+i);
1192 }
1193 break;
1194 }
1195 }
1196
1197 if (!CurSU) {
1198 // Can't backtrack. If it's too expensive to copy the value, then try
1199 // duplicate the nodes that produces these "too expensive to copy"
1200 // values to break the dependency. In case even that doesn't work,
1201 // insert cross class copies.
1202 // If it's not too expensive, i.e. cost != -1, issue copies.
1203 SUnit *TrySU = Interferences[0];
1204 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1205 assert(LRegs.size() == 1 && "Can't handle this yet!");
1206 unsigned Reg = LRegs[0];
1207 SUnit *LRDef = LiveRegDefs[Reg];
1208 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1209 const TargetRegisterClass *RC =
1210 TRI->getMinimalPhysRegClass(Reg, VT);
1211 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1212
Evan Chengb4c6a342011-03-10 00:16:32 +00001213 // If cross copy register class is the same as RC, then it must be possible
1214 // copy the value directly. Do not try duplicate the def.
1215 // If cross copy register class is not the same as RC, then it's possible to
1216 // copy the value but it require cross register class copies and it is
1217 // expensive.
1218 // If cross copy register class is null, then it's not possible to copy
1219 // the value at all.
Andrew Trick528fad92010-12-23 05:42:20 +00001220 SUnit *NewDef = 0;
Evan Chengb4c6a342011-03-10 00:16:32 +00001221 if (DestRC != RC) {
Andrew Trick528fad92010-12-23 05:42:20 +00001222 NewDef = CopyAndMoveSuccessors(LRDef);
Evan Chengb4c6a342011-03-10 00:16:32 +00001223 if (!DestRC && !NewDef)
1224 report_fatal_error("Can't handle live physical register dependency!");
1225 }
Andrew Trick528fad92010-12-23 05:42:20 +00001226 if (!NewDef) {
1227 // Issue copies, these can be expensive cross register class copies.
1228 SmallVector<SUnit*, 2> Copies;
1229 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1230 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1231 << " to SU #" << Copies.front()->NodeNum << "\n");
1232 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1233 /*Reg=*/0, /*isNormalMemory=*/false,
1234 /*isMustAlias=*/false,
1235 /*isArtificial=*/true));
1236 NewDef = Copies.back();
1237 }
1238
1239 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1240 << " to SU #" << TrySU->NodeNum << "\n");
1241 LiveRegDefs[Reg] = NewDef;
1242 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1243 /*Reg=*/0, /*isNormalMemory=*/false,
1244 /*isMustAlias=*/false,
1245 /*isArtificial=*/true));
1246 TrySU->isAvailable = false;
1247 CurSU = NewDef;
1248 }
1249
1250 assert(CurSU && "Unable to resolve live physical register dependencies!");
1251
1252 // Add the nodes that aren't ready back onto the available list.
1253 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1254 Interferences[i]->isPending = false;
1255 // May no longer be available due to backtracking.
1256 if (Interferences[i]->isAvailable) {
1257 AvailableQueue->push(Interferences[i]);
1258 }
1259 }
1260 return CurSU;
1261}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001262
Evan Chengd38c22b2006-05-11 23:55:42 +00001263/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1264/// schedulers.
1265void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001266 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001267 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001268
Evan Chengd38c22b2006-05-11 23:55:42 +00001269 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001270 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001271 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001272 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1273 RootSU->isAvailable = true;
1274 AvailableQueue->push(RootSU);
1275 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001276
1277 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001278 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001279 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001280 while (!AvailableQueue->empty()) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00001281 DEBUG(dbgs() << "\nExamining Available:\n";
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001282 AvailableQueue->dump(this));
1283
Andrew Trick528fad92010-12-23 05:42:20 +00001284 // Pick the best node to schedule taking all constraints into
1285 // consideration.
1286 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001287
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001288 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001289
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001290 ScheduleNodeBottomUp(SU);
1291
1292 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1293 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1294 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1295 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1296 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001297 }
1298
Evan Chengd38c22b2006-05-11 23:55:42 +00001299 // Reverse the order if it is bottom up.
1300 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001301
Evan Chengd38c22b2006-05-11 23:55:42 +00001302#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001303 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001304#endif
1305}
1306
1307//===----------------------------------------------------------------------===//
1308// Top-Down Scheduling
1309//===----------------------------------------------------------------------===//
1310
1311/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +00001312/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +00001313void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +00001314 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001315
Evan Chengd38c22b2006-05-11 23:55:42 +00001316#ifndef NDEBUG
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001317 if (SuccSU->NumPredsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +00001318 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +00001319 SuccSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +00001320 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +00001321 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +00001322 }
1323#endif
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001324 --SuccSU->NumPredsLeft;
1325
Dan Gohmanb9543432009-02-10 23:27:53 +00001326 // If all the node's predecessors are scheduled, this node is ready
1327 // to be scheduled. Ignore the special ExitSU node.
1328 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001329 SuccSU->isAvailable = true;
1330 AvailableQueue->push(SuccSU);
1331 }
1332}
1333
Dan Gohmanb9543432009-02-10 23:27:53 +00001334void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1335 // Top down: release successors
1336 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1337 I != E; ++I) {
1338 assert(!I->isAssignedRegDep() &&
1339 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1340
1341 ReleaseSucc(SU, &*I);
1342 }
1343}
1344
Evan Chengd38c22b2006-05-11 23:55:42 +00001345/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1346/// count of its successors. If a successor pending count is zero, add it to
1347/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +00001348void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +00001349 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +00001350 DEBUG(SU->dump(this));
Evan Chengd38c22b2006-05-11 23:55:42 +00001351
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001352 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1353 SU->setDepthToAtLeast(CurCycle);
Dan Gohman92a36d72008-11-17 21:31:02 +00001354 Sequence.push_back(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001355
Dan Gohmanb9543432009-02-10 23:27:53 +00001356 ReleaseSuccessors(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001357 SU->isScheduled = true;
Dan Gohman92a36d72008-11-17 21:31:02 +00001358 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001359}
1360
Dan Gohman54a187e2007-08-20 19:28:38 +00001361/// ListScheduleTopDown - The main loop of list scheduling for top-down
1362/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +00001363void ScheduleDAGRRList::ListScheduleTopDown() {
Evan Chengbdd062d2010-05-20 06:13:19 +00001364 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001365
Dan Gohmanb9543432009-02-10 23:27:53 +00001366 // Release any successors of the special Entry node.
1367 ReleaseSuccessors(&EntrySU);
1368
Evan Chengd38c22b2006-05-11 23:55:42 +00001369 // All leaves to Available queue.
1370 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1371 // It is available if it has no predecessors.
Dan Gohman4370f262008-04-15 01:22:18 +00001372 if (SUnits[i].Preds.empty()) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001373 AvailableQueue->push(&SUnits[i]);
1374 SUnits[i].isAvailable = true;
1375 }
1376 }
Andrew Trick2085a962010-12-21 22:25:04 +00001377
Evan Chengd38c22b2006-05-11 23:55:42 +00001378 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001379 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001380 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001381 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +00001382 SUnit *CurSU = AvailableQueue->pop();
Andrew Trick2085a962010-12-21 22:25:04 +00001383
Dan Gohmanc602dd42008-11-21 00:10:42 +00001384 if (CurSU)
Andrew Trick528fad92010-12-23 05:42:20 +00001385 ScheduleNodeTopDown(CurSU);
Dan Gohman4370f262008-04-15 01:22:18 +00001386 ++CurCycle;
Evan Chengbdd062d2010-05-20 06:13:19 +00001387 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001388 }
Andrew Trick2085a962010-12-21 22:25:04 +00001389
Evan Chengd38c22b2006-05-11 23:55:42 +00001390#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001391 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001392#endif
1393}
1394
1395
Evan Chengd38c22b2006-05-11 23:55:42 +00001396//===----------------------------------------------------------------------===//
Andrew Trick9ccce772011-01-14 21:11:41 +00001397// RegReductionPriorityQueue Definition
Evan Chengd38c22b2006-05-11 23:55:42 +00001398//===----------------------------------------------------------------------===//
1399//
1400// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1401// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001402//
Evan Chengd38c22b2006-05-11 23:55:42 +00001403namespace {
Andrew Trick9ccce772011-01-14 21:11:41 +00001404class RegReductionPQBase;
Andrew Trick2085a962010-12-21 22:25:04 +00001405
Andrew Trick9ccce772011-01-14 21:11:41 +00001406struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1407 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1408};
1409
Andrew Trick3013b6a2011-06-15 17:16:12 +00001410#ifndef NDEBUG
1411template<class SF>
1412struct reverse_sort : public queue_sort {
1413 SF &SortFunc;
1414 reverse_sort(SF &sf) : SortFunc(sf) {}
1415 reverse_sort(const reverse_sort &RHS) : SortFunc(RHS.SortFunc) {}
1416
1417 bool operator()(SUnit* left, SUnit* right) const {
1418 // reverse left/right rather than simply !SortFunc(left, right)
1419 // to expose different paths in the comparison logic.
1420 return SortFunc(right, left);
1421 }
1422};
1423#endif // NDEBUG
1424
Andrew Trick9ccce772011-01-14 21:11:41 +00001425/// bu_ls_rr_sort - Priority function for bottom up register pressure
1426// reduction scheduler.
1427struct bu_ls_rr_sort : public queue_sort {
1428 enum {
1429 IsBottomUp = true,
1430 HasReadyFilter = false
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001431 };
1432
Andrew Trick9ccce772011-01-14 21:11:41 +00001433 RegReductionPQBase *SPQ;
1434 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1435 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001436
Andrew Trick9ccce772011-01-14 21:11:41 +00001437 bool operator()(SUnit* left, SUnit* right) const;
1438};
Andrew Trick2085a962010-12-21 22:25:04 +00001439
Andrew Trick9ccce772011-01-14 21:11:41 +00001440// td_ls_rr_sort - Priority function for top down register pressure reduction
1441// scheduler.
1442struct td_ls_rr_sort : public queue_sort {
1443 enum {
1444 IsBottomUp = false,
1445 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001446 };
1447
Andrew Trick9ccce772011-01-14 21:11:41 +00001448 RegReductionPQBase *SPQ;
1449 td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1450 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001451
Andrew Trick9ccce772011-01-14 21:11:41 +00001452 bool operator()(const SUnit* left, const SUnit* right) const;
1453};
Andrew Trick2085a962010-12-21 22:25:04 +00001454
Andrew Trick9ccce772011-01-14 21:11:41 +00001455// src_ls_rr_sort - Priority function for source order scheduler.
1456struct src_ls_rr_sort : public queue_sort {
1457 enum {
1458 IsBottomUp = true,
1459 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001460 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001461
Andrew Trick9ccce772011-01-14 21:11:41 +00001462 RegReductionPQBase *SPQ;
1463 src_ls_rr_sort(RegReductionPQBase *spq)
1464 : SPQ(spq) {}
1465 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1466 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001467
Andrew Trick9ccce772011-01-14 21:11:41 +00001468 bool operator()(SUnit* left, SUnit* right) const;
1469};
Andrew Trick2085a962010-12-21 22:25:04 +00001470
Andrew Trick9ccce772011-01-14 21:11:41 +00001471// hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1472struct hybrid_ls_rr_sort : public queue_sort {
1473 enum {
1474 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001475 HasReadyFilter = false
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001476 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001477
Andrew Trick9ccce772011-01-14 21:11:41 +00001478 RegReductionPQBase *SPQ;
1479 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1480 : SPQ(spq) {}
1481 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1482 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001483
Andrew Trick9ccce772011-01-14 21:11:41 +00001484 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Chenga77f3d32010-07-21 06:09:07 +00001485
Andrew Trick9ccce772011-01-14 21:11:41 +00001486 bool operator()(SUnit* left, SUnit* right) const;
1487};
1488
1489// ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1490// scheduler.
1491struct ilp_ls_rr_sort : public queue_sort {
1492 enum {
1493 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001494 HasReadyFilter = false
Evan Chengbdd062d2010-05-20 06:13:19 +00001495 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001496
Andrew Trick9ccce772011-01-14 21:11:41 +00001497 RegReductionPQBase *SPQ;
1498 ilp_ls_rr_sort(RegReductionPQBase *spq)
1499 : SPQ(spq) {}
1500 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1501 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001502
Andrew Trick9ccce772011-01-14 21:11:41 +00001503 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Cheng37b740c2010-07-24 00:39:05 +00001504
Andrew Trick9ccce772011-01-14 21:11:41 +00001505 bool operator()(SUnit* left, SUnit* right) const;
1506};
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001507
Andrew Trick9ccce772011-01-14 21:11:41 +00001508class RegReductionPQBase : public SchedulingPriorityQueue {
1509protected:
1510 std::vector<SUnit*> Queue;
1511 unsigned CurQueueId;
1512 bool TracksRegPressure;
1513
1514 // SUnits - The SUnits for the current graph.
1515 std::vector<SUnit> *SUnits;
1516
1517 MachineFunction &MF;
1518 const TargetInstrInfo *TII;
1519 const TargetRegisterInfo *TRI;
1520 const TargetLowering *TLI;
1521 ScheduleDAGRRList *scheduleDAG;
1522
1523 // SethiUllmanNumbers - The SethiUllman number for each node.
1524 std::vector<unsigned> SethiUllmanNumbers;
1525
1526 /// RegPressure - Tracking current reg pressure per register class.
1527 ///
1528 std::vector<unsigned> RegPressure;
1529
1530 /// RegLimit - Tracking the number of allocatable registers per register
1531 /// class.
1532 std::vector<unsigned> RegLimit;
1533
1534public:
1535 RegReductionPQBase(MachineFunction &mf,
1536 bool hasReadyFilter,
1537 bool tracksrp,
1538 const TargetInstrInfo *tii,
1539 const TargetRegisterInfo *tri,
1540 const TargetLowering *tli)
1541 : SchedulingPriorityQueue(hasReadyFilter),
1542 CurQueueId(0), TracksRegPressure(tracksrp),
1543 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1544 if (TracksRegPressure) {
1545 unsigned NumRC = TRI->getNumRegClasses();
1546 RegLimit.resize(NumRC);
1547 RegPressure.resize(NumRC);
1548 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1549 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1550 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1551 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichdf616942011-03-07 21:56:36 +00001552 RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
Andrew Trick9ccce772011-01-14 21:11:41 +00001553 }
1554 }
1555
1556 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1557 scheduleDAG = scheduleDag;
1558 }
1559
1560 ScheduleHazardRecognizer* getHazardRec() {
1561 return scheduleDAG->getHazardRec();
1562 }
1563
1564 void initNodes(std::vector<SUnit> &sunits);
1565
1566 void addNode(const SUnit *SU);
1567
1568 void updateNode(const SUnit *SU);
1569
1570 void releaseState() {
1571 SUnits = 0;
1572 SethiUllmanNumbers.clear();
1573 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1574 }
1575
1576 unsigned getNodePriority(const SUnit *SU) const;
1577
1578 unsigned getNodeOrdering(const SUnit *SU) const {
Andrew Trick3bd8b7a2011-03-25 06:40:55 +00001579 if (!SU->getNode()) return 0;
1580
Andrew Trick9ccce772011-01-14 21:11:41 +00001581 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1582 }
1583
1584 bool empty() const { return Queue.empty(); }
1585
1586 void push(SUnit *U) {
1587 assert(!U->NodeQueueId && "Node in the queue already");
1588 U->NodeQueueId = ++CurQueueId;
1589 Queue.push_back(U);
1590 }
1591
1592 void remove(SUnit *SU) {
1593 assert(!Queue.empty() && "Queue is empty!");
1594 assert(SU->NodeQueueId != 0 && "Not in queue!");
1595 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1596 SU);
1597 if (I != prior(Queue.end()))
1598 std::swap(*I, Queue.back());
1599 Queue.pop_back();
1600 SU->NodeQueueId = 0;
1601 }
1602
Andrew Trickd0548ae2011-02-04 03:18:17 +00001603 bool tracksRegPressure() const { return TracksRegPressure; }
1604
Andrew Trick9ccce772011-01-14 21:11:41 +00001605 void dumpRegPressure() const;
1606
1607 bool HighRegPressure(const SUnit *SU) const;
1608
Andrew Trick641e2d42011-03-05 08:00:22 +00001609 bool MayReduceRegPressure(SUnit *SU) const;
1610
1611 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
Andrew Trick9ccce772011-01-14 21:11:41 +00001612
1613 void ScheduledNode(SUnit *SU);
1614
1615 void UnscheduledNode(SUnit *SU);
1616
1617protected:
1618 bool canClobber(const SUnit *SU, const SUnit *Op);
1619 void AddPseudoTwoAddrDeps();
1620 void PrescheduleNodesWithMultipleUses();
1621 void CalculateSethiUllmanNumbers();
1622};
1623
1624template<class SF>
Andrew Trick3013b6a2011-06-15 17:16:12 +00001625static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
1626 std::vector<SUnit *>::iterator Best = Q.begin();
1627 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1628 E = Q.end(); I != E; ++I)
1629 if (Picker(*Best, *I))
1630 Best = I;
1631 SUnit *V = *Best;
1632 if (Best != prior(Q.end()))
1633 std::swap(*Best, Q.back());
1634 Q.pop_back();
1635 return V;
1636}
Andrew Trick9ccce772011-01-14 21:11:41 +00001637
Andrew Trick3013b6a2011-06-15 17:16:12 +00001638template<class SF>
1639SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
1640#ifndef NDEBUG
1641 if (DAG->StressSched) {
1642 reverse_sort<SF> RPicker(Picker);
1643 return popFromQueueImpl(Q, RPicker);
1644 }
1645#endif
1646 (void)DAG;
1647 return popFromQueueImpl(Q, Picker);
1648}
1649
1650template<class SF>
1651class RegReductionPriorityQueue : public RegReductionPQBase {
Andrew Trick9ccce772011-01-14 21:11:41 +00001652 SF Picker;
1653
1654public:
1655 RegReductionPriorityQueue(MachineFunction &mf,
1656 bool tracksrp,
1657 const TargetInstrInfo *tii,
1658 const TargetRegisterInfo *tri,
1659 const TargetLowering *tli)
1660 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1661 Picker(this) {}
1662
1663 bool isBottomUp() const { return SF::IsBottomUp; }
1664
1665 bool isReady(SUnit *U) const {
1666 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1667 }
1668
1669 SUnit *pop() {
1670 if (Queue.empty()) return NULL;
1671
Andrew Trick3013b6a2011-06-15 17:16:12 +00001672 SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
Andrew Trick9ccce772011-01-14 21:11:41 +00001673 V->NodeQueueId = 0;
1674 return V;
1675 }
1676
1677 void dump(ScheduleDAG *DAG) const {
1678 // Emulate pop() without clobbering NodeQueueIds.
1679 std::vector<SUnit*> DumpQueue = Queue;
1680 SF DumpPicker = Picker;
1681 while (!DumpQueue.empty()) {
Andrew Trick3013b6a2011-06-15 17:16:12 +00001682 SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
Andrew Trick9ccce772011-01-14 21:11:41 +00001683 if (isBottomUp())
1684 dbgs() << "Height " << SU->getHeight() << ": ";
1685 else
1686 dbgs() << "Depth " << SU->getDepth() << ": ";
1687 SU->dump(DAG);
1688 }
1689 }
1690};
1691
1692typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1693BURegReductionPriorityQueue;
1694
1695typedef RegReductionPriorityQueue<td_ls_rr_sort>
1696TDRegReductionPriorityQueue;
1697
1698typedef RegReductionPriorityQueue<src_ls_rr_sort>
1699SrcRegReductionPriorityQueue;
1700
1701typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1702HybridBURRPriorityQueue;
1703
1704typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1705ILPBURRPriorityQueue;
1706} // end anonymous namespace
1707
1708//===----------------------------------------------------------------------===//
1709// Static Node Priority for Register Pressure Reduction
1710//===----------------------------------------------------------------------===//
Evan Chengd38c22b2006-05-11 23:55:42 +00001711
Andrew Trickbfbd9722011-04-14 05:15:06 +00001712// Check for special nodes that bypass scheduling heuristics.
1713// Currently this pushes TokenFactor nodes down, but may be used for other
1714// pseudo-ops as well.
1715//
1716// Return -1 to schedule right above left, 1 for left above right.
1717// Return 0 if no bias exists.
1718static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
1719 bool LSchedLow = left->isScheduleLow;
1720 bool RSchedLow = right->isScheduleLow;
1721 if (LSchedLow != RSchedLow)
1722 return LSchedLow < RSchedLow ? 1 : -1;
1723 return 0;
1724}
1725
Dan Gohman186f65d2008-11-20 03:30:37 +00001726/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1727/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001728static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001729CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001730 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1731 if (SethiUllmanNumber != 0)
1732 return SethiUllmanNumber;
1733
1734 unsigned Extra = 0;
1735 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1736 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001737 if (I->isCtrl()) continue; // ignore chain preds
1738 SUnit *PredSU = I->getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001739 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001740 if (PredSethiUllman > SethiUllmanNumber) {
1741 SethiUllmanNumber = PredSethiUllman;
1742 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001743 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001744 ++Extra;
1745 }
1746
1747 SethiUllmanNumber += Extra;
1748
1749 if (SethiUllmanNumber == 0)
1750 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001751
Evan Cheng7e4abde2008-07-02 09:23:51 +00001752 return SethiUllmanNumber;
1753}
1754
Andrew Trick9ccce772011-01-14 21:11:41 +00001755/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1756/// scheduling units.
1757void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1758 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001759
Andrew Trick9ccce772011-01-14 21:11:41 +00001760 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1761 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
Evan Chengd38c22b2006-05-11 23:55:42 +00001762}
1763
Andrew Trick9ccce772011-01-14 21:11:41 +00001764void RegReductionPQBase::addNode(const SUnit *SU) {
1765 unsigned SUSize = SethiUllmanNumbers.size();
1766 if (SUnits->size() > SUSize)
1767 SethiUllmanNumbers.resize(SUSize*2, 0);
1768 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1769}
1770
1771void RegReductionPQBase::updateNode(const SUnit *SU) {
1772 SethiUllmanNumbers[SU->NodeNum] = 0;
1773 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1774}
1775
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001776// Lower priority means schedule further down. For bottom-up scheduling, lower
1777// priority SUs are scheduled before higher priority SUs.
Andrew Trick9ccce772011-01-14 21:11:41 +00001778unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1779 assert(SU->NodeNum < SethiUllmanNumbers.size());
1780 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1781 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1782 // CopyToReg should be close to its uses to facilitate coalescing and
1783 // avoid spilling.
1784 return 0;
1785 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1786 Opc == TargetOpcode::SUBREG_TO_REG ||
1787 Opc == TargetOpcode::INSERT_SUBREG)
1788 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1789 // close to their uses to facilitate coalescing.
1790 return 0;
1791 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1792 // If SU does not have a register use, i.e. it doesn't produce a value
1793 // that would be consumed (e.g. store), then it terminates a chain of
1794 // computation. Give it a large SethiUllman number so it will be
1795 // scheduled right before its predecessors that it doesn't lengthen
1796 // their live ranges.
1797 return 0xffff;
1798 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1799 // If SU does not have a register def, schedule it close to its uses
1800 // because it does not lengthen any live ranges.
1801 return 0;
Evan Cheng1355bbd2011-04-26 21:31:35 +00001802#if 1
Andrew Trick9ccce772011-01-14 21:11:41 +00001803 return SethiUllmanNumbers[SU->NodeNum];
Evan Cheng1355bbd2011-04-26 21:31:35 +00001804#else
1805 unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
1806 if (SU->isCallOp) {
1807 // FIXME: This assumes all of the defs are used as call operands.
1808 int NP = (int)Priority - SU->getNode()->getNumValues();
1809 return (NP > 0) ? NP : 0;
1810 }
1811 return Priority;
1812#endif
Andrew Trick9ccce772011-01-14 21:11:41 +00001813}
1814
1815//===----------------------------------------------------------------------===//
1816// Register Pressure Tracking
1817//===----------------------------------------------------------------------===//
1818
1819void RegReductionPQBase::dumpRegPressure() const {
1820 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1821 E = TRI->regclass_end(); I != E; ++I) {
1822 const TargetRegisterClass *RC = *I;
1823 unsigned Id = RC->getID();
1824 unsigned RP = RegPressure[Id];
1825 if (!RP) continue;
1826 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1827 << '\n');
1828 }
1829}
1830
1831bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1832 if (!TLI)
1833 return false;
1834
1835 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1836 I != E; ++I) {
1837 if (I->isCtrl())
1838 continue;
1839 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001840 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1841 // to cover the number of registers defined (they are all live).
1842 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001843 continue;
1844 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001845 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1846 RegDefPos.IsValid(); RegDefPos.Advance()) {
Owen Anderson96adc4a2011-06-15 23:35:18 +00001847 unsigned RCId, Cost;
1848 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
1849
Andrew Trick9ccce772011-01-14 21:11:41 +00001850 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1851 return true;
1852 }
1853 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001854 return false;
1855}
1856
Andrew Trick641e2d42011-03-05 08:00:22 +00001857bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00001858 const SDNode *N = SU->getNode();
1859
1860 if (!N->isMachineOpcode() || !SU->NumSuccs)
1861 return false;
1862
1863 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1864 for (unsigned i = 0; i != NumDefs; ++i) {
1865 EVT VT = N->getValueType(i);
1866 if (!N->hasAnyUseOfValue(i))
1867 continue;
1868 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1869 if (RegPressure[RCId] >= RegLimit[RCId])
1870 return true;
1871 }
1872 return false;
1873}
1874
Andrew Trick641e2d42011-03-05 08:00:22 +00001875// Compute the register pressure contribution by this instruction by count up
1876// for uses that are not live and down for defs. Only count register classes
1877// that are already under high pressure. As a side effect, compute the number of
1878// uses of registers that are already live.
1879//
1880// FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1881// so could probably be factored.
1882int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1883 LiveUses = 0;
1884 int PDiff = 0;
1885 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1886 I != E; ++I) {
1887 if (I->isCtrl())
1888 continue;
1889 SUnit *PredSU = I->getSUnit();
1890 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1891 // to cover the number of registers defined (they are all live).
1892 if (PredSU->NumRegDefsLeft == 0) {
1893 if (PredSU->getNode()->isMachineOpcode())
1894 ++LiveUses;
1895 continue;
1896 }
1897 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1898 RegDefPos.IsValid(); RegDefPos.Advance()) {
1899 EVT VT = RegDefPos.GetValue();
1900 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1901 if (RegPressure[RCId] >= RegLimit[RCId])
1902 ++PDiff;
1903 }
1904 }
1905 const SDNode *N = SU->getNode();
1906
Eric Christopher7238cba2011-03-08 19:35:47 +00001907 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
Andrew Trick641e2d42011-03-05 08:00:22 +00001908 return PDiff;
1909
1910 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1911 for (unsigned i = 0; i != NumDefs; ++i) {
1912 EVT VT = N->getValueType(i);
1913 if (!N->hasAnyUseOfValue(i))
1914 continue;
1915 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1916 if (RegPressure[RCId] >= RegLimit[RCId])
1917 --PDiff;
1918 }
1919 return PDiff;
1920}
1921
Andrew Trick9ccce772011-01-14 21:11:41 +00001922void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1923 if (!TracksRegPressure)
1924 return;
1925
Eric Christopher7238cba2011-03-08 19:35:47 +00001926 if (!SU->getNode())
1927 return;
Andrew Tricka8846e02011-03-23 20:40:18 +00001928
Andrew Trick9ccce772011-01-14 21:11:41 +00001929 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1930 I != E; ++I) {
1931 if (I->isCtrl())
1932 continue;
1933 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001934 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1935 // to cover the number of registers defined (they are all live).
1936 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick9ccce772011-01-14 21:11:41 +00001937 continue;
1938 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001939 // FIXME: The ScheduleDAG currently loses information about which of a
1940 // node's values is consumed by each dependence. Consequently, if the node
1941 // defines multiple register classes, we don't know which to pressurize
1942 // here. Instead the following loop consumes the register defs in an
1943 // arbitrary order. At least it handles the common case of clustered loads
1944 // to the same class. For precise liveness, each SDep needs to indicate the
1945 // result number. But that tightly couples the ScheduleDAG with the
1946 // SelectionDAG making updates tricky. A simpler hack would be to attach a
1947 // value type or register class to SDep.
1948 //
1949 // The most important aspect of register tracking is balancing the increase
1950 // here with the reduction further below. Note that this SU may use multiple
1951 // defs in PredSU. The can't be determined here, but we've already
1952 // compensated by reducing NumRegDefsLeft in PredSU during
1953 // ScheduleDAGSDNodes::AddSchedEdges.
1954 --PredSU->NumRegDefsLeft;
1955 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
1956 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1957 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1958 if (SkipRegDefs)
Andrew Trick9ccce772011-01-14 21:11:41 +00001959 continue;
Owen Anderson96adc4a2011-06-15 23:35:18 +00001960
1961 unsigned RCId, Cost;
1962 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
1963 RegPressure[RCId] += Cost;
Andrew Trickd0548ae2011-02-04 03:18:17 +00001964 break;
Andrew Trick9ccce772011-01-14 21:11:41 +00001965 }
1966 }
1967
Andrew Trickd0548ae2011-02-04 03:18:17 +00001968 // We should have this assert, but there may be dead SDNodes that never
1969 // materialize as SUnits, so they don't appear to generate liveness.
1970 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
1971 int SkipRegDefs = (int)SU->NumRegDefsLeft;
1972 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
1973 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1974 if (SkipRegDefs > 0)
1975 continue;
Owen Anderson96adc4a2011-06-15 23:35:18 +00001976 unsigned RCId, Cost;
1977 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
1978 if (RegPressure[RCId] < Cost) {
Andrew Trickd0548ae2011-02-04 03:18:17 +00001979 // Register pressure tracking is imprecise. This can happen. But we try
1980 // hard not to let it happen because it likely results in poor scheduling.
1981 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
1982 RegPressure[RCId] = 0;
1983 }
1984 else {
Owen Anderson96adc4a2011-06-15 23:35:18 +00001985 RegPressure[RCId] -= Cost;
Andrew Trick9ccce772011-01-14 21:11:41 +00001986 }
1987 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001988 dumpRegPressure();
1989}
1990
1991void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
1992 if (!TracksRegPressure)
1993 return;
1994
1995 const SDNode *N = SU->getNode();
Eric Christopher7238cba2011-03-08 19:35:47 +00001996 if (!N) return;
Andrew Tricka8846e02011-03-23 20:40:18 +00001997
Andrew Trick9ccce772011-01-14 21:11:41 +00001998 if (!N->isMachineOpcode()) {
1999 if (N->getOpcode() != ISD::CopyToReg)
2000 return;
2001 } else {
2002 unsigned Opc = N->getMachineOpcode();
2003 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2004 Opc == TargetOpcode::INSERT_SUBREG ||
2005 Opc == TargetOpcode::SUBREG_TO_REG ||
2006 Opc == TargetOpcode::REG_SEQUENCE ||
2007 Opc == TargetOpcode::IMPLICIT_DEF)
2008 return;
2009 }
2010
2011 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2012 I != E; ++I) {
2013 if (I->isCtrl())
2014 continue;
2015 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002016 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
2017 // counts data deps.
2018 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00002019 continue;
2020 const SDNode *PN = PredSU->getNode();
2021 if (!PN->isMachineOpcode()) {
2022 if (PN->getOpcode() == ISD::CopyFromReg) {
2023 EVT VT = PN->getValueType(0);
2024 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2025 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2026 }
2027 continue;
2028 }
2029 unsigned POpc = PN->getMachineOpcode();
2030 if (POpc == TargetOpcode::IMPLICIT_DEF)
2031 continue;
2032 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
2033 EVT VT = PN->getOperand(0).getValueType();
2034 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2035 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2036 continue;
2037 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
2038 POpc == TargetOpcode::SUBREG_TO_REG) {
2039 EVT VT = PN->getValueType(0);
2040 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2041 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2042 continue;
2043 }
2044 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
2045 for (unsigned i = 0; i != NumDefs; ++i) {
2046 EVT VT = PN->getValueType(i);
2047 if (!PN->hasAnyUseOfValue(i))
2048 continue;
2049 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2050 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
2051 // Register pressure tracking is imprecise. This can happen.
2052 RegPressure[RCId] = 0;
2053 else
2054 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
2055 }
2056 }
2057
2058 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
2059 // may transfer data dependencies to CopyToReg.
2060 if (SU->NumSuccs && N->isMachineOpcode()) {
2061 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2062 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2063 EVT VT = N->getValueType(i);
2064 if (VT == MVT::Glue || VT == MVT::Other)
2065 continue;
2066 if (!N->hasAnyUseOfValue(i))
2067 continue;
2068 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2069 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2070 }
2071 }
2072
2073 dumpRegPressure();
2074}
2075
2076//===----------------------------------------------------------------------===//
2077// Dynamic Node Priority for Register Pressure Reduction
2078//===----------------------------------------------------------------------===//
2079
Evan Chengb9e3db62007-03-14 22:43:40 +00002080/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00002081/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00002082static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002083 unsigned MaxHeight = 0;
Evan Cheng28748552007-03-13 23:25:11 +00002084 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00002085 I != E; ++I) {
Evan Chengce3bbe52009-02-10 08:30:11 +00002086 if (I->isCtrl()) continue; // ignore chain succs
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002087 unsigned Height = I->getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00002088 // If there are bunch of CopyToRegs stacked up, they should be considered
2089 // to be at the same position.
Dan Gohman2d170892008-12-09 22:54:47 +00002090 if (I->getSUnit()->getNode() &&
2091 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002092 Height = closestSucc(I->getSUnit())+1;
2093 if (Height > MaxHeight)
2094 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00002095 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002096 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00002097}
2098
Evan Cheng61bc51e2007-12-20 02:22:36 +00002099/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00002100/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00002101static unsigned calcMaxScratches(const SUnit *SU) {
2102 unsigned Scratches = 0;
2103 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Chengb5704992009-02-12 09:52:13 +00002104 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002105 if (I->isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00002106 Scratches++;
2107 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00002108 return Scratches;
2109}
2110
Andrew Trickb53a00d2011-04-13 00:38:32 +00002111/// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2112/// CopyFromReg from a virtual register.
2113static bool hasOnlyLiveInOpers(const SUnit *SU) {
2114 bool RetVal = false;
2115 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2116 I != E; ++I) {
2117 if (I->isCtrl()) continue;
2118 const SUnit *PredSU = I->getSUnit();
2119 if (PredSU->getNode() &&
2120 PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2121 unsigned Reg =
2122 cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2123 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2124 RetVal = true;
2125 continue;
2126 }
2127 }
2128 return false;
2129 }
2130 return RetVal;
2131}
2132
2133/// hasOnlyLiveOutUses - Return true if SU has only value successors that are
Evan Cheng6c1414f2010-10-29 18:09:28 +00002134/// CopyToReg to a virtual register. This SU def is probably a liveout and
2135/// it has no other use. It should be scheduled closer to the terminator.
2136static bool hasOnlyLiveOutUses(const SUnit *SU) {
2137 bool RetVal = false;
2138 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2139 I != E; ++I) {
2140 if (I->isCtrl()) continue;
2141 const SUnit *SuccSU = I->getSUnit();
2142 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2143 unsigned Reg =
2144 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2145 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2146 RetVal = true;
2147 continue;
2148 }
2149 }
2150 return false;
2151 }
2152 return RetVal;
2153}
2154
Andrew Trickb53a00d2011-04-13 00:38:32 +00002155// Set isVRegCycle for a node with only live in opers and live out uses. Also
2156// set isVRegCycle for its CopyFromReg operands.
2157//
2158// This is only relevant for single-block loops, in which case the VRegCycle
2159// node is likely an induction variable in which the operand and target virtual
2160// registers should be coalesced (e.g. pre/post increment values). Setting the
2161// isVRegCycle flag helps the scheduler prioritize other uses of the same
2162// CopyFromReg so that this node becomes the virtual register "kill". This
2163// avoids interference between the values live in and out of the block and
2164// eliminates a copy inside the loop.
2165static void initVRegCycle(SUnit *SU) {
2166 if (DisableSchedVRegCycle)
2167 return;
2168
2169 if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2170 return;
2171
2172 DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
2173
2174 SU->isVRegCycle = true;
2175
2176 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002177 I != E; ++I) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002178 if (I->isCtrl()) continue;
2179 I->getSUnit()->isVRegCycle = true;
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002180 }
Andrew Trick1b60ad62011-04-12 20:14:07 +00002181}
2182
Andrew Trickb53a00d2011-04-13 00:38:32 +00002183// After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2184// CopyFromReg operands. We should no longer penalize other uses of this VReg.
2185static void resetVRegCycle(SUnit *SU) {
2186 if (!SU->isVRegCycle)
2187 return;
2188
2189 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2190 I != E; ++I) {
Andrew Trick1b60ad62011-04-12 20:14:07 +00002191 if (I->isCtrl()) continue; // ignore chain preds
Andrew Trickb53a00d2011-04-13 00:38:32 +00002192 SUnit *PredSU = I->getSUnit();
2193 if (PredSU->isVRegCycle) {
2194 assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2195 "VRegCycle def must be CopyFromReg");
2196 I->getSUnit()->isVRegCycle = 0;
2197 }
2198 }
2199}
2200
2201// Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2202// means a node that defines the VRegCycle has not been scheduled yet.
2203static bool hasVRegCycleUse(const SUnit *SU) {
2204 // If this SU also defines the VReg, don't hoist it as a "use".
2205 if (SU->isVRegCycle)
2206 return false;
2207
2208 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2209 I != E; ++I) {
2210 if (I->isCtrl()) continue; // ignore chain preds
2211 if (I->getSUnit()->isVRegCycle &&
2212 I->getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
2213 DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
2214 return true;
Andrew Trick2ad0b372011-04-07 19:54:57 +00002215 }
2216 }
2217 return false;
2218}
2219
Andrew Trick9ccce772011-01-14 21:11:41 +00002220// Check for either a dependence (latency) or resource (hazard) stall.
2221//
2222// Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2223static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2224 if ((int)SPQ->getCurCycle() < Height) return true;
2225 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2226 != ScheduleHazardRecognizer::NoHazard)
2227 return true;
2228 return false;
2229}
2230
2231// Return -1 if left has higher priority, 1 if right has higher priority.
2232// Return 0 if latency-based priority is equivalent.
2233static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2234 RegReductionPQBase *SPQ) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002235 // Scheduling an instruction that uses a VReg whose postincrement has not yet
2236 // been scheduled will induce a copy. Model this as an extra cycle of latency.
2237 int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2238 int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2239 int LHeight = (int)left->getHeight() + LPenalty;
2240 int RHeight = (int)right->getHeight() + RPenalty;
Andrew Trick9ccce772011-01-14 21:11:41 +00002241
2242 bool LStall = (!checkPref || left->SchedulingPref == Sched::Latency) &&
2243 BUHasStall(left, LHeight, SPQ);
2244 bool RStall = (!checkPref || right->SchedulingPref == Sched::Latency) &&
2245 BUHasStall(right, RHeight, SPQ);
2246
2247 // If scheduling one of the node will cause a pipeline stall, delay it.
2248 // If scheduling either one of the node will cause a pipeline stall, sort
2249 // them according to their height.
2250 if (LStall) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002251 if (!RStall) {
2252 DEBUG(++FactorCount[FactStall]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002253 return 1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002254 }
2255 if (LHeight != RHeight) {
2256 DEBUG(++FactorCount[FactStall]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002257 return LHeight > RHeight ? 1 : -1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002258 }
2259 } else if (RStall) {
2260 DEBUG(++FactorCount[FactStall]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002261 return -1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002262 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002263
Andrew Trick47ff14b2011-01-21 05:51:33 +00002264 // If either node is scheduling for latency, sort them by height/depth
Andrew Trick9ccce772011-01-14 21:11:41 +00002265 // and latency.
2266 if (!checkPref || (left->SchedulingPref == Sched::Latency ||
2267 right->SchedulingPref == Sched::Latency)) {
Andrew Trick47ff14b2011-01-21 05:51:33 +00002268 if (DisableSchedCycles) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002269 if (LHeight != RHeight) {
2270 DEBUG(++FactorCount[FactHeight]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002271 return LHeight > RHeight ? 1 : -1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002272 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002273 }
Andrew Trick47ff14b2011-01-21 05:51:33 +00002274 else {
2275 // If neither instruction stalls (!LStall && !RStall) then
Eric Christopher9cb33de2011-03-06 21:13:45 +00002276 // its height is already covered so only its depth matters. We also reach
Andrew Trick47ff14b2011-01-21 05:51:33 +00002277 // this if both stall but have the same height.
Andrew Trickb53a00d2011-04-13 00:38:32 +00002278 int LDepth = left->getDepth() - LPenalty;
2279 int RDepth = right->getDepth() - RPenalty;
Andrew Trick47ff14b2011-01-21 05:51:33 +00002280 if (LDepth != RDepth) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002281 DEBUG(++FactorCount[FactDepth]);
Andrew Trick47ff14b2011-01-21 05:51:33 +00002282 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2283 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2284 << ") depth " << RDepth << "\n");
2285 return LDepth < RDepth ? 1 : -1;
2286 }
2287 }
Andrew Trickb53a00d2011-04-13 00:38:32 +00002288 if (left->Latency != right->Latency) {
2289 DEBUG(++FactorCount[FactOther]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002290 return left->Latency > right->Latency ? 1 : -1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002291 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002292 }
2293 return 0;
2294}
2295
2296static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002297 // Schedule physical register definitions close to their use. This is
2298 // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
2299 // long as shortening physreg live ranges is generally good, we can defer
2300 // creating a subtarget hook.
2301 if (!DisableSchedPhysRegJoin) {
2302 bool LHasPhysReg = left->hasPhysRegDefs;
2303 bool RHasPhysReg = right->hasPhysRegDefs;
2304 if (LHasPhysReg != RHasPhysReg) {
2305 DEBUG(++FactorCount[FactRegUses]);
2306 #ifndef NDEBUG
2307 const char *PhysRegMsg[] = {" has no physreg", " defines a physreg"};
2308 #endif
2309 DEBUG(dbgs() << " SU (" << left->NodeNum << ") "
2310 << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
2311 << PhysRegMsg[RHasPhysReg] << "\n");
2312 return LHasPhysReg < RHasPhysReg;
2313 }
2314 }
2315
Evan Cheng2f647542011-04-26 04:57:37 +00002316 // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
Evan Cheng6730f032007-01-08 23:55:53 +00002317 unsigned LPriority = SPQ->getNodePriority(left);
2318 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng1355bbd2011-04-26 21:31:35 +00002319
2320 // Be really careful about hoisting call operands above previous calls.
2321 // Only allows it if it would reduce register pressure.
2322 if (left->isCall && right->isCallOp) {
2323 unsigned RNumVals = right->getNode()->getNumValues();
2324 RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2325 }
2326 if (right->isCall && left->isCallOp) {
2327 unsigned LNumVals = left->getNode()->getNumValues();
2328 LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2329 }
2330
Andrew Trick641e2d42011-03-05 08:00:22 +00002331 if (LPriority != RPriority) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002332 DEBUG(++FactorCount[FactStatic]);
Evan Cheng73bdf042008-03-01 00:39:47 +00002333 return LPriority > RPriority;
Andrew Trick641e2d42011-03-05 08:00:22 +00002334 }
Andrew Trick52b3e382011-03-08 01:51:56 +00002335
Evan Cheng1355bbd2011-04-26 21:31:35 +00002336 // One or both of the nodes are calls and their sethi-ullman numbers are the
2337 // same, then keep source order.
2338 if (left->isCall || right->isCall) {
2339 unsigned LOrder = SPQ->getNodeOrdering(left);
2340 unsigned ROrder = SPQ->getNodeOrdering(right);
2341
2342 // Prefer an ordering where the lower the non-zero order number, the higher
2343 // the preference.
2344 if ((LOrder || ROrder) && LOrder != ROrder)
2345 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2346 }
2347
Evan Cheng73bdf042008-03-01 00:39:47 +00002348 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2349 // e.g.
2350 // t1 = op t2, c1
2351 // t3 = op t4, c2
2352 //
2353 // and the following instructions are both ready.
2354 // t2 = op c3
2355 // t4 = op c4
2356 //
2357 // Then schedule t2 = op first.
2358 // i.e.
2359 // t4 = op c4
2360 // t2 = op c3
2361 // t1 = op t2, c1
2362 // t3 = op t4, c2
2363 //
2364 // This creates more short live intervals.
2365 unsigned LDist = closestSucc(left);
2366 unsigned RDist = closestSucc(right);
Andrew Trickb53a00d2011-04-13 00:38:32 +00002367 if (LDist != RDist) {
2368 DEBUG(++FactorCount[FactOther]);
Evan Cheng73bdf042008-03-01 00:39:47 +00002369 return LDist < RDist;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002370 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002371
Evan Cheng3a14efa2009-02-12 08:59:45 +00002372 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00002373 unsigned LScratch = calcMaxScratches(left);
2374 unsigned RScratch = calcMaxScratches(right);
Andrew Trickb53a00d2011-04-13 00:38:32 +00002375 if (LScratch != RScratch) {
2376 DEBUG(++FactorCount[FactOther]);
Evan Cheng73bdf042008-03-01 00:39:47 +00002377 return LScratch > RScratch;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002378 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002379
Evan Cheng1355bbd2011-04-26 21:31:35 +00002380 // Comparing latency against a call makes little sense unless the node
2381 // is register pressure-neutral.
2382 if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
2383 return (left->NodeQueueId > right->NodeQueueId);
2384
2385 // Do not compare latencies when one or both of the nodes are calls.
2386 if (!DisableSchedCycles &&
2387 !(left->isCall || right->isCall)) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002388 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2389 if (result != 0)
2390 return result > 0;
2391 }
2392 else {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002393 if (left->getHeight() != right->getHeight()) {
2394 DEBUG(++FactorCount[FactHeight]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002395 return left->getHeight() > right->getHeight();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002396 }
Andrew Trick2085a962010-12-21 22:25:04 +00002397
Andrew Trickb53a00d2011-04-13 00:38:32 +00002398 if (left->getDepth() != right->getDepth()) {
2399 DEBUG(++FactorCount[FactDepth]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002400 return left->getDepth() < right->getDepth();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002401 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002402 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002403
Andrew Trick2085a962010-12-21 22:25:04 +00002404 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002405 "NodeQueueId cannot be zero");
Andrew Trickb53a00d2011-04-13 00:38:32 +00002406 DEBUG(++FactorCount[FactOther]);
Roman Levenstein6b371142008-04-29 09:07:59 +00002407 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002408}
2409
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002410// Bottom up
Andrew Trick9ccce772011-01-14 21:11:41 +00002411bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002412 if (int res = checkSpecialNodes(left, right))
2413 return res > 0;
2414
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002415 return BURRSort(left, right, SPQ);
2416}
2417
2418// Source order, otherwise bottom up.
Andrew Trick9ccce772011-01-14 21:11:41 +00002419bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002420 if (int res = checkSpecialNodes(left, right))
2421 return res > 0;
2422
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002423 unsigned LOrder = SPQ->getNodeOrdering(left);
2424 unsigned ROrder = SPQ->getNodeOrdering(right);
2425
2426 // Prefer an ordering where the lower the non-zero order number, the higher
2427 // the preference.
2428 if ((LOrder || ROrder) && LOrder != ROrder)
2429 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2430
2431 return BURRSort(left, right, SPQ);
2432}
2433
Andrew Trick9ccce772011-01-14 21:11:41 +00002434// If the time between now and when the instruction will be ready can cover
2435// the spill code, then avoid adding it to the ready queue. This gives long
2436// stalls highest priority and allows hoisting across calls. It should also
2437// speed up processing the available queue.
2438bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2439 static const unsigned ReadyDelay = 3;
2440
2441 if (SPQ->MayReduceRegPressure(SU)) return true;
2442
2443 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2444
2445 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2446 != ScheduleHazardRecognizer::NoHazard)
2447 return false;
2448
2449 return true;
2450}
2451
2452// Return true if right should be scheduled with higher priority than left.
2453bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002454 if (int res = checkSpecialNodes(left, right))
2455 return res > 0;
2456
Evan Chengdebf9c52010-11-03 00:45:17 +00002457 if (left->isCall || right->isCall)
2458 // No way to compute latency of calls.
2459 return BURRSort(left, right, SPQ);
2460
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002461 bool LHigh = SPQ->HighRegPressure(left);
2462 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002463 // Avoid causing spills. If register pressure is high, schedule for
2464 // register pressure reduction.
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002465 if (LHigh && !RHigh) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002466 DEBUG(++FactorCount[FactPressureDiff]);
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002467 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2468 << right->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002469 return true;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002470 }
2471 else if (!LHigh && RHigh) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002472 DEBUG(++FactorCount[FactPressureDiff]);
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002473 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2474 << left->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002475 return false;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002476 }
Andrew Trickb53a00d2011-04-13 00:38:32 +00002477 if (!LHigh && !RHigh) {
2478 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2479 if (result != 0)
2480 return result > 0;
Evan Chengcc2efe12010-05-28 23:26:21 +00002481 }
Evan Chengbdd062d2010-05-20 06:13:19 +00002482 return BURRSort(left, right, SPQ);
2483}
2484
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002485// Schedule as many instructions in each cycle as possible. So don't make an
2486// instruction available unless it is ready in the current cycle.
2487bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00002488 if (SU->getHeight() > CurCycle) return false;
2489
2490 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2491 != ScheduleHazardRecognizer::NoHazard)
2492 return false;
2493
Andrew Trickc88b7ec2011-03-04 02:03:45 +00002494 return true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002495}
2496
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002497static bool canEnableCoalescing(SUnit *SU) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002498 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2499 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2500 // CopyToReg should be close to its uses to facilitate coalescing and
2501 // avoid spilling.
2502 return true;
2503
2504 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2505 Opc == TargetOpcode::SUBREG_TO_REG ||
2506 Opc == TargetOpcode::INSERT_SUBREG)
2507 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2508 // close to their uses to facilitate coalescing.
2509 return true;
2510
2511 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2512 // If SU does not have a register def, schedule it close to its uses
2513 // because it does not lengthen any live ranges.
2514 return true;
2515
2516 return false;
2517}
2518
Andrew Trickb8390b72011-03-05 08:04:11 +00002519// list-ilp is currently an experimental scheduler that allows various
2520// heuristics to be enabled prior to the normal register reduction logic.
Andrew Trick9ccce772011-01-14 21:11:41 +00002521bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002522 if (int res = checkSpecialNodes(left, right))
2523 return res > 0;
2524
Evan Chengdebf9c52010-11-03 00:45:17 +00002525 if (left->isCall || right->isCall)
2526 // No way to compute latency of calls.
2527 return BURRSort(left, right, SPQ);
2528
Andrew Trick52b3e382011-03-08 01:51:56 +00002529 unsigned LLiveUses = 0, RLiveUses = 0;
2530 int LPDiff = 0, RPDiff = 0;
2531 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2532 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2533 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2534 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002535 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
2536 DEBUG(++FactorCount[FactPressureDiff]);
Andrew Trick52b3e382011-03-08 01:51:56 +00002537 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2538 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002539 return LPDiff > RPDiff;
2540 }
2541
Andrew Trick52b3e382011-03-08 01:51:56 +00002542 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002543 bool LReduce = canEnableCoalescing(left);
2544 bool RReduce = canEnableCoalescing(right);
Andrew Trick52b3e382011-03-08 01:51:56 +00002545 DEBUG(if (LReduce != RReduce) ++FactorCount[FactPressureDiff]);
2546 if (LReduce && !RReduce) return false;
2547 if (RReduce && !LReduce) return true;
2548 }
2549
2550 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2551 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2552 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002553 DEBUG(++FactorCount[FactRegUses]);
2554 return LLiveUses < RLiveUses;
2555 }
2556
Andrew Trick52b3e382011-03-08 01:51:56 +00002557 if (!DisableSchedStalls) {
2558 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2559 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
2560 if (LStall != RStall) {
2561 DEBUG(++FactorCount[FactHeight]);
2562 return left->getHeight() > right->getHeight();
2563 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002564 }
2565
Andrew Trick25cedf32011-03-05 10:29:25 +00002566 if (!DisableSchedCriticalPath) {
2567 int spread = (int)left->getDepth() - (int)right->getDepth();
2568 if (std::abs(spread) > MaxReorderWindow) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002569 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2570 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2571 << right->getDepth() << "\n");
Andrew Trick25cedf32011-03-05 10:29:25 +00002572 DEBUG(++FactorCount[FactDepth]);
2573 return left->getDepth() < right->getDepth();
2574 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002575 }
2576
2577 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002578 int spread = (int)left->getHeight() - (int)right->getHeight();
2579 if (std::abs(spread) > MaxReorderWindow) {
2580 DEBUG(++FactorCount[FactHeight]);
2581 return left->getHeight() > right->getHeight();
2582 }
Evan Cheng37b740c2010-07-24 00:39:05 +00002583 }
2584
2585 return BURRSort(left, right, SPQ);
2586}
2587
Andrew Trickb53a00d2011-04-13 00:38:32 +00002588void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2589 SUnits = &sunits;
2590 // Add pseudo dependency edges for two-address nodes.
2591 AddPseudoTwoAddrDeps();
2592 // Reroute edges to nodes with multiple uses.
2593 if (!TracksRegPressure)
2594 PrescheduleNodesWithMultipleUses();
2595 // Calculate node priorities.
2596 CalculateSethiUllmanNumbers();
2597
2598 // For single block loops, mark nodes that look like canonical IV increments.
2599 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) {
2600 for (unsigned i = 0, e = sunits.size(); i != e; ++i) {
2601 initVRegCycle(&sunits[i]);
2602 }
2603 }
2604}
2605
Andrew Trick9ccce772011-01-14 21:11:41 +00002606//===----------------------------------------------------------------------===//
2607// Preschedule for Register Pressure
2608//===----------------------------------------------------------------------===//
2609
2610bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002611 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002612 unsigned Opc = SU->getNode()->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002613 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002614 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002615 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002616 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002617 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002618 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002619 if (DU->getNodeId() != -1 &&
2620 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002621 return true;
2622 }
2623 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002624 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002625 return false;
2626}
2627
Evan Chengf9891412007-12-20 09:25:31 +00002628/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002629/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002630static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002631 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002632 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002633 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002634 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2635 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002636 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002637 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002638 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002639 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002640 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002641 const unsigned *SUImpDefs =
2642 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2643 if (!SUImpDefs)
2644 return false;
2645 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002646 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002647 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002648 continue;
2649 if (!N->hasAnyUseOfValue(i))
2650 continue;
2651 unsigned Reg = ImpDefs[i - NumDefs];
2652 for (;*SUImpDefs; ++SUImpDefs) {
2653 unsigned SUReg = *SUImpDefs;
2654 if (TRI->regsOverlap(Reg, SUReg))
2655 return true;
2656 }
Evan Chengf9891412007-12-20 09:25:31 +00002657 }
2658 }
2659 return false;
2660}
2661
Dan Gohman9a658d72009-03-24 00:49:12 +00002662/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2663/// are not handled well by the general register pressure reduction
2664/// heuristics. When presented with code like this:
2665///
2666/// N
2667/// / |
2668/// / |
2669/// U store
2670/// |
2671/// ...
2672///
2673/// the heuristics tend to push the store up, but since the
2674/// operand of the store has another use (U), this would increase
2675/// the length of that other use (the U->N edge).
2676///
2677/// This function transforms code like the above to route U's
2678/// dependence through the store when possible, like this:
2679///
2680/// N
2681/// ||
2682/// ||
2683/// store
2684/// |
2685/// U
2686/// |
2687/// ...
2688///
2689/// This results in the store being scheduled immediately
2690/// after N, which shortens the U->N live range, reducing
2691/// register pressure.
2692///
Andrew Trick9ccce772011-01-14 21:11:41 +00002693void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
Dan Gohman9a658d72009-03-24 00:49:12 +00002694 // Visit all the nodes in topological order, working top-down.
2695 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2696 SUnit *SU = &(*SUnits)[i];
2697 // For now, only look at nodes with no data successors, such as stores.
2698 // These are especially important, due to the heuristics in
2699 // getNodePriority for nodes with no data successors.
2700 if (SU->NumSuccs != 0)
2701 continue;
2702 // For now, only look at nodes with exactly one data predecessor.
2703 if (SU->NumPreds != 1)
2704 continue;
2705 // Avoid prescheduling copies to virtual registers, which don't behave
2706 // like other nodes from the perspective of scheduling heuristics.
2707 if (SDNode *N = SU->getNode())
2708 if (N->getOpcode() == ISD::CopyToReg &&
2709 TargetRegisterInfo::isVirtualRegister
2710 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2711 continue;
2712
2713 // Locate the single data predecessor.
2714 SUnit *PredSU = 0;
2715 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2716 EE = SU->Preds.end(); II != EE; ++II)
2717 if (!II->isCtrl()) {
2718 PredSU = II->getSUnit();
2719 break;
2720 }
2721 assert(PredSU);
2722
2723 // Don't rewrite edges that carry physregs, because that requires additional
2724 // support infrastructure.
2725 if (PredSU->hasPhysRegDefs)
2726 continue;
2727 // Short-circuit the case where SU is PredSU's only data successor.
2728 if (PredSU->NumSuccs == 1)
2729 continue;
2730 // Avoid prescheduling to copies from virtual registers, which don't behave
Andrew Trickd0548ae2011-02-04 03:18:17 +00002731 // like other nodes from the perspective of scheduling heuristics.
Dan Gohman9a658d72009-03-24 00:49:12 +00002732 if (SDNode *N = SU->getNode())
2733 if (N->getOpcode() == ISD::CopyFromReg &&
2734 TargetRegisterInfo::isVirtualRegister
2735 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2736 continue;
2737
2738 // Perform checks on the successors of PredSU.
2739 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2740 EE = PredSU->Succs.end(); II != EE; ++II) {
2741 SUnit *PredSuccSU = II->getSUnit();
2742 if (PredSuccSU == SU) continue;
2743 // If PredSU has another successor with no data successors, for
2744 // now don't attempt to choose either over the other.
2745 if (PredSuccSU->NumSuccs == 0)
2746 goto outer_loop_continue;
2747 // Don't break physical register dependencies.
2748 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2749 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2750 goto outer_loop_continue;
2751 // Don't introduce graph cycles.
2752 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2753 goto outer_loop_continue;
2754 }
2755
2756 // Ok, the transformation is safe and the heuristics suggest it is
2757 // profitable. Update the graph.
Evan Chengbdd062d2010-05-20 06:13:19 +00002758 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2759 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002760 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002761 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2762 SDep Edge = PredSU->Succs[i];
2763 assert(!Edge.isAssignedRegDep());
2764 SUnit *SuccSU = Edge.getSUnit();
2765 if (SuccSU != SU) {
2766 Edge.setSUnit(PredSU);
2767 scheduleDAG->RemovePred(SuccSU, Edge);
2768 scheduleDAG->AddPred(SU, Edge);
2769 Edge.setSUnit(SU);
2770 scheduleDAG->AddPred(SuccSU, Edge);
2771 --i;
2772 }
2773 }
2774 outer_loop_continue:;
2775 }
2776}
2777
Evan Chengd38c22b2006-05-11 23:55:42 +00002778/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2779/// it as a def&use operand. Add a pseudo control edge from it to the other
2780/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002781/// first (lower in the schedule). If both nodes are two-address, favor the
2782/// one that has a CopyToReg use (more likely to be a loop induction update).
2783/// If both are two-address, but one is commutable while the other is not
2784/// commutable, favor the one that's not commutable.
Andrew Trick9ccce772011-01-14 21:11:41 +00002785void RegReductionPQBase::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002786 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
Dan Gohmane955c482008-08-05 14:45:15 +00002787 SUnit *SU = &(*SUnits)[i];
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002788 if (!SU->isTwoAddress)
2789 continue;
2790
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002791 SDNode *Node = SU->getNode();
Chris Lattner11a33812010-12-23 17:24:32 +00002792 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002793 continue;
2794
Evan Cheng6c1414f2010-10-29 18:09:28 +00002795 bool isLiveOut = hasOnlyLiveOutUses(SU);
Dan Gohman17059682008-07-17 19:10:17 +00002796 unsigned Opc = Node->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002797 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002798 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002799 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002800 for (unsigned j = 0; j != NumOps; ++j) {
Dan Gohman82016c22008-11-19 02:00:32 +00002801 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2802 continue;
2803 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2804 if (DU->getNodeId() == -1)
2805 continue;
2806 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2807 if (!DUSU) continue;
2808 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2809 E = DUSU->Succs.end(); I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002810 if (I->isCtrl()) continue;
2811 SUnit *SuccSU = I->getSUnit();
Dan Gohman82016c22008-11-19 02:00:32 +00002812 if (SuccSU == SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002813 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002814 // Be conservative. Ignore if nodes aren't at roughly the same
2815 // depth and height.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002816 if (SuccSU->getHeight() < SU->getHeight() &&
2817 (SU->getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002818 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002819 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2820 // constrains whatever is using the copy, instead of the copy
2821 // itself. In the case that the copy is coalesced, this
2822 // preserves the intent of the pseudo two-address heurietics.
2823 while (SuccSU->Succs.size() == 1 &&
2824 SuccSU->getNode()->isMachineOpcode() &&
2825 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002826 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002827 SuccSU = SuccSU->Succs.front().getSUnit();
2828 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002829 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2830 continue;
2831 // Don't constrain nodes with physical register defs if the
2832 // predecessor can clobber them.
Dan Gohmanf3746cb2009-03-24 00:50:07 +00002833 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
Dan Gohman82016c22008-11-19 02:00:32 +00002834 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002835 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002836 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002837 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2838 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002839 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002840 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2841 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2842 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002843 continue;
2844 if ((!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002845 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Dan Gohman82016c22008-11-19 02:00:32 +00002846 (!SU->isCommutable && SuccSU->isCommutable)) &&
2847 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002848 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002849 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
Dan Gohman79c35162009-01-06 01:19:04 +00002850 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
Dan Gohmanbf8e5202009-01-06 01:28:56 +00002851 /*Reg=*/0, /*isNormalMemory=*/false,
2852 /*isMustAlias=*/false,
Dan Gohman2d170892008-12-09 22:54:47 +00002853 /*isArtificial=*/true));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002854 }
2855 }
2856 }
2857 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002858}
2859
Roman Levenstein30d09512008-03-27 09:44:37 +00002860/// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
Roman Levensteinbc674502008-03-27 09:14:57 +00002861/// predecessors of the successors of the SUnit SU. Stop when the provided
2862/// limit is exceeded.
Andrew Trick2085a962010-12-21 22:25:04 +00002863static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
Roman Levensteinbc674502008-03-27 09:14:57 +00002864 unsigned Limit) {
2865 unsigned Sum = 0;
2866 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2867 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002868 const SUnit *SuccSU = I->getSUnit();
Roman Levensteinbc674502008-03-27 09:14:57 +00002869 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2870 EE = SuccSU->Preds.end(); II != EE; ++II) {
Dan Gohman2d170892008-12-09 22:54:47 +00002871 SUnit *PredSU = II->getSUnit();
Evan Cheng16d72072008-03-29 18:34:22 +00002872 if (!PredSU->isScheduled)
2873 if (++Sum > Limit)
2874 return Sum;
Roman Levensteinbc674502008-03-27 09:14:57 +00002875 }
2876 }
2877 return Sum;
2878}
2879
Evan Chengd38c22b2006-05-11 23:55:42 +00002880
2881// Top down
2882bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002883 if (int res = checkSpecialNodes(left, right))
2884 return res < 0;
2885
Evan Cheng6730f032007-01-08 23:55:53 +00002886 unsigned LPriority = SPQ->getNodePriority(left);
2887 unsigned RPriority = SPQ->getNodePriority(right);
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002888 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2889 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00002890 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2891 bool RIsFloater = RIsTarget && right->NumPreds == 0;
Roman Levensteinbc674502008-03-27 09:14:57 +00002892 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2893 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00002894
2895 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2896 return false;
2897 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2898 return true;
2899
Evan Chengd38c22b2006-05-11 23:55:42 +00002900 if (LIsFloater)
2901 LBonus -= 2;
2902 if (RIsFloater)
2903 RBonus -= 2;
2904 if (left->NumSuccs == 1)
2905 LBonus += 2;
2906 if (right->NumSuccs == 1)
2907 RBonus += 2;
2908
Evan Cheng73bdf042008-03-01 00:39:47 +00002909 if (LPriority+LBonus != RPriority+RBonus)
2910 return LPriority+LBonus < RPriority+RBonus;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00002911
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002912 if (left->getDepth() != right->getDepth())
2913 return left->getDepth() < right->getDepth();
Evan Cheng73bdf042008-03-01 00:39:47 +00002914
2915 if (left->NumSuccsLeft != right->NumSuccsLeft)
2916 return left->NumSuccsLeft > right->NumSuccsLeft;
2917
Andrew Trick2085a962010-12-21 22:25:04 +00002918 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002919 "NodeQueueId cannot be zero");
2920 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002921}
2922
Evan Chengd38c22b2006-05-11 23:55:42 +00002923//===----------------------------------------------------------------------===//
2924// Public Constructor Functions
2925//===----------------------------------------------------------------------===//
2926
Dan Gohmandfaf6462009-02-11 04:27:20 +00002927llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002928llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2929 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002930 const TargetMachine &TM = IS->TM;
2931 const TargetInstrInfo *TII = TM.getInstrInfo();
2932 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002933
Evan Chenga77f3d32010-07-21 06:09:07 +00002934 BURegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002935 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002936 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002937 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002938 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002939}
2940
Dan Gohmandfaf6462009-02-11 04:27:20 +00002941llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002942llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2943 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002944 const TargetMachine &TM = IS->TM;
2945 const TargetInstrInfo *TII = TM.getInstrInfo();
2946 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002947
Evan Chenga77f3d32010-07-21 06:09:07 +00002948 TDRegReductionPriorityQueue *PQ =
2949 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002950 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Dan Gohman3f656df2008-11-20 02:45:51 +00002951 PQ->setScheduleDAG(SD);
2952 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002953}
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002954
2955llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002956llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2957 CodeGenOpt::Level OptLevel) {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002958 const TargetMachine &TM = IS->TM;
2959 const TargetInstrInfo *TII = TM.getInstrInfo();
2960 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002961
Evan Chenga77f3d32010-07-21 06:09:07 +00002962 SrcRegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002963 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002964 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002965 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002966 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002967}
2968
2969llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002970llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2971 CodeGenOpt::Level OptLevel) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002972 const TargetMachine &TM = IS->TM;
2973 const TargetInstrInfo *TII = TM.getInstrInfo();
2974 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Evan Chenga77f3d32010-07-21 06:09:07 +00002975 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002976
Evan Chenga77f3d32010-07-21 06:09:07 +00002977 HybridBURRPriorityQueue *PQ =
Evan Chengdf907f42010-07-23 22:39:59 +00002978 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002979
2980 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002981 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002982 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002983}
Evan Cheng37b740c2010-07-24 00:39:05 +00002984
2985llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002986llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2987 CodeGenOpt::Level OptLevel) {
Evan Cheng37b740c2010-07-24 00:39:05 +00002988 const TargetMachine &TM = IS->TM;
2989 const TargetInstrInfo *TII = TM.getInstrInfo();
2990 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2991 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002992
Evan Cheng37b740c2010-07-24 00:39:05 +00002993 ILPBURRPriorityQueue *PQ =
2994 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002995 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00002996 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002997 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00002998}