blob: f44adfc2162115cc9428c23344e6e8297ecde493 [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
Bill Wendling8cbc25d2010-01-23 10:26:57 +000048 sourceListDAGScheduler("source",
49 "Similar to list-burr but schedules in source "
50 "order when possible",
51 createSourceListDAGScheduler);
Jim Laskey95eda5b2006-08-01 14:21:23 +000052
Evan Chengbdd062d2010-05-20 06:13:19 +000053static RegisterScheduler
Evan Cheng725211e2010-05-21 00:42:32 +000054 hybridListDAGScheduler("list-hybrid",
Evan Cheng37b740c2010-07-24 00:39:05 +000055 "Bottom-up register pressure aware list scheduling "
56 "which tries to balance latency and register pressure",
Evan Chengbdd062d2010-05-20 06:13:19 +000057 createHybridListDAGScheduler);
58
Evan Cheng37b740c2010-07-24 00:39:05 +000059static RegisterScheduler
60 ILPListDAGScheduler("list-ilp",
61 "Bottom-up register pressure aware list scheduling "
62 "which tries to balance ILP and register pressure",
63 createILPListDAGScheduler);
64
Andrew Trick47ff14b2011-01-21 05:51:33 +000065static cl::opt<bool> DisableSchedCycles(
Andrew Trickbd428ec2011-01-21 06:19:05 +000066 "disable-sched-cycles", cl::Hidden, cl::init(false),
Andrew Trick47ff14b2011-01-21 05:51:33 +000067 cl::desc("Disable cycle-level precision during preRA scheduling"));
Andrew Trick10ffc2b2010-12-24 05:03:26 +000068
Andrew Trick641e2d42011-03-05 08:00:22 +000069// Temporary sched=list-ilp flags until the heuristics are robust.
Andrew Trickbfbd9722011-04-14 05:15:06 +000070// Some options are also available under sched=list-hybrid.
Andrew Trick641e2d42011-03-05 08:00:22 +000071static cl::opt<bool> DisableSchedRegPressure(
72 "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
73 cl::desc("Disable regpressure priority in sched=list-ilp"));
74static cl::opt<bool> DisableSchedLiveUses(
Andrew Trickdd017322011-03-06 00:03:32 +000075 "disable-sched-live-uses", cl::Hidden, cl::init(true),
Andrew Trick641e2d42011-03-05 08:00:22 +000076 cl::desc("Disable live use priority in sched=list-ilp"));
Andrew Trick2ad0b372011-04-07 19:54:57 +000077static cl::opt<bool> DisableSchedVRegCycle(
78 "disable-sched-vrcycle", cl::Hidden, cl::init(false),
79 cl::desc("Disable virtual register cycle interference checks"));
Andrew Trickbfbd9722011-04-14 05:15:06 +000080static cl::opt<bool> DisableSchedPhysRegJoin(
81 "disable-sched-physreg-join", cl::Hidden, cl::init(false),
82 cl::desc("Disable physreg def-use affinity"));
Andrew Trick641e2d42011-03-05 08:00:22 +000083static cl::opt<bool> DisableSchedStalls(
Andrew Trickdd017322011-03-06 00:03:32 +000084 "disable-sched-stalls", cl::Hidden, cl::init(true),
Andrew Trick641e2d42011-03-05 08:00:22 +000085 cl::desc("Disable no-stall priority in sched=list-ilp"));
86static cl::opt<bool> DisableSchedCriticalPath(
87 "disable-sched-critical-path", cl::Hidden, cl::init(false),
88 cl::desc("Disable critical path priority in sched=list-ilp"));
89static cl::opt<bool> DisableSchedHeight(
90 "disable-sched-height", cl::Hidden, cl::init(false),
91 cl::desc("Disable scheduled-height priority in sched=list-ilp"));
Evan Chengd33b2d62011-11-10 07:43:16 +000092static cl::opt<bool> Disable2AddrHack(
93 "disable-2addr-hack", cl::Hidden, cl::init(true),
94 cl::desc("Disable scheduler's two-address hack"));
Andrew Trick641e2d42011-03-05 08:00:22 +000095
96static cl::opt<int> MaxReorderWindow(
97 "max-sched-reorder", cl::Hidden, cl::init(6),
98 cl::desc("Number of instructions to allow ahead of the critical path "
99 "in sched=list-ilp"));
100
101static cl::opt<unsigned> AvgIPC(
102 "sched-avg-ipc", cl::Hidden, cl::init(1),
103 cl::desc("Average inst/cycle whan no target itinerary exists."));
104
Evan Chengd38c22b2006-05-11 23:55:42 +0000105namespace {
Evan Chengd38c22b2006-05-11 23:55:42 +0000106//===----------------------------------------------------------------------===//
107/// ScheduleDAGRRList - The actual register reduction list scheduler
108/// implementation. This supports both top-down and bottom-up scheduling.
109///
Nick Lewycky02d5f772009-10-25 06:33:48 +0000110class ScheduleDAGRRList : public ScheduleDAGSDNodes {
Evan Chengd38c22b2006-05-11 23:55:42 +0000111private:
Evan Chengbdd062d2010-05-20 06:13:19 +0000112 /// NeedLatency - True if the scheduler will make use of latency information.
113 ///
114 bool NeedLatency;
115
Evan Chengd38c22b2006-05-11 23:55:42 +0000116 /// AvailableQueue - The priority queue to use for the available SUnits.
Evan Chengd38c22b2006-05-11 23:55:42 +0000117 SchedulingPriorityQueue *AvailableQueue;
118
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000119 /// PendingQueue - This contains all of the instructions whose operands have
120 /// been issued, but their results are not ready yet (due to the latency of
121 /// the operation). Once the operands becomes available, the instruction is
122 /// added to the AvailableQueue.
123 std::vector<SUnit*> PendingQueue;
124
125 /// HazardRec - The hazard recognizer to use.
126 ScheduleHazardRecognizer *HazardRec;
127
Andrew Trick528fad92010-12-23 05:42:20 +0000128 /// CurCycle - The current scheduler state corresponds to this cycle.
129 unsigned CurCycle;
130
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000131 /// MinAvailableCycle - Cycle of the soonest available instruction.
132 unsigned MinAvailableCycle;
133
Andrew Trick641e2d42011-03-05 08:00:22 +0000134 /// IssueCount - Count instructions issued in this cycle
135 /// Currently valid only for bottom-up scheduling.
136 unsigned IssueCount;
137
Dan Gohmanc07f6862008-09-23 18:50:48 +0000138 /// LiveRegDefs - A set of physical registers and their definition
Evan Cheng5924bf72007-09-25 01:54:36 +0000139 /// that are "live". These nodes must be scheduled before any other nodes that
140 /// modifies the registers can be scheduled.
Dan Gohmanc07f6862008-09-23 18:50:48 +0000141 unsigned NumLiveRegs;
Evan Cheng5924bf72007-09-25 01:54:36 +0000142 std::vector<SUnit*> LiveRegDefs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000143 std::vector<SUnit*> LiveRegGens;
Evan Cheng5924bf72007-09-25 01:54:36 +0000144
Dan Gohmanad2134d2008-11-25 00:52:40 +0000145 /// Topo - A topological ordering for SUnits which permits fast IsReachable
146 /// and similar queries.
147 ScheduleDAGTopologicalSort Topo;
148
Eli Friedmand5c173f2011-12-07 22:24:28 +0000149 // Hack to keep track of the inverse of FindCallSeqStart without more crazy
150 // DAG crawling.
151 DenseMap<SUnit*, SUnit*> CallSeqEndForStart;
152
Evan Chengd38c22b2006-05-11 23:55:42 +0000153public:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000154 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
155 SchedulingPriorityQueue *availqueue,
156 CodeGenOpt::Level OptLevel)
Dan Gohman90fb5522011-10-20 21:44:34 +0000157 : ScheduleDAGSDNodes(mf),
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000158 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
159 Topo(SUnits) {
160
161 const TargetMachine &tm = mf.getTarget();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000162 if (DisableSchedCycles || !NeedLatency)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000163 HazardRec = new ScheduleHazardRecognizer();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000164 else
165 HazardRec = tm.getInstrInfo()->CreateTargetHazardRecognizer(&tm, this);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000166 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000167
168 ~ScheduleDAGRRList() {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000169 delete HazardRec;
Evan Chengd38c22b2006-05-11 23:55:42 +0000170 delete AvailableQueue;
171 }
172
173 void Schedule();
174
Andrew Trick9ccce772011-01-14 21:11:41 +0000175 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
176
Roman Levenstein733a4d62008-03-26 11:23:38 +0000177 /// IsReachable - Checks if SU is reachable from TargetSU.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000178 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
179 return Topo.IsReachable(SU, TargetSU);
180 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000181
Dan Gohman60d68442009-01-29 19:49:27 +0000182 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000183 /// create a cycle.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000184 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
185 return Topo.WillCreateCycle(SU, TargetSU);
186 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000187
Dan Gohman2d170892008-12-09 22:54:47 +0000188 /// AddPred - adds a predecessor edge to SUnit SU.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000189 /// This returns true if this is a new predecessor.
190 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000191 void AddPred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000192 Topo.AddPred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000193 SU->addPred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000194 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000195
Dan Gohman2d170892008-12-09 22:54:47 +0000196 /// RemovePred - removes a predecessor edge from SUnit SU.
197 /// This returns true if an edge was removed.
198 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000199 void RemovePred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000200 Topo.RemovePred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000201 SU->removePred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000202 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000203
Evan Chengd38c22b2006-05-11 23:55:42 +0000204private:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000205 bool isReady(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000206 return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000207 AvailableQueue->isReady(SU);
208 }
209
Dan Gohman60d68442009-01-29 19:49:27 +0000210 void ReleasePred(SUnit *SU, const SDep *PredEdge);
Andrew Tricka52f3252010-12-23 04:16:14 +0000211 void ReleasePredecessors(SUnit *SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000212 void ReleasePending();
213 void AdvanceToCycle(unsigned NextCycle);
214 void AdvancePastStalls(SUnit *SU);
215 void EmitNode(SUnit *SU);
Andrew Trick528fad92010-12-23 05:42:20 +0000216 void ScheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000217 void CapturePred(SDep *PredEdge);
Evan Cheng8e136a92007-09-26 21:36:17 +0000218 void UnscheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000219 void RestoreHazardCheckerBottomUp();
220 void BacktrackBottomUp(SUnit*, SUnit*);
Evan Cheng8e136a92007-09-26 21:36:17 +0000221 SUnit *CopyAndMoveSuccessors(SUnit*);
Evan Chengb2c42c62009-01-12 03:19:55 +0000222 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
223 const TargetRegisterClass*,
224 const TargetRegisterClass*,
225 SmallVector<SUnit*, 2>&);
Evan Cheng1ec79b42007-09-27 07:09:03 +0000226 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000227
Andrew Trick528fad92010-12-23 05:42:20 +0000228 SUnit *PickNodeToScheduleBottomUp();
Evan Chengd38c22b2006-05-11 23:55:42 +0000229 void ListScheduleBottomUp();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000230
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000231 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000232 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000233 SUnit *CreateNewSUnit(SDNode *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000234 unsigned NumSUnits = SUnits.size();
Andrew Trick52226d42012-03-07 23:00:49 +0000235 SUnit *NewNode = newSUnit(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000236 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000237 if (NewNode->NodeNum >= NumSUnits)
238 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000239 return NewNode;
240 }
241
Roman Levenstein733a4d62008-03-26 11:23:38 +0000242 /// CreateClone - Creates a new SUnit from an existing one.
243 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000244 SUnit *CreateClone(SUnit *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000245 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000246 SUnit *NewNode = Clone(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000247 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000248 if (NewNode->NodeNum >= NumSUnits)
249 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000250 return NewNode;
251 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000252
Andrew Trick52226d42012-03-07 23:00:49 +0000253 /// forceUnitLatencies - Register-pressure-reducing scheduling doesn't
Evan Chengbdd062d2010-05-20 06:13:19 +0000254 /// need actual latency information but the hybrid scheduler does.
Andrew Trick52226d42012-03-07 23:00:49 +0000255 bool forceUnitLatencies() const {
Evan Chengbdd062d2010-05-20 06:13:19 +0000256 return !NeedLatency;
257 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000258};
259} // end anonymous namespace
260
Owen Anderson96adc4a2011-06-15 23:35:18 +0000261/// GetCostForDef - Looks up the register class and cost for a given definition.
262/// Typically this just means looking up the representative register class,
Owen Andersonca2f78a2011-11-16 01:02:57 +0000263/// but for untyped values (MVT::Untyped) it means inspecting the node's
Owen Anderson96adc4a2011-06-15 23:35:18 +0000264/// opcode to determine what register class is being generated.
265static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos,
266 const TargetLowering *TLI,
267 const TargetInstrInfo *TII,
268 const TargetRegisterInfo *TRI,
269 unsigned &RegClass, unsigned &Cost) {
270 EVT VT = RegDefPos.GetValue();
271
272 // Special handling for untyped values. These values can only come from
273 // the expansion of custom DAG-to-DAG patterns.
Owen Andersonca2f78a2011-11-16 01:02:57 +0000274 if (VT == MVT::Untyped) {
Owen Andersond1955e72011-06-21 22:54:23 +0000275 const SDNode *Node = RegDefPos.GetNode();
276 unsigned Opcode = Node->getMachineOpcode();
277
278 if (Opcode == TargetOpcode::REG_SEQUENCE) {
279 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
280 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
281 RegClass = RC->getID();
282 Cost = 1;
283 return;
284 }
285
Owen Anderson96adc4a2011-06-15 23:35:18 +0000286 unsigned Idx = RegDefPos.GetIdx();
Evan Cheng6cc775f2011-06-28 19:10:37 +0000287 const MCInstrDesc Desc = TII->get(Opcode);
Evan Cheng8d71a752011-06-27 21:26:13 +0000288 const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx, TRI);
Owen Anderson96adc4a2011-06-15 23:35:18 +0000289 RegClass = RC->getID();
290 // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
291 // better way to determine it.
292 Cost = 1;
293 } else {
294 RegClass = TLI->getRepRegClassFor(VT)->getID();
295 Cost = TLI->getRepRegClassCostFor(VT);
296 }
297}
Evan Chengd38c22b2006-05-11 23:55:42 +0000298
299/// Schedule - Schedule the DAG using list scheduling.
300void ScheduleDAGRRList::Schedule() {
Evan Chenga77f3d32010-07-21 06:09:07 +0000301 DEBUG(dbgs()
302 << "********** List Scheduling BB#" << BB->getNumber()
Evan Cheng6c1414f2010-10-29 18:09:28 +0000303 << " '" << BB->getName() << "' **********\n");
Evan Cheng5924bf72007-09-25 01:54:36 +0000304
Andrew Trick528fad92010-12-23 05:42:20 +0000305 CurCycle = 0;
Andrew Trick641e2d42011-03-05 08:00:22 +0000306 IssueCount = 0;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000307 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
Dan Gohmanc07f6862008-09-23 18:50:48 +0000308 NumLiveRegs = 0;
Dan Gohman198b7ff2011-11-03 21:49:52 +0000309 // Allocate slots for each physical register, plus one for a special register
310 // to track the virtual resource of a calling sequence.
311 LiveRegDefs.resize(TRI->getNumRegs() + 1, NULL);
312 LiveRegGens.resize(TRI->getNumRegs() + 1, NULL);
Eli Friedmand5c173f2011-12-07 22:24:28 +0000313 CallSeqEndForStart.clear();
Evan Cheng5924bf72007-09-25 01:54:36 +0000314
Dan Gohman04543e72008-12-23 18:36:58 +0000315 // Build the scheduling graph.
Dan Gohman918ec532009-10-09 23:33:48 +0000316 BuildSchedGraph(NULL);
Evan Chengd38c22b2006-05-11 23:55:42 +0000317
Evan Chengd38c22b2006-05-11 23:55:42 +0000318 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Dan Gohman22d07b12008-11-18 02:06:40 +0000319 SUnits[su].dumpAll(this));
Dan Gohmanad2134d2008-11-25 00:52:40 +0000320 Topo.InitDAGTopologicalSorting();
Evan Chengd38c22b2006-05-11 23:55:42 +0000321
Dan Gohman46520a22008-06-21 19:18:17 +0000322 AvailableQueue->initNodes(SUnits);
Andrew Trick2085a962010-12-21 22:25:04 +0000323
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000324 HazardRec->Reset();
325
Dan Gohman90fb5522011-10-20 21:44:34 +0000326 // Execute the actual scheduling loop.
327 ListScheduleBottomUp();
Andrew Trick2085a962010-12-21 22:25:04 +0000328
Evan Chengd38c22b2006-05-11 23:55:42 +0000329 AvailableQueue->releaseState();
Andrew Trickedee68c2012-03-07 05:21:40 +0000330
331 DEBUG({
332 dbgs() << "*** Final schedule ***\n";
333 dumpSchedule();
334 dbgs() << '\n';
335 });
Evan Chengafed73e2006-05-12 01:58:24 +0000336}
Evan Chengd38c22b2006-05-11 23:55:42 +0000337
338//===----------------------------------------------------------------------===//
339// Bottom-Up Scheduling
340//===----------------------------------------------------------------------===//
341
Evan Chengd38c22b2006-05-11 23:55:42 +0000342/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000343/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +0000344void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000345 SUnit *PredSU = PredEdge->getSUnit();
Reid Klecknercea8dab2009-09-30 20:43:07 +0000346
Evan Chengd38c22b2006-05-11 23:55:42 +0000347#ifndef NDEBUG
Reid Klecknercea8dab2009-09-30 20:43:07 +0000348 if (PredSU->NumSuccsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +0000349 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +0000350 PredSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +0000351 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +0000352 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +0000353 }
354#endif
Reid Klecknercea8dab2009-09-30 20:43:07 +0000355 --PredSU->NumSuccsLeft;
356
Andrew Trick52226d42012-03-07 23:00:49 +0000357 if (!forceUnitLatencies()) {
Evan Chengbdd062d2010-05-20 06:13:19 +0000358 // Updating predecessor's height. This is now the cycle when the
359 // predecessor can be scheduled without causing a pipeline stall.
360 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
361 }
362
Dan Gohmanb9543432009-02-10 23:27:53 +0000363 // If all the node's successors are scheduled, this node is ready
364 // to be scheduled. Ignore the special EntrySU node.
365 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
Dan Gohman4370f262008-04-15 01:22:18 +0000366 PredSU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000367
368 unsigned Height = PredSU->getHeight();
369 if (Height < MinAvailableCycle)
370 MinAvailableCycle = Height;
371
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000372 if (isReady(PredSU)) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000373 AvailableQueue->push(PredSU);
374 }
375 // CapturePred and others may have left the node in the pending queue, avoid
376 // adding it twice.
377 else if (!PredSU->isPending) {
378 PredSU->isPending = true;
379 PendingQueue.push_back(PredSU);
380 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000381 }
382}
383
Dan Gohman198b7ff2011-11-03 21:49:52 +0000384/// IsChainDependent - Test if Outer is reachable from Inner through
385/// chain dependencies.
386static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
387 unsigned NestLevel,
388 const TargetInstrInfo *TII) {
389 SDNode *N = Outer;
390 for (;;) {
391 if (N == Inner)
392 return true;
393 // For a TokenFactor, examine each operand. There may be multiple ways
394 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
395 // most nesting in order to ensure that we find the corresponding match.
396 if (N->getOpcode() == ISD::TokenFactor) {
397 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
398 if (IsChainDependent(N->getOperand(i).getNode(), Inner, NestLevel, TII))
399 return true;
400 return false;
401 }
402 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
403 if (N->isMachineOpcode()) {
404 if (N->getMachineOpcode() ==
405 (unsigned)TII->getCallFrameDestroyOpcode()) {
406 ++NestLevel;
407 } else if (N->getMachineOpcode() ==
408 (unsigned)TII->getCallFrameSetupOpcode()) {
409 if (NestLevel == 0)
410 return false;
411 --NestLevel;
412 }
413 }
414 // Otherwise, find the chain and continue climbing.
415 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
416 if (N->getOperand(i).getValueType() == MVT::Other) {
417 N = N->getOperand(i).getNode();
418 goto found_chain_operand;
419 }
420 return false;
421 found_chain_operand:;
422 if (N->getOpcode() == ISD::EntryToken)
423 return false;
424 }
425}
426
427/// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
428/// the corresponding (lowered) CALLSEQ_BEGIN node.
429///
430/// NestLevel and MaxNested are used in recursion to indcate the current level
431/// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
432/// level seen so far.
433///
434/// TODO: It would be better to give CALLSEQ_END an explicit operand to point
435/// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
436static SDNode *
437FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
438 const TargetInstrInfo *TII) {
439 for (;;) {
440 // For a TokenFactor, examine each operand. There may be multiple ways
441 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
442 // most nesting in order to ensure that we find the corresponding match.
443 if (N->getOpcode() == ISD::TokenFactor) {
444 SDNode *Best = 0;
445 unsigned BestMaxNest = MaxNest;
446 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
447 unsigned MyNestLevel = NestLevel;
448 unsigned MyMaxNest = MaxNest;
449 if (SDNode *New = FindCallSeqStart(N->getOperand(i).getNode(),
450 MyNestLevel, MyMaxNest, TII))
451 if (!Best || (MyMaxNest > BestMaxNest)) {
452 Best = New;
453 BestMaxNest = MyMaxNest;
454 }
455 }
456 assert(Best);
457 MaxNest = BestMaxNest;
458 return Best;
459 }
460 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
461 if (N->isMachineOpcode()) {
462 if (N->getMachineOpcode() ==
463 (unsigned)TII->getCallFrameDestroyOpcode()) {
464 ++NestLevel;
465 MaxNest = std::max(MaxNest, NestLevel);
466 } else if (N->getMachineOpcode() ==
467 (unsigned)TII->getCallFrameSetupOpcode()) {
468 assert(NestLevel != 0);
469 --NestLevel;
470 if (NestLevel == 0)
471 return N;
472 }
473 }
474 // Otherwise, find the chain and continue climbing.
475 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
476 if (N->getOperand(i).getValueType() == MVT::Other) {
477 N = N->getOperand(i).getNode();
478 goto found_chain_operand;
479 }
480 return 0;
481 found_chain_operand:;
482 if (N->getOpcode() == ISD::EntryToken)
483 return 0;
484 }
485}
486
Andrew Trick033efdf2010-12-23 03:15:51 +0000487/// Call ReleasePred for each predecessor, then update register live def/gen.
488/// Always update LiveRegDefs for a register dependence even if the current SU
489/// also defines the register. This effectively create one large live range
490/// across a sequence of two-address node. This is important because the
491/// entire chain must be scheduled together. Example:
492///
493/// flags = (3) add
494/// flags = (2) addc flags
495/// flags = (1) addc flags
496///
497/// results in
498///
499/// LiveRegDefs[flags] = 3
Andrew Tricka52f3252010-12-23 04:16:14 +0000500/// LiveRegGens[flags] = 1
Andrew Trick033efdf2010-12-23 03:15:51 +0000501///
502/// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
503/// interference on flags.
Andrew Tricka52f3252010-12-23 04:16:14 +0000504void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000505 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000506 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000507 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000508 ReleasePred(SU, &*I);
509 if (I->isAssignedRegDep()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000510 // This is a physical register dependency and it's impossible or
Andrew Trick2085a962010-12-21 22:25:04 +0000511 // expensive to copy the register. Make sure nothing that can
Evan Cheng5924bf72007-09-25 01:54:36 +0000512 // clobber the register is scheduled between the predecessor and
513 // this node.
Andrew Tricka52f3252010-12-23 04:16:14 +0000514 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
Andrew Trick033efdf2010-12-23 03:15:51 +0000515 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
516 "interference on register dependence");
Andrew Tricka52f3252010-12-23 04:16:14 +0000517 LiveRegDefs[I->getReg()] = I->getSUnit();
518 if (!LiveRegGens[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000519 ++NumLiveRegs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000520 LiveRegGens[I->getReg()] = SU;
Evan Cheng5924bf72007-09-25 01:54:36 +0000521 }
522 }
523 }
Dan Gohman198b7ff2011-11-03 21:49:52 +0000524
525 // If we're scheduling a lowered CALLSEQ_END, find the corresponding
526 // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
527 // these nodes, to prevent other calls from being interscheduled with them.
528 unsigned CallResource = TRI->getNumRegs();
529 if (!LiveRegDefs[CallResource])
530 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
531 if (Node->isMachineOpcode() &&
532 Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
533 unsigned NestLevel = 0;
534 unsigned MaxNest = 0;
535 SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
536
537 SUnit *Def = &SUnits[N->getNodeId()];
Eli Friedmand5c173f2011-12-07 22:24:28 +0000538 CallSeqEndForStart[Def] = SU;
539
Dan Gohman198b7ff2011-11-03 21:49:52 +0000540 ++NumLiveRegs;
541 LiveRegDefs[CallResource] = Def;
542 LiveRegGens[CallResource] = SU;
543 break;
544 }
Dan Gohmanb9543432009-02-10 23:27:53 +0000545}
546
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000547/// Check to see if any of the pending instructions are ready to issue. If
548/// so, add them to the available queue.
549void ScheduleDAGRRList::ReleasePending() {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000550 if (DisableSchedCycles) {
Andrew Trick5ce945c2010-12-24 07:10:19 +0000551 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
552 return;
553 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000554
555 // If the available queue is empty, it is safe to reset MinAvailableCycle.
556 if (AvailableQueue->empty())
557 MinAvailableCycle = UINT_MAX;
558
559 // Check to see if any of the pending instructions are ready to issue. If
560 // so, add them to the available queue.
561 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman90fb5522011-10-20 21:44:34 +0000562 unsigned ReadyCycle = PendingQueue[i]->getHeight();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000563 if (ReadyCycle < MinAvailableCycle)
564 MinAvailableCycle = ReadyCycle;
565
566 if (PendingQueue[i]->isAvailable) {
567 if (!isReady(PendingQueue[i]))
568 continue;
569 AvailableQueue->push(PendingQueue[i]);
570 }
571 PendingQueue[i]->isPending = false;
572 PendingQueue[i] = PendingQueue.back();
573 PendingQueue.pop_back();
574 --i; --e;
575 }
576}
577
578/// Move the scheduler state forward by the specified number of Cycles.
579void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
580 if (NextCycle <= CurCycle)
581 return;
582
Andrew Trick641e2d42011-03-05 08:00:22 +0000583 IssueCount = 0;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000584 AvailableQueue->setCurCycle(NextCycle);
Andrew Trick47ff14b2011-01-21 05:51:33 +0000585 if (!HazardRec->isEnabled()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000586 // Bypass lots of virtual calls in case of long latency.
587 CurCycle = NextCycle;
588 }
589 else {
590 for (; CurCycle != NextCycle; ++CurCycle) {
Dan Gohman90fb5522011-10-20 21:44:34 +0000591 HazardRec->RecedeCycle();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000592 }
593 }
594 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
595 // available Q to release pending nodes at least once before popping.
596 ReleasePending();
597}
598
599/// Move the scheduler state forward until the specified node's dependents are
600/// ready and can be scheduled with no resource conflicts.
601void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000602 if (DisableSchedCycles)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000603 return;
604
Andrew Trickb53a00d2011-04-13 00:38:32 +0000605 // FIXME: Nodes such as CopyFromReg probably should not advance the current
606 // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
607 // has predecessors the cycle will be advanced when they are scheduled.
608 // But given the crude nature of modeling latency though such nodes, we
609 // currently need to treat these nodes like real instructions.
610 // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
611
Dan Gohman90fb5522011-10-20 21:44:34 +0000612 unsigned ReadyCycle = SU->getHeight();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000613
614 // Bump CurCycle to account for latency. We assume the latency of other
615 // available instructions may be hidden by the stall (not a full pipe stall).
616 // This updates the hazard recognizer's cycle before reserving resources for
617 // this instruction.
618 AdvanceToCycle(ReadyCycle);
619
620 // Calls are scheduled in their preceding cycle, so don't conflict with
621 // hazards from instructions after the call. EmitNode will reset the
622 // scoreboard state before emitting the call.
Dan Gohman90fb5522011-10-20 21:44:34 +0000623 if (SU->isCall)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000624 return;
625
626 // FIXME: For resource conflicts in very long non-pipelined stages, we
627 // should probably skip ahead here to avoid useless scoreboard checks.
628 int Stalls = 0;
629 while (true) {
630 ScheduleHazardRecognizer::HazardType HT =
Dan Gohman90fb5522011-10-20 21:44:34 +0000631 HazardRec->getHazardType(SU, -Stalls);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000632
633 if (HT == ScheduleHazardRecognizer::NoHazard)
634 break;
635
636 ++Stalls;
637 }
638 AdvanceToCycle(CurCycle + Stalls);
639}
640
641/// Record this SUnit in the HazardRecognizer.
642/// Does not update CurCycle.
643void ScheduleDAGRRList::EmitNode(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000644 if (!HazardRec->isEnabled())
Andrew Trickc9405662010-12-24 06:46:50 +0000645 return;
646
647 // Check for phys reg copy.
648 if (!SU->getNode())
649 return;
650
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000651 switch (SU->getNode()->getOpcode()) {
652 default:
653 assert(SU->getNode()->isMachineOpcode() &&
654 "This target-independent node should not be scheduled.");
655 break;
656 case ISD::MERGE_VALUES:
657 case ISD::TokenFactor:
658 case ISD::CopyToReg:
659 case ISD::CopyFromReg:
660 case ISD::EH_LABEL:
661 // Noops don't affect the scoreboard state. Copies are likely to be
662 // removed.
663 return;
664 case ISD::INLINEASM:
665 // For inline asm, clear the pipeline state.
666 HazardRec->Reset();
667 return;
668 }
Dan Gohman90fb5522011-10-20 21:44:34 +0000669 if (SU->isCall) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000670 // Calls are scheduled with their preceding instructions. For bottom-up
671 // scheduling, clear the pipeline state before emitting.
672 HazardRec->Reset();
673 }
674
675 HazardRec->EmitInstruction(SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000676}
677
Andrew Trickb53a00d2011-04-13 00:38:32 +0000678static void resetVRegCycle(SUnit *SU);
679
Dan Gohmanb9543432009-02-10 23:27:53 +0000680/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
681/// count of its predecessors. If a predecessor pending count is zero, add it to
682/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000683void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Andrew Trick1b60ad62011-04-12 20:14:07 +0000684 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000685 DEBUG(SU->dump(this));
686
Evan Chengbdd062d2010-05-20 06:13:19 +0000687#ifndef NDEBUG
688 if (CurCycle < SU->getHeight())
Andrew Trickb53a00d2011-04-13 00:38:32 +0000689 DEBUG(dbgs() << " Height [" << SU->getHeight()
690 << "] pipeline stall!\n");
Evan Chengbdd062d2010-05-20 06:13:19 +0000691#endif
692
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000693 // FIXME: Do not modify node height. It may interfere with
694 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
Eric Christopher1b4b1e52011-03-21 18:06:21 +0000695 // node its ready cycle can aid heuristics, and after scheduling it can
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000696 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000697 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000698
699 // Reserve resources for the scheduled intruction.
700 EmitNode(SU);
701
Dan Gohmanb9543432009-02-10 23:27:53 +0000702 Sequence.push_back(SU);
703
Andrew Trick52226d42012-03-07 23:00:49 +0000704 AvailableQueue->scheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000705
Andrew Trick641e2d42011-03-05 08:00:22 +0000706 // If HazardRec is disabled, and each inst counts as one cycle, then
Andrew Trickb53a00d2011-04-13 00:38:32 +0000707 // advance CurCycle before ReleasePredecessors to avoid useless pushes to
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000708 // PendingQueue for schedulers that implement HasReadyFilter.
Andrew Trick641e2d42011-03-05 08:00:22 +0000709 if (!HazardRec->isEnabled() && AvgIPC < 2)
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000710 AdvanceToCycle(CurCycle + 1);
711
Andrew Trick033efdf2010-12-23 03:15:51 +0000712 // Update liveness of predecessors before successors to avoid treating a
713 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000714 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000715
716 // Release all the implicit physical register defs that are live.
717 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
718 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000719 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
720 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
721 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
722 --NumLiveRegs;
723 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000724 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000725 }
726 }
Dan Gohman198b7ff2011-11-03 21:49:52 +0000727 // Release the special call resource dependence, if this is the beginning
728 // of a call.
729 unsigned CallResource = TRI->getNumRegs();
730 if (LiveRegDefs[CallResource] == SU)
731 for (const SDNode *SUNode = SU->getNode(); SUNode;
732 SUNode = SUNode->getGluedNode()) {
733 if (SUNode->isMachineOpcode() &&
734 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
735 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
736 --NumLiveRegs;
737 LiveRegDefs[CallResource] = NULL;
738 LiveRegGens[CallResource] = NULL;
739 }
740 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000741
Andrew Trickb53a00d2011-04-13 00:38:32 +0000742 resetVRegCycle(SU);
743
Evan Chengd38c22b2006-05-11 23:55:42 +0000744 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000745
746 // Conditions under which the scheduler should eagerly advance the cycle:
747 // (1) No available instructions
748 // (2) All pipelines full, so available instructions must have hazards.
749 //
Andrew Trickb53a00d2011-04-13 00:38:32 +0000750 // If HazardRec is disabled, the cycle was pre-advanced before calling
751 // ReleasePredecessors. In that case, IssueCount should remain 0.
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000752 //
753 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
Andrew Trickb53a00d2011-04-13 00:38:32 +0000754 if (HazardRec->isEnabled() || AvgIPC > 1) {
755 if (SU->getNode() && SU->getNode()->isMachineOpcode())
756 ++IssueCount;
757 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
758 || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
759 AdvanceToCycle(CurCycle + 1);
760 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000761}
762
Evan Cheng5924bf72007-09-25 01:54:36 +0000763/// CapturePred - This does the opposite of ReleasePred. Since SU is being
764/// unscheduled, incrcease the succ left count of its predecessors. Remove
765/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000766void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000767 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000768 if (PredSU->isAvailable) {
769 PredSU->isAvailable = false;
770 if (!PredSU->isPending)
771 AvailableQueue->remove(PredSU);
772 }
773
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000774 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000775 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000776}
777
778/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
779/// its predecessor states to reflect the change.
780void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000781 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000782 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000783
Evan Cheng5924bf72007-09-25 01:54:36 +0000784 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
785 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000786 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000787 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000788 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000789 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000790 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000791 --NumLiveRegs;
Dan Gohman2d170892008-12-09 22:54:47 +0000792 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000793 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000794 }
795 }
796
Dan Gohman198b7ff2011-11-03 21:49:52 +0000797 // Reclaim the special call resource dependence, if this is the beginning
798 // of a call.
799 unsigned CallResource = TRI->getNumRegs();
800 for (const SDNode *SUNode = SU->getNode(); SUNode;
801 SUNode = SUNode->getGluedNode()) {
802 if (SUNode->isMachineOpcode() &&
803 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
804 ++NumLiveRegs;
805 LiveRegDefs[CallResource] = SU;
Eli Friedmand5c173f2011-12-07 22:24:28 +0000806 LiveRegGens[CallResource] = CallSeqEndForStart[SU];
Dan Gohman198b7ff2011-11-03 21:49:52 +0000807 }
808 }
809
810 // Release the special call resource dependence, if this is the end
811 // of a call.
812 if (LiveRegGens[CallResource] == SU)
813 for (const SDNode *SUNode = SU->getNode(); SUNode;
814 SUNode = SUNode->getGluedNode()) {
815 if (SUNode->isMachineOpcode() &&
816 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
817 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
818 --NumLiveRegs;
819 LiveRegDefs[CallResource] = NULL;
820 LiveRegGens[CallResource] = NULL;
821 }
822 }
823
Evan Cheng5924bf72007-09-25 01:54:36 +0000824 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
825 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000826 if (I->isAssignedRegDep()) {
Eli Friedman0bdc0832011-12-07 22:06:02 +0000827 if (!LiveRegDefs[I->getReg()])
828 ++NumLiveRegs;
Andrew Trick033efdf2010-12-23 03:15:51 +0000829 // This becomes the nearest def. Note that an earlier def may still be
830 // pending if this is a two-address node.
831 LiveRegDefs[I->getReg()] = SU;
Andrew Tricka52f3252010-12-23 04:16:14 +0000832 if (LiveRegGens[I->getReg()] == NULL ||
833 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
834 LiveRegGens[I->getReg()] = I->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000835 }
836 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000837 if (SU->getHeight() < MinAvailableCycle)
838 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000839
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000840 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000841 SU->isScheduled = false;
842 SU->isAvailable = true;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000843 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000844 // Don't make available until backtracking is complete.
845 SU->isPending = true;
846 PendingQueue.push_back(SU);
847 }
848 else {
849 AvailableQueue->push(SU);
850 }
Andrew Trick52226d42012-03-07 23:00:49 +0000851 AvailableQueue->unscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000852}
853
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000854/// After backtracking, the hazard checker needs to be restored to a state
855/// corresponding the the current cycle.
856void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
857 HazardRec->Reset();
858
859 unsigned LookAhead = std::min((unsigned)Sequence.size(),
860 HazardRec->getMaxLookAhead());
861 if (LookAhead == 0)
862 return;
863
864 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
865 unsigned HazardCycle = (*I)->getHeight();
866 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
867 SUnit *SU = *I;
868 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
869 HazardRec->RecedeCycle();
870 }
871 EmitNode(SU);
872 }
873}
874
Evan Cheng8e136a92007-09-26 21:36:17 +0000875/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000876/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000877void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
878 SUnit *OldSU = Sequence.back();
879 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000880 Sequence.pop_back();
881 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000882 // Don't try to remove SU from AvailableQueue.
883 SU->isAvailable = false;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000884 // FIXME: use ready cycle instead of height
885 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000886 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000887 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000888 if (OldSU == BtSU)
889 break;
890 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000891 }
892
Dan Gohman60d68442009-01-29 19:49:27 +0000893 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000894
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000895 RestoreHazardCheckerBottomUp();
896
Andrew Trick5ce945c2010-12-24 07:10:19 +0000897 ReleasePending();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000898
Evan Cheng1ec79b42007-09-27 07:09:03 +0000899 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000900}
901
Evan Cheng3b245872010-02-05 01:27:11 +0000902static bool isOperandOf(const SUnit *SU, SDNode *N) {
903 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000904 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000905 if (SUNode->isOperandOf(N))
906 return true;
907 }
908 return false;
909}
910
Evan Cheng5924bf72007-09-25 01:54:36 +0000911/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
912/// successors to the newly created node.
913SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000914 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000915 if (!N)
916 return NULL;
917
Andrew Trickc9405662010-12-24 06:46:50 +0000918 if (SU->getNode()->getGluedNode())
919 return NULL;
920
Evan Cheng79e97132007-10-05 01:39:18 +0000921 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000922 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000923 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000924 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000925 if (VT == MVT::Glue)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000926 return NULL;
Owen Anderson9f944592009-08-11 20:47:22 +0000927 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000928 TryUnfold = true;
929 }
Evan Cheng79e97132007-10-05 01:39:18 +0000930 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000931 const SDValue &Op = N->getOperand(i);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000932 EVT VT = Op.getNode()->getValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000933 if (VT == MVT::Glue)
Evan Cheng79e97132007-10-05 01:39:18 +0000934 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000935 }
936
937 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000938 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000939 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000940 return NULL;
941
Pete Cooper7c7ba1b2011-11-15 21:57:53 +0000942 // unfolding an x86 DEC64m operation results in store, dec, load which
943 // can't be handled here so quit
944 if (NewNodes.size() == 3)
945 return NULL;
946
Evan Chengbdd062d2010-05-20 06:13:19 +0000947 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000948 assert(NewNodes.size() == 2 && "Expected a load folding node!");
949
950 N = NewNodes[1];
951 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000952 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000953 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000954 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000955 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
956 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000957 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000958
Dan Gohmane52e0892008-11-11 21:34:44 +0000959 // LoadNode may already exist. This can happen when there is another
960 // load from the same location and producing the same type of value
961 // but it has different alignment or volatileness.
962 bool isNewLoad = true;
963 SUnit *LoadSU;
964 if (LoadNode->getNodeId() != -1) {
965 LoadSU = &SUnits[LoadNode->getNodeId()];
966 isNewLoad = false;
967 } else {
968 LoadSU = CreateNewSUnit(LoadNode);
969 LoadNode->setNodeId(LoadSU->NodeNum);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000970
971 InitNumRegDefsLeft(LoadSU);
Andrew Trick52226d42012-03-07 23:00:49 +0000972 computeLatency(LoadSU);
Dan Gohmane52e0892008-11-11 21:34:44 +0000973 }
974
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000975 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000976 assert(N->getNodeId() == -1 && "Node already inserted!");
977 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +0000978
Evan Cheng6cc775f2011-06-28 19:10:37 +0000979 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
980 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
981 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000982 NewSU->isTwoAddress = true;
983 break;
984 }
985 }
Evan Cheng6cc775f2011-06-28 19:10:37 +0000986 if (MCID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000987 NewSU->isCommutable = true;
Andrew Trickd0548ae2011-02-04 03:18:17 +0000988
989 InitNumRegDefsLeft(NewSU);
Andrew Trick52226d42012-03-07 23:00:49 +0000990 computeLatency(NewSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000991
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000992 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +0000993 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +0000994 SmallVector<SDep, 4> ChainSuccs;
995 SmallVector<SDep, 4> LoadPreds;
996 SmallVector<SDep, 4> NodePreds;
997 SmallVector<SDep, 4> NodeSuccs;
998 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
999 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001000 if (I->isCtrl())
Dan Gohman15af5522009-03-06 02:23:01 +00001001 ChainPreds.push_back(*I);
Evan Cheng3b245872010-02-05 01:27:11 +00001002 else if (isOperandOf(I->getSUnit(), LoadNode))
Dan Gohman2d170892008-12-09 22:54:47 +00001003 LoadPreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +00001004 else
Dan Gohman2d170892008-12-09 22:54:47 +00001005 NodePreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +00001006 }
1007 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1008 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001009 if (I->isCtrl())
1010 ChainSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +00001011 else
Dan Gohman2d170892008-12-09 22:54:47 +00001012 NodeSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +00001013 }
1014
Dan Gohmaned0e8d42009-03-23 20:20:43 +00001015 // Now assign edges to the newly-created nodes.
Dan Gohman15af5522009-03-06 02:23:01 +00001016 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
1017 const SDep &Pred = ChainPreds[i];
1018 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +00001019 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +00001020 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001021 }
Evan Cheng79e97132007-10-05 01:39:18 +00001022 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +00001023 const SDep &Pred = LoadPreds[i];
1024 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +00001025 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +00001026 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +00001027 }
1028 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +00001029 const SDep &Pred = NodePreds[i];
1030 RemovePred(SU, Pred);
1031 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +00001032 }
1033 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +00001034 SDep D = NodeSuccs[i];
1035 SUnit *SuccDep = D.getSUnit();
1036 D.setSUnit(SU);
1037 RemovePred(SuccDep, D);
1038 D.setSUnit(NewSU);
1039 AddPred(SuccDep, D);
Andrew Trickd0548ae2011-02-04 03:18:17 +00001040 // Balance register pressure.
1041 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
1042 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
1043 --NewSU->NumRegDefsLeft;
Evan Cheng79e97132007-10-05 01:39:18 +00001044 }
1045 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +00001046 SDep D = ChainSuccs[i];
1047 SUnit *SuccDep = D.getSUnit();
1048 D.setSUnit(SU);
1049 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001050 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +00001051 D.setSUnit(LoadSU);
1052 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001053 }
Andrew Trick2085a962010-12-21 22:25:04 +00001054 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +00001055
1056 // Add a data dependency to reflect that NewSU reads the value defined
1057 // by LoadSU.
1058 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
Evan Cheng79e97132007-10-05 01:39:18 +00001059
Evan Cheng91e0fc92007-12-18 08:42:10 +00001060 if (isNewLoad)
1061 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +00001062 AvailableQueue->addNode(NewSU);
1063
1064 ++NumUnfolds;
1065
1066 if (NewSU->NumSuccsLeft == 0) {
1067 NewSU->isAvailable = true;
1068 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +00001069 }
1070 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +00001071 }
1072
Evan Chengbdd062d2010-05-20 06:13:19 +00001073 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001074 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +00001075
1076 // New SUnit has the exact same predecessors.
1077 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1078 I != E; ++I)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001079 if (!I->isArtificial())
Dan Gohman2d170892008-12-09 22:54:47 +00001080 AddPred(NewSU, *I);
Evan Cheng5924bf72007-09-25 01:54:36 +00001081
1082 // Only copy scheduled successors. Cut them from old node's successor
1083 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +00001084 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +00001085 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1086 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001087 if (I->isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +00001088 continue;
Dan Gohman2d170892008-12-09 22:54:47 +00001089 SUnit *SuccSU = I->getSUnit();
1090 if (SuccSU->isScheduled) {
Dan Gohman2d170892008-12-09 22:54:47 +00001091 SDep D = *I;
1092 D.setSUnit(NewSU);
1093 AddPred(SuccSU, D);
1094 D.setSUnit(SU);
1095 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +00001096 }
1097 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001098 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +00001099 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng5924bf72007-09-25 01:54:36 +00001100
1101 AvailableQueue->updateNode(SU);
1102 AvailableQueue->addNode(NewSU);
1103
Evan Cheng1ec79b42007-09-27 07:09:03 +00001104 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +00001105 return NewSU;
1106}
1107
Evan Chengb2c42c62009-01-12 03:19:55 +00001108/// InsertCopiesAndMoveSuccs - Insert register copies and move all
1109/// scheduled successors of the given SUnit to the last copy.
1110void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
1111 const TargetRegisterClass *DestRC,
1112 const TargetRegisterClass *SrcRC,
Evan Cheng1ec79b42007-09-27 07:09:03 +00001113 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001114 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +00001115 CopyFromSU->CopySrcRC = SrcRC;
1116 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +00001117
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001118 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +00001119 CopyToSU->CopySrcRC = DestRC;
1120 CopyToSU->CopyDstRC = SrcRC;
1121
1122 // Only copy scheduled successors. Cut them from old node's successor
1123 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +00001124 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +00001125 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1126 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001127 if (I->isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +00001128 continue;
Dan Gohman2d170892008-12-09 22:54:47 +00001129 SUnit *SuccSU = I->getSUnit();
1130 if (SuccSU->isScheduled) {
1131 SDep D = *I;
1132 D.setSUnit(CopyToSU);
1133 AddPred(SuccSU, D);
1134 DelDeps.push_back(std::make_pair(SuccSU, *I));
Evan Cheng8e136a92007-09-26 21:36:17 +00001135 }
Andrew Trick13acae02011-03-23 20:42:39 +00001136 else {
1137 // Avoid scheduling the def-side copy before other successors. Otherwise
1138 // we could introduce another physreg interference on the copy and
1139 // continue inserting copies indefinitely.
1140 SDep D(CopyFromSU, SDep::Order, /*Latency=*/0,
1141 /*Reg=*/0, /*isNormalMemory=*/false,
1142 /*isMustAlias=*/false, /*isArtificial=*/true);
1143 AddPred(SuccSU, D);
1144 }
Evan Cheng8e136a92007-09-26 21:36:17 +00001145 }
Evan Chengb2c42c62009-01-12 03:19:55 +00001146 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +00001147 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng8e136a92007-09-26 21:36:17 +00001148
Dan Gohman2d170892008-12-09 22:54:47 +00001149 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
1150 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
Evan Cheng8e136a92007-09-26 21:36:17 +00001151
1152 AvailableQueue->updateNode(SU);
1153 AvailableQueue->addNode(CopyFromSU);
1154 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001155 Copies.push_back(CopyFromSU);
1156 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +00001157
Evan Chengb2c42c62009-01-12 03:19:55 +00001158 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +00001159}
1160
1161/// getPhysicalRegisterVT - Returns the ValueType of the physical register
1162/// definition of the specified node.
1163/// FIXME: Move to SelectionDAG?
Owen Anderson53aa7a92009-08-10 22:56:29 +00001164static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +00001165 const TargetInstrInfo *TII) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001166 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1167 assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
1168 unsigned NumRes = MCID.getNumDefs();
Craig Topper5a4bcc72012-03-08 08:22:45 +00001169 for (const uint16_t *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +00001170 if (Reg == *ImpDef)
1171 break;
1172 ++NumRes;
1173 }
1174 return N->getValueType(NumRes);
1175}
1176
Evan Chengb8905c42009-03-04 01:41:49 +00001177/// CheckForLiveRegDef - Return true and update live register vector if the
1178/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001179static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Evan Chengb8905c42009-03-04 01:41:49 +00001180 std::vector<SUnit*> &LiveRegDefs,
1181 SmallSet<unsigned, 4> &RegAdded,
1182 SmallVector<unsigned, 4> &LRegs,
1183 const TargetRegisterInfo *TRI) {
Craig Topper1d326582012-03-04 10:43:23 +00001184 for (const uint16_t *AliasI = TRI->getOverlaps(Reg); *AliasI; ++AliasI) {
Andrew Trick12acde112010-12-23 03:43:21 +00001185
1186 // Check if Ref is live.
Andrew Trick0af2e472011-06-07 00:38:12 +00001187 if (!LiveRegDefs[*AliasI]) continue;
Andrew Trick12acde112010-12-23 03:43:21 +00001188
1189 // Allow multiple uses of the same def.
Andrew Trick0af2e472011-06-07 00:38:12 +00001190 if (LiveRegDefs[*AliasI] == SU) continue;
Andrew Trick12acde112010-12-23 03:43:21 +00001191
1192 // Add Reg to the set of interfering live regs.
Andrew Trick0af2e472011-06-07 00:38:12 +00001193 if (RegAdded.insert(*AliasI)) {
Andrew Trick0af2e472011-06-07 00:38:12 +00001194 LRegs.push_back(*AliasI);
1195 }
Evan Chengb8905c42009-03-04 01:41:49 +00001196 }
Evan Chengb8905c42009-03-04 01:41:49 +00001197}
1198
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001199/// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
1200/// by RegMask, and add them to LRegs.
1201static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
1202 std::vector<SUnit*> &LiveRegDefs,
1203 SmallSet<unsigned, 4> &RegAdded,
1204 SmallVector<unsigned, 4> &LRegs) {
1205 // Look at all live registers. Skip Reg0 and the special CallResource.
1206 for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
1207 if (!LiveRegDefs[i]) continue;
1208 if (LiveRegDefs[i] == SU) continue;
1209 if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
1210 if (RegAdded.insert(i))
1211 LRegs.push_back(i);
1212 }
1213}
1214
1215/// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
1216static const uint32_t *getNodeRegMask(const SDNode *N) {
1217 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1218 if (const RegisterMaskSDNode *Op =
1219 dyn_cast<RegisterMaskSDNode>(N->getOperand(i).getNode()))
1220 return Op->getRegMask();
1221 return NULL;
1222}
1223
Evan Cheng5924bf72007-09-25 01:54:36 +00001224/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1225/// scheduling of the given node to satisfy live physical register dependencies.
1226/// If the specific node is the last one that's available to schedule, do
1227/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001228bool ScheduleDAGRRList::
1229DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +00001230 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +00001231 return false;
1232
Evan Chenge6f92252007-09-27 18:46:06 +00001233 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +00001234 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001235 //
1236 // If SU is the currently live definition of the same register that it uses,
1237 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +00001238 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1239 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001240 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Evan Chengb8905c42009-03-04 01:41:49 +00001241 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
1242 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001243 }
1244
Chris Lattner11a33812010-12-23 17:24:32 +00001245 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +00001246 if (Node->getOpcode() == ISD::INLINEASM) {
1247 // Inline asm can clobber physical defs.
1248 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +00001249 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +00001250 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +00001251
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001252 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +00001253 unsigned Flags =
1254 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001255 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +00001256
1257 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001258 if (InlineAsm::isRegDefKind(Flags) ||
Jakob Stoklund Olesen537a3022011-06-27 04:08:33 +00001259 InlineAsm::isRegDefEarlyClobberKind(Flags) ||
1260 InlineAsm::isClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +00001261 // Check for def of register or earlyclobber register.
1262 for (; NumVals; --NumVals, ++i) {
1263 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1264 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1265 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1266 }
1267 } else
1268 i += NumVals;
1269 }
1270 continue;
1271 }
1272
Dan Gohman072734e2008-11-13 23:24:17 +00001273 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +00001274 continue;
Dan Gohman198b7ff2011-11-03 21:49:52 +00001275 // If we're in the middle of scheduling a call, don't begin scheduling
1276 // another call. Also, don't allow any physical registers to be live across
1277 // the call.
1278 if (Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
1279 // Check the special calling-sequence resource.
1280 unsigned CallResource = TRI->getNumRegs();
1281 if (LiveRegDefs[CallResource]) {
1282 SDNode *Gen = LiveRegGens[CallResource]->getNode();
1283 while (SDNode *Glued = Gen->getGluedNode())
1284 Gen = Glued;
1285 if (!IsChainDependent(Gen, Node, 0, TII) && RegAdded.insert(CallResource))
1286 LRegs.push_back(CallResource);
1287 }
1288 }
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001289 if (const uint32_t *RegMask = getNodeRegMask(Node))
1290 CheckForLiveRegDefMasked(SU, RegMask, LiveRegDefs, RegAdded, LRegs);
1291
Evan Cheng6cc775f2011-06-28 19:10:37 +00001292 const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
1293 if (!MCID.ImplicitDefs)
Evan Cheng5924bf72007-09-25 01:54:36 +00001294 continue;
Craig Topper5a4bcc72012-03-08 08:22:45 +00001295 for (const uint16_t *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
Evan Chengb8905c42009-03-04 01:41:49 +00001296 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001297 }
Andrew Trick2085a962010-12-21 22:25:04 +00001298
Evan Cheng5924bf72007-09-25 01:54:36 +00001299 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +00001300}
1301
Andrew Trick528fad92010-12-23 05:42:20 +00001302/// Return a node that can be scheduled in this cycle. Requirements:
1303/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001304/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +00001305/// (3) No Interferences: may unschedule to break register interferences.
1306SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1307 SmallVector<SUnit*, 4> Interferences;
1308 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1309
1310 SUnit *CurSU = AvailableQueue->pop();
1311 while (CurSU) {
1312 SmallVector<unsigned, 4> LRegs;
1313 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1314 break;
1315 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1316
1317 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1318 Interferences.push_back(CurSU);
1319 CurSU = AvailableQueue->pop();
1320 }
1321 if (CurSU) {
1322 // Add the nodes that aren't ready back onto the available list.
1323 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1324 Interferences[i]->isPending = false;
1325 assert(Interferences[i]->isAvailable && "must still be available");
1326 AvailableQueue->push(Interferences[i]);
1327 }
1328 return CurSU;
1329 }
1330
1331 // All candidates are delayed due to live physical reg dependencies.
1332 // Try backtracking, code duplication, or inserting cross class copies
1333 // to resolve it.
1334 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1335 SUnit *TrySU = Interferences[i];
1336 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1337
1338 // Try unscheduling up to the point where it's safe to schedule
1339 // this node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001340 SUnit *BtSU = NULL;
1341 unsigned LiveCycle = UINT_MAX;
Andrew Trick528fad92010-12-23 05:42:20 +00001342 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1343 unsigned Reg = LRegs[j];
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001344 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1345 BtSU = LiveRegGens[Reg];
1346 LiveCycle = BtSU->getHeight();
1347 }
Andrew Trick528fad92010-12-23 05:42:20 +00001348 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001349 if (!WillCreateCycle(TrySU, BtSU)) {
1350 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001351
1352 // Force the current node to be scheduled before the node that
1353 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001354 if (BtSU->isAvailable) {
1355 BtSU->isAvailable = false;
1356 if (!BtSU->isPending)
1357 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001358 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001359 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
Andrew Trick528fad92010-12-23 05:42:20 +00001360 /*Reg=*/0, /*isNormalMemory=*/false,
1361 /*isMustAlias=*/false, /*isArtificial=*/true));
1362
1363 // If one or more successors has been unscheduled, then the current
1364 // node is no longer avaialable. Schedule a successor that's now
1365 // available instead.
1366 if (!TrySU->isAvailable) {
1367 CurSU = AvailableQueue->pop();
1368 }
1369 else {
1370 CurSU = TrySU;
1371 TrySU->isPending = false;
1372 Interferences.erase(Interferences.begin()+i);
1373 }
1374 break;
1375 }
1376 }
1377
1378 if (!CurSU) {
1379 // Can't backtrack. If it's too expensive to copy the value, then try
1380 // duplicate the nodes that produces these "too expensive to copy"
1381 // values to break the dependency. In case even that doesn't work,
1382 // insert cross class copies.
1383 // If it's not too expensive, i.e. cost != -1, issue copies.
1384 SUnit *TrySU = Interferences[0];
1385 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1386 assert(LRegs.size() == 1 && "Can't handle this yet!");
1387 unsigned Reg = LRegs[0];
1388 SUnit *LRDef = LiveRegDefs[Reg];
1389 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1390 const TargetRegisterClass *RC =
1391 TRI->getMinimalPhysRegClass(Reg, VT);
1392 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1393
Evan Chengb4c6a342011-03-10 00:16:32 +00001394 // If cross copy register class is the same as RC, then it must be possible
1395 // copy the value directly. Do not try duplicate the def.
1396 // If cross copy register class is not the same as RC, then it's possible to
1397 // copy the value but it require cross register class copies and it is
1398 // expensive.
1399 // If cross copy register class is null, then it's not possible to copy
1400 // the value at all.
Andrew Trick528fad92010-12-23 05:42:20 +00001401 SUnit *NewDef = 0;
Evan Chengb4c6a342011-03-10 00:16:32 +00001402 if (DestRC != RC) {
Andrew Trick528fad92010-12-23 05:42:20 +00001403 NewDef = CopyAndMoveSuccessors(LRDef);
Evan Chengb4c6a342011-03-10 00:16:32 +00001404 if (!DestRC && !NewDef)
1405 report_fatal_error("Can't handle live physical register dependency!");
1406 }
Andrew Trick528fad92010-12-23 05:42:20 +00001407 if (!NewDef) {
1408 // Issue copies, these can be expensive cross register class copies.
1409 SmallVector<SUnit*, 2> Copies;
1410 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1411 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1412 << " to SU #" << Copies.front()->NodeNum << "\n");
1413 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1414 /*Reg=*/0, /*isNormalMemory=*/false,
1415 /*isMustAlias=*/false,
1416 /*isArtificial=*/true));
1417 NewDef = Copies.back();
1418 }
1419
1420 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1421 << " to SU #" << TrySU->NodeNum << "\n");
1422 LiveRegDefs[Reg] = NewDef;
1423 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1424 /*Reg=*/0, /*isNormalMemory=*/false,
1425 /*isMustAlias=*/false,
1426 /*isArtificial=*/true));
1427 TrySU->isAvailable = false;
1428 CurSU = NewDef;
1429 }
1430
1431 assert(CurSU && "Unable to resolve live physical register dependencies!");
1432
1433 // Add the nodes that aren't ready back onto the available list.
1434 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1435 Interferences[i]->isPending = false;
1436 // May no longer be available due to backtracking.
1437 if (Interferences[i]->isAvailable) {
1438 AvailableQueue->push(Interferences[i]);
1439 }
1440 }
1441 return CurSU;
1442}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001443
Evan Chengd38c22b2006-05-11 23:55:42 +00001444/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1445/// schedulers.
1446void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001447 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001448 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001449
Evan Chengd38c22b2006-05-11 23:55:42 +00001450 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001451 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001452 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001453 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1454 RootSU->isAvailable = true;
1455 AvailableQueue->push(RootSU);
1456 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001457
1458 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001459 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001460 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001461 while (!AvailableQueue->empty()) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00001462 DEBUG(dbgs() << "\nExamining Available:\n";
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001463 AvailableQueue->dump(this));
1464
Andrew Trick528fad92010-12-23 05:42:20 +00001465 // Pick the best node to schedule taking all constraints into
1466 // consideration.
1467 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001468
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001469 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001470
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001471 ScheduleNodeBottomUp(SU);
1472
1473 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1474 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1475 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1476 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1477 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001478 }
1479
Evan Chengd38c22b2006-05-11 23:55:42 +00001480 // Reverse the order if it is bottom up.
1481 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001482
Evan Chengd38c22b2006-05-11 23:55:42 +00001483#ifndef NDEBUG
Andrew Trick46a58662012-03-07 05:21:36 +00001484 VerifyScheduledSequence(/*isBottomUp=*/true);
Evan Chengd38c22b2006-05-11 23:55:42 +00001485#endif
1486}
1487
1488//===----------------------------------------------------------------------===//
Andrew Trick9ccce772011-01-14 21:11:41 +00001489// RegReductionPriorityQueue Definition
Evan Chengd38c22b2006-05-11 23:55:42 +00001490//===----------------------------------------------------------------------===//
1491//
1492// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1493// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001494//
Evan Chengd38c22b2006-05-11 23:55:42 +00001495namespace {
Andrew Trick9ccce772011-01-14 21:11:41 +00001496class RegReductionPQBase;
Andrew Trick2085a962010-12-21 22:25:04 +00001497
Andrew Trick9ccce772011-01-14 21:11:41 +00001498struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1499 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1500};
1501
Andrew Trick3013b6a2011-06-15 17:16:12 +00001502#ifndef NDEBUG
1503template<class SF>
1504struct reverse_sort : public queue_sort {
1505 SF &SortFunc;
1506 reverse_sort(SF &sf) : SortFunc(sf) {}
1507 reverse_sort(const reverse_sort &RHS) : SortFunc(RHS.SortFunc) {}
1508
1509 bool operator()(SUnit* left, SUnit* right) const {
1510 // reverse left/right rather than simply !SortFunc(left, right)
1511 // to expose different paths in the comparison logic.
1512 return SortFunc(right, left);
1513 }
1514};
1515#endif // NDEBUG
1516
Andrew Trick9ccce772011-01-14 21:11:41 +00001517/// bu_ls_rr_sort - Priority function for bottom up register pressure
1518// reduction scheduler.
1519struct bu_ls_rr_sort : public queue_sort {
1520 enum {
1521 IsBottomUp = true,
1522 HasReadyFilter = false
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001523 };
1524
Andrew Trick9ccce772011-01-14 21:11:41 +00001525 RegReductionPQBase *SPQ;
1526 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1527 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001528
Andrew Trick9ccce772011-01-14 21:11:41 +00001529 bool operator()(SUnit* left, SUnit* right) const;
1530};
Andrew Trick2085a962010-12-21 22:25:04 +00001531
Andrew Trick9ccce772011-01-14 21:11:41 +00001532// src_ls_rr_sort - Priority function for source order scheduler.
1533struct src_ls_rr_sort : public queue_sort {
1534 enum {
1535 IsBottomUp = true,
1536 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001537 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001538
Andrew Trick9ccce772011-01-14 21:11:41 +00001539 RegReductionPQBase *SPQ;
1540 src_ls_rr_sort(RegReductionPQBase *spq)
1541 : SPQ(spq) {}
1542 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1543 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001544
Andrew Trick9ccce772011-01-14 21:11:41 +00001545 bool operator()(SUnit* left, SUnit* right) const;
1546};
Andrew Trick2085a962010-12-21 22:25:04 +00001547
Andrew Trick9ccce772011-01-14 21:11:41 +00001548// hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1549struct hybrid_ls_rr_sort : public queue_sort {
1550 enum {
1551 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001552 HasReadyFilter = false
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001553 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001554
Andrew Trick9ccce772011-01-14 21:11:41 +00001555 RegReductionPQBase *SPQ;
1556 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1557 : SPQ(spq) {}
1558 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1559 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001560
Andrew Trick9ccce772011-01-14 21:11:41 +00001561 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Chenga77f3d32010-07-21 06:09:07 +00001562
Andrew Trick9ccce772011-01-14 21:11:41 +00001563 bool operator()(SUnit* left, SUnit* right) const;
1564};
1565
1566// ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1567// scheduler.
1568struct ilp_ls_rr_sort : public queue_sort {
1569 enum {
1570 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001571 HasReadyFilter = false
Evan Chengbdd062d2010-05-20 06:13:19 +00001572 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001573
Andrew Trick9ccce772011-01-14 21:11:41 +00001574 RegReductionPQBase *SPQ;
1575 ilp_ls_rr_sort(RegReductionPQBase *spq)
1576 : SPQ(spq) {}
1577 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1578 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001579
Andrew Trick9ccce772011-01-14 21:11:41 +00001580 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Cheng37b740c2010-07-24 00:39:05 +00001581
Andrew Trick9ccce772011-01-14 21:11:41 +00001582 bool operator()(SUnit* left, SUnit* right) const;
1583};
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001584
Andrew Trick9ccce772011-01-14 21:11:41 +00001585class RegReductionPQBase : public SchedulingPriorityQueue {
1586protected:
1587 std::vector<SUnit*> Queue;
1588 unsigned CurQueueId;
1589 bool TracksRegPressure;
1590
1591 // SUnits - The SUnits for the current graph.
1592 std::vector<SUnit> *SUnits;
1593
1594 MachineFunction &MF;
1595 const TargetInstrInfo *TII;
1596 const TargetRegisterInfo *TRI;
1597 const TargetLowering *TLI;
1598 ScheduleDAGRRList *scheduleDAG;
1599
1600 // SethiUllmanNumbers - The SethiUllman number for each node.
1601 std::vector<unsigned> SethiUllmanNumbers;
1602
1603 /// RegPressure - Tracking current reg pressure per register class.
1604 ///
1605 std::vector<unsigned> RegPressure;
1606
1607 /// RegLimit - Tracking the number of allocatable registers per register
1608 /// class.
1609 std::vector<unsigned> RegLimit;
1610
1611public:
1612 RegReductionPQBase(MachineFunction &mf,
1613 bool hasReadyFilter,
1614 bool tracksrp,
1615 const TargetInstrInfo *tii,
1616 const TargetRegisterInfo *tri,
1617 const TargetLowering *tli)
1618 : SchedulingPriorityQueue(hasReadyFilter),
1619 CurQueueId(0), TracksRegPressure(tracksrp),
1620 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1621 if (TracksRegPressure) {
1622 unsigned NumRC = TRI->getNumRegClasses();
1623 RegLimit.resize(NumRC);
1624 RegPressure.resize(NumRC);
1625 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1626 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1627 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1628 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichdf616942011-03-07 21:56:36 +00001629 RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
Andrew Trick9ccce772011-01-14 21:11:41 +00001630 }
1631 }
1632
1633 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1634 scheduleDAG = scheduleDag;
1635 }
1636
1637 ScheduleHazardRecognizer* getHazardRec() {
1638 return scheduleDAG->getHazardRec();
1639 }
1640
1641 void initNodes(std::vector<SUnit> &sunits);
1642
1643 void addNode(const SUnit *SU);
1644
1645 void updateNode(const SUnit *SU);
1646
1647 void releaseState() {
1648 SUnits = 0;
1649 SethiUllmanNumbers.clear();
1650 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1651 }
1652
1653 unsigned getNodePriority(const SUnit *SU) const;
1654
1655 unsigned getNodeOrdering(const SUnit *SU) const {
Andrew Trick3bd8b7a2011-03-25 06:40:55 +00001656 if (!SU->getNode()) return 0;
1657
Andrew Trick9ccce772011-01-14 21:11:41 +00001658 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1659 }
1660
1661 bool empty() const { return Queue.empty(); }
1662
1663 void push(SUnit *U) {
1664 assert(!U->NodeQueueId && "Node in the queue already");
1665 U->NodeQueueId = ++CurQueueId;
1666 Queue.push_back(U);
1667 }
1668
1669 void remove(SUnit *SU) {
1670 assert(!Queue.empty() && "Queue is empty!");
1671 assert(SU->NodeQueueId != 0 && "Not in queue!");
1672 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1673 SU);
1674 if (I != prior(Queue.end()))
1675 std::swap(*I, Queue.back());
1676 Queue.pop_back();
1677 SU->NodeQueueId = 0;
1678 }
1679
Andrew Trickd0548ae2011-02-04 03:18:17 +00001680 bool tracksRegPressure() const { return TracksRegPressure; }
1681
Andrew Trick9ccce772011-01-14 21:11:41 +00001682 void dumpRegPressure() const;
1683
1684 bool HighRegPressure(const SUnit *SU) const;
1685
Andrew Trick641e2d42011-03-05 08:00:22 +00001686 bool MayReduceRegPressure(SUnit *SU) const;
1687
1688 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
Andrew Trick9ccce772011-01-14 21:11:41 +00001689
Andrew Trick52226d42012-03-07 23:00:49 +00001690 void scheduledNode(SUnit *SU);
Andrew Trick9ccce772011-01-14 21:11:41 +00001691
Andrew Trick52226d42012-03-07 23:00:49 +00001692 void unscheduledNode(SUnit *SU);
Andrew Trick9ccce772011-01-14 21:11:41 +00001693
1694protected:
1695 bool canClobber(const SUnit *SU, const SUnit *Op);
Duncan Sands635e4ef2011-11-09 14:20:48 +00001696 void AddPseudoTwoAddrDeps();
Andrew Trick9ccce772011-01-14 21:11:41 +00001697 void PrescheduleNodesWithMultipleUses();
1698 void CalculateSethiUllmanNumbers();
1699};
1700
1701template<class SF>
Andrew Trick3013b6a2011-06-15 17:16:12 +00001702static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
1703 std::vector<SUnit *>::iterator Best = Q.begin();
1704 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1705 E = Q.end(); I != E; ++I)
1706 if (Picker(*Best, *I))
1707 Best = I;
1708 SUnit *V = *Best;
1709 if (Best != prior(Q.end()))
1710 std::swap(*Best, Q.back());
1711 Q.pop_back();
1712 return V;
1713}
Andrew Trick9ccce772011-01-14 21:11:41 +00001714
Andrew Trick3013b6a2011-06-15 17:16:12 +00001715template<class SF>
1716SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
1717#ifndef NDEBUG
1718 if (DAG->StressSched) {
1719 reverse_sort<SF> RPicker(Picker);
1720 return popFromQueueImpl(Q, RPicker);
1721 }
1722#endif
1723 (void)DAG;
1724 return popFromQueueImpl(Q, Picker);
1725}
1726
1727template<class SF>
1728class RegReductionPriorityQueue : public RegReductionPQBase {
Andrew Trick9ccce772011-01-14 21:11:41 +00001729 SF Picker;
1730
1731public:
1732 RegReductionPriorityQueue(MachineFunction &mf,
1733 bool tracksrp,
1734 const TargetInstrInfo *tii,
1735 const TargetRegisterInfo *tri,
1736 const TargetLowering *tli)
1737 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
1738 Picker(this) {}
1739
1740 bool isBottomUp() const { return SF::IsBottomUp; }
1741
1742 bool isReady(SUnit *U) const {
1743 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1744 }
1745
1746 SUnit *pop() {
1747 if (Queue.empty()) return NULL;
1748
Andrew Trick3013b6a2011-06-15 17:16:12 +00001749 SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
Andrew Trick9ccce772011-01-14 21:11:41 +00001750 V->NodeQueueId = 0;
1751 return V;
1752 }
1753
1754 void dump(ScheduleDAG *DAG) const {
1755 // Emulate pop() without clobbering NodeQueueIds.
1756 std::vector<SUnit*> DumpQueue = Queue;
1757 SF DumpPicker = Picker;
1758 while (!DumpQueue.empty()) {
Andrew Trick3013b6a2011-06-15 17:16:12 +00001759 SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
Dan Gohman90fb5522011-10-20 21:44:34 +00001760 dbgs() << "Height " << SU->getHeight() << ": ";
Andrew Trick9ccce772011-01-14 21:11:41 +00001761 SU->dump(DAG);
1762 }
1763 }
1764};
1765
1766typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1767BURegReductionPriorityQueue;
1768
Andrew Trick9ccce772011-01-14 21:11:41 +00001769typedef RegReductionPriorityQueue<src_ls_rr_sort>
1770SrcRegReductionPriorityQueue;
1771
1772typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1773HybridBURRPriorityQueue;
1774
1775typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1776ILPBURRPriorityQueue;
1777} // end anonymous namespace
1778
1779//===----------------------------------------------------------------------===//
1780// Static Node Priority for Register Pressure Reduction
1781//===----------------------------------------------------------------------===//
Evan Chengd38c22b2006-05-11 23:55:42 +00001782
Andrew Trickbfbd9722011-04-14 05:15:06 +00001783// Check for special nodes that bypass scheduling heuristics.
1784// Currently this pushes TokenFactor nodes down, but may be used for other
1785// pseudo-ops as well.
1786//
1787// Return -1 to schedule right above left, 1 for left above right.
1788// Return 0 if no bias exists.
1789static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
1790 bool LSchedLow = left->isScheduleLow;
1791 bool RSchedLow = right->isScheduleLow;
1792 if (LSchedLow != RSchedLow)
1793 return LSchedLow < RSchedLow ? 1 : -1;
1794 return 0;
1795}
1796
Dan Gohman186f65d2008-11-20 03:30:37 +00001797/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1798/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001799static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001800CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001801 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1802 if (SethiUllmanNumber != 0)
1803 return SethiUllmanNumber;
1804
1805 unsigned Extra = 0;
1806 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1807 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001808 if (I->isCtrl()) continue; // ignore chain preds
1809 SUnit *PredSU = I->getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001810 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001811 if (PredSethiUllman > SethiUllmanNumber) {
1812 SethiUllmanNumber = PredSethiUllman;
1813 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001814 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001815 ++Extra;
1816 }
1817
1818 SethiUllmanNumber += Extra;
1819
1820 if (SethiUllmanNumber == 0)
1821 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001822
Evan Cheng7e4abde2008-07-02 09:23:51 +00001823 return SethiUllmanNumber;
1824}
1825
Andrew Trick9ccce772011-01-14 21:11:41 +00001826/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1827/// scheduling units.
1828void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1829 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001830
Andrew Trick9ccce772011-01-14 21:11:41 +00001831 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1832 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
Evan Chengd38c22b2006-05-11 23:55:42 +00001833}
1834
Andrew Trick9ccce772011-01-14 21:11:41 +00001835void RegReductionPQBase::addNode(const SUnit *SU) {
1836 unsigned SUSize = SethiUllmanNumbers.size();
1837 if (SUnits->size() > SUSize)
1838 SethiUllmanNumbers.resize(SUSize*2, 0);
1839 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1840}
1841
1842void RegReductionPQBase::updateNode(const SUnit *SU) {
1843 SethiUllmanNumbers[SU->NodeNum] = 0;
1844 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1845}
1846
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001847// Lower priority means schedule further down. For bottom-up scheduling, lower
1848// priority SUs are scheduled before higher priority SUs.
Andrew Trick9ccce772011-01-14 21:11:41 +00001849unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1850 assert(SU->NodeNum < SethiUllmanNumbers.size());
1851 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1852 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1853 // CopyToReg should be close to its uses to facilitate coalescing and
1854 // avoid spilling.
1855 return 0;
1856 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1857 Opc == TargetOpcode::SUBREG_TO_REG ||
1858 Opc == TargetOpcode::INSERT_SUBREG)
1859 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1860 // close to their uses to facilitate coalescing.
1861 return 0;
1862 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1863 // If SU does not have a register use, i.e. it doesn't produce a value
1864 // that would be consumed (e.g. store), then it terminates a chain of
1865 // computation. Give it a large SethiUllman number so it will be
1866 // scheduled right before its predecessors that it doesn't lengthen
1867 // their live ranges.
1868 return 0xffff;
1869 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1870 // If SU does not have a register def, schedule it close to its uses
1871 // because it does not lengthen any live ranges.
1872 return 0;
Evan Cheng1355bbd2011-04-26 21:31:35 +00001873#if 1
Andrew Trick9ccce772011-01-14 21:11:41 +00001874 return SethiUllmanNumbers[SU->NodeNum];
Evan Cheng1355bbd2011-04-26 21:31:35 +00001875#else
1876 unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
1877 if (SU->isCallOp) {
1878 // FIXME: This assumes all of the defs are used as call operands.
1879 int NP = (int)Priority - SU->getNode()->getNumValues();
1880 return (NP > 0) ? NP : 0;
1881 }
1882 return Priority;
1883#endif
Andrew Trick9ccce772011-01-14 21:11:41 +00001884}
1885
1886//===----------------------------------------------------------------------===//
1887// Register Pressure Tracking
1888//===----------------------------------------------------------------------===//
1889
1890void RegReductionPQBase::dumpRegPressure() const {
1891 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1892 E = TRI->regclass_end(); I != E; ++I) {
1893 const TargetRegisterClass *RC = *I;
1894 unsigned Id = RC->getID();
1895 unsigned RP = RegPressure[Id];
1896 if (!RP) continue;
1897 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1898 << '\n');
1899 }
1900}
1901
1902bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1903 if (!TLI)
1904 return false;
1905
1906 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1907 I != E; ++I) {
1908 if (I->isCtrl())
1909 continue;
1910 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001911 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1912 // to cover the number of registers defined (they are all live).
1913 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001914 continue;
1915 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001916 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1917 RegDefPos.IsValid(); RegDefPos.Advance()) {
Owen Anderson96adc4a2011-06-15 23:35:18 +00001918 unsigned RCId, Cost;
1919 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
1920
Andrew Trick9ccce772011-01-14 21:11:41 +00001921 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1922 return true;
1923 }
1924 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001925 return false;
1926}
1927
Andrew Trick641e2d42011-03-05 08:00:22 +00001928bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00001929 const SDNode *N = SU->getNode();
1930
1931 if (!N->isMachineOpcode() || !SU->NumSuccs)
1932 return false;
1933
1934 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1935 for (unsigned i = 0; i != NumDefs; ++i) {
1936 EVT VT = N->getValueType(i);
1937 if (!N->hasAnyUseOfValue(i))
1938 continue;
1939 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1940 if (RegPressure[RCId] >= RegLimit[RCId])
1941 return true;
1942 }
1943 return false;
1944}
1945
Andrew Trick641e2d42011-03-05 08:00:22 +00001946// Compute the register pressure contribution by this instruction by count up
1947// for uses that are not live and down for defs. Only count register classes
1948// that are already under high pressure. As a side effect, compute the number of
1949// uses of registers that are already live.
1950//
1951// FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1952// so could probably be factored.
1953int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1954 LiveUses = 0;
1955 int PDiff = 0;
1956 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1957 I != E; ++I) {
1958 if (I->isCtrl())
1959 continue;
1960 SUnit *PredSU = I->getSUnit();
1961 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1962 // to cover the number of registers defined (they are all live).
1963 if (PredSU->NumRegDefsLeft == 0) {
1964 if (PredSU->getNode()->isMachineOpcode())
1965 ++LiveUses;
1966 continue;
1967 }
1968 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1969 RegDefPos.IsValid(); RegDefPos.Advance()) {
1970 EVT VT = RegDefPos.GetValue();
1971 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1972 if (RegPressure[RCId] >= RegLimit[RCId])
1973 ++PDiff;
1974 }
1975 }
1976 const SDNode *N = SU->getNode();
1977
Eric Christopher7238cba2011-03-08 19:35:47 +00001978 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
Andrew Trick641e2d42011-03-05 08:00:22 +00001979 return PDiff;
1980
1981 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1982 for (unsigned i = 0; i != NumDefs; ++i) {
1983 EVT VT = N->getValueType(i);
1984 if (!N->hasAnyUseOfValue(i))
1985 continue;
1986 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1987 if (RegPressure[RCId] >= RegLimit[RCId])
1988 --PDiff;
1989 }
1990 return PDiff;
1991}
1992
Andrew Trick52226d42012-03-07 23:00:49 +00001993void RegReductionPQBase::scheduledNode(SUnit *SU) {
Andrew Trick9ccce772011-01-14 21:11:41 +00001994 if (!TracksRegPressure)
1995 return;
1996
Eric Christopher7238cba2011-03-08 19:35:47 +00001997 if (!SU->getNode())
1998 return;
Andrew Tricka8846e02011-03-23 20:40:18 +00001999
Andrew Trick9ccce772011-01-14 21:11:41 +00002000 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2001 I != E; ++I) {
2002 if (I->isCtrl())
2003 continue;
2004 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00002005 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2006 // to cover the number of registers defined (they are all live).
2007 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002008 continue;
2009 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00002010 // FIXME: The ScheduleDAG currently loses information about which of a
2011 // node's values is consumed by each dependence. Consequently, if the node
2012 // defines multiple register classes, we don't know which to pressurize
2013 // here. Instead the following loop consumes the register defs in an
2014 // arbitrary order. At least it handles the common case of clustered loads
2015 // to the same class. For precise liveness, each SDep needs to indicate the
2016 // result number. But that tightly couples the ScheduleDAG with the
2017 // SelectionDAG making updates tricky. A simpler hack would be to attach a
2018 // value type or register class to SDep.
2019 //
2020 // The most important aspect of register tracking is balancing the increase
2021 // here with the reduction further below. Note that this SU may use multiple
2022 // defs in PredSU. The can't be determined here, but we've already
2023 // compensated by reducing NumRegDefsLeft in PredSU during
2024 // ScheduleDAGSDNodes::AddSchedEdges.
2025 --PredSU->NumRegDefsLeft;
2026 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
2027 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2028 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2029 if (SkipRegDefs)
Andrew Trick9ccce772011-01-14 21:11:41 +00002030 continue;
Owen Anderson96adc4a2011-06-15 23:35:18 +00002031
2032 unsigned RCId, Cost;
2033 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
2034 RegPressure[RCId] += Cost;
Andrew Trickd0548ae2011-02-04 03:18:17 +00002035 break;
Andrew Trick9ccce772011-01-14 21:11:41 +00002036 }
2037 }
2038
Andrew Trickd0548ae2011-02-04 03:18:17 +00002039 // We should have this assert, but there may be dead SDNodes that never
2040 // materialize as SUnits, so they don't appear to generate liveness.
2041 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
2042 int SkipRegDefs = (int)SU->NumRegDefsLeft;
2043 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
2044 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2045 if (SkipRegDefs > 0)
2046 continue;
Owen Anderson96adc4a2011-06-15 23:35:18 +00002047 unsigned RCId, Cost;
2048 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost);
2049 if (RegPressure[RCId] < Cost) {
Andrew Trickd0548ae2011-02-04 03:18:17 +00002050 // Register pressure tracking is imprecise. This can happen. But we try
2051 // hard not to let it happen because it likely results in poor scheduling.
2052 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
2053 RegPressure[RCId] = 0;
2054 }
2055 else {
Owen Anderson96adc4a2011-06-15 23:35:18 +00002056 RegPressure[RCId] -= Cost;
Andrew Trick9ccce772011-01-14 21:11:41 +00002057 }
2058 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002059 dumpRegPressure();
2060}
2061
Andrew Trick52226d42012-03-07 23:00:49 +00002062void RegReductionPQBase::unscheduledNode(SUnit *SU) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002063 if (!TracksRegPressure)
2064 return;
2065
2066 const SDNode *N = SU->getNode();
Eric Christopher7238cba2011-03-08 19:35:47 +00002067 if (!N) return;
Andrew Tricka8846e02011-03-23 20:40:18 +00002068
Andrew Trick9ccce772011-01-14 21:11:41 +00002069 if (!N->isMachineOpcode()) {
2070 if (N->getOpcode() != ISD::CopyToReg)
2071 return;
2072 } else {
2073 unsigned Opc = N->getMachineOpcode();
2074 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2075 Opc == TargetOpcode::INSERT_SUBREG ||
2076 Opc == TargetOpcode::SUBREG_TO_REG ||
2077 Opc == TargetOpcode::REG_SEQUENCE ||
2078 Opc == TargetOpcode::IMPLICIT_DEF)
2079 return;
2080 }
2081
2082 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2083 I != E; ++I) {
2084 if (I->isCtrl())
2085 continue;
2086 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002087 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
2088 // counts data deps.
2089 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00002090 continue;
2091 const SDNode *PN = PredSU->getNode();
2092 if (!PN->isMachineOpcode()) {
2093 if (PN->getOpcode() == ISD::CopyFromReg) {
2094 EVT VT = PN->getValueType(0);
2095 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2096 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2097 }
2098 continue;
2099 }
2100 unsigned POpc = PN->getMachineOpcode();
2101 if (POpc == TargetOpcode::IMPLICIT_DEF)
2102 continue;
Andrew Trick31f25bc2011-06-27 18:01:20 +00002103 if (POpc == TargetOpcode::EXTRACT_SUBREG ||
2104 POpc == TargetOpcode::INSERT_SUBREG ||
2105 POpc == TargetOpcode::SUBREG_TO_REG) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002106 EVT VT = PN->getValueType(0);
2107 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2108 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2109 continue;
2110 }
2111 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
2112 for (unsigned i = 0; i != NumDefs; ++i) {
2113 EVT VT = PN->getValueType(i);
2114 if (!PN->hasAnyUseOfValue(i))
2115 continue;
2116 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2117 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
2118 // Register pressure tracking is imprecise. This can happen.
2119 RegPressure[RCId] = 0;
2120 else
2121 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
2122 }
2123 }
2124
2125 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
2126 // may transfer data dependencies to CopyToReg.
2127 if (SU->NumSuccs && N->isMachineOpcode()) {
2128 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2129 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2130 EVT VT = N->getValueType(i);
2131 if (VT == MVT::Glue || VT == MVT::Other)
2132 continue;
2133 if (!N->hasAnyUseOfValue(i))
2134 continue;
2135 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2136 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2137 }
2138 }
2139
2140 dumpRegPressure();
2141}
2142
2143//===----------------------------------------------------------------------===//
2144// Dynamic Node Priority for Register Pressure Reduction
2145//===----------------------------------------------------------------------===//
2146
Evan Chengb9e3db62007-03-14 22:43:40 +00002147/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00002148/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00002149static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002150 unsigned MaxHeight = 0;
Evan Cheng28748552007-03-13 23:25:11 +00002151 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00002152 I != E; ++I) {
Evan Chengce3bbe52009-02-10 08:30:11 +00002153 if (I->isCtrl()) continue; // ignore chain succs
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002154 unsigned Height = I->getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00002155 // If there are bunch of CopyToRegs stacked up, they should be considered
2156 // to be at the same position.
Dan Gohman2d170892008-12-09 22:54:47 +00002157 if (I->getSUnit()->getNode() &&
2158 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002159 Height = closestSucc(I->getSUnit())+1;
2160 if (Height > MaxHeight)
2161 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00002162 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002163 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00002164}
2165
Evan Cheng61bc51e2007-12-20 02:22:36 +00002166/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00002167/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00002168static unsigned calcMaxScratches(const SUnit *SU) {
2169 unsigned Scratches = 0;
2170 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Chengb5704992009-02-12 09:52:13 +00002171 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002172 if (I->isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00002173 Scratches++;
2174 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00002175 return Scratches;
2176}
2177
Andrew Trickb53a00d2011-04-13 00:38:32 +00002178/// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2179/// CopyFromReg from a virtual register.
2180static bool hasOnlyLiveInOpers(const SUnit *SU) {
2181 bool RetVal = false;
2182 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2183 I != E; ++I) {
2184 if (I->isCtrl()) continue;
2185 const SUnit *PredSU = I->getSUnit();
2186 if (PredSU->getNode() &&
2187 PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2188 unsigned Reg =
2189 cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2190 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2191 RetVal = true;
2192 continue;
2193 }
2194 }
2195 return false;
2196 }
2197 return RetVal;
2198}
2199
2200/// hasOnlyLiveOutUses - Return true if SU has only value successors that are
Evan Cheng6c1414f2010-10-29 18:09:28 +00002201/// CopyToReg to a virtual register. This SU def is probably a liveout and
2202/// it has no other use. It should be scheduled closer to the terminator.
2203static bool hasOnlyLiveOutUses(const SUnit *SU) {
2204 bool RetVal = false;
2205 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2206 I != E; ++I) {
2207 if (I->isCtrl()) continue;
2208 const SUnit *SuccSU = I->getSUnit();
2209 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2210 unsigned Reg =
2211 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2212 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2213 RetVal = true;
2214 continue;
2215 }
2216 }
2217 return false;
2218 }
2219 return RetVal;
2220}
2221
Andrew Trickb53a00d2011-04-13 00:38:32 +00002222// Set isVRegCycle for a node with only live in opers and live out uses. Also
2223// set isVRegCycle for its CopyFromReg operands.
2224//
2225// This is only relevant for single-block loops, in which case the VRegCycle
2226// node is likely an induction variable in which the operand and target virtual
2227// registers should be coalesced (e.g. pre/post increment values). Setting the
2228// isVRegCycle flag helps the scheduler prioritize other uses of the same
2229// CopyFromReg so that this node becomes the virtual register "kill". This
2230// avoids interference between the values live in and out of the block and
2231// eliminates a copy inside the loop.
2232static void initVRegCycle(SUnit *SU) {
2233 if (DisableSchedVRegCycle)
2234 return;
2235
2236 if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2237 return;
2238
2239 DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
2240
2241 SU->isVRegCycle = true;
2242
2243 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002244 I != E; ++I) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002245 if (I->isCtrl()) continue;
2246 I->getSUnit()->isVRegCycle = true;
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002247 }
Andrew Trick1b60ad62011-04-12 20:14:07 +00002248}
2249
Andrew Trickb53a00d2011-04-13 00:38:32 +00002250// After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2251// CopyFromReg operands. We should no longer penalize other uses of this VReg.
2252static void resetVRegCycle(SUnit *SU) {
2253 if (!SU->isVRegCycle)
2254 return;
2255
2256 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2257 I != E; ++I) {
Andrew Trick1b60ad62011-04-12 20:14:07 +00002258 if (I->isCtrl()) continue; // ignore chain preds
Andrew Trickb53a00d2011-04-13 00:38:32 +00002259 SUnit *PredSU = I->getSUnit();
2260 if (PredSU->isVRegCycle) {
2261 assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2262 "VRegCycle def must be CopyFromReg");
2263 I->getSUnit()->isVRegCycle = 0;
2264 }
2265 }
2266}
2267
2268// Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2269// means a node that defines the VRegCycle has not been scheduled yet.
2270static bool hasVRegCycleUse(const SUnit *SU) {
2271 // If this SU also defines the VReg, don't hoist it as a "use".
2272 if (SU->isVRegCycle)
2273 return false;
2274
2275 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2276 I != E; ++I) {
2277 if (I->isCtrl()) continue; // ignore chain preds
2278 if (I->getSUnit()->isVRegCycle &&
2279 I->getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
2280 DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
2281 return true;
Andrew Trick2ad0b372011-04-07 19:54:57 +00002282 }
2283 }
2284 return false;
2285}
2286
Andrew Trick9ccce772011-01-14 21:11:41 +00002287// Check for either a dependence (latency) or resource (hazard) stall.
2288//
2289// Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2290static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2291 if ((int)SPQ->getCurCycle() < Height) return true;
2292 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2293 != ScheduleHazardRecognizer::NoHazard)
2294 return true;
2295 return false;
2296}
2297
2298// Return -1 if left has higher priority, 1 if right has higher priority.
2299// Return 0 if latency-based priority is equivalent.
2300static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2301 RegReductionPQBase *SPQ) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002302 // Scheduling an instruction that uses a VReg whose postincrement has not yet
2303 // been scheduled will induce a copy. Model this as an extra cycle of latency.
2304 int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2305 int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2306 int LHeight = (int)left->getHeight() + LPenalty;
2307 int RHeight = (int)right->getHeight() + RPenalty;
Andrew Trick9ccce772011-01-14 21:11:41 +00002308
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002309 bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
Andrew Trick9ccce772011-01-14 21:11:41 +00002310 BUHasStall(left, LHeight, SPQ);
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002311 bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
Andrew Trick9ccce772011-01-14 21:11:41 +00002312 BUHasStall(right, RHeight, SPQ);
2313
2314 // If scheduling one of the node will cause a pipeline stall, delay it.
2315 // If scheduling either one of the node will cause a pipeline stall, sort
2316 // them according to their height.
2317 if (LStall) {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002318 if (!RStall)
Andrew Trick9ccce772011-01-14 21:11:41 +00002319 return 1;
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002320 if (LHeight != RHeight)
Andrew Trick9ccce772011-01-14 21:11:41 +00002321 return LHeight > RHeight ? 1 : -1;
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002322 } else if (RStall)
Andrew Trick9ccce772011-01-14 21:11:41 +00002323 return -1;
2324
Andrew Trick47ff14b2011-01-21 05:51:33 +00002325 // If either node is scheduling for latency, sort them by height/depth
Andrew Trick9ccce772011-01-14 21:11:41 +00002326 // and latency.
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002327 if (!checkPref || (left->SchedulingPref == Sched::ILP ||
2328 right->SchedulingPref == Sched::ILP)) {
Andrew Trick47ff14b2011-01-21 05:51:33 +00002329 if (DisableSchedCycles) {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002330 if (LHeight != RHeight)
Andrew Trick9ccce772011-01-14 21:11:41 +00002331 return LHeight > RHeight ? 1 : -1;
2332 }
Andrew Trick47ff14b2011-01-21 05:51:33 +00002333 else {
2334 // If neither instruction stalls (!LStall && !RStall) then
Eric Christopher9cb33de2011-03-06 21:13:45 +00002335 // its height is already covered so only its depth matters. We also reach
Andrew Trick47ff14b2011-01-21 05:51:33 +00002336 // this if both stall but have the same height.
Andrew Trickb53a00d2011-04-13 00:38:32 +00002337 int LDepth = left->getDepth() - LPenalty;
2338 int RDepth = right->getDepth() - RPenalty;
Andrew Trick47ff14b2011-01-21 05:51:33 +00002339 if (LDepth != RDepth) {
2340 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2341 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2342 << ") depth " << RDepth << "\n");
2343 return LDepth < RDepth ? 1 : -1;
2344 }
2345 }
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002346 if (left->Latency != right->Latency)
Andrew Trick9ccce772011-01-14 21:11:41 +00002347 return left->Latency > right->Latency ? 1 : -1;
2348 }
2349 return 0;
2350}
2351
2352static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002353 // Schedule physical register definitions close to their use. This is
2354 // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
2355 // long as shortening physreg live ranges is generally good, we can defer
2356 // creating a subtarget hook.
2357 if (!DisableSchedPhysRegJoin) {
2358 bool LHasPhysReg = left->hasPhysRegDefs;
2359 bool RHasPhysReg = right->hasPhysRegDefs;
2360 if (LHasPhysReg != RHasPhysReg) {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002361 #ifndef NDEBUG
2362 const char *PhysRegMsg[] = {" has no physreg", " defines a physreg"};
2363 #endif
2364 DEBUG(dbgs() << " SU (" << left->NodeNum << ") "
2365 << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
2366 << PhysRegMsg[RHasPhysReg] << "\n");
2367 return LHasPhysReg < RHasPhysReg;
2368 }
2369 }
2370
Evan Cheng2f647542011-04-26 04:57:37 +00002371 // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
Evan Cheng6730f032007-01-08 23:55:53 +00002372 unsigned LPriority = SPQ->getNodePriority(left);
2373 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng1355bbd2011-04-26 21:31:35 +00002374
2375 // Be really careful about hoisting call operands above previous calls.
2376 // Only allows it if it would reduce register pressure.
2377 if (left->isCall && right->isCallOp) {
2378 unsigned RNumVals = right->getNode()->getNumValues();
2379 RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2380 }
2381 if (right->isCall && left->isCallOp) {
2382 unsigned LNumVals = left->getNode()->getNumValues();
2383 LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2384 }
2385
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002386 if (LPriority != RPriority)
Evan Cheng73bdf042008-03-01 00:39:47 +00002387 return LPriority > RPriority;
Andrew Trick52b3e382011-03-08 01:51:56 +00002388
Evan Cheng1355bbd2011-04-26 21:31:35 +00002389 // One or both of the nodes are calls and their sethi-ullman numbers are the
2390 // same, then keep source order.
2391 if (left->isCall || right->isCall) {
2392 unsigned LOrder = SPQ->getNodeOrdering(left);
2393 unsigned ROrder = SPQ->getNodeOrdering(right);
2394
2395 // Prefer an ordering where the lower the non-zero order number, the higher
2396 // the preference.
2397 if ((LOrder || ROrder) && LOrder != ROrder)
2398 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2399 }
2400
Evan Cheng73bdf042008-03-01 00:39:47 +00002401 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2402 // e.g.
2403 // t1 = op t2, c1
2404 // t3 = op t4, c2
2405 //
2406 // and the following instructions are both ready.
2407 // t2 = op c3
2408 // t4 = op c4
2409 //
2410 // Then schedule t2 = op first.
2411 // i.e.
2412 // t4 = op c4
2413 // t2 = op c3
2414 // t1 = op t2, c1
2415 // t3 = op t4, c2
2416 //
2417 // This creates more short live intervals.
2418 unsigned LDist = closestSucc(left);
2419 unsigned RDist = closestSucc(right);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002420 if (LDist != RDist)
Evan Cheng73bdf042008-03-01 00:39:47 +00002421 return LDist < RDist;
2422
Evan Cheng3a14efa2009-02-12 08:59:45 +00002423 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00002424 unsigned LScratch = calcMaxScratches(left);
2425 unsigned RScratch = calcMaxScratches(right);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002426 if (LScratch != RScratch)
Evan Cheng73bdf042008-03-01 00:39:47 +00002427 return LScratch > RScratch;
2428
Evan Cheng1355bbd2011-04-26 21:31:35 +00002429 // Comparing latency against a call makes little sense unless the node
2430 // is register pressure-neutral.
2431 if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
2432 return (left->NodeQueueId > right->NodeQueueId);
2433
2434 // Do not compare latencies when one or both of the nodes are calls.
2435 if (!DisableSchedCycles &&
2436 !(left->isCall || right->isCall)) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002437 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2438 if (result != 0)
2439 return result > 0;
2440 }
2441 else {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002442 if (left->getHeight() != right->getHeight())
Andrew Trick9ccce772011-01-14 21:11:41 +00002443 return left->getHeight() > right->getHeight();
Andrew Trick2085a962010-12-21 22:25:04 +00002444
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002445 if (left->getDepth() != right->getDepth())
Andrew Trick9ccce772011-01-14 21:11:41 +00002446 return left->getDepth() < right->getDepth();
2447 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002448
Andrew Trick2085a962010-12-21 22:25:04 +00002449 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002450 "NodeQueueId cannot be zero");
2451 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002452}
2453
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002454// Bottom up
Andrew Trick9ccce772011-01-14 21:11:41 +00002455bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002456 if (int res = checkSpecialNodes(left, right))
2457 return res > 0;
2458
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002459 return BURRSort(left, right, SPQ);
2460}
2461
2462// Source order, otherwise bottom up.
Andrew Trick9ccce772011-01-14 21:11:41 +00002463bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002464 if (int res = checkSpecialNodes(left, right))
2465 return res > 0;
2466
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002467 unsigned LOrder = SPQ->getNodeOrdering(left);
2468 unsigned ROrder = SPQ->getNodeOrdering(right);
2469
2470 // Prefer an ordering where the lower the non-zero order number, the higher
2471 // the preference.
2472 if ((LOrder || ROrder) && LOrder != ROrder)
2473 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2474
2475 return BURRSort(left, right, SPQ);
2476}
2477
Andrew Trick9ccce772011-01-14 21:11:41 +00002478// If the time between now and when the instruction will be ready can cover
2479// the spill code, then avoid adding it to the ready queue. This gives long
2480// stalls highest priority and allows hoisting across calls. It should also
2481// speed up processing the available queue.
2482bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2483 static const unsigned ReadyDelay = 3;
2484
2485 if (SPQ->MayReduceRegPressure(SU)) return true;
2486
2487 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2488
2489 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2490 != ScheduleHazardRecognizer::NoHazard)
2491 return false;
2492
2493 return true;
2494}
2495
2496// Return true if right should be scheduled with higher priority than left.
2497bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002498 if (int res = checkSpecialNodes(left, right))
2499 return res > 0;
2500
Evan Chengdebf9c52010-11-03 00:45:17 +00002501 if (left->isCall || right->isCall)
2502 // No way to compute latency of calls.
2503 return BURRSort(left, right, SPQ);
2504
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002505 bool LHigh = SPQ->HighRegPressure(left);
2506 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002507 // Avoid causing spills. If register pressure is high, schedule for
2508 // register pressure reduction.
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002509 if (LHigh && !RHigh) {
2510 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2511 << right->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002512 return true;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002513 }
2514 else if (!LHigh && RHigh) {
2515 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2516 << left->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002517 return false;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002518 }
Andrew Trickb53a00d2011-04-13 00:38:32 +00002519 if (!LHigh && !RHigh) {
2520 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2521 if (result != 0)
2522 return result > 0;
Evan Chengcc2efe12010-05-28 23:26:21 +00002523 }
Evan Chengbdd062d2010-05-20 06:13:19 +00002524 return BURRSort(left, right, SPQ);
2525}
2526
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002527// Schedule as many instructions in each cycle as possible. So don't make an
2528// instruction available unless it is ready in the current cycle.
2529bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00002530 if (SU->getHeight() > CurCycle) return false;
2531
2532 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2533 != ScheduleHazardRecognizer::NoHazard)
2534 return false;
2535
Andrew Trickc88b7ec2011-03-04 02:03:45 +00002536 return true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002537}
2538
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002539static bool canEnableCoalescing(SUnit *SU) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002540 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2541 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2542 // CopyToReg should be close to its uses to facilitate coalescing and
2543 // avoid spilling.
2544 return true;
2545
2546 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2547 Opc == TargetOpcode::SUBREG_TO_REG ||
2548 Opc == TargetOpcode::INSERT_SUBREG)
2549 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2550 // close to their uses to facilitate coalescing.
2551 return true;
2552
2553 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2554 // If SU does not have a register def, schedule it close to its uses
2555 // because it does not lengthen any live ranges.
2556 return true;
2557
2558 return false;
2559}
2560
Andrew Trickb8390b72011-03-05 08:04:11 +00002561// list-ilp is currently an experimental scheduler that allows various
2562// heuristics to be enabled prior to the normal register reduction logic.
Andrew Trick9ccce772011-01-14 21:11:41 +00002563bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002564 if (int res = checkSpecialNodes(left, right))
2565 return res > 0;
2566
Evan Chengdebf9c52010-11-03 00:45:17 +00002567 if (left->isCall || right->isCall)
2568 // No way to compute latency of calls.
2569 return BURRSort(left, right, SPQ);
2570
Andrew Trick52b3e382011-03-08 01:51:56 +00002571 unsigned LLiveUses = 0, RLiveUses = 0;
2572 int LPDiff = 0, RPDiff = 0;
2573 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2574 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2575 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2576 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002577 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002578 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2579 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002580 return LPDiff > RPDiff;
2581 }
2582
Andrew Trick52b3e382011-03-08 01:51:56 +00002583 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002584 bool LReduce = canEnableCoalescing(left);
2585 bool RReduce = canEnableCoalescing(right);
Andrew Trick52b3e382011-03-08 01:51:56 +00002586 if (LReduce && !RReduce) return false;
2587 if (RReduce && !LReduce) return true;
2588 }
2589
2590 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2591 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2592 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002593 return LLiveUses < RLiveUses;
2594 }
2595
Andrew Trick52b3e382011-03-08 01:51:56 +00002596 if (!DisableSchedStalls) {
2597 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2598 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002599 if (LStall != RStall)
Andrew Trick52b3e382011-03-08 01:51:56 +00002600 return left->getHeight() > right->getHeight();
Andrew Trick641e2d42011-03-05 08:00:22 +00002601 }
2602
Andrew Trick25cedf32011-03-05 10:29:25 +00002603 if (!DisableSchedCriticalPath) {
2604 int spread = (int)left->getDepth() - (int)right->getDepth();
2605 if (std::abs(spread) > MaxReorderWindow) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002606 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2607 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2608 << right->getDepth() << "\n");
Andrew Trick25cedf32011-03-05 10:29:25 +00002609 return left->getDepth() < right->getDepth();
2610 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002611 }
2612
2613 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002614 int spread = (int)left->getHeight() - (int)right->getHeight();
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002615 if (std::abs(spread) > MaxReorderWindow)
Andrew Trick52b3e382011-03-08 01:51:56 +00002616 return left->getHeight() > right->getHeight();
Evan Cheng37b740c2010-07-24 00:39:05 +00002617 }
2618
2619 return BURRSort(left, right, SPQ);
2620}
2621
Andrew Trickb53a00d2011-04-13 00:38:32 +00002622void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2623 SUnits = &sunits;
2624 // Add pseudo dependency edges for two-address nodes.
Evan Chengd33b2d62011-11-10 07:43:16 +00002625 if (!Disable2AddrHack)
2626 AddPseudoTwoAddrDeps();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002627 // Reroute edges to nodes with multiple uses.
2628 if (!TracksRegPressure)
2629 PrescheduleNodesWithMultipleUses();
2630 // Calculate node priorities.
2631 CalculateSethiUllmanNumbers();
2632
2633 // For single block loops, mark nodes that look like canonical IV increments.
2634 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) {
2635 for (unsigned i = 0, e = sunits.size(); i != e; ++i) {
2636 initVRegCycle(&sunits[i]);
2637 }
2638 }
2639}
2640
Andrew Trick9ccce772011-01-14 21:11:41 +00002641//===----------------------------------------------------------------------===//
2642// Preschedule for Register Pressure
2643//===----------------------------------------------------------------------===//
2644
2645bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002646 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002647 unsigned Opc = SU->getNode()->getMachineOpcode();
Evan Cheng6cc775f2011-06-28 19:10:37 +00002648 const MCInstrDesc &MCID = TII->get(Opc);
2649 unsigned NumRes = MCID.getNumDefs();
2650 unsigned NumOps = MCID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002651 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00002652 if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002653 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002654 if (DU->getNodeId() != -1 &&
2655 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002656 return true;
2657 }
2658 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002659 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002660 return false;
2661}
2662
Andrew Trick832a6a192011-09-01 00:54:31 +00002663/// canClobberReachingPhysRegUse - True if SU would clobber one of it's
2664/// successor's explicit physregs whose definition can reach DepSU.
2665/// i.e. DepSU should not be scheduled above SU.
2666static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
2667 ScheduleDAGRRList *scheduleDAG,
2668 const TargetInstrInfo *TII,
2669 const TargetRegisterInfo *TRI) {
Craig Topper5a4bcc72012-03-08 08:22:45 +00002670 const uint16_t *ImpDefs
Andrew Trick832a6a192011-09-01 00:54:31 +00002671 = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002672 const uint32_t *RegMask = getNodeRegMask(SU->getNode());
2673 if(!ImpDefs && !RegMask)
Andrew Trick832a6a192011-09-01 00:54:31 +00002674 return false;
2675
2676 for (SUnit::const_succ_iterator SI = SU->Succs.begin(), SE = SU->Succs.end();
2677 SI != SE; ++SI) {
2678 SUnit *SuccSU = SI->getSUnit();
2679 for (SUnit::const_pred_iterator PI = SuccSU->Preds.begin(),
2680 PE = SuccSU->Preds.end(); PI != PE; ++PI) {
2681 if (!PI->isAssignedRegDep())
2682 continue;
2683
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002684 if (RegMask && MachineOperand::clobbersPhysReg(RegMask, PI->getReg()) &&
2685 scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
2686 return true;
2687
2688 if (ImpDefs)
Craig Topper5a4bcc72012-03-08 08:22:45 +00002689 for (const uint16_t *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002690 // Return true if SU clobbers this physical register use and the
2691 // definition of the register reaches from DepSU. IsReachable queries
2692 // a topological forward sort of the DAG (following the successors).
2693 if (TRI->regsOverlap(*ImpDef, PI->getReg()) &&
2694 scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
2695 return true;
Andrew Trick832a6a192011-09-01 00:54:31 +00002696 }
2697 }
2698 return false;
2699}
2700
Evan Chengf9891412007-12-20 09:25:31 +00002701/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002702/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002703static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002704 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002705 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002706 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002707 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
Craig Topper5a4bcc72012-03-08 08:22:45 +00002708 const uint16_t *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002709 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002710 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002711 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002712 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002713 continue;
Craig Topper5a4bcc72012-03-08 08:22:45 +00002714 const uint16_t *SUImpDefs =
Dan Gohmana366da12009-03-23 16:23:01 +00002715 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002716 const uint32_t *SURegMask = getNodeRegMask(SUNode);
2717 if (!SUImpDefs && !SURegMask)
2718 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002719 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002720 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002721 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002722 continue;
2723 if (!N->hasAnyUseOfValue(i))
2724 continue;
2725 unsigned Reg = ImpDefs[i - NumDefs];
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002726 if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
2727 return true;
2728 if (!SUImpDefs)
2729 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002730 for (;*SUImpDefs; ++SUImpDefs) {
2731 unsigned SUReg = *SUImpDefs;
2732 if (TRI->regsOverlap(Reg, SUReg))
2733 return true;
2734 }
Evan Chengf9891412007-12-20 09:25:31 +00002735 }
2736 }
2737 return false;
2738}
2739
Dan Gohman9a658d72009-03-24 00:49:12 +00002740/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2741/// are not handled well by the general register pressure reduction
2742/// heuristics. When presented with code like this:
2743///
2744/// N
2745/// / |
2746/// / |
2747/// U store
2748/// |
2749/// ...
2750///
2751/// the heuristics tend to push the store up, but since the
2752/// operand of the store has another use (U), this would increase
2753/// the length of that other use (the U->N edge).
2754///
2755/// This function transforms code like the above to route U's
2756/// dependence through the store when possible, like this:
2757///
2758/// N
2759/// ||
2760/// ||
2761/// store
2762/// |
2763/// U
2764/// |
2765/// ...
2766///
2767/// This results in the store being scheduled immediately
2768/// after N, which shortens the U->N live range, reducing
2769/// register pressure.
2770///
Andrew Trick9ccce772011-01-14 21:11:41 +00002771void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
Dan Gohman9a658d72009-03-24 00:49:12 +00002772 // Visit all the nodes in topological order, working top-down.
2773 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2774 SUnit *SU = &(*SUnits)[i];
2775 // For now, only look at nodes with no data successors, such as stores.
2776 // These are especially important, due to the heuristics in
2777 // getNodePriority for nodes with no data successors.
2778 if (SU->NumSuccs != 0)
2779 continue;
2780 // For now, only look at nodes with exactly one data predecessor.
2781 if (SU->NumPreds != 1)
2782 continue;
2783 // Avoid prescheduling copies to virtual registers, which don't behave
2784 // like other nodes from the perspective of scheduling heuristics.
2785 if (SDNode *N = SU->getNode())
2786 if (N->getOpcode() == ISD::CopyToReg &&
2787 TargetRegisterInfo::isVirtualRegister
2788 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2789 continue;
2790
2791 // Locate the single data predecessor.
2792 SUnit *PredSU = 0;
2793 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2794 EE = SU->Preds.end(); II != EE; ++II)
2795 if (!II->isCtrl()) {
2796 PredSU = II->getSUnit();
2797 break;
2798 }
2799 assert(PredSU);
2800
2801 // Don't rewrite edges that carry physregs, because that requires additional
2802 // support infrastructure.
2803 if (PredSU->hasPhysRegDefs)
2804 continue;
2805 // Short-circuit the case where SU is PredSU's only data successor.
2806 if (PredSU->NumSuccs == 1)
2807 continue;
2808 // Avoid prescheduling to copies from virtual registers, which don't behave
Andrew Trickd0548ae2011-02-04 03:18:17 +00002809 // like other nodes from the perspective of scheduling heuristics.
Dan Gohman9a658d72009-03-24 00:49:12 +00002810 if (SDNode *N = SU->getNode())
2811 if (N->getOpcode() == ISD::CopyFromReg &&
2812 TargetRegisterInfo::isVirtualRegister
2813 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2814 continue;
2815
2816 // Perform checks on the successors of PredSU.
2817 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2818 EE = PredSU->Succs.end(); II != EE; ++II) {
2819 SUnit *PredSuccSU = II->getSUnit();
2820 if (PredSuccSU == SU) continue;
2821 // If PredSU has another successor with no data successors, for
2822 // now don't attempt to choose either over the other.
2823 if (PredSuccSU->NumSuccs == 0)
2824 goto outer_loop_continue;
2825 // Don't break physical register dependencies.
2826 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2827 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2828 goto outer_loop_continue;
2829 // Don't introduce graph cycles.
2830 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2831 goto outer_loop_continue;
2832 }
2833
2834 // Ok, the transformation is safe and the heuristics suggest it is
2835 // profitable. Update the graph.
Evan Chengbdd062d2010-05-20 06:13:19 +00002836 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2837 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002838 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002839 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2840 SDep Edge = PredSU->Succs[i];
2841 assert(!Edge.isAssignedRegDep());
2842 SUnit *SuccSU = Edge.getSUnit();
2843 if (SuccSU != SU) {
2844 Edge.setSUnit(PredSU);
2845 scheduleDAG->RemovePred(SuccSU, Edge);
2846 scheduleDAG->AddPred(SU, Edge);
2847 Edge.setSUnit(SU);
2848 scheduleDAG->AddPred(SuccSU, Edge);
2849 --i;
2850 }
2851 }
2852 outer_loop_continue:;
2853 }
2854}
2855
Evan Chengd38c22b2006-05-11 23:55:42 +00002856/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2857/// it as a def&use operand. Add a pseudo control edge from it to the other
2858/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002859/// first (lower in the schedule). If both nodes are two-address, favor the
2860/// one that has a CopyToReg use (more likely to be a loop induction update).
2861/// If both are two-address, but one is commutable while the other is not
2862/// commutable, favor the one that's not commutable.
Duncan Sands635e4ef2011-11-09 14:20:48 +00002863void RegReductionPQBase::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002864 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
Dan Gohmane955c482008-08-05 14:45:15 +00002865 SUnit *SU = &(*SUnits)[i];
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002866 if (!SU->isTwoAddress)
2867 continue;
2868
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002869 SDNode *Node = SU->getNode();
Chris Lattner11a33812010-12-23 17:24:32 +00002870 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002871 continue;
2872
Evan Cheng6c1414f2010-10-29 18:09:28 +00002873 bool isLiveOut = hasOnlyLiveOutUses(SU);
Dan Gohman17059682008-07-17 19:10:17 +00002874 unsigned Opc = Node->getMachineOpcode();
Evan Cheng6cc775f2011-06-28 19:10:37 +00002875 const MCInstrDesc &MCID = TII->get(Opc);
2876 unsigned NumRes = MCID.getNumDefs();
2877 unsigned NumOps = MCID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002878 for (unsigned j = 0; j != NumOps; ++j) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00002879 if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
Dan Gohman82016c22008-11-19 02:00:32 +00002880 continue;
2881 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2882 if (DU->getNodeId() == -1)
2883 continue;
2884 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2885 if (!DUSU) continue;
2886 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2887 E = DUSU->Succs.end(); I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002888 if (I->isCtrl()) continue;
2889 SUnit *SuccSU = I->getSUnit();
Dan Gohman82016c22008-11-19 02:00:32 +00002890 if (SuccSU == SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002891 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002892 // Be conservative. Ignore if nodes aren't at roughly the same
2893 // depth and height.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002894 if (SuccSU->getHeight() < SU->getHeight() &&
2895 (SU->getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002896 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002897 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2898 // constrains whatever is using the copy, instead of the copy
2899 // itself. In the case that the copy is coalesced, this
2900 // preserves the intent of the pseudo two-address heurietics.
2901 while (SuccSU->Succs.size() == 1 &&
2902 SuccSU->getNode()->isMachineOpcode() &&
2903 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002904 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002905 SuccSU = SuccSU->Succs.front().getSUnit();
2906 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002907 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2908 continue;
2909 // Don't constrain nodes with physical register defs if the
2910 // predecessor can clobber them.
Dan Gohmanf3746cb2009-03-24 00:50:07 +00002911 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
Dan Gohman82016c22008-11-19 02:00:32 +00002912 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002913 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002914 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002915 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2916 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002917 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002918 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2919 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2920 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002921 continue;
Andrew Trick832a6a192011-09-01 00:54:31 +00002922 if (!canClobberReachingPhysRegUse(SuccSU, SU, scheduleDAG, TII, TRI) &&
2923 (!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002924 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Dan Gohman82016c22008-11-19 02:00:32 +00002925 (!SU->isCommutable && SuccSU->isCommutable)) &&
2926 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002927 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002928 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
Dan Gohman79c35162009-01-06 01:19:04 +00002929 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
Dan Gohmanbf8e5202009-01-06 01:28:56 +00002930 /*Reg=*/0, /*isNormalMemory=*/false,
2931 /*isMustAlias=*/false,
Dan Gohman2d170892008-12-09 22:54:47 +00002932 /*isArtificial=*/true));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002933 }
2934 }
2935 }
2936 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002937}
2938
Evan Chengd38c22b2006-05-11 23:55:42 +00002939//===----------------------------------------------------------------------===//
2940// Public Constructor Functions
2941//===----------------------------------------------------------------------===//
2942
Dan Gohmandfaf6462009-02-11 04:27:20 +00002943llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002944llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2945 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002946 const TargetMachine &TM = IS->TM;
2947 const TargetInstrInfo *TII = TM.getInstrInfo();
2948 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002949
Evan Chenga77f3d32010-07-21 06:09:07 +00002950 BURegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002951 new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002952 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002953 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002954 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002955}
2956
Dan Gohmandfaf6462009-02-11 04:27:20 +00002957llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002958llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2959 CodeGenOpt::Level OptLevel) {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002960 const TargetMachine &TM = IS->TM;
2961 const TargetInstrInfo *TII = TM.getInstrInfo();
2962 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002963
Evan Chenga77f3d32010-07-21 06:09:07 +00002964 SrcRegReductionPriorityQueue *PQ =
Evan Chengbf32e542010-07-22 06:24:48 +00002965 new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002966 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002967 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002968 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002969}
2970
2971llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002972llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2973 CodeGenOpt::Level OptLevel) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002974 const TargetMachine &TM = IS->TM;
2975 const TargetInstrInfo *TII = TM.getInstrInfo();
2976 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Evan Chenga77f3d32010-07-21 06:09:07 +00002977 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002978
Evan Chenga77f3d32010-07-21 06:09:07 +00002979 HybridBURRPriorityQueue *PQ =
Evan Chengdf907f42010-07-23 22:39:59 +00002980 new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002981
2982 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002983 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002984 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002985}
Evan Cheng37b740c2010-07-24 00:39:05 +00002986
2987llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002988llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2989 CodeGenOpt::Level OptLevel) {
Evan Cheng37b740c2010-07-24 00:39:05 +00002990 const TargetMachine &TM = IS->TM;
2991 const TargetInstrInfo *TII = TM.getInstrInfo();
2992 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2993 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002994
Evan Cheng37b740c2010-07-24 00:39:05 +00002995 ILPBURRPriorityQueue *PQ =
2996 new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002997 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00002998 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002999 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00003000}