blob: f09b38164a992613cf54e60636638b67bd35af4b [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) {
293 unsigned Opcode = RegDefPos.GetNode()->getMachineOpcode();
294 unsigned Idx = RegDefPos.GetIdx();
295 const TargetInstrDesc Desc = TII->get(Opcode);
296 const TargetRegisterClass *RC = Desc.getRegClass(Idx, TRI);
297 RegClass = RC->getID();
298 // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
299 // better way to determine it.
300 Cost = 1;
301 } else {
302 RegClass = TLI->getRepRegClassFor(VT)->getID();
303 Cost = TLI->getRepRegClassCostFor(VT);
304 }
305}
Evan Chengd38c22b2006-05-11 23:55:42 +0000306
307/// Schedule - Schedule the DAG using list scheduling.
308void ScheduleDAGRRList::Schedule() {
Evan Chenga77f3d32010-07-21 06:09:07 +0000309 DEBUG(dbgs()
310 << "********** List Scheduling BB#" << BB->getNumber()
Evan Cheng6c1414f2010-10-29 18:09:28 +0000311 << " '" << BB->getName() << "' **********\n");
Andrew Trick641e2d42011-03-05 08:00:22 +0000312#ifndef NDEBUG
313 for (int i = 0; i < NumFactors; ++i) {
314 FactorCount[i] = 0;
315 }
316#endif //!NDEBUG
Evan Cheng5924bf72007-09-25 01:54:36 +0000317
Andrew Trick528fad92010-12-23 05:42:20 +0000318 CurCycle = 0;
Andrew Trick641e2d42011-03-05 08:00:22 +0000319 IssueCount = 0;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000320 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
Dan Gohmanc07f6862008-09-23 18:50:48 +0000321 NumLiveRegs = 0;
Andrew Trick2085a962010-12-21 22:25:04 +0000322 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
Andrew Tricka52f3252010-12-23 04:16:14 +0000323 LiveRegGens.resize(TRI->getNumRegs(), NULL);
Evan Cheng5924bf72007-09-25 01:54:36 +0000324
Dan Gohman04543e72008-12-23 18:36:58 +0000325 // Build the scheduling graph.
Dan Gohman918ec532009-10-09 23:33:48 +0000326 BuildSchedGraph(NULL);
Evan Chengd38c22b2006-05-11 23:55:42 +0000327
Evan Chengd38c22b2006-05-11 23:55:42 +0000328 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Dan Gohman22d07b12008-11-18 02:06:40 +0000329 SUnits[su].dumpAll(this));
Dan Gohmanad2134d2008-11-25 00:52:40 +0000330 Topo.InitDAGTopologicalSorting();
Evan Chengd38c22b2006-05-11 23:55:42 +0000331
Dan Gohman46520a22008-06-21 19:18:17 +0000332 AvailableQueue->initNodes(SUnits);
Andrew Trick2085a962010-12-21 22:25:04 +0000333
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000334 HazardRec->Reset();
335
Evan Chengd38c22b2006-05-11 23:55:42 +0000336 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
337 if (isBottomUp)
338 ListScheduleBottomUp();
339 else
340 ListScheduleTopDown();
Andrew Trick2085a962010-12-21 22:25:04 +0000341
Andrew Trick641e2d42011-03-05 08:00:22 +0000342#ifndef NDEBUG
343 for (int i = 0; i < NumFactors; ++i) {
344 DEBUG(dbgs() << FactorName[i] << "\t" << FactorCount[i] << "\n");
345 }
346#endif // !NDEBUG
Evan Chengd38c22b2006-05-11 23:55:42 +0000347 AvailableQueue->releaseState();
Evan Chengafed73e2006-05-12 01:58:24 +0000348}
Evan Chengd38c22b2006-05-11 23:55:42 +0000349
350//===----------------------------------------------------------------------===//
351// Bottom-Up Scheduling
352//===----------------------------------------------------------------------===//
353
Evan Chengd38c22b2006-05-11 23:55:42 +0000354/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000355/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +0000356void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000357 SUnit *PredSU = PredEdge->getSUnit();
Reid Klecknercea8dab2009-09-30 20:43:07 +0000358
Evan Chengd38c22b2006-05-11 23:55:42 +0000359#ifndef NDEBUG
Reid Klecknercea8dab2009-09-30 20:43:07 +0000360 if (PredSU->NumSuccsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +0000361 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +0000362 PredSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +0000363 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +0000364 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +0000365 }
366#endif
Reid Klecknercea8dab2009-09-30 20:43:07 +0000367 --PredSU->NumSuccsLeft;
368
Evan Chengbdd062d2010-05-20 06:13:19 +0000369 if (!ForceUnitLatencies()) {
370 // Updating predecessor's height. This is now the cycle when the
371 // predecessor can be scheduled without causing a pipeline stall.
372 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
373 }
374
Dan Gohmanb9543432009-02-10 23:27:53 +0000375 // If all the node's successors are scheduled, this node is ready
376 // to be scheduled. Ignore the special EntrySU node.
377 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
Dan Gohman4370f262008-04-15 01:22:18 +0000378 PredSU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000379
380 unsigned Height = PredSU->getHeight();
381 if (Height < MinAvailableCycle)
382 MinAvailableCycle = Height;
383
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000384 if (isReady(PredSU)) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000385 AvailableQueue->push(PredSU);
386 }
387 // CapturePred and others may have left the node in the pending queue, avoid
388 // adding it twice.
389 else if (!PredSU->isPending) {
390 PredSU->isPending = true;
391 PendingQueue.push_back(PredSU);
392 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000393 }
394}
395
Andrew Trick033efdf2010-12-23 03:15:51 +0000396/// Call ReleasePred for each predecessor, then update register live def/gen.
397/// Always update LiveRegDefs for a register dependence even if the current SU
398/// also defines the register. This effectively create one large live range
399/// across a sequence of two-address node. This is important because the
400/// entire chain must be scheduled together. Example:
401///
402/// flags = (3) add
403/// flags = (2) addc flags
404/// flags = (1) addc flags
405///
406/// results in
407///
408/// LiveRegDefs[flags] = 3
Andrew Tricka52f3252010-12-23 04:16:14 +0000409/// LiveRegGens[flags] = 1
Andrew Trick033efdf2010-12-23 03:15:51 +0000410///
411/// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
412/// interference on flags.
Andrew Tricka52f3252010-12-23 04:16:14 +0000413void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000414 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000415 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000416 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000417 ReleasePred(SU, &*I);
418 if (I->isAssignedRegDep()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000419 // This is a physical register dependency and it's impossible or
Andrew Trick2085a962010-12-21 22:25:04 +0000420 // expensive to copy the register. Make sure nothing that can
Evan Cheng5924bf72007-09-25 01:54:36 +0000421 // clobber the register is scheduled between the predecessor and
422 // this node.
Andrew Tricka52f3252010-12-23 04:16:14 +0000423 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
Andrew Trick033efdf2010-12-23 03:15:51 +0000424 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
425 "interference on register dependence");
Andrew Tricka52f3252010-12-23 04:16:14 +0000426 LiveRegDefs[I->getReg()] = I->getSUnit();
427 if (!LiveRegGens[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000428 ++NumLiveRegs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000429 LiveRegGens[I->getReg()] = SU;
Evan Cheng5924bf72007-09-25 01:54:36 +0000430 }
431 }
432 }
Dan Gohmanb9543432009-02-10 23:27:53 +0000433}
434
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000435/// Check to see if any of the pending instructions are ready to issue. If
436/// so, add them to the available queue.
437void ScheduleDAGRRList::ReleasePending() {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000438 if (DisableSchedCycles) {
Andrew Trick5ce945c2010-12-24 07:10:19 +0000439 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
440 return;
441 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000442
443 // If the available queue is empty, it is safe to reset MinAvailableCycle.
444 if (AvailableQueue->empty())
445 MinAvailableCycle = UINT_MAX;
446
447 // Check to see if any of the pending instructions are ready to issue. If
448 // so, add them to the available queue.
449 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
450 unsigned ReadyCycle =
451 isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDepth();
452 if (ReadyCycle < MinAvailableCycle)
453 MinAvailableCycle = ReadyCycle;
454
455 if (PendingQueue[i]->isAvailable) {
456 if (!isReady(PendingQueue[i]))
457 continue;
458 AvailableQueue->push(PendingQueue[i]);
459 }
460 PendingQueue[i]->isPending = false;
461 PendingQueue[i] = PendingQueue.back();
462 PendingQueue.pop_back();
463 --i; --e;
464 }
465}
466
467/// Move the scheduler state forward by the specified number of Cycles.
468void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
469 if (NextCycle <= CurCycle)
470 return;
471
Andrew Trick641e2d42011-03-05 08:00:22 +0000472 IssueCount = 0;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000473 AvailableQueue->setCurCycle(NextCycle);
Andrew Trick47ff14b2011-01-21 05:51:33 +0000474 if (!HazardRec->isEnabled()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000475 // Bypass lots of virtual calls in case of long latency.
476 CurCycle = NextCycle;
477 }
478 else {
479 for (; CurCycle != NextCycle; ++CurCycle) {
480 if (isBottomUp)
481 HazardRec->RecedeCycle();
482 else
483 HazardRec->AdvanceCycle();
484 }
485 }
486 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
487 // available Q to release pending nodes at least once before popping.
488 ReleasePending();
489}
490
491/// Move the scheduler state forward until the specified node's dependents are
492/// ready and can be scheduled with no resource conflicts.
493void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000494 if (DisableSchedCycles)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000495 return;
496
Andrew Trickb53a00d2011-04-13 00:38:32 +0000497 // FIXME: Nodes such as CopyFromReg probably should not advance the current
498 // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
499 // has predecessors the cycle will be advanced when they are scheduled.
500 // But given the crude nature of modeling latency though such nodes, we
501 // currently need to treat these nodes like real instructions.
502 // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
503
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000504 unsigned ReadyCycle = isBottomUp ? SU->getHeight() : SU->getDepth();
505
506 // Bump CurCycle to account for latency. We assume the latency of other
507 // available instructions may be hidden by the stall (not a full pipe stall).
508 // This updates the hazard recognizer's cycle before reserving resources for
509 // this instruction.
510 AdvanceToCycle(ReadyCycle);
511
512 // Calls are scheduled in their preceding cycle, so don't conflict with
513 // hazards from instructions after the call. EmitNode will reset the
514 // scoreboard state before emitting the call.
515 if (isBottomUp && SU->isCall)
516 return;
517
518 // FIXME: For resource conflicts in very long non-pipelined stages, we
519 // should probably skip ahead here to avoid useless scoreboard checks.
520 int Stalls = 0;
521 while (true) {
522 ScheduleHazardRecognizer::HazardType HT =
523 HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
524
525 if (HT == ScheduleHazardRecognizer::NoHazard)
526 break;
527
528 ++Stalls;
529 }
530 AdvanceToCycle(CurCycle + Stalls);
531}
532
533/// Record this SUnit in the HazardRecognizer.
534/// Does not update CurCycle.
535void ScheduleDAGRRList::EmitNode(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000536 if (!HazardRec->isEnabled())
Andrew Trickc9405662010-12-24 06:46:50 +0000537 return;
538
539 // Check for phys reg copy.
540 if (!SU->getNode())
541 return;
542
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000543 switch (SU->getNode()->getOpcode()) {
544 default:
545 assert(SU->getNode()->isMachineOpcode() &&
546 "This target-independent node should not be scheduled.");
547 break;
548 case ISD::MERGE_VALUES:
549 case ISD::TokenFactor:
550 case ISD::CopyToReg:
551 case ISD::CopyFromReg:
552 case ISD::EH_LABEL:
553 // Noops don't affect the scoreboard state. Copies are likely to be
554 // removed.
555 return;
556 case ISD::INLINEASM:
557 // For inline asm, clear the pipeline state.
558 HazardRec->Reset();
559 return;
560 }
561 if (isBottomUp && SU->isCall) {
562 // Calls are scheduled with their preceding instructions. For bottom-up
563 // scheduling, clear the pipeline state before emitting.
564 HazardRec->Reset();
565 }
566
567 HazardRec->EmitInstruction(SU);
568
569 if (!isBottomUp && SU->isCall) {
570 HazardRec->Reset();
571 }
572}
573
Andrew Trickb53a00d2011-04-13 00:38:32 +0000574static void resetVRegCycle(SUnit *SU);
575
Dan Gohmanb9543432009-02-10 23:27:53 +0000576/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
577/// count of its predecessors. If a predecessor pending count is zero, add it to
578/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000579void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Andrew Trick1b60ad62011-04-12 20:14:07 +0000580 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000581 DEBUG(SU->dump(this));
582
Evan Chengbdd062d2010-05-20 06:13:19 +0000583#ifndef NDEBUG
584 if (CurCycle < SU->getHeight())
Andrew Trickb53a00d2011-04-13 00:38:32 +0000585 DEBUG(dbgs() << " Height [" << SU->getHeight()
586 << "] pipeline stall!\n");
Evan Chengbdd062d2010-05-20 06:13:19 +0000587#endif
588
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000589 // FIXME: Do not modify node height. It may interfere with
590 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
Eric Christopher1b4b1e52011-03-21 18:06:21 +0000591 // node its ready cycle can aid heuristics, and after scheduling it can
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000592 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000593 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000594
595 // Reserve resources for the scheduled intruction.
596 EmitNode(SU);
597
Dan Gohmanb9543432009-02-10 23:27:53 +0000598 Sequence.push_back(SU);
599
Evan Cheng28590382010-07-21 23:53:58 +0000600 AvailableQueue->ScheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000601
Andrew Trick641e2d42011-03-05 08:00:22 +0000602 // If HazardRec is disabled, and each inst counts as one cycle, then
Andrew Trickb53a00d2011-04-13 00:38:32 +0000603 // advance CurCycle before ReleasePredecessors to avoid useless pushes to
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000604 // PendingQueue for schedulers that implement HasReadyFilter.
Andrew Trick641e2d42011-03-05 08:00:22 +0000605 if (!HazardRec->isEnabled() && AvgIPC < 2)
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000606 AdvanceToCycle(CurCycle + 1);
607
Andrew Trick033efdf2010-12-23 03:15:51 +0000608 // Update liveness of predecessors before successors to avoid treating a
609 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000610 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000611
612 // Release all the implicit physical register defs that are live.
613 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
614 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000615 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
616 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
617 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
618 --NumLiveRegs;
619 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000620 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000621 }
622 }
623
Andrew Trickb53a00d2011-04-13 00:38:32 +0000624 resetVRegCycle(SU);
625
Evan Chengd38c22b2006-05-11 23:55:42 +0000626 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000627
628 // Conditions under which the scheduler should eagerly advance the cycle:
629 // (1) No available instructions
630 // (2) All pipelines full, so available instructions must have hazards.
631 //
Andrew Trickb53a00d2011-04-13 00:38:32 +0000632 // If HazardRec is disabled, the cycle was pre-advanced before calling
633 // ReleasePredecessors. In that case, IssueCount should remain 0.
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000634 //
635 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
Andrew Trickb53a00d2011-04-13 00:38:32 +0000636 if (HazardRec->isEnabled() || AvgIPC > 1) {
637 if (SU->getNode() && SU->getNode()->isMachineOpcode())
638 ++IssueCount;
639 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
640 || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
641 AdvanceToCycle(CurCycle + 1);
642 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000643}
644
Evan Cheng5924bf72007-09-25 01:54:36 +0000645/// CapturePred - This does the opposite of ReleasePred. Since SU is being
646/// unscheduled, incrcease the succ left count of its predecessors. Remove
647/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000648void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000649 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000650 if (PredSU->isAvailable) {
651 PredSU->isAvailable = false;
652 if (!PredSU->isPending)
653 AvailableQueue->remove(PredSU);
654 }
655
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000656 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000657 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000658}
659
660/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
661/// its predecessor states to reflect the change.
662void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000663 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000664 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000665
Evan Cheng5924bf72007-09-25 01:54:36 +0000666 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
667 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000668 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000669 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000670 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000671 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000672 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000673 --NumLiveRegs;
Dan Gohman2d170892008-12-09 22:54:47 +0000674 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000675 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000676 }
677 }
678
679 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
680 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000681 if (I->isAssignedRegDep()) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000682 // This becomes the nearest def. Note that an earlier def may still be
683 // pending if this is a two-address node.
684 LiveRegDefs[I->getReg()] = SU;
Dan Gohman2d170892008-12-09 22:54:47 +0000685 if (!LiveRegDefs[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000686 ++NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000687 }
Andrew Tricka52f3252010-12-23 04:16:14 +0000688 if (LiveRegGens[I->getReg()] == NULL ||
689 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
690 LiveRegGens[I->getReg()] = I->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000691 }
692 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000693 if (SU->getHeight() < MinAvailableCycle)
694 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000695
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000696 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000697 SU->isScheduled = false;
698 SU->isAvailable = true;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000699 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000700 // Don't make available until backtracking is complete.
701 SU->isPending = true;
702 PendingQueue.push_back(SU);
703 }
704 else {
705 AvailableQueue->push(SU);
706 }
Evan Cheng28590382010-07-21 23:53:58 +0000707 AvailableQueue->UnscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000708}
709
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000710/// After backtracking, the hazard checker needs to be restored to a state
711/// corresponding the the current cycle.
712void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
713 HazardRec->Reset();
714
715 unsigned LookAhead = std::min((unsigned)Sequence.size(),
716 HazardRec->getMaxLookAhead());
717 if (LookAhead == 0)
718 return;
719
720 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
721 unsigned HazardCycle = (*I)->getHeight();
722 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
723 SUnit *SU = *I;
724 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
725 HazardRec->RecedeCycle();
726 }
727 EmitNode(SU);
728 }
729}
730
Evan Cheng8e136a92007-09-26 21:36:17 +0000731/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000732/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000733void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
734 SUnit *OldSU = Sequence.back();
735 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000736 Sequence.pop_back();
737 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000738 // Don't try to remove SU from AvailableQueue.
739 SU->isAvailable = false;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000740 // FIXME: use ready cycle instead of height
741 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000742 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000743 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000744 if (OldSU == BtSU)
745 break;
746 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000747 }
748
Dan Gohman60d68442009-01-29 19:49:27 +0000749 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000750
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000751 RestoreHazardCheckerBottomUp();
752
Andrew Trick5ce945c2010-12-24 07:10:19 +0000753 ReleasePending();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000754
Evan Cheng1ec79b42007-09-27 07:09:03 +0000755 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000756}
757
Evan Cheng3b245872010-02-05 01:27:11 +0000758static bool isOperandOf(const SUnit *SU, SDNode *N) {
759 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000760 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000761 if (SUNode->isOperandOf(N))
762 return true;
763 }
764 return false;
765}
766
Evan Cheng5924bf72007-09-25 01:54:36 +0000767/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
768/// successors to the newly created node.
769SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000770 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000771 if (!N)
772 return NULL;
773
Andrew Trickc9405662010-12-24 06:46:50 +0000774 if (SU->getNode()->getGluedNode())
775 return NULL;
776
Evan Cheng79e97132007-10-05 01:39:18 +0000777 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000778 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000779 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000780 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000781 if (VT == MVT::Glue)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000782 return NULL;
Owen Anderson9f944592009-08-11 20:47:22 +0000783 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000784 TryUnfold = true;
785 }
Evan Cheng79e97132007-10-05 01:39:18 +0000786 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000787 const SDValue &Op = N->getOperand(i);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000788 EVT VT = Op.getNode()->getValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000789 if (VT == MVT::Glue)
Evan Cheng79e97132007-10-05 01:39:18 +0000790 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000791 }
792
793 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000794 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000795 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000796 return NULL;
797
Evan Chengbdd062d2010-05-20 06:13:19 +0000798 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000799 assert(NewNodes.size() == 2 && "Expected a load folding node!");
800
801 N = NewNodes[1];
802 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000803 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000804 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000805 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000806 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
807 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000808 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000809
Dan Gohmane52e0892008-11-11 21:34:44 +0000810 // LoadNode may already exist. This can happen when there is another
811 // load from the same location and producing the same type of value
812 // but it has different alignment or volatileness.
813 bool isNewLoad = true;
814 SUnit *LoadSU;
815 if (LoadNode->getNodeId() != -1) {
816 LoadSU = &SUnits[LoadNode->getNodeId()];
817 isNewLoad = false;
818 } else {
819 LoadSU = CreateNewSUnit(LoadNode);
820 LoadNode->setNodeId(LoadSU->NodeNum);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000821
822 InitNumRegDefsLeft(LoadSU);
Dan Gohmane52e0892008-11-11 21:34:44 +0000823 ComputeLatency(LoadSU);
824 }
825
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000826 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000827 assert(N->getNodeId() == -1 && "Node already inserted!");
828 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +0000829
Dan Gohman17059682008-07-17 19:10:17 +0000830 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Dan Gohman856c0122008-02-16 00:25:40 +0000831 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000832 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000833 NewSU->isTwoAddress = true;
834 break;
835 }
836 }
Chris Lattnerfd2e3382008-01-07 06:47:00 +0000837 if (TID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000838 NewSU->isCommutable = true;
Andrew Trickd0548ae2011-02-04 03:18:17 +0000839
840 InitNumRegDefsLeft(NewSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000841 ComputeLatency(NewSU);
842
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000843 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +0000844 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +0000845 SmallVector<SDep, 4> ChainSuccs;
846 SmallVector<SDep, 4> LoadPreds;
847 SmallVector<SDep, 4> NodePreds;
848 SmallVector<SDep, 4> NodeSuccs;
849 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
850 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000851 if (I->isCtrl())
Dan Gohman15af5522009-03-06 02:23:01 +0000852 ChainPreds.push_back(*I);
Evan Cheng3b245872010-02-05 01:27:11 +0000853 else if (isOperandOf(I->getSUnit(), LoadNode))
Dan Gohman2d170892008-12-09 22:54:47 +0000854 LoadPreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000855 else
Dan Gohman2d170892008-12-09 22:54:47 +0000856 NodePreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000857 }
858 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
859 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000860 if (I->isCtrl())
861 ChainSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000862 else
Dan Gohman2d170892008-12-09 22:54:47 +0000863 NodeSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +0000864 }
865
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000866 // Now assign edges to the newly-created nodes.
Dan Gohman15af5522009-03-06 02:23:01 +0000867 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
868 const SDep &Pred = ChainPreds[i];
869 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +0000870 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +0000871 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000872 }
Evan Cheng79e97132007-10-05 01:39:18 +0000873 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000874 const SDep &Pred = LoadPreds[i];
875 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +0000876 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +0000877 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000878 }
879 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000880 const SDep &Pred = NodePreds[i];
881 RemovePred(SU, Pred);
882 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +0000883 }
884 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000885 SDep D = NodeSuccs[i];
886 SUnit *SuccDep = D.getSUnit();
887 D.setSUnit(SU);
888 RemovePred(SuccDep, D);
889 D.setSUnit(NewSU);
890 AddPred(SuccDep, D);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000891 // Balance register pressure.
892 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
893 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
894 --NewSU->NumRegDefsLeft;
Evan Cheng79e97132007-10-05 01:39:18 +0000895 }
896 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +0000897 SDep D = ChainSuccs[i];
898 SUnit *SuccDep = D.getSUnit();
899 D.setSUnit(SU);
900 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000901 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +0000902 D.setSUnit(LoadSU);
903 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000904 }
Andrew Trick2085a962010-12-21 22:25:04 +0000905 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000906
907 // Add a data dependency to reflect that NewSU reads the value defined
908 // by LoadSU.
909 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
Evan Cheng79e97132007-10-05 01:39:18 +0000910
Evan Cheng91e0fc92007-12-18 08:42:10 +0000911 if (isNewLoad)
912 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000913 AvailableQueue->addNode(NewSU);
914
915 ++NumUnfolds;
916
917 if (NewSU->NumSuccsLeft == 0) {
918 NewSU->isAvailable = true;
919 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +0000920 }
921 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000922 }
923
Evan Chengbdd062d2010-05-20 06:13:19 +0000924 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000925 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000926
927 // New SUnit has the exact same predecessors.
928 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
929 I != E; ++I)
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000930 if (!I->isArtificial())
Dan Gohman2d170892008-12-09 22:54:47 +0000931 AddPred(NewSU, *I);
Evan Cheng5924bf72007-09-25 01:54:36 +0000932
933 // Only copy scheduled successors. Cut them from old node's successor
934 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000935 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +0000936 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
937 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000938 if (I->isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +0000939 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000940 SUnit *SuccSU = I->getSUnit();
941 if (SuccSU->isScheduled) {
Dan Gohman2d170892008-12-09 22:54:47 +0000942 SDep D = *I;
943 D.setSUnit(NewSU);
944 AddPred(SuccSU, D);
945 D.setSUnit(SU);
946 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +0000947 }
948 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000949 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000950 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng5924bf72007-09-25 01:54:36 +0000951
952 AvailableQueue->updateNode(SU);
953 AvailableQueue->addNode(NewSU);
954
Evan Cheng1ec79b42007-09-27 07:09:03 +0000955 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +0000956 return NewSU;
957}
958
Evan Chengb2c42c62009-01-12 03:19:55 +0000959/// InsertCopiesAndMoveSuccs - Insert register copies and move all
960/// scheduled successors of the given SUnit to the last copy.
961void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
962 const TargetRegisterClass *DestRC,
963 const TargetRegisterClass *SrcRC,
Evan Cheng1ec79b42007-09-27 07:09:03 +0000964 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000965 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000966 CopyFromSU->CopySrcRC = SrcRC;
967 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +0000968
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000969 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +0000970 CopyToSU->CopySrcRC = DestRC;
971 CopyToSU->CopyDstRC = SrcRC;
972
973 // Only copy scheduled successors. Cut them from old node's successor
974 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +0000975 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +0000976 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
977 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000978 if (I->isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +0000979 continue;
Dan Gohman2d170892008-12-09 22:54:47 +0000980 SUnit *SuccSU = I->getSUnit();
981 if (SuccSU->isScheduled) {
982 SDep D = *I;
983 D.setSUnit(CopyToSU);
984 AddPred(SuccSU, D);
985 DelDeps.push_back(std::make_pair(SuccSU, *I));
Evan Cheng8e136a92007-09-26 21:36:17 +0000986 }
Andrew Trick13acae02011-03-23 20:42:39 +0000987 else {
988 // Avoid scheduling the def-side copy before other successors. Otherwise
989 // we could introduce another physreg interference on the copy and
990 // continue inserting copies indefinitely.
991 SDep D(CopyFromSU, SDep::Order, /*Latency=*/0,
992 /*Reg=*/0, /*isNormalMemory=*/false,
993 /*isMustAlias=*/false, /*isArtificial=*/true);
994 AddPred(SuccSU, D);
995 }
Evan Cheng8e136a92007-09-26 21:36:17 +0000996 }
Evan Chengb2c42c62009-01-12 03:19:55 +0000997 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +0000998 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng8e136a92007-09-26 21:36:17 +0000999
Dan Gohman2d170892008-12-09 22:54:47 +00001000 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
1001 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
Evan Cheng8e136a92007-09-26 21:36:17 +00001002
1003 AvailableQueue->updateNode(SU);
1004 AvailableQueue->addNode(CopyFromSU);
1005 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001006 Copies.push_back(CopyFromSU);
1007 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +00001008
Evan Chengb2c42c62009-01-12 03:19:55 +00001009 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +00001010}
1011
1012/// getPhysicalRegisterVT - Returns the ValueType of the physical register
1013/// definition of the specified node.
1014/// FIXME: Move to SelectionDAG?
Owen Anderson53aa7a92009-08-10 22:56:29 +00001015static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +00001016 const TargetInstrInfo *TII) {
Dan Gohman17059682008-07-17 19:10:17 +00001017 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
Evan Cheng8e136a92007-09-26 21:36:17 +00001018 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
Chris Lattnerb0d06b42008-01-07 03:13:06 +00001019 unsigned NumRes = TID.getNumDefs();
1020 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +00001021 if (Reg == *ImpDef)
1022 break;
1023 ++NumRes;
1024 }
1025 return N->getValueType(NumRes);
1026}
1027
Evan Chengb8905c42009-03-04 01:41:49 +00001028/// CheckForLiveRegDef - Return true and update live register vector if the
1029/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001030static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Evan Chengb8905c42009-03-04 01:41:49 +00001031 std::vector<SUnit*> &LiveRegDefs,
1032 SmallSet<unsigned, 4> &RegAdded,
1033 SmallVector<unsigned, 4> &LRegs,
1034 const TargetRegisterInfo *TRI) {
Andrew Trick12acde112010-12-23 03:43:21 +00001035 for (const unsigned *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
1036
1037 // Check if Ref is live.
Andrew Trick0af2e472011-06-07 00:38:12 +00001038 if (!LiveRegDefs[*AliasI]) continue;
Andrew Trick12acde112010-12-23 03:43:21 +00001039
1040 // Allow multiple uses of the same def.
Andrew Trick0af2e472011-06-07 00:38:12 +00001041 if (LiveRegDefs[*AliasI] == SU) continue;
Andrew Trick12acde112010-12-23 03:43:21 +00001042
1043 // Add Reg to the set of interfering live regs.
Andrew Trick0af2e472011-06-07 00:38:12 +00001044 if (RegAdded.insert(*AliasI)) {
Andrew Trick0af2e472011-06-07 00:38:12 +00001045 LRegs.push_back(*AliasI);
1046 }
Evan Chengb8905c42009-03-04 01:41:49 +00001047 }
Evan Chengb8905c42009-03-04 01:41:49 +00001048}
1049
Evan Cheng5924bf72007-09-25 01:54:36 +00001050/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1051/// scheduling of the given node to satisfy live physical register dependencies.
1052/// If the specific node is the last one that's available to schedule, do
1053/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001054bool ScheduleDAGRRList::
1055DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +00001056 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +00001057 return false;
1058
Evan Chenge6f92252007-09-27 18:46:06 +00001059 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +00001060 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001061 //
1062 // If SU is the currently live definition of the same register that it uses,
1063 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +00001064 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1065 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001066 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Evan Chengb8905c42009-03-04 01:41:49 +00001067 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
1068 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001069 }
1070
Chris Lattner11a33812010-12-23 17:24:32 +00001071 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +00001072 if (Node->getOpcode() == ISD::INLINEASM) {
1073 // Inline asm can clobber physical defs.
1074 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +00001075 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +00001076 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +00001077
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001078 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +00001079 unsigned Flags =
1080 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001081 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +00001082
1083 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001084 if (InlineAsm::isRegDefKind(Flags) ||
1085 InlineAsm::isRegDefEarlyClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +00001086 // Check for def of register or earlyclobber register.
1087 for (; NumVals; --NumVals, ++i) {
1088 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1089 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1090 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1091 }
1092 } else
1093 i += NumVals;
1094 }
1095 continue;
1096 }
1097
Dan Gohman072734e2008-11-13 23:24:17 +00001098 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +00001099 continue;
Dan Gohman17059682008-07-17 19:10:17 +00001100 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
Evan Cheng5924bf72007-09-25 01:54:36 +00001101 if (!TID.ImplicitDefs)
1102 continue;
Evan Chengb8905c42009-03-04 01:41:49 +00001103 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg)
1104 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001105 }
Andrew Trick2085a962010-12-21 22:25:04 +00001106
Evan Cheng5924bf72007-09-25 01:54:36 +00001107 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +00001108}
1109
Andrew Trick528fad92010-12-23 05:42:20 +00001110/// Return a node that can be scheduled in this cycle. Requirements:
1111/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001112/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +00001113/// (3) No Interferences: may unschedule to break register interferences.
1114SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1115 SmallVector<SUnit*, 4> Interferences;
1116 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1117
1118 SUnit *CurSU = AvailableQueue->pop();
1119 while (CurSU) {
1120 SmallVector<unsigned, 4> LRegs;
1121 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1122 break;
1123 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1124
1125 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1126 Interferences.push_back(CurSU);
1127 CurSU = AvailableQueue->pop();
1128 }
1129 if (CurSU) {
1130 // Add the nodes that aren't ready back onto the available list.
1131 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1132 Interferences[i]->isPending = false;
1133 assert(Interferences[i]->isAvailable && "must still be available");
1134 AvailableQueue->push(Interferences[i]);
1135 }
1136 return CurSU;
1137 }
1138
1139 // All candidates are delayed due to live physical reg dependencies.
1140 // Try backtracking, code duplication, or inserting cross class copies
1141 // to resolve it.
1142 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1143 SUnit *TrySU = Interferences[i];
1144 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1145
1146 // Try unscheduling up to the point where it's safe to schedule
1147 // this node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001148 SUnit *BtSU = NULL;
1149 unsigned LiveCycle = UINT_MAX;
Andrew Trick528fad92010-12-23 05:42:20 +00001150 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1151 unsigned Reg = LRegs[j];
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001152 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1153 BtSU = LiveRegGens[Reg];
1154 LiveCycle = BtSU->getHeight();
1155 }
Andrew Trick528fad92010-12-23 05:42:20 +00001156 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001157 if (!WillCreateCycle(TrySU, BtSU)) {
1158 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001159
1160 // Force the current node to be scheduled before the node that
1161 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001162 if (BtSU->isAvailable) {
1163 BtSU->isAvailable = false;
1164 if (!BtSU->isPending)
1165 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001166 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001167 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
Andrew Trick528fad92010-12-23 05:42:20 +00001168 /*Reg=*/0, /*isNormalMemory=*/false,
1169 /*isMustAlias=*/false, /*isArtificial=*/true));
1170
1171 // If one or more successors has been unscheduled, then the current
1172 // node is no longer avaialable. Schedule a successor that's now
1173 // available instead.
1174 if (!TrySU->isAvailable) {
1175 CurSU = AvailableQueue->pop();
1176 }
1177 else {
1178 CurSU = TrySU;
1179 TrySU->isPending = false;
1180 Interferences.erase(Interferences.begin()+i);
1181 }
1182 break;
1183 }
1184 }
1185
1186 if (!CurSU) {
1187 // Can't backtrack. If it's too expensive to copy the value, then try
1188 // duplicate the nodes that produces these "too expensive to copy"
1189 // values to break the dependency. In case even that doesn't work,
1190 // insert cross class copies.
1191 // If it's not too expensive, i.e. cost != -1, issue copies.
1192 SUnit *TrySU = Interferences[0];
1193 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1194 assert(LRegs.size() == 1 && "Can't handle this yet!");
1195 unsigned Reg = LRegs[0];
1196 SUnit *LRDef = LiveRegDefs[Reg];
1197 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1198 const TargetRegisterClass *RC =
1199 TRI->getMinimalPhysRegClass(Reg, VT);
1200 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1201
Evan Chengb4c6a342011-03-10 00:16:32 +00001202 // If cross copy register class is the same as RC, then it must be possible
1203 // copy the value directly. Do not try duplicate the def.
1204 // If cross copy register class is not the same as RC, then it's possible to
1205 // copy the value but it require cross register class copies and it is
1206 // expensive.
1207 // If cross copy register class is null, then it's not possible to copy
1208 // the value at all.
Andrew Trick528fad92010-12-23 05:42:20 +00001209 SUnit *NewDef = 0;
Evan Chengb4c6a342011-03-10 00:16:32 +00001210 if (DestRC != RC) {
Andrew Trick528fad92010-12-23 05:42:20 +00001211 NewDef = CopyAndMoveSuccessors(LRDef);
Evan Chengb4c6a342011-03-10 00:16:32 +00001212 if (!DestRC && !NewDef)
1213 report_fatal_error("Can't handle live physical register dependency!");
1214 }
Andrew Trick528fad92010-12-23 05:42:20 +00001215 if (!NewDef) {
1216 // Issue copies, these can be expensive cross register class copies.
1217 SmallVector<SUnit*, 2> Copies;
1218 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1219 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1220 << " to SU #" << Copies.front()->NodeNum << "\n");
1221 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1222 /*Reg=*/0, /*isNormalMemory=*/false,
1223 /*isMustAlias=*/false,
1224 /*isArtificial=*/true));
1225 NewDef = Copies.back();
1226 }
1227
1228 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1229 << " to SU #" << TrySU->NodeNum << "\n");
1230 LiveRegDefs[Reg] = NewDef;
1231 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1232 /*Reg=*/0, /*isNormalMemory=*/false,
1233 /*isMustAlias=*/false,
1234 /*isArtificial=*/true));
1235 TrySU->isAvailable = false;
1236 CurSU = NewDef;
1237 }
1238
1239 assert(CurSU && "Unable to resolve live physical register dependencies!");
1240
1241 // Add the nodes that aren't ready back onto the available list.
1242 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1243 Interferences[i]->isPending = false;
1244 // May no longer be available due to backtracking.
1245 if (Interferences[i]->isAvailable) {
1246 AvailableQueue->push(Interferences[i]);
1247 }
1248 }
1249 return CurSU;
1250}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001251
Evan Chengd38c22b2006-05-11 23:55:42 +00001252/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1253/// schedulers.
1254void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001255 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001256 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001257
Evan Chengd38c22b2006-05-11 23:55:42 +00001258 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001259 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001260 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001261 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1262 RootSU->isAvailable = true;
1263 AvailableQueue->push(RootSU);
1264 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001265
1266 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001267 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001268 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001269 while (!AvailableQueue->empty()) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00001270 DEBUG(dbgs() << "\nExamining Available:\n";
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001271 AvailableQueue->dump(this));
1272
Andrew Trick528fad92010-12-23 05:42:20 +00001273 // Pick the best node to schedule taking all constraints into
1274 // consideration.
1275 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001276
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001277 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001278
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001279 ScheduleNodeBottomUp(SU);
1280
1281 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1282 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1283 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1284 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1285 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001286 }
1287
Evan Chengd38c22b2006-05-11 23:55:42 +00001288 // Reverse the order if it is bottom up.
1289 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001290
Evan Chengd38c22b2006-05-11 23:55:42 +00001291#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001292 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001293#endif
1294}
1295
1296//===----------------------------------------------------------------------===//
1297// Top-Down Scheduling
1298//===----------------------------------------------------------------------===//
1299
1300/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +00001301/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +00001302void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +00001303 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001304
Evan Chengd38c22b2006-05-11 23:55:42 +00001305#ifndef NDEBUG
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001306 if (SuccSU->NumPredsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +00001307 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +00001308 SuccSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +00001309 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +00001310 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +00001311 }
1312#endif
Reid Kleckner8ff5c192009-09-30 20:15:38 +00001313 --SuccSU->NumPredsLeft;
1314
Dan Gohmanb9543432009-02-10 23:27:53 +00001315 // If all the node's predecessors are scheduled, this node is ready
1316 // to be scheduled. Ignore the special ExitSU node.
1317 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001318 SuccSU->isAvailable = true;
1319 AvailableQueue->push(SuccSU);
1320 }
1321}
1322
Dan Gohmanb9543432009-02-10 23:27:53 +00001323void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
1324 // Top down: release successors
1325 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1326 I != E; ++I) {
1327 assert(!I->isAssignedRegDep() &&
1328 "The list-tdrr scheduler doesn't yet support physreg dependencies!");
1329
1330 ReleaseSucc(SU, &*I);
1331 }
1332}
1333
Evan Chengd38c22b2006-05-11 23:55:42 +00001334/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1335/// count of its successors. If a successor pending count is zero, add it to
1336/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +00001337void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +00001338 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +00001339 DEBUG(SU->dump(this));
Evan Chengd38c22b2006-05-11 23:55:42 +00001340
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001341 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1342 SU->setDepthToAtLeast(CurCycle);
Dan Gohman92a36d72008-11-17 21:31:02 +00001343 Sequence.push_back(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001344
Dan Gohmanb9543432009-02-10 23:27:53 +00001345 ReleaseSuccessors(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001346 SU->isScheduled = true;
Dan Gohman92a36d72008-11-17 21:31:02 +00001347 AvailableQueue->ScheduledNode(SU);
Evan Chengd38c22b2006-05-11 23:55:42 +00001348}
1349
Dan Gohman54a187e2007-08-20 19:28:38 +00001350/// ListScheduleTopDown - The main loop of list scheduling for top-down
1351/// schedulers.
Evan Chengd38c22b2006-05-11 23:55:42 +00001352void ScheduleDAGRRList::ListScheduleTopDown() {
Evan Chengbdd062d2010-05-20 06:13:19 +00001353 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001354
Dan Gohmanb9543432009-02-10 23:27:53 +00001355 // Release any successors of the special Entry node.
1356 ReleaseSuccessors(&EntrySU);
1357
Evan Chengd38c22b2006-05-11 23:55:42 +00001358 // All leaves to Available queue.
1359 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1360 // It is available if it has no predecessors.
Dan Gohman4370f262008-04-15 01:22:18 +00001361 if (SUnits[i].Preds.empty()) {
Evan Chengd38c22b2006-05-11 23:55:42 +00001362 AvailableQueue->push(&SUnits[i]);
1363 SUnits[i].isAvailable = true;
1364 }
1365 }
Andrew Trick2085a962010-12-21 22:25:04 +00001366
Evan Chengd38c22b2006-05-11 23:55:42 +00001367 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001368 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001369 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001370 while (!AvailableQueue->empty()) {
Evan Cheng5924bf72007-09-25 01:54:36 +00001371 SUnit *CurSU = AvailableQueue->pop();
Andrew Trick2085a962010-12-21 22:25:04 +00001372
Dan Gohmanc602dd42008-11-21 00:10:42 +00001373 if (CurSU)
Andrew Trick528fad92010-12-23 05:42:20 +00001374 ScheduleNodeTopDown(CurSU);
Dan Gohman4370f262008-04-15 01:22:18 +00001375 ++CurCycle;
Evan Chengbdd062d2010-05-20 06:13:19 +00001376 AvailableQueue->setCurCycle(CurCycle);
Evan Chengd38c22b2006-05-11 23:55:42 +00001377 }
Andrew Trick2085a962010-12-21 22:25:04 +00001378
Evan Chengd38c22b2006-05-11 23:55:42 +00001379#ifndef NDEBUG
Dan Gohman4ce15e12008-11-20 01:26:25 +00001380 VerifySchedule(isBottomUp);
Evan Chengd38c22b2006-05-11 23:55:42 +00001381#endif
1382}
1383
1384
Evan Chengd38c22b2006-05-11 23:55:42 +00001385//===----------------------------------------------------------------------===//
Andrew Trick9ccce772011-01-14 21:11:41 +00001386// RegReductionPriorityQueue Definition
Evan Chengd38c22b2006-05-11 23:55:42 +00001387//===----------------------------------------------------------------------===//
1388//
1389// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1390// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001391//
Evan Chengd38c22b2006-05-11 23:55:42 +00001392namespace {
Andrew Trick9ccce772011-01-14 21:11:41 +00001393class RegReductionPQBase;
Andrew Trick2085a962010-12-21 22:25:04 +00001394
Andrew Trick9ccce772011-01-14 21:11:41 +00001395struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1396 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1397};
1398
Andrew Trick3013b6a2011-06-15 17:16:12 +00001399#ifndef NDEBUG
1400template<class SF>
1401struct reverse_sort : public queue_sort {
1402 SF &SortFunc;
1403 reverse_sort(SF &sf) : SortFunc(sf) {}
1404 reverse_sort(const reverse_sort &RHS) : SortFunc(RHS.SortFunc) {}
1405
1406 bool operator()(SUnit* left, SUnit* right) const {
1407 // reverse left/right rather than simply !SortFunc(left, right)
1408 // to expose different paths in the comparison logic.
1409 return SortFunc(right, left);
1410 }
1411};
1412#endif // NDEBUG
1413
Andrew Trick9ccce772011-01-14 21:11:41 +00001414/// bu_ls_rr_sort - Priority function for bottom up register pressure
1415// reduction scheduler.
1416struct bu_ls_rr_sort : public queue_sort {
1417 enum {
1418 IsBottomUp = true,
1419 HasReadyFilter = false
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001420 };
1421
Andrew Trick9ccce772011-01-14 21:11:41 +00001422 RegReductionPQBase *SPQ;
1423 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1424 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001425
Andrew Trick9ccce772011-01-14 21:11:41 +00001426 bool operator()(SUnit* left, SUnit* right) const;
1427};
Andrew Trick2085a962010-12-21 22:25:04 +00001428
Andrew Trick9ccce772011-01-14 21:11:41 +00001429// td_ls_rr_sort - Priority function for top down register pressure reduction
1430// scheduler.
1431struct td_ls_rr_sort : public queue_sort {
1432 enum {
1433 IsBottomUp = false,
1434 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001435 };
1436
Andrew Trick9ccce772011-01-14 21:11:41 +00001437 RegReductionPQBase *SPQ;
1438 td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1439 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001440
Andrew Trick9ccce772011-01-14 21:11:41 +00001441 bool operator()(const SUnit* left, const SUnit* right) const;
1442};
Andrew Trick2085a962010-12-21 22:25:04 +00001443
Andrew Trick9ccce772011-01-14 21:11:41 +00001444// src_ls_rr_sort - Priority function for source order scheduler.
1445struct src_ls_rr_sort : public queue_sort {
1446 enum {
1447 IsBottomUp = true,
1448 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001449 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001450
Andrew Trick9ccce772011-01-14 21:11:41 +00001451 RegReductionPQBase *SPQ;
1452 src_ls_rr_sort(RegReductionPQBase *spq)
1453 : SPQ(spq) {}
1454 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1455 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001456
Andrew Trick9ccce772011-01-14 21:11:41 +00001457 bool operator()(SUnit* left, SUnit* right) const;
1458};
Andrew Trick2085a962010-12-21 22:25:04 +00001459
Andrew Trick9ccce772011-01-14 21:11:41 +00001460// hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1461struct hybrid_ls_rr_sort : public queue_sort {
1462 enum {
1463 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001464 HasReadyFilter = false
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001465 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001466
Andrew Trick9ccce772011-01-14 21:11:41 +00001467 RegReductionPQBase *SPQ;
1468 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1469 : SPQ(spq) {}
1470 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1471 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001472
Andrew Trick9ccce772011-01-14 21:11:41 +00001473 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Chenga77f3d32010-07-21 06:09:07 +00001474
Andrew Trick9ccce772011-01-14 21:11:41 +00001475 bool operator()(SUnit* left, SUnit* right) const;
1476};
1477
1478// ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1479// scheduler.
1480struct ilp_ls_rr_sort : public queue_sort {
1481 enum {
1482 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001483 HasReadyFilter = false
Evan Chengbdd062d2010-05-20 06:13:19 +00001484 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001485
Andrew Trick9ccce772011-01-14 21:11:41 +00001486 RegReductionPQBase *SPQ;
1487 ilp_ls_rr_sort(RegReductionPQBase *spq)
1488 : SPQ(spq) {}
1489 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1490 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001491
Andrew Trick9ccce772011-01-14 21:11:41 +00001492 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Cheng37b740c2010-07-24 00:39:05 +00001493
Andrew Trick9ccce772011-01-14 21:11:41 +00001494 bool operator()(SUnit* left, SUnit* right) const;
1495};
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001496
Andrew Trick9ccce772011-01-14 21:11:41 +00001497class RegReductionPQBase : public SchedulingPriorityQueue {
1498protected:
1499 std::vector<SUnit*> Queue;
1500 unsigned CurQueueId;
1501 bool TracksRegPressure;
1502
1503 // SUnits - The SUnits for the current graph.
1504 std::vector<SUnit> *SUnits;
1505
1506 MachineFunction &MF;
1507 const TargetInstrInfo *TII;
1508 const TargetRegisterInfo *TRI;
1509 const TargetLowering *TLI;
1510 ScheduleDAGRRList *scheduleDAG;
1511
1512 // SethiUllmanNumbers - The SethiUllman number for each node.
1513 std::vector<unsigned> SethiUllmanNumbers;
1514
1515 /// RegPressure - Tracking current reg pressure per register class.
1516 ///
1517 std::vector<unsigned> RegPressure;
1518
1519 /// RegLimit - Tracking the number of allocatable registers per register
1520 /// class.
1521 std::vector<unsigned> RegLimit;
1522
1523public:
1524 RegReductionPQBase(MachineFunction &mf,
1525 bool hasReadyFilter,
1526 bool tracksrp,
1527 const TargetInstrInfo *tii,
1528 const TargetRegisterInfo *tri,
1529 const TargetLowering *tli)
1530 : SchedulingPriorityQueue(hasReadyFilter),
1531 CurQueueId(0), TracksRegPressure(tracksrp),
1532 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1533 if (TracksRegPressure) {
1534 unsigned NumRC = TRI->getNumRegClasses();
1535 RegLimit.resize(NumRC);
1536 RegPressure.resize(NumRC);
1537 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1538 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1539 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1540 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichdf616942011-03-07 21:56:36 +00001541 RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
Andrew Trick9ccce772011-01-14 21:11:41 +00001542 }
1543 }
1544
1545 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1546 scheduleDAG = scheduleDag;
1547 }
1548
1549 ScheduleHazardRecognizer* getHazardRec() {
1550 return scheduleDAG->getHazardRec();
1551 }
1552
1553 void initNodes(std::vector<SUnit> &sunits);
1554
1555 void addNode(const SUnit *SU);
1556
1557 void updateNode(const SUnit *SU);
1558
1559 void releaseState() {
1560 SUnits = 0;
1561 SethiUllmanNumbers.clear();
1562 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1563 }
1564
1565 unsigned getNodePriority(const SUnit *SU) const;
1566
1567 unsigned getNodeOrdering(const SUnit *SU) const {
Andrew Trick3bd8b7a2011-03-25 06:40:55 +00001568 if (!SU->getNode()) return 0;
1569
Andrew Trick9ccce772011-01-14 21:11:41 +00001570 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1571 }
1572
1573 bool empty() const { return Queue.empty(); }
1574
1575 void push(SUnit *U) {
1576 assert(!U->NodeQueueId && "Node in the queue already");
1577 U->NodeQueueId = ++CurQueueId;
1578 Queue.push_back(U);
1579 }
1580
1581 void remove(SUnit *SU) {
1582 assert(!Queue.empty() && "Queue is empty!");
1583 assert(SU->NodeQueueId != 0 && "Not in queue!");
1584 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1585 SU);
1586 if (I != prior(Queue.end()))
1587 std::swap(*I, Queue.back());
1588 Queue.pop_back();
1589 SU->NodeQueueId = 0;
1590 }
1591
Andrew Trickd0548ae2011-02-04 03:18:17 +00001592 bool tracksRegPressure() const { return TracksRegPressure; }
1593
Andrew Trick9ccce772011-01-14 21:11:41 +00001594 void dumpRegPressure() const;
1595
1596 bool HighRegPressure(const SUnit *SU) const;
1597
Andrew Trick641e2d42011-03-05 08:00:22 +00001598 bool MayReduceRegPressure(SUnit *SU) const;
1599
1600 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
Andrew Trick9ccce772011-01-14 21:11:41 +00001601
1602 void ScheduledNode(SUnit *SU);
1603
1604 void UnscheduledNode(SUnit *SU);
1605
1606protected:
1607 bool canClobber(const SUnit *SU, const SUnit *Op);
1608 void AddPseudoTwoAddrDeps();
1609 void PrescheduleNodesWithMultipleUses();
1610 void CalculateSethiUllmanNumbers();
1611};
1612
1613template<class SF>
Andrew Trick3013b6a2011-06-15 17:16:12 +00001614static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
1615 std::vector<SUnit *>::iterator Best = Q.begin();
1616 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1617 E = Q.end(); I != E; ++I)
1618 if (Picker(*Best, *I))
1619 Best = I;
1620 SUnit *V = *Best;
1621 if (Best != prior(Q.end()))
1622 std::swap(*Best, Q.back());
1623 Q.pop_back();
1624 return V;
1625}
Andrew Trick9ccce772011-01-14 21:11:41 +00001626
Andrew Trick3013b6a2011-06-15 17:16:12 +00001627template<class SF>
1628SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
1629#ifndef NDEBUG
1630 if (DAG->StressSched) {
1631 reverse_sort<SF> RPicker(Picker);
1632 return popFromQueueImpl(Q, RPicker);
1633 }
1634#endif
1635 (void)DAG;
1636 return popFromQueueImpl(Q, Picker);
1637}
1638
1639template<class SF>
1640class RegReductionPriorityQueue : public RegReductionPQBase {
Andrew Trick9ccce772011-01-14 21:11:41 +00001641 SF Picker;
1642
1643public:
1644 RegReductionPriorityQueue(MachineFunction &mf,
1645 bool tracksrp,
1646 const TargetInstrInfo *tii,
1647 const TargetRegisterInfo *tri,
1648 const TargetLowering *tli)
1649 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1650 Picker(this) {}
1651
1652 bool isBottomUp() const { return SF::IsBottomUp; }
1653
1654 bool isReady(SUnit *U) const {
1655 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1656 }
1657
1658 SUnit *pop() {
1659 if (Queue.empty()) return NULL;
1660
Andrew Trick3013b6a2011-06-15 17:16:12 +00001661 SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
Andrew Trick9ccce772011-01-14 21:11:41 +00001662 V->NodeQueueId = 0;
1663 return V;
1664 }
1665
1666 void dump(ScheduleDAG *DAG) const {
1667 // Emulate pop() without clobbering NodeQueueIds.
1668 std::vector<SUnit*> DumpQueue = Queue;
1669 SF DumpPicker = Picker;
1670 while (!DumpQueue.empty()) {
Andrew Trick3013b6a2011-06-15 17:16:12 +00001671 SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
Andrew Trick9ccce772011-01-14 21:11:41 +00001672 if (isBottomUp())
1673 dbgs() << "Height " << SU->getHeight() << ": ";
1674 else
1675 dbgs() << "Depth " << SU->getDepth() << ": ";
1676 SU->dump(DAG);
1677 }
1678 }
1679};
1680
1681typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1682BURegReductionPriorityQueue;
1683
1684typedef RegReductionPriorityQueue<td_ls_rr_sort>
1685TDRegReductionPriorityQueue;
1686
1687typedef RegReductionPriorityQueue<src_ls_rr_sort>
1688SrcRegReductionPriorityQueue;
1689
1690typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1691HybridBURRPriorityQueue;
1692
1693typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1694ILPBURRPriorityQueue;
1695} // end anonymous namespace
1696
1697//===----------------------------------------------------------------------===//
1698// Static Node Priority for Register Pressure Reduction
1699//===----------------------------------------------------------------------===//
Evan Chengd38c22b2006-05-11 23:55:42 +00001700
Andrew Trickbfbd9722011-04-14 05:15:06 +00001701// Check for special nodes that bypass scheduling heuristics.
1702// Currently this pushes TokenFactor nodes down, but may be used for other
1703// pseudo-ops as well.
1704//
1705// Return -1 to schedule right above left, 1 for left above right.
1706// Return 0 if no bias exists.
1707static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
1708 bool LSchedLow = left->isScheduleLow;
1709 bool RSchedLow = right->isScheduleLow;
1710 if (LSchedLow != RSchedLow)
1711 return LSchedLow < RSchedLow ? 1 : -1;
1712 return 0;
1713}
1714
Dan Gohman186f65d2008-11-20 03:30:37 +00001715/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1716/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001717static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001718CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001719 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1720 if (SethiUllmanNumber != 0)
1721 return SethiUllmanNumber;
1722
1723 unsigned Extra = 0;
1724 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1725 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001726 if (I->isCtrl()) continue; // ignore chain preds
1727 SUnit *PredSU = I->getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001728 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001729 if (PredSethiUllman > SethiUllmanNumber) {
1730 SethiUllmanNumber = PredSethiUllman;
1731 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001732 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001733 ++Extra;
1734 }
1735
1736 SethiUllmanNumber += Extra;
1737
1738 if (SethiUllmanNumber == 0)
1739 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001740
Evan Cheng7e4abde2008-07-02 09:23:51 +00001741 return SethiUllmanNumber;
1742}
1743
Andrew Trick9ccce772011-01-14 21:11:41 +00001744/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1745/// scheduling units.
1746void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1747 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001748
Andrew Trick9ccce772011-01-14 21:11:41 +00001749 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1750 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
Evan Chengd38c22b2006-05-11 23:55:42 +00001751}
1752
Andrew Trick9ccce772011-01-14 21:11:41 +00001753void RegReductionPQBase::addNode(const SUnit *SU) {
1754 unsigned SUSize = SethiUllmanNumbers.size();
1755 if (SUnits->size() > SUSize)
1756 SethiUllmanNumbers.resize(SUSize*2, 0);
1757 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1758}
1759
1760void RegReductionPQBase::updateNode(const SUnit *SU) {
1761 SethiUllmanNumbers[SU->NodeNum] = 0;
1762 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1763}
1764
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001765// Lower priority means schedule further down. For bottom-up scheduling, lower
1766// priority SUs are scheduled before higher priority SUs.
Andrew Trick9ccce772011-01-14 21:11:41 +00001767unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1768 assert(SU->NodeNum < SethiUllmanNumbers.size());
1769 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1770 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1771 // CopyToReg should be close to its uses to facilitate coalescing and
1772 // avoid spilling.
1773 return 0;
1774 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1775 Opc == TargetOpcode::SUBREG_TO_REG ||
1776 Opc == TargetOpcode::INSERT_SUBREG)
1777 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1778 // close to their uses to facilitate coalescing.
1779 return 0;
1780 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1781 // If SU does not have a register use, i.e. it doesn't produce a value
1782 // that would be consumed (e.g. store), then it terminates a chain of
1783 // computation. Give it a large SethiUllman number so it will be
1784 // scheduled right before its predecessors that it doesn't lengthen
1785 // their live ranges.
1786 return 0xffff;
1787 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1788 // If SU does not have a register def, schedule it close to its uses
1789 // because it does not lengthen any live ranges.
1790 return 0;
Evan Cheng1355bbd2011-04-26 21:31:35 +00001791#if 1
Andrew Trick9ccce772011-01-14 21:11:41 +00001792 return SethiUllmanNumbers[SU->NodeNum];
Evan Cheng1355bbd2011-04-26 21:31:35 +00001793#else
1794 unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
1795 if (SU->isCallOp) {
1796 // FIXME: This assumes all of the defs are used as call operands.
1797 int NP = (int)Priority - SU->getNode()->getNumValues();
1798 return (NP > 0) ? NP : 0;
1799 }
1800 return Priority;
1801#endif
Andrew Trick9ccce772011-01-14 21:11:41 +00001802}
1803
1804//===----------------------------------------------------------------------===//
1805// Register Pressure Tracking
1806//===----------------------------------------------------------------------===//
1807
1808void RegReductionPQBase::dumpRegPressure() const {
1809 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1810 E = TRI->regclass_end(); I != E; ++I) {
1811 const TargetRegisterClass *RC = *I;
1812 unsigned Id = RC->getID();
1813 unsigned RP = RegPressure[Id];
1814 if (!RP) continue;
1815 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1816 << '\n');
1817 }
1818}
1819
1820bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1821 if (!TLI)
1822 return false;
1823
1824 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1825 I != E; ++I) {
1826 if (I->isCtrl())
1827 continue;
1828 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001829 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1830 // to cover the number of registers defined (they are all live).
1831 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001832 continue;
1833 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001834 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1835 RegDefPos.IsValid(); RegDefPos.Advance()) {
1836 EVT VT = RegDefPos.GetValue();
Owen Anderson96adc4a2011-06-15 23:35:18 +00001837
1838 unsigned RCId, Cost;
1839 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
1840
Andrew Trick9ccce772011-01-14 21:11:41 +00001841 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1842 return true;
1843 }
1844 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001845 return false;
1846}
1847
Andrew Trick641e2d42011-03-05 08:00:22 +00001848bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00001849 const SDNode *N = SU->getNode();
1850
1851 if (!N->isMachineOpcode() || !SU->NumSuccs)
1852 return false;
1853
1854 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1855 for (unsigned i = 0; i != NumDefs; ++i) {
1856 EVT VT = N->getValueType(i);
1857 if (!N->hasAnyUseOfValue(i))
1858 continue;
1859 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1860 if (RegPressure[RCId] >= RegLimit[RCId])
1861 return true;
1862 }
1863 return false;
1864}
1865
Andrew Trick641e2d42011-03-05 08:00:22 +00001866// Compute the register pressure contribution by this instruction by count up
1867// for uses that are not live and down for defs. Only count register classes
1868// that are already under high pressure. As a side effect, compute the number of
1869// uses of registers that are already live.
1870//
1871// FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1872// so could probably be factored.
1873int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1874 LiveUses = 0;
1875 int PDiff = 0;
1876 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1877 I != E; ++I) {
1878 if (I->isCtrl())
1879 continue;
1880 SUnit *PredSU = I->getSUnit();
1881 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1882 // to cover the number of registers defined (they are all live).
1883 if (PredSU->NumRegDefsLeft == 0) {
1884 if (PredSU->getNode()->isMachineOpcode())
1885 ++LiveUses;
1886 continue;
1887 }
1888 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1889 RegDefPos.IsValid(); RegDefPos.Advance()) {
1890 EVT VT = RegDefPos.GetValue();
1891 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1892 if (RegPressure[RCId] >= RegLimit[RCId])
1893 ++PDiff;
1894 }
1895 }
1896 const SDNode *N = SU->getNode();
1897
Eric Christopher7238cba2011-03-08 19:35:47 +00001898 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
Andrew Trick641e2d42011-03-05 08:00:22 +00001899 return PDiff;
1900
1901 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1902 for (unsigned i = 0; i != NumDefs; ++i) {
1903 EVT VT = N->getValueType(i);
1904 if (!N->hasAnyUseOfValue(i))
1905 continue;
1906 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1907 if (RegPressure[RCId] >= RegLimit[RCId])
1908 --PDiff;
1909 }
1910 return PDiff;
1911}
1912
Andrew Trick9ccce772011-01-14 21:11:41 +00001913void RegReductionPQBase::ScheduledNode(SUnit *SU) {
1914 if (!TracksRegPressure)
1915 return;
1916
Eric Christopher7238cba2011-03-08 19:35:47 +00001917 if (!SU->getNode())
1918 return;
Andrew Tricka8846e02011-03-23 20:40:18 +00001919
Andrew Trick9ccce772011-01-14 21:11:41 +00001920 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1921 I != E; ++I) {
1922 if (I->isCtrl())
1923 continue;
1924 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001925 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1926 // to cover the number of registers defined (they are all live).
1927 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick9ccce772011-01-14 21:11:41 +00001928 continue;
1929 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001930 // FIXME: The ScheduleDAG currently loses information about which of a
1931 // node's values is consumed by each dependence. Consequently, if the node
1932 // defines multiple register classes, we don't know which to pressurize
1933 // here. Instead the following loop consumes the register defs in an
1934 // arbitrary order. At least it handles the common case of clustered loads
1935 // to the same class. For precise liveness, each SDep needs to indicate the
1936 // result number. But that tightly couples the ScheduleDAG with the
1937 // SelectionDAG making updates tricky. A simpler hack would be to attach a
1938 // value type or register class to SDep.
1939 //
1940 // The most important aspect of register tracking is balancing the increase
1941 // here with the reduction further below. Note that this SU may use multiple
1942 // defs in PredSU. The can't be determined here, but we've already
1943 // compensated by reducing NumRegDefsLeft in PredSU during
1944 // ScheduleDAGSDNodes::AddSchedEdges.
1945 --PredSU->NumRegDefsLeft;
1946 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
1947 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1948 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1949 if (SkipRegDefs)
Andrew Trick9ccce772011-01-14 21:11:41 +00001950 continue;
Owen Anderson96adc4a2011-06-15 23:35:18 +00001951
1952 unsigned RCId, Cost;
1953 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
1954 RegPressure[RCId] += Cost;
Andrew Trickd0548ae2011-02-04 03:18:17 +00001955 break;
Andrew Trick9ccce772011-01-14 21:11:41 +00001956 }
1957 }
1958
Andrew Trickd0548ae2011-02-04 03:18:17 +00001959 // We should have this assert, but there may be dead SDNodes that never
1960 // materialize as SUnits, so they don't appear to generate liveness.
1961 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
1962 int SkipRegDefs = (int)SU->NumRegDefsLeft;
1963 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
1964 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
1965 if (SkipRegDefs > 0)
1966 continue;
Owen Anderson96adc4a2011-06-15 23:35:18 +00001967 unsigned RCId, Cost;
1968 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
1969 if (RegPressure[RCId] < Cost) {
Andrew Trickd0548ae2011-02-04 03:18:17 +00001970 // Register pressure tracking is imprecise. This can happen. But we try
1971 // hard not to let it happen because it likely results in poor scheduling.
1972 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
1973 RegPressure[RCId] = 0;
1974 }
1975 else {
Owen Anderson96adc4a2011-06-15 23:35:18 +00001976 RegPressure[RCId] -= Cost;
Andrew Trick9ccce772011-01-14 21:11:41 +00001977 }
1978 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001979 dumpRegPressure();
1980}
1981
1982void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
1983 if (!TracksRegPressure)
1984 return;
1985
1986 const SDNode *N = SU->getNode();
Eric Christopher7238cba2011-03-08 19:35:47 +00001987 if (!N) return;
Andrew Tricka8846e02011-03-23 20:40:18 +00001988
Andrew Trick9ccce772011-01-14 21:11:41 +00001989 if (!N->isMachineOpcode()) {
1990 if (N->getOpcode() != ISD::CopyToReg)
1991 return;
1992 } else {
1993 unsigned Opc = N->getMachineOpcode();
1994 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1995 Opc == TargetOpcode::INSERT_SUBREG ||
1996 Opc == TargetOpcode::SUBREG_TO_REG ||
1997 Opc == TargetOpcode::REG_SEQUENCE ||
1998 Opc == TargetOpcode::IMPLICIT_DEF)
1999 return;
2000 }
2001
2002 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2003 I != E; ++I) {
2004 if (I->isCtrl())
2005 continue;
2006 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002007 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
2008 // counts data deps.
2009 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00002010 continue;
2011 const SDNode *PN = PredSU->getNode();
2012 if (!PN->isMachineOpcode()) {
2013 if (PN->getOpcode() == ISD::CopyFromReg) {
2014 EVT VT = PN->getValueType(0);
2015 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2016 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2017 }
2018 continue;
2019 }
2020 unsigned POpc = PN->getMachineOpcode();
2021 if (POpc == TargetOpcode::IMPLICIT_DEF)
2022 continue;
2023 if (POpc == TargetOpcode::EXTRACT_SUBREG) {
2024 EVT VT = PN->getOperand(0).getValueType();
2025 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2026 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2027 continue;
2028 } else if (POpc == TargetOpcode::INSERT_SUBREG ||
2029 POpc == TargetOpcode::SUBREG_TO_REG) {
2030 EVT VT = PN->getValueType(0);
2031 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2032 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2033 continue;
2034 }
2035 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
2036 for (unsigned i = 0; i != NumDefs; ++i) {
2037 EVT VT = PN->getValueType(i);
2038 if (!PN->hasAnyUseOfValue(i))
2039 continue;
2040 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2041 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
2042 // Register pressure tracking is imprecise. This can happen.
2043 RegPressure[RCId] = 0;
2044 else
2045 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
2046 }
2047 }
2048
2049 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
2050 // may transfer data dependencies to CopyToReg.
2051 if (SU->NumSuccs && N->isMachineOpcode()) {
2052 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2053 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2054 EVT VT = N->getValueType(i);
2055 if (VT == MVT::Glue || VT == MVT::Other)
2056 continue;
2057 if (!N->hasAnyUseOfValue(i))
2058 continue;
2059 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2060 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2061 }
2062 }
2063
2064 dumpRegPressure();
2065}
2066
2067//===----------------------------------------------------------------------===//
2068// Dynamic Node Priority for Register Pressure Reduction
2069//===----------------------------------------------------------------------===//
2070
Evan Chengb9e3db62007-03-14 22:43:40 +00002071/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00002072/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00002073static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002074 unsigned MaxHeight = 0;
Evan Cheng28748552007-03-13 23:25:11 +00002075 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00002076 I != E; ++I) {
Evan Chengce3bbe52009-02-10 08:30:11 +00002077 if (I->isCtrl()) continue; // ignore chain succs
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002078 unsigned Height = I->getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00002079 // If there are bunch of CopyToRegs stacked up, they should be considered
2080 // to be at the same position.
Dan Gohman2d170892008-12-09 22:54:47 +00002081 if (I->getSUnit()->getNode() &&
2082 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002083 Height = closestSucc(I->getSUnit())+1;
2084 if (Height > MaxHeight)
2085 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00002086 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002087 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00002088}
2089
Evan Cheng61bc51e2007-12-20 02:22:36 +00002090/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00002091/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00002092static unsigned calcMaxScratches(const SUnit *SU) {
2093 unsigned Scratches = 0;
2094 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Chengb5704992009-02-12 09:52:13 +00002095 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002096 if (I->isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00002097 Scratches++;
2098 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00002099 return Scratches;
2100}
2101
Andrew Trickb53a00d2011-04-13 00:38:32 +00002102/// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2103/// CopyFromReg from a virtual register.
2104static bool hasOnlyLiveInOpers(const SUnit *SU) {
2105 bool RetVal = false;
2106 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2107 I != E; ++I) {
2108 if (I->isCtrl()) continue;
2109 const SUnit *PredSU = I->getSUnit();
2110 if (PredSU->getNode() &&
2111 PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2112 unsigned Reg =
2113 cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2114 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2115 RetVal = true;
2116 continue;
2117 }
2118 }
2119 return false;
2120 }
2121 return RetVal;
2122}
2123
2124/// hasOnlyLiveOutUses - Return true if SU has only value successors that are
Evan Cheng6c1414f2010-10-29 18:09:28 +00002125/// CopyToReg to a virtual register. This SU def is probably a liveout and
2126/// it has no other use. It should be scheduled closer to the terminator.
2127static bool hasOnlyLiveOutUses(const SUnit *SU) {
2128 bool RetVal = false;
2129 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2130 I != E; ++I) {
2131 if (I->isCtrl()) continue;
2132 const SUnit *SuccSU = I->getSUnit();
2133 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2134 unsigned Reg =
2135 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2136 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2137 RetVal = true;
2138 continue;
2139 }
2140 }
2141 return false;
2142 }
2143 return RetVal;
2144}
2145
Andrew Trickb53a00d2011-04-13 00:38:32 +00002146// Set isVRegCycle for a node with only live in opers and live out uses. Also
2147// set isVRegCycle for its CopyFromReg operands.
2148//
2149// This is only relevant for single-block loops, in which case the VRegCycle
2150// node is likely an induction variable in which the operand and target virtual
2151// registers should be coalesced (e.g. pre/post increment values). Setting the
2152// isVRegCycle flag helps the scheduler prioritize other uses of the same
2153// CopyFromReg so that this node becomes the virtual register "kill". This
2154// avoids interference between the values live in and out of the block and
2155// eliminates a copy inside the loop.
2156static void initVRegCycle(SUnit *SU) {
2157 if (DisableSchedVRegCycle)
2158 return;
2159
2160 if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2161 return;
2162
2163 DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
2164
2165 SU->isVRegCycle = true;
2166
2167 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002168 I != E; ++I) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002169 if (I->isCtrl()) continue;
2170 I->getSUnit()->isVRegCycle = true;
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002171 }
Andrew Trick1b60ad62011-04-12 20:14:07 +00002172}
2173
Andrew Trickb53a00d2011-04-13 00:38:32 +00002174// After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2175// CopyFromReg operands. We should no longer penalize other uses of this VReg.
2176static void resetVRegCycle(SUnit *SU) {
2177 if (!SU->isVRegCycle)
2178 return;
2179
2180 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2181 I != E; ++I) {
Andrew Trick1b60ad62011-04-12 20:14:07 +00002182 if (I->isCtrl()) continue; // ignore chain preds
Andrew Trickb53a00d2011-04-13 00:38:32 +00002183 SUnit *PredSU = I->getSUnit();
2184 if (PredSU->isVRegCycle) {
2185 assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2186 "VRegCycle def must be CopyFromReg");
2187 I->getSUnit()->isVRegCycle = 0;
2188 }
2189 }
2190}
2191
2192// Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2193// means a node that defines the VRegCycle has not been scheduled yet.
2194static bool hasVRegCycleUse(const SUnit *SU) {
2195 // If this SU also defines the VReg, don't hoist it as a "use".
2196 if (SU->isVRegCycle)
2197 return false;
2198
2199 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2200 I != E; ++I) {
2201 if (I->isCtrl()) continue; // ignore chain preds
2202 if (I->getSUnit()->isVRegCycle &&
2203 I->getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
2204 DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
2205 return true;
Andrew Trick2ad0b372011-04-07 19:54:57 +00002206 }
2207 }
2208 return false;
2209}
2210
Andrew Trick9ccce772011-01-14 21:11:41 +00002211// Check for either a dependence (latency) or resource (hazard) stall.
2212//
2213// Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2214static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2215 if ((int)SPQ->getCurCycle() < Height) return true;
2216 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2217 != ScheduleHazardRecognizer::NoHazard)
2218 return true;
2219 return false;
2220}
2221
2222// Return -1 if left has higher priority, 1 if right has higher priority.
2223// Return 0 if latency-based priority is equivalent.
2224static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2225 RegReductionPQBase *SPQ) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002226 // Scheduling an instruction that uses a VReg whose postincrement has not yet
2227 // been scheduled will induce a copy. Model this as an extra cycle of latency.
2228 int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2229 int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2230 int LHeight = (int)left->getHeight() + LPenalty;
2231 int RHeight = (int)right->getHeight() + RPenalty;
Andrew Trick9ccce772011-01-14 21:11:41 +00002232
2233 bool LStall = (!checkPref || left->SchedulingPref == Sched::Latency) &&
2234 BUHasStall(left, LHeight, SPQ);
2235 bool RStall = (!checkPref || right->SchedulingPref == Sched::Latency) &&
2236 BUHasStall(right, RHeight, SPQ);
2237
2238 // If scheduling one of the node will cause a pipeline stall, delay it.
2239 // If scheduling either one of the node will cause a pipeline stall, sort
2240 // them according to their height.
2241 if (LStall) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002242 if (!RStall) {
2243 DEBUG(++FactorCount[FactStall]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002244 return 1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002245 }
2246 if (LHeight != RHeight) {
2247 DEBUG(++FactorCount[FactStall]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002248 return LHeight > RHeight ? 1 : -1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002249 }
2250 } else if (RStall) {
2251 DEBUG(++FactorCount[FactStall]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002252 return -1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002253 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002254
Andrew Trick47ff14b2011-01-21 05:51:33 +00002255 // If either node is scheduling for latency, sort them by height/depth
Andrew Trick9ccce772011-01-14 21:11:41 +00002256 // and latency.
2257 if (!checkPref || (left->SchedulingPref == Sched::Latency ||
2258 right->SchedulingPref == Sched::Latency)) {
Andrew Trick47ff14b2011-01-21 05:51:33 +00002259 if (DisableSchedCycles) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002260 if (LHeight != RHeight) {
2261 DEBUG(++FactorCount[FactHeight]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002262 return LHeight > RHeight ? 1 : -1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002263 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002264 }
Andrew Trick47ff14b2011-01-21 05:51:33 +00002265 else {
2266 // If neither instruction stalls (!LStall && !RStall) then
Eric Christopher9cb33de2011-03-06 21:13:45 +00002267 // its height is already covered so only its depth matters. We also reach
Andrew Trick47ff14b2011-01-21 05:51:33 +00002268 // this if both stall but have the same height.
Andrew Trickb53a00d2011-04-13 00:38:32 +00002269 int LDepth = left->getDepth() - LPenalty;
2270 int RDepth = right->getDepth() - RPenalty;
Andrew Trick47ff14b2011-01-21 05:51:33 +00002271 if (LDepth != RDepth) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002272 DEBUG(++FactorCount[FactDepth]);
Andrew Trick47ff14b2011-01-21 05:51:33 +00002273 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2274 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2275 << ") depth " << RDepth << "\n");
2276 return LDepth < RDepth ? 1 : -1;
2277 }
2278 }
Andrew Trickb53a00d2011-04-13 00:38:32 +00002279 if (left->Latency != right->Latency) {
2280 DEBUG(++FactorCount[FactOther]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002281 return left->Latency > right->Latency ? 1 : -1;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002282 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002283 }
2284 return 0;
2285}
2286
2287static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002288 // Schedule physical register definitions close to their use. This is
2289 // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
2290 // long as shortening physreg live ranges is generally good, we can defer
2291 // creating a subtarget hook.
2292 if (!DisableSchedPhysRegJoin) {
2293 bool LHasPhysReg = left->hasPhysRegDefs;
2294 bool RHasPhysReg = right->hasPhysRegDefs;
2295 if (LHasPhysReg != RHasPhysReg) {
2296 DEBUG(++FactorCount[FactRegUses]);
2297 #ifndef NDEBUG
2298 const char *PhysRegMsg[] = {" has no physreg", " defines a physreg"};
2299 #endif
2300 DEBUG(dbgs() << " SU (" << left->NodeNum << ") "
2301 << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
2302 << PhysRegMsg[RHasPhysReg] << "\n");
2303 return LHasPhysReg < RHasPhysReg;
2304 }
2305 }
2306
Evan Cheng2f647542011-04-26 04:57:37 +00002307 // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
Evan Cheng6730f032007-01-08 23:55:53 +00002308 unsigned LPriority = SPQ->getNodePriority(left);
2309 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng1355bbd2011-04-26 21:31:35 +00002310
2311 // Be really careful about hoisting call operands above previous calls.
2312 // Only allows it if it would reduce register pressure.
2313 if (left->isCall && right->isCallOp) {
2314 unsigned RNumVals = right->getNode()->getNumValues();
2315 RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2316 }
2317 if (right->isCall && left->isCallOp) {
2318 unsigned LNumVals = left->getNode()->getNumValues();
2319 LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2320 }
2321
Andrew Trick641e2d42011-03-05 08:00:22 +00002322 if (LPriority != RPriority) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002323 DEBUG(++FactorCount[FactStatic]);
Evan Cheng73bdf042008-03-01 00:39:47 +00002324 return LPriority > RPriority;
Andrew Trick641e2d42011-03-05 08:00:22 +00002325 }
Andrew Trick52b3e382011-03-08 01:51:56 +00002326
Evan Cheng1355bbd2011-04-26 21:31:35 +00002327 // One or both of the nodes are calls and their sethi-ullman numbers are the
2328 // same, then keep source order.
2329 if (left->isCall || right->isCall) {
2330 unsigned LOrder = SPQ->getNodeOrdering(left);
2331 unsigned ROrder = SPQ->getNodeOrdering(right);
2332
2333 // Prefer an ordering where the lower the non-zero order number, the higher
2334 // the preference.
2335 if ((LOrder || ROrder) && LOrder != ROrder)
2336 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2337 }
2338
Evan Cheng73bdf042008-03-01 00:39:47 +00002339 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2340 // e.g.
2341 // t1 = op t2, c1
2342 // t3 = op t4, c2
2343 //
2344 // and the following instructions are both ready.
2345 // t2 = op c3
2346 // t4 = op c4
2347 //
2348 // Then schedule t2 = op first.
2349 // i.e.
2350 // t4 = op c4
2351 // t2 = op c3
2352 // t1 = op t2, c1
2353 // t3 = op t4, c2
2354 //
2355 // This creates more short live intervals.
2356 unsigned LDist = closestSucc(left);
2357 unsigned RDist = closestSucc(right);
Andrew Trickb53a00d2011-04-13 00:38:32 +00002358 if (LDist != RDist) {
2359 DEBUG(++FactorCount[FactOther]);
Evan Cheng73bdf042008-03-01 00:39:47 +00002360 return LDist < RDist;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002361 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002362
Evan Cheng3a14efa2009-02-12 08:59:45 +00002363 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00002364 unsigned LScratch = calcMaxScratches(left);
2365 unsigned RScratch = calcMaxScratches(right);
Andrew Trickb53a00d2011-04-13 00:38:32 +00002366 if (LScratch != RScratch) {
2367 DEBUG(++FactorCount[FactOther]);
Evan Cheng73bdf042008-03-01 00:39:47 +00002368 return LScratch > RScratch;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002369 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002370
Evan Cheng1355bbd2011-04-26 21:31:35 +00002371 // Comparing latency against a call makes little sense unless the node
2372 // is register pressure-neutral.
2373 if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
2374 return (left->NodeQueueId > right->NodeQueueId);
2375
2376 // Do not compare latencies when one or both of the nodes are calls.
2377 if (!DisableSchedCycles &&
2378 !(left->isCall || right->isCall)) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002379 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2380 if (result != 0)
2381 return result > 0;
2382 }
2383 else {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002384 if (left->getHeight() != right->getHeight()) {
2385 DEBUG(++FactorCount[FactHeight]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002386 return left->getHeight() > right->getHeight();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002387 }
Andrew Trick2085a962010-12-21 22:25:04 +00002388
Andrew Trickb53a00d2011-04-13 00:38:32 +00002389 if (left->getDepth() != right->getDepth()) {
2390 DEBUG(++FactorCount[FactDepth]);
Andrew Trick9ccce772011-01-14 21:11:41 +00002391 return left->getDepth() < right->getDepth();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002392 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002393 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002394
Andrew Trick2085a962010-12-21 22:25:04 +00002395 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002396 "NodeQueueId cannot be zero");
Andrew Trickb53a00d2011-04-13 00:38:32 +00002397 DEBUG(++FactorCount[FactOther]);
Roman Levenstein6b371142008-04-29 09:07:59 +00002398 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002399}
2400
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002401// Bottom up
Andrew Trick9ccce772011-01-14 21:11:41 +00002402bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002403 if (int res = checkSpecialNodes(left, right))
2404 return res > 0;
2405
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002406 return BURRSort(left, right, SPQ);
2407}
2408
2409// Source order, otherwise bottom up.
Andrew Trick9ccce772011-01-14 21:11:41 +00002410bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002411 if (int res = checkSpecialNodes(left, right))
2412 return res > 0;
2413
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002414 unsigned LOrder = SPQ->getNodeOrdering(left);
2415 unsigned ROrder = SPQ->getNodeOrdering(right);
2416
2417 // Prefer an ordering where the lower the non-zero order number, the higher
2418 // the preference.
2419 if ((LOrder || ROrder) && LOrder != ROrder)
2420 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2421
2422 return BURRSort(left, right, SPQ);
2423}
2424
Andrew Trick9ccce772011-01-14 21:11:41 +00002425// If the time between now and when the instruction will be ready can cover
2426// the spill code, then avoid adding it to the ready queue. This gives long
2427// stalls highest priority and allows hoisting across calls. It should also
2428// speed up processing the available queue.
2429bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2430 static const unsigned ReadyDelay = 3;
2431
2432 if (SPQ->MayReduceRegPressure(SU)) return true;
2433
2434 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2435
2436 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2437 != ScheduleHazardRecognizer::NoHazard)
2438 return false;
2439
2440 return true;
2441}
2442
2443// Return true if right should be scheduled with higher priority than left.
2444bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002445 if (int res = checkSpecialNodes(left, right))
2446 return res > 0;
2447
Evan Chengdebf9c52010-11-03 00:45:17 +00002448 if (left->isCall || right->isCall)
2449 // No way to compute latency of calls.
2450 return BURRSort(left, right, SPQ);
2451
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002452 bool LHigh = SPQ->HighRegPressure(left);
2453 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002454 // Avoid causing spills. If register pressure is high, schedule for
2455 // register pressure reduction.
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002456 if (LHigh && !RHigh) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002457 DEBUG(++FactorCount[FactPressureDiff]);
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002458 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2459 << right->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002460 return true;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002461 }
2462 else if (!LHigh && RHigh) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002463 DEBUG(++FactorCount[FactPressureDiff]);
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002464 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2465 << left->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002466 return false;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002467 }
Andrew Trickb53a00d2011-04-13 00:38:32 +00002468 if (!LHigh && !RHigh) {
2469 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2470 if (result != 0)
2471 return result > 0;
Evan Chengcc2efe12010-05-28 23:26:21 +00002472 }
Evan Chengbdd062d2010-05-20 06:13:19 +00002473 return BURRSort(left, right, SPQ);
2474}
2475
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002476// Schedule as many instructions in each cycle as possible. So don't make an
2477// instruction available unless it is ready in the current cycle.
2478bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00002479 if (SU->getHeight() > CurCycle) return false;
2480
2481 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2482 != ScheduleHazardRecognizer::NoHazard)
2483 return false;
2484
Andrew Trickc88b7ec2011-03-04 02:03:45 +00002485 return true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002486}
2487
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002488static bool canEnableCoalescing(SUnit *SU) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002489 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2490 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2491 // CopyToReg should be close to its uses to facilitate coalescing and
2492 // avoid spilling.
2493 return true;
2494
2495 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2496 Opc == TargetOpcode::SUBREG_TO_REG ||
2497 Opc == TargetOpcode::INSERT_SUBREG)
2498 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2499 // close to their uses to facilitate coalescing.
2500 return true;
2501
2502 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2503 // If SU does not have a register def, schedule it close to its uses
2504 // because it does not lengthen any live ranges.
2505 return true;
2506
2507 return false;
2508}
2509
Andrew Trickb8390b72011-03-05 08:04:11 +00002510// list-ilp is currently an experimental scheduler that allows various
2511// heuristics to be enabled prior to the normal register reduction logic.
Andrew Trick9ccce772011-01-14 21:11:41 +00002512bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002513 if (int res = checkSpecialNodes(left, right))
2514 return res > 0;
2515
Evan Chengdebf9c52010-11-03 00:45:17 +00002516 if (left->isCall || right->isCall)
2517 // No way to compute latency of calls.
2518 return BURRSort(left, right, SPQ);
2519
Andrew Trick52b3e382011-03-08 01:51:56 +00002520 unsigned LLiveUses = 0, RLiveUses = 0;
2521 int LPDiff = 0, RPDiff = 0;
2522 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2523 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2524 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2525 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002526 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
2527 DEBUG(++FactorCount[FactPressureDiff]);
Andrew Trick52b3e382011-03-08 01:51:56 +00002528 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2529 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002530 return LPDiff > RPDiff;
2531 }
2532
Andrew Trick52b3e382011-03-08 01:51:56 +00002533 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002534 bool LReduce = canEnableCoalescing(left);
2535 bool RReduce = canEnableCoalescing(right);
Andrew Trick52b3e382011-03-08 01:51:56 +00002536 DEBUG(if (LReduce != RReduce) ++FactorCount[FactPressureDiff]);
2537 if (LReduce && !RReduce) return false;
2538 if (RReduce && !LReduce) return true;
2539 }
2540
2541 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2542 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2543 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002544 DEBUG(++FactorCount[FactRegUses]);
2545 return LLiveUses < RLiveUses;
2546 }
2547
Andrew Trick52b3e382011-03-08 01:51:56 +00002548 if (!DisableSchedStalls) {
2549 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2550 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
2551 if (LStall != RStall) {
2552 DEBUG(++FactorCount[FactHeight]);
2553 return left->getHeight() > right->getHeight();
2554 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002555 }
2556
Andrew Trick25cedf32011-03-05 10:29:25 +00002557 if (!DisableSchedCriticalPath) {
2558 int spread = (int)left->getDepth() - (int)right->getDepth();
2559 if (std::abs(spread) > MaxReorderWindow) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002560 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2561 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2562 << right->getDepth() << "\n");
Andrew Trick25cedf32011-03-05 10:29:25 +00002563 DEBUG(++FactorCount[FactDepth]);
2564 return left->getDepth() < right->getDepth();
2565 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002566 }
2567
2568 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002569 int spread = (int)left->getHeight() - (int)right->getHeight();
2570 if (std::abs(spread) > MaxReorderWindow) {
2571 DEBUG(++FactorCount[FactHeight]);
2572 return left->getHeight() > right->getHeight();
2573 }
Evan Cheng37b740c2010-07-24 00:39:05 +00002574 }
2575
2576 return BURRSort(left, right, SPQ);
2577}
2578
Andrew Trickb53a00d2011-04-13 00:38:32 +00002579void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2580 SUnits = &sunits;
2581 // Add pseudo dependency edges for two-address nodes.
2582 AddPseudoTwoAddrDeps();
2583 // Reroute edges to nodes with multiple uses.
2584 if (!TracksRegPressure)
2585 PrescheduleNodesWithMultipleUses();
2586 // Calculate node priorities.
2587 CalculateSethiUllmanNumbers();
2588
2589 // For single block loops, mark nodes that look like canonical IV increments.
2590 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) {
2591 for (unsigned i = 0, e = sunits.size(); i != e; ++i) {
2592 initVRegCycle(&sunits[i]);
2593 }
2594 }
2595}
2596
Andrew Trick9ccce772011-01-14 21:11:41 +00002597//===----------------------------------------------------------------------===//
2598// Preschedule for Register Pressure
2599//===----------------------------------------------------------------------===//
2600
2601bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002602 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002603 unsigned Opc = SU->getNode()->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002604 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002605 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002606 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002607 for (unsigned i = 0; i != NumOps; ++i) {
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002608 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002609 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002610 if (DU->getNodeId() != -1 &&
2611 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002612 return true;
2613 }
2614 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002615 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002616 return false;
2617}
2618
Evan Chengf9891412007-12-20 09:25:31 +00002619/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002620/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002621static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002622 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002623 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002624 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002625 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2626 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002627 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002628 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002629 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002630 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002631 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002632 const unsigned *SUImpDefs =
2633 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
2634 if (!SUImpDefs)
2635 return false;
2636 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002637 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002638 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002639 continue;
2640 if (!N->hasAnyUseOfValue(i))
2641 continue;
2642 unsigned Reg = ImpDefs[i - NumDefs];
2643 for (;*SUImpDefs; ++SUImpDefs) {
2644 unsigned SUReg = *SUImpDefs;
2645 if (TRI->regsOverlap(Reg, SUReg))
2646 return true;
2647 }
Evan Chengf9891412007-12-20 09:25:31 +00002648 }
2649 }
2650 return false;
2651}
2652
Dan Gohman9a658d72009-03-24 00:49:12 +00002653/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2654/// are not handled well by the general register pressure reduction
2655/// heuristics. When presented with code like this:
2656///
2657/// N
2658/// / |
2659/// / |
2660/// U store
2661/// |
2662/// ...
2663///
2664/// the heuristics tend to push the store up, but since the
2665/// operand of the store has another use (U), this would increase
2666/// the length of that other use (the U->N edge).
2667///
2668/// This function transforms code like the above to route U's
2669/// dependence through the store when possible, like this:
2670///
2671/// N
2672/// ||
2673/// ||
2674/// store
2675/// |
2676/// U
2677/// |
2678/// ...
2679///
2680/// This results in the store being scheduled immediately
2681/// after N, which shortens the U->N live range, reducing
2682/// register pressure.
2683///
Andrew Trick9ccce772011-01-14 21:11:41 +00002684void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
Dan Gohman9a658d72009-03-24 00:49:12 +00002685 // Visit all the nodes in topological order, working top-down.
2686 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2687 SUnit *SU = &(*SUnits)[i];
2688 // For now, only look at nodes with no data successors, such as stores.
2689 // These are especially important, due to the heuristics in
2690 // getNodePriority for nodes with no data successors.
2691 if (SU->NumSuccs != 0)
2692 continue;
2693 // For now, only look at nodes with exactly one data predecessor.
2694 if (SU->NumPreds != 1)
2695 continue;
2696 // Avoid prescheduling copies to virtual registers, which don't behave
2697 // like other nodes from the perspective of scheduling heuristics.
2698 if (SDNode *N = SU->getNode())
2699 if (N->getOpcode() == ISD::CopyToReg &&
2700 TargetRegisterInfo::isVirtualRegister
2701 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2702 continue;
2703
2704 // Locate the single data predecessor.
2705 SUnit *PredSU = 0;
2706 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2707 EE = SU->Preds.end(); II != EE; ++II)
2708 if (!II->isCtrl()) {
2709 PredSU = II->getSUnit();
2710 break;
2711 }
2712 assert(PredSU);
2713
2714 // Don't rewrite edges that carry physregs, because that requires additional
2715 // support infrastructure.
2716 if (PredSU->hasPhysRegDefs)
2717 continue;
2718 // Short-circuit the case where SU is PredSU's only data successor.
2719 if (PredSU->NumSuccs == 1)
2720 continue;
2721 // Avoid prescheduling to copies from virtual registers, which don't behave
Andrew Trickd0548ae2011-02-04 03:18:17 +00002722 // like other nodes from the perspective of scheduling heuristics.
Dan Gohman9a658d72009-03-24 00:49:12 +00002723 if (SDNode *N = SU->getNode())
2724 if (N->getOpcode() == ISD::CopyFromReg &&
2725 TargetRegisterInfo::isVirtualRegister
2726 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2727 continue;
2728
2729 // Perform checks on the successors of PredSU.
2730 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2731 EE = PredSU->Succs.end(); II != EE; ++II) {
2732 SUnit *PredSuccSU = II->getSUnit();
2733 if (PredSuccSU == SU) continue;
2734 // If PredSU has another successor with no data successors, for
2735 // now don't attempt to choose either over the other.
2736 if (PredSuccSU->NumSuccs == 0)
2737 goto outer_loop_continue;
2738 // Don't break physical register dependencies.
2739 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2740 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2741 goto outer_loop_continue;
2742 // Don't introduce graph cycles.
2743 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2744 goto outer_loop_continue;
2745 }
2746
2747 // Ok, the transformation is safe and the heuristics suggest it is
2748 // profitable. Update the graph.
Evan Chengbdd062d2010-05-20 06:13:19 +00002749 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2750 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002751 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002752 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2753 SDep Edge = PredSU->Succs[i];
2754 assert(!Edge.isAssignedRegDep());
2755 SUnit *SuccSU = Edge.getSUnit();
2756 if (SuccSU != SU) {
2757 Edge.setSUnit(PredSU);
2758 scheduleDAG->RemovePred(SuccSU, Edge);
2759 scheduleDAG->AddPred(SU, Edge);
2760 Edge.setSUnit(SU);
2761 scheduleDAG->AddPred(SuccSU, Edge);
2762 --i;
2763 }
2764 }
2765 outer_loop_continue:;
2766 }
2767}
2768
Evan Chengd38c22b2006-05-11 23:55:42 +00002769/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2770/// it as a def&use operand. Add a pseudo control edge from it to the other
2771/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002772/// first (lower in the schedule). If both nodes are two-address, favor the
2773/// one that has a CopyToReg use (more likely to be a loop induction update).
2774/// If both are two-address, but one is commutable while the other is not
2775/// commutable, favor the one that's not commutable.
Andrew Trick9ccce772011-01-14 21:11:41 +00002776void RegReductionPQBase::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002777 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
Dan Gohmane955c482008-08-05 14:45:15 +00002778 SUnit *SU = &(*SUnits)[i];
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002779 if (!SU->isTwoAddress)
2780 continue;
2781
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002782 SDNode *Node = SU->getNode();
Chris Lattner11a33812010-12-23 17:24:32 +00002783 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002784 continue;
2785
Evan Cheng6c1414f2010-10-29 18:09:28 +00002786 bool isLiveOut = hasOnlyLiveOutUses(SU);
Dan Gohman17059682008-07-17 19:10:17 +00002787 unsigned Opc = Node->getMachineOpcode();
Chris Lattner03ad8852008-01-07 07:27:27 +00002788 const TargetInstrDesc &TID = TII->get(Opc);
Chris Lattnerfd2e3382008-01-07 06:47:00 +00002789 unsigned NumRes = TID.getNumDefs();
Dan Gohman0340d1e2008-02-15 20:50:13 +00002790 unsigned NumOps = TID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002791 for (unsigned j = 0; j != NumOps; ++j) {
Dan Gohman82016c22008-11-19 02:00:32 +00002792 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
2793 continue;
2794 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2795 if (DU->getNodeId() == -1)
2796 continue;
2797 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2798 if (!DUSU) continue;
2799 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2800 E = DUSU->Succs.end(); I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002801 if (I->isCtrl()) continue;
2802 SUnit *SuccSU = I->getSUnit();
Dan Gohman82016c22008-11-19 02:00:32 +00002803 if (SuccSU == SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002804 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002805 // Be conservative. Ignore if nodes aren't at roughly the same
2806 // depth and height.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002807 if (SuccSU->getHeight() < SU->getHeight() &&
2808 (SU->getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002809 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002810 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2811 // constrains whatever is using the copy, instead of the copy
2812 // itself. In the case that the copy is coalesced, this
2813 // preserves the intent of the pseudo two-address heurietics.
2814 while (SuccSU->Succs.size() == 1 &&
2815 SuccSU->getNode()->isMachineOpcode() &&
2816 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002817 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002818 SuccSU = SuccSU->Succs.front().getSUnit();
2819 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002820 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2821 continue;
2822 // Don't constrain nodes with physical register defs if the
2823 // predecessor can clobber them.
Dan Gohmanf3746cb2009-03-24 00:50:07 +00002824 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
Dan Gohman82016c22008-11-19 02:00:32 +00002825 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002826 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002827 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002828 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2829 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002830 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002831 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2832 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2833 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002834 continue;
2835 if ((!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002836 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Dan Gohman82016c22008-11-19 02:00:32 +00002837 (!SU->isCommutable && SuccSU->isCommutable)) &&
2838 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002839 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002840 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
Dan Gohman79c35162009-01-06 01:19:04 +00002841 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
Dan Gohmanbf8e5202009-01-06 01:28:56 +00002842 /*Reg=*/0, /*isNormalMemory=*/false,
2843 /*isMustAlias=*/false,
Dan Gohman2d170892008-12-09 22:54:47 +00002844 /*isArtificial=*/true));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002845 }
2846 }
2847 }
2848 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002849}
2850
Roman Levenstein30d09512008-03-27 09:44:37 +00002851/// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
Roman Levensteinbc674502008-03-27 09:14:57 +00002852/// predecessors of the successors of the SUnit SU. Stop when the provided
2853/// limit is exceeded.
Andrew Trick2085a962010-12-21 22:25:04 +00002854static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
Roman Levensteinbc674502008-03-27 09:14:57 +00002855 unsigned Limit) {
2856 unsigned Sum = 0;
2857 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2858 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002859 const SUnit *SuccSU = I->getSUnit();
Roman Levensteinbc674502008-03-27 09:14:57 +00002860 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
2861 EE = SuccSU->Preds.end(); II != EE; ++II) {
Dan Gohman2d170892008-12-09 22:54:47 +00002862 SUnit *PredSU = II->getSUnit();
Evan Cheng16d72072008-03-29 18:34:22 +00002863 if (!PredSU->isScheduled)
2864 if (++Sum > Limit)
2865 return Sum;
Roman Levensteinbc674502008-03-27 09:14:57 +00002866 }
2867 }
2868 return Sum;
2869}
2870
Evan Chengd38c22b2006-05-11 23:55:42 +00002871
2872// Top down
2873bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002874 if (int res = checkSpecialNodes(left, right))
2875 return res < 0;
2876
Evan Cheng6730f032007-01-08 23:55:53 +00002877 unsigned LPriority = SPQ->getNodePriority(left);
2878 unsigned RPriority = SPQ->getNodePriority(right);
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002879 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
2880 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
Evan Chengd38c22b2006-05-11 23:55:42 +00002881 bool LIsFloater = LIsTarget && left->NumPreds == 0;
2882 bool RIsFloater = RIsTarget && right->NumPreds == 0;
Roman Levensteinbc674502008-03-27 09:14:57 +00002883 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
2884 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
Evan Chengd38c22b2006-05-11 23:55:42 +00002885
2886 if (left->NumSuccs == 0 && right->NumSuccs != 0)
2887 return false;
2888 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
2889 return true;
2890
Evan Chengd38c22b2006-05-11 23:55:42 +00002891 if (LIsFloater)
2892 LBonus -= 2;
2893 if (RIsFloater)
2894 RBonus -= 2;
2895 if (left->NumSuccs == 1)
2896 LBonus += 2;
2897 if (right->NumSuccs == 1)
2898 RBonus += 2;
2899
Evan Cheng73bdf042008-03-01 00:39:47 +00002900 if (LPriority+LBonus != RPriority+RBonus)
2901 return LPriority+LBonus < RPriority+RBonus;
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00002902
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002903 if (left->getDepth() != right->getDepth())
2904 return left->getDepth() < right->getDepth();
Evan Cheng73bdf042008-03-01 00:39:47 +00002905
2906 if (left->NumSuccsLeft != right->NumSuccsLeft)
2907 return left->NumSuccsLeft > right->NumSuccsLeft;
2908
Andrew Trick2085a962010-12-21 22:25:04 +00002909 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002910 "NodeQueueId cannot be zero");
2911 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002912}
2913
Evan Chengd38c22b2006-05-11 23:55:42 +00002914//===----------------------------------------------------------------------===//
2915// Public Constructor Functions
2916//===----------------------------------------------------------------------===//
2917
Dan Gohmandfaf6462009-02-11 04:27:20 +00002918llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002919llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2920 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002921 const TargetMachine &TM = IS->TM;
2922 const TargetInstrInfo *TII = TM.getInstrInfo();
2923 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002924
Evan Chenga77f3d32010-07-21 06:09:07 +00002925 BURegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002926 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002927 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002928 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002929 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002930}
2931
Dan Gohmandfaf6462009-02-11 04:27:20 +00002932llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002933llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
2934 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002935 const TargetMachine &TM = IS->TM;
2936 const TargetInstrInfo *TII = TM.getInstrInfo();
2937 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002938
Evan Chenga77f3d32010-07-21 06:09:07 +00002939 TDRegReductionPriorityQueue *PQ =
2940 new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002941 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Dan Gohman3f656df2008-11-20 02:45:51 +00002942 PQ->setScheduleDAG(SD);
2943 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002944}
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002945
2946llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002947llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2948 CodeGenOpt::Level OptLevel) {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002949 const TargetMachine &TM = IS->TM;
2950 const TargetInstrInfo *TII = TM.getInstrInfo();
2951 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002952
Evan Chenga77f3d32010-07-21 06:09:07 +00002953 SrcRegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002954 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002955 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002956 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002957 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002958}
2959
2960llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002961llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2962 CodeGenOpt::Level OptLevel) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002963 const TargetMachine &TM = IS->TM;
2964 const TargetInstrInfo *TII = TM.getInstrInfo();
2965 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Evan Chenga77f3d32010-07-21 06:09:07 +00002966 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002967
Evan Chenga77f3d32010-07-21 06:09:07 +00002968 HybridBURRPriorityQueue *PQ =
Evan Chengdf907f42010-07-23 22:39:59 +00002969 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002970
2971 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002972 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002973 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002974}
Evan Cheng37b740c2010-07-24 00:39:05 +00002975
2976llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002977llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2978 CodeGenOpt::Level OptLevel) {
Evan Cheng37b740c2010-07-24 00:39:05 +00002979 const TargetMachine &TM = IS->TM;
2980 const TargetInstrInfo *TII = TM.getInstrInfo();
2981 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2982 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002983
Evan Cheng37b740c2010-07-24 00:39:05 +00002984 ILPBURRPriorityQueue *PQ =
2985 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002986 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00002987 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002988 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00002989}