blob: a8f6f0dff80d965c4340349a3c06819bd69e8f73 [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,
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +0000269 unsigned &RegClass, unsigned &Cost,
270 const MachineFunction &MF) {
Owen Anderson96adc4a2011-06-15 23:35:18 +0000271 EVT VT = RegDefPos.GetValue();
272
273 // Special handling for untyped values. These values can only come from
274 // the expansion of custom DAG-to-DAG patterns.
Owen Andersonca2f78a2011-11-16 01:02:57 +0000275 if (VT == MVT::Untyped) {
Owen Andersond1955e72011-06-21 22:54:23 +0000276 const SDNode *Node = RegDefPos.GetNode();
277 unsigned Opcode = Node->getMachineOpcode();
278
279 if (Opcode == TargetOpcode::REG_SEQUENCE) {
280 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
281 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
282 RegClass = RC->getID();
283 Cost = 1;
284 return;
285 }
286
Owen Anderson96adc4a2011-06-15 23:35:18 +0000287 unsigned Idx = RegDefPos.GetIdx();
Evan Cheng6cc775f2011-06-28 19:10:37 +0000288 const MCInstrDesc Desc = TII->get(Opcode);
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +0000289 const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx, TRI, MF);
Owen Anderson96adc4a2011-06-15 23:35:18 +0000290 RegClass = RC->getID();
291 // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
292 // better way to determine it.
293 Cost = 1;
294 } else {
295 RegClass = TLI->getRepRegClassFor(VT)->getID();
296 Cost = TLI->getRepRegClassCostFor(VT);
297 }
298}
Evan Chengd38c22b2006-05-11 23:55:42 +0000299
300/// Schedule - Schedule the DAG using list scheduling.
301void ScheduleDAGRRList::Schedule() {
Evan Chenga77f3d32010-07-21 06:09:07 +0000302 DEBUG(dbgs()
303 << "********** List Scheduling BB#" << BB->getNumber()
Evan Cheng6c1414f2010-10-29 18:09:28 +0000304 << " '" << BB->getName() << "' **********\n");
Evan Cheng5924bf72007-09-25 01:54:36 +0000305
Andrew Trick528fad92010-12-23 05:42:20 +0000306 CurCycle = 0;
Andrew Trick641e2d42011-03-05 08:00:22 +0000307 IssueCount = 0;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000308 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
Dan Gohmanc07f6862008-09-23 18:50:48 +0000309 NumLiveRegs = 0;
Dan Gohman198b7ff2011-11-03 21:49:52 +0000310 // Allocate slots for each physical register, plus one for a special register
311 // to track the virtual resource of a calling sequence.
312 LiveRegDefs.resize(TRI->getNumRegs() + 1, NULL);
313 LiveRegGens.resize(TRI->getNumRegs() + 1, NULL);
Eli Friedmand5c173f2011-12-07 22:24:28 +0000314 CallSeqEndForStart.clear();
Evan Cheng5924bf72007-09-25 01:54:36 +0000315
Dan Gohman04543e72008-12-23 18:36:58 +0000316 // Build the scheduling graph.
Dan Gohman918ec532009-10-09 23:33:48 +0000317 BuildSchedGraph(NULL);
Evan Chengd38c22b2006-05-11 23:55:42 +0000318
Evan Chengd38c22b2006-05-11 23:55:42 +0000319 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
Dan Gohman22d07b12008-11-18 02:06:40 +0000320 SUnits[su].dumpAll(this));
Dan Gohmanad2134d2008-11-25 00:52:40 +0000321 Topo.InitDAGTopologicalSorting();
Evan Chengd38c22b2006-05-11 23:55:42 +0000322
Dan Gohman46520a22008-06-21 19:18:17 +0000323 AvailableQueue->initNodes(SUnits);
Andrew Trick2085a962010-12-21 22:25:04 +0000324
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000325 HazardRec->Reset();
326
Dan Gohman90fb5522011-10-20 21:44:34 +0000327 // Execute the actual scheduling loop.
328 ListScheduleBottomUp();
Andrew Trick2085a962010-12-21 22:25:04 +0000329
Evan Chengd38c22b2006-05-11 23:55:42 +0000330 AvailableQueue->releaseState();
Andrew Trickedee68c2012-03-07 05:21:40 +0000331
332 DEBUG({
333 dbgs() << "*** Final schedule ***\n";
334 dumpSchedule();
335 dbgs() << '\n';
336 });
Evan Chengafed73e2006-05-12 01:58:24 +0000337}
Evan Chengd38c22b2006-05-11 23:55:42 +0000338
339//===----------------------------------------------------------------------===//
340// Bottom-Up Scheduling
341//===----------------------------------------------------------------------===//
342
Evan Chengd38c22b2006-05-11 23:55:42 +0000343/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000344/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +0000345void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000346 SUnit *PredSU = PredEdge->getSUnit();
Reid Klecknercea8dab2009-09-30 20:43:07 +0000347
Evan Chengd38c22b2006-05-11 23:55:42 +0000348#ifndef NDEBUG
Reid Klecknercea8dab2009-09-30 20:43:07 +0000349 if (PredSU->NumSuccsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +0000350 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +0000351 PredSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +0000352 dbgs() << " has been released too many times!\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +0000353 llvm_unreachable(0);
Evan Chengd38c22b2006-05-11 23:55:42 +0000354 }
355#endif
Reid Klecknercea8dab2009-09-30 20:43:07 +0000356 --PredSU->NumSuccsLeft;
357
Andrew Trick52226d42012-03-07 23:00:49 +0000358 if (!forceUnitLatencies()) {
Evan Chengbdd062d2010-05-20 06:13:19 +0000359 // Updating predecessor's height. This is now the cycle when the
360 // predecessor can be scheduled without causing a pipeline stall.
361 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
362 }
363
Dan Gohmanb9543432009-02-10 23:27:53 +0000364 // If all the node's successors are scheduled, this node is ready
365 // to be scheduled. Ignore the special EntrySU node.
366 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
Dan Gohman4370f262008-04-15 01:22:18 +0000367 PredSU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000368
369 unsigned Height = PredSU->getHeight();
370 if (Height < MinAvailableCycle)
371 MinAvailableCycle = Height;
372
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000373 if (isReady(PredSU)) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000374 AvailableQueue->push(PredSU);
375 }
376 // CapturePred and others may have left the node in the pending queue, avoid
377 // adding it twice.
378 else if (!PredSU->isPending) {
379 PredSU->isPending = true;
380 PendingQueue.push_back(PredSU);
381 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000382 }
383}
384
Dan Gohman198b7ff2011-11-03 21:49:52 +0000385/// IsChainDependent - Test if Outer is reachable from Inner through
386/// chain dependencies.
387static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
388 unsigned NestLevel,
389 const TargetInstrInfo *TII) {
390 SDNode *N = Outer;
391 for (;;) {
392 if (N == Inner)
393 return true;
394 // For a TokenFactor, examine each operand. There may be multiple ways
395 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
396 // most nesting in order to ensure that we find the corresponding match.
397 if (N->getOpcode() == ISD::TokenFactor) {
398 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
399 if (IsChainDependent(N->getOperand(i).getNode(), Inner, NestLevel, TII))
400 return true;
401 return false;
402 }
403 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
404 if (N->isMachineOpcode()) {
405 if (N->getMachineOpcode() ==
406 (unsigned)TII->getCallFrameDestroyOpcode()) {
407 ++NestLevel;
408 } else if (N->getMachineOpcode() ==
409 (unsigned)TII->getCallFrameSetupOpcode()) {
410 if (NestLevel == 0)
411 return false;
412 --NestLevel;
413 }
414 }
415 // Otherwise, find the chain and continue climbing.
416 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
417 if (N->getOperand(i).getValueType() == MVT::Other) {
418 N = N->getOperand(i).getNode();
419 goto found_chain_operand;
420 }
421 return false;
422 found_chain_operand:;
423 if (N->getOpcode() == ISD::EntryToken)
424 return false;
425 }
426}
427
428/// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
429/// the corresponding (lowered) CALLSEQ_BEGIN node.
430///
431/// NestLevel and MaxNested are used in recursion to indcate the current level
432/// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
433/// level seen so far.
434///
435/// TODO: It would be better to give CALLSEQ_END an explicit operand to point
436/// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
437static SDNode *
438FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
439 const TargetInstrInfo *TII) {
440 for (;;) {
441 // For a TokenFactor, examine each operand. There may be multiple ways
442 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
443 // most nesting in order to ensure that we find the corresponding match.
444 if (N->getOpcode() == ISD::TokenFactor) {
445 SDNode *Best = 0;
446 unsigned BestMaxNest = MaxNest;
447 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
448 unsigned MyNestLevel = NestLevel;
449 unsigned MyMaxNest = MaxNest;
450 if (SDNode *New = FindCallSeqStart(N->getOperand(i).getNode(),
451 MyNestLevel, MyMaxNest, TII))
452 if (!Best || (MyMaxNest > BestMaxNest)) {
453 Best = New;
454 BestMaxNest = MyMaxNest;
455 }
456 }
457 assert(Best);
458 MaxNest = BestMaxNest;
459 return Best;
460 }
461 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
462 if (N->isMachineOpcode()) {
463 if (N->getMachineOpcode() ==
464 (unsigned)TII->getCallFrameDestroyOpcode()) {
465 ++NestLevel;
466 MaxNest = std::max(MaxNest, NestLevel);
467 } else if (N->getMachineOpcode() ==
468 (unsigned)TII->getCallFrameSetupOpcode()) {
469 assert(NestLevel != 0);
470 --NestLevel;
471 if (NestLevel == 0)
472 return N;
473 }
474 }
475 // Otherwise, find the chain and continue climbing.
476 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
477 if (N->getOperand(i).getValueType() == MVT::Other) {
478 N = N->getOperand(i).getNode();
479 goto found_chain_operand;
480 }
481 return 0;
482 found_chain_operand:;
483 if (N->getOpcode() == ISD::EntryToken)
484 return 0;
485 }
486}
487
Andrew Trick033efdf2010-12-23 03:15:51 +0000488/// Call ReleasePred for each predecessor, then update register live def/gen.
489/// Always update LiveRegDefs for a register dependence even if the current SU
490/// also defines the register. This effectively create one large live range
491/// across a sequence of two-address node. This is important because the
492/// entire chain must be scheduled together. Example:
493///
494/// flags = (3) add
495/// flags = (2) addc flags
496/// flags = (1) addc flags
497///
498/// results in
499///
500/// LiveRegDefs[flags] = 3
Andrew Tricka52f3252010-12-23 04:16:14 +0000501/// LiveRegGens[flags] = 1
Andrew Trick033efdf2010-12-23 03:15:51 +0000502///
503/// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
504/// interference on flags.
Andrew Tricka52f3252010-12-23 04:16:14 +0000505void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000506 // Bottom up: release predecessors
Chris Lattnerd86418a2006-08-17 00:09:56 +0000507 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Cheng5924bf72007-09-25 01:54:36 +0000508 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000509 ReleasePred(SU, &*I);
510 if (I->isAssignedRegDep()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000511 // This is a physical register dependency and it's impossible or
Andrew Trick2085a962010-12-21 22:25:04 +0000512 // expensive to copy the register. Make sure nothing that can
Evan Cheng5924bf72007-09-25 01:54:36 +0000513 // clobber the register is scheduled between the predecessor and
514 // this node.
Andrew Tricka52f3252010-12-23 04:16:14 +0000515 SUnit *RegDef = LiveRegDefs[I->getReg()]; (void)RegDef;
Andrew Trick033efdf2010-12-23 03:15:51 +0000516 assert((!RegDef || RegDef == SU || RegDef == I->getSUnit()) &&
517 "interference on register dependence");
Andrew Tricka52f3252010-12-23 04:16:14 +0000518 LiveRegDefs[I->getReg()] = I->getSUnit();
519 if (!LiveRegGens[I->getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000520 ++NumLiveRegs;
Andrew Tricka52f3252010-12-23 04:16:14 +0000521 LiveRegGens[I->getReg()] = SU;
Evan Cheng5924bf72007-09-25 01:54:36 +0000522 }
523 }
524 }
Dan Gohman198b7ff2011-11-03 21:49:52 +0000525
526 // If we're scheduling a lowered CALLSEQ_END, find the corresponding
527 // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
528 // these nodes, to prevent other calls from being interscheduled with them.
529 unsigned CallResource = TRI->getNumRegs();
530 if (!LiveRegDefs[CallResource])
531 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
532 if (Node->isMachineOpcode() &&
533 Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
534 unsigned NestLevel = 0;
535 unsigned MaxNest = 0;
536 SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
537
538 SUnit *Def = &SUnits[N->getNodeId()];
Eli Friedmand5c173f2011-12-07 22:24:28 +0000539 CallSeqEndForStart[Def] = SU;
540
Dan Gohman198b7ff2011-11-03 21:49:52 +0000541 ++NumLiveRegs;
542 LiveRegDefs[CallResource] = Def;
543 LiveRegGens[CallResource] = SU;
544 break;
545 }
Dan Gohmanb9543432009-02-10 23:27:53 +0000546}
547
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000548/// Check to see if any of the pending instructions are ready to issue. If
549/// so, add them to the available queue.
550void ScheduleDAGRRList::ReleasePending() {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000551 if (DisableSchedCycles) {
Andrew Trick5ce945c2010-12-24 07:10:19 +0000552 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
553 return;
554 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000555
556 // If the available queue is empty, it is safe to reset MinAvailableCycle.
557 if (AvailableQueue->empty())
558 MinAvailableCycle = UINT_MAX;
559
560 // Check to see if any of the pending instructions are ready to issue. If
561 // so, add them to the available queue.
562 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman90fb5522011-10-20 21:44:34 +0000563 unsigned ReadyCycle = PendingQueue[i]->getHeight();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000564 if (ReadyCycle < MinAvailableCycle)
565 MinAvailableCycle = ReadyCycle;
566
567 if (PendingQueue[i]->isAvailable) {
568 if (!isReady(PendingQueue[i]))
569 continue;
570 AvailableQueue->push(PendingQueue[i]);
571 }
572 PendingQueue[i]->isPending = false;
573 PendingQueue[i] = PendingQueue.back();
574 PendingQueue.pop_back();
575 --i; --e;
576 }
577}
578
579/// Move the scheduler state forward by the specified number of Cycles.
580void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
581 if (NextCycle <= CurCycle)
582 return;
583
Andrew Trick641e2d42011-03-05 08:00:22 +0000584 IssueCount = 0;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000585 AvailableQueue->setCurCycle(NextCycle);
Andrew Trick47ff14b2011-01-21 05:51:33 +0000586 if (!HazardRec->isEnabled()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000587 // Bypass lots of virtual calls in case of long latency.
588 CurCycle = NextCycle;
589 }
590 else {
591 for (; CurCycle != NextCycle; ++CurCycle) {
Dan Gohman90fb5522011-10-20 21:44:34 +0000592 HazardRec->RecedeCycle();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000593 }
594 }
595 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
596 // available Q to release pending nodes at least once before popping.
597 ReleasePending();
598}
599
600/// Move the scheduler state forward until the specified node's dependents are
601/// ready and can be scheduled with no resource conflicts.
602void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000603 if (DisableSchedCycles)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000604 return;
605
Andrew Trickb53a00d2011-04-13 00:38:32 +0000606 // FIXME: Nodes such as CopyFromReg probably should not advance the current
607 // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
608 // has predecessors the cycle will be advanced when they are scheduled.
609 // But given the crude nature of modeling latency though such nodes, we
610 // currently need to treat these nodes like real instructions.
611 // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
612
Dan Gohman90fb5522011-10-20 21:44:34 +0000613 unsigned ReadyCycle = SU->getHeight();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000614
615 // Bump CurCycle to account for latency. We assume the latency of other
616 // available instructions may be hidden by the stall (not a full pipe stall).
617 // This updates the hazard recognizer's cycle before reserving resources for
618 // this instruction.
619 AdvanceToCycle(ReadyCycle);
620
621 // Calls are scheduled in their preceding cycle, so don't conflict with
622 // hazards from instructions after the call. EmitNode will reset the
623 // scoreboard state before emitting the call.
Dan Gohman90fb5522011-10-20 21:44:34 +0000624 if (SU->isCall)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000625 return;
626
627 // FIXME: For resource conflicts in very long non-pipelined stages, we
628 // should probably skip ahead here to avoid useless scoreboard checks.
629 int Stalls = 0;
630 while (true) {
631 ScheduleHazardRecognizer::HazardType HT =
Dan Gohman90fb5522011-10-20 21:44:34 +0000632 HazardRec->getHazardType(SU, -Stalls);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000633
634 if (HT == ScheduleHazardRecognizer::NoHazard)
635 break;
636
637 ++Stalls;
638 }
639 AdvanceToCycle(CurCycle + Stalls);
640}
641
642/// Record this SUnit in the HazardRecognizer.
643/// Does not update CurCycle.
644void ScheduleDAGRRList::EmitNode(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000645 if (!HazardRec->isEnabled())
Andrew Trickc9405662010-12-24 06:46:50 +0000646 return;
647
648 // Check for phys reg copy.
649 if (!SU->getNode())
650 return;
651
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000652 switch (SU->getNode()->getOpcode()) {
653 default:
654 assert(SU->getNode()->isMachineOpcode() &&
655 "This target-independent node should not be scheduled.");
656 break;
657 case ISD::MERGE_VALUES:
658 case ISD::TokenFactor:
Nadav Rotem7c277da2012-09-06 09:17:37 +0000659 case ISD::LIFETIME_START:
660 case ISD::LIFETIME_END:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000661 case ISD::CopyToReg:
662 case ISD::CopyFromReg:
663 case ISD::EH_LABEL:
664 // Noops don't affect the scoreboard state. Copies are likely to be
665 // removed.
666 return;
667 case ISD::INLINEASM:
668 // For inline asm, clear the pipeline state.
669 HazardRec->Reset();
670 return;
671 }
Dan Gohman90fb5522011-10-20 21:44:34 +0000672 if (SU->isCall) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000673 // Calls are scheduled with their preceding instructions. For bottom-up
674 // scheduling, clear the pipeline state before emitting.
675 HazardRec->Reset();
676 }
677
678 HazardRec->EmitInstruction(SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000679}
680
Andrew Trickb53a00d2011-04-13 00:38:32 +0000681static void resetVRegCycle(SUnit *SU);
682
Dan Gohmanb9543432009-02-10 23:27:53 +0000683/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
684/// count of its predecessors. If a predecessor pending count is zero, add it to
685/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000686void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Andrew Trick1b60ad62011-04-12 20:14:07 +0000687 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000688 DEBUG(SU->dump(this));
689
Evan Chengbdd062d2010-05-20 06:13:19 +0000690#ifndef NDEBUG
691 if (CurCycle < SU->getHeight())
Andrew Trickb53a00d2011-04-13 00:38:32 +0000692 DEBUG(dbgs() << " Height [" << SU->getHeight()
693 << "] pipeline stall!\n");
Evan Chengbdd062d2010-05-20 06:13:19 +0000694#endif
695
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000696 // FIXME: Do not modify node height. It may interfere with
697 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
Eric Christopher1b4b1e52011-03-21 18:06:21 +0000698 // node its ready cycle can aid heuristics, and after scheduling it can
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000699 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000700 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000701
702 // Reserve resources for the scheduled intruction.
703 EmitNode(SU);
704
Dan Gohmanb9543432009-02-10 23:27:53 +0000705 Sequence.push_back(SU);
706
Andrew Trick52226d42012-03-07 23:00:49 +0000707 AvailableQueue->scheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000708
Andrew Trick641e2d42011-03-05 08:00:22 +0000709 // If HazardRec is disabled, and each inst counts as one cycle, then
Andrew Trickb53a00d2011-04-13 00:38:32 +0000710 // advance CurCycle before ReleasePredecessors to avoid useless pushes to
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000711 // PendingQueue for schedulers that implement HasReadyFilter.
Andrew Trick641e2d42011-03-05 08:00:22 +0000712 if (!HazardRec->isEnabled() && AvgIPC < 2)
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000713 AdvanceToCycle(CurCycle + 1);
714
Andrew Trick033efdf2010-12-23 03:15:51 +0000715 // Update liveness of predecessors before successors to avoid treating a
716 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000717 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000718
719 // Release all the implicit physical register defs that are live.
720 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
721 I != E; ++I) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000722 // LiveRegDegs[I->getReg()] != SU when SU is a two-address node.
723 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] == SU) {
724 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
725 --NumLiveRegs;
726 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000727 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000728 }
729 }
Dan Gohman198b7ff2011-11-03 21:49:52 +0000730 // Release the special call resource dependence, if this is the beginning
731 // of a call.
732 unsigned CallResource = TRI->getNumRegs();
733 if (LiveRegDefs[CallResource] == SU)
734 for (const SDNode *SUNode = SU->getNode(); SUNode;
735 SUNode = SUNode->getGluedNode()) {
736 if (SUNode->isMachineOpcode() &&
737 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
738 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
739 --NumLiveRegs;
740 LiveRegDefs[CallResource] = NULL;
741 LiveRegGens[CallResource] = NULL;
742 }
743 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000744
Andrew Trickb53a00d2011-04-13 00:38:32 +0000745 resetVRegCycle(SU);
746
Evan Chengd38c22b2006-05-11 23:55:42 +0000747 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000748
749 // Conditions under which the scheduler should eagerly advance the cycle:
750 // (1) No available instructions
751 // (2) All pipelines full, so available instructions must have hazards.
752 //
Andrew Trickb53a00d2011-04-13 00:38:32 +0000753 // If HazardRec is disabled, the cycle was pre-advanced before calling
754 // ReleasePredecessors. In that case, IssueCount should remain 0.
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000755 //
756 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
Andrew Trickb53a00d2011-04-13 00:38:32 +0000757 if (HazardRec->isEnabled() || AvgIPC > 1) {
758 if (SU->getNode() && SU->getNode()->isMachineOpcode())
759 ++IssueCount;
760 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
761 || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
762 AdvanceToCycle(CurCycle + 1);
763 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000764}
765
Evan Cheng5924bf72007-09-25 01:54:36 +0000766/// CapturePred - This does the opposite of ReleasePred. Since SU is being
767/// unscheduled, incrcease the succ left count of its predecessors. Remove
768/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000769void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000770 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000771 if (PredSU->isAvailable) {
772 PredSU->isAvailable = false;
773 if (!PredSU->isPending)
774 AvailableQueue->remove(PredSU);
775 }
776
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000777 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000778 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000779}
780
781/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
782/// its predecessor states to reflect the change.
783void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000784 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000785 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000786
Evan Cheng5924bf72007-09-25 01:54:36 +0000787 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
788 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000789 CapturePred(&*I);
Andrew Tricka52f3252010-12-23 04:16:14 +0000790 if (I->isAssignedRegDep() && SU == LiveRegGens[I->getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000791 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Dan Gohman2d170892008-12-09 22:54:47 +0000792 assert(LiveRegDefs[I->getReg()] == I->getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000793 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000794 --NumLiveRegs;
Dan Gohman2d170892008-12-09 22:54:47 +0000795 LiveRegDefs[I->getReg()] = NULL;
Andrew Tricka52f3252010-12-23 04:16:14 +0000796 LiveRegGens[I->getReg()] = NULL;
Evan Cheng5924bf72007-09-25 01:54:36 +0000797 }
798 }
799
Dan Gohman198b7ff2011-11-03 21:49:52 +0000800 // Reclaim the special call resource dependence, if this is the beginning
801 // of a call.
802 unsigned CallResource = TRI->getNumRegs();
803 for (const SDNode *SUNode = SU->getNode(); SUNode;
804 SUNode = SUNode->getGluedNode()) {
805 if (SUNode->isMachineOpcode() &&
806 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameSetupOpcode()) {
807 ++NumLiveRegs;
808 LiveRegDefs[CallResource] = SU;
Eli Friedmand5c173f2011-12-07 22:24:28 +0000809 LiveRegGens[CallResource] = CallSeqEndForStart[SU];
Dan Gohman198b7ff2011-11-03 21:49:52 +0000810 }
811 }
812
813 // Release the special call resource dependence, if this is the end
814 // of a call.
815 if (LiveRegGens[CallResource] == SU)
816 for (const SDNode *SUNode = SU->getNode(); SUNode;
817 SUNode = SUNode->getGluedNode()) {
818 if (SUNode->isMachineOpcode() &&
819 SUNode->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
820 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
821 --NumLiveRegs;
822 LiveRegDefs[CallResource] = NULL;
823 LiveRegGens[CallResource] = NULL;
824 }
825 }
826
Evan Cheng5924bf72007-09-25 01:54:36 +0000827 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
828 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +0000829 if (I->isAssignedRegDep()) {
Eli Friedman0bdc0832011-12-07 22:06:02 +0000830 if (!LiveRegDefs[I->getReg()])
831 ++NumLiveRegs;
Andrew Trick033efdf2010-12-23 03:15:51 +0000832 // This becomes the nearest def. Note that an earlier def may still be
833 // pending if this is a two-address node.
834 LiveRegDefs[I->getReg()] = SU;
Andrew Tricka52f3252010-12-23 04:16:14 +0000835 if (LiveRegGens[I->getReg()] == NULL ||
836 I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight())
837 LiveRegGens[I->getReg()] = I->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000838 }
839 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000840 if (SU->getHeight() < MinAvailableCycle)
841 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000842
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000843 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000844 SU->isScheduled = false;
845 SU->isAvailable = true;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000846 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000847 // Don't make available until backtracking is complete.
848 SU->isPending = true;
849 PendingQueue.push_back(SU);
850 }
851 else {
852 AvailableQueue->push(SU);
853 }
Andrew Trick52226d42012-03-07 23:00:49 +0000854 AvailableQueue->unscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000855}
856
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000857/// After backtracking, the hazard checker needs to be restored to a state
Sylvestre Ledru35521e22012-07-23 08:51:15 +0000858/// corresponding the current cycle.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000859void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
860 HazardRec->Reset();
861
862 unsigned LookAhead = std::min((unsigned)Sequence.size(),
863 HazardRec->getMaxLookAhead());
864 if (LookAhead == 0)
865 return;
866
867 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
868 unsigned HazardCycle = (*I)->getHeight();
869 for (std::vector<SUnit*>::const_iterator E = Sequence.end(); I != E; ++I) {
870 SUnit *SU = *I;
871 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
872 HazardRec->RecedeCycle();
873 }
874 EmitNode(SU);
875 }
876}
877
Evan Cheng8e136a92007-09-26 21:36:17 +0000878/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000879/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000880void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
881 SUnit *OldSU = Sequence.back();
882 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000883 Sequence.pop_back();
884 if (SU->isSucc(OldSU))
Evan Cheng8e136a92007-09-26 21:36:17 +0000885 // Don't try to remove SU from AvailableQueue.
886 SU->isAvailable = false;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000887 // FIXME: use ready cycle instead of height
888 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000889 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000890 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000891 if (OldSU == BtSU)
892 break;
893 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000894 }
895
Dan Gohman60d68442009-01-29 19:49:27 +0000896 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000897
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000898 RestoreHazardCheckerBottomUp();
899
Andrew Trick5ce945c2010-12-24 07:10:19 +0000900 ReleasePending();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000901
Evan Cheng1ec79b42007-09-27 07:09:03 +0000902 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000903}
904
Evan Cheng3b245872010-02-05 01:27:11 +0000905static bool isOperandOf(const SUnit *SU, SDNode *N) {
906 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000907 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000908 if (SUNode->isOperandOf(N))
909 return true;
910 }
911 return false;
912}
913
Evan Cheng5924bf72007-09-25 01:54:36 +0000914/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
915/// successors to the newly created node.
916SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000917 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000918 if (!N)
919 return NULL;
920
Andrew Trickc9405662010-12-24 06:46:50 +0000921 if (SU->getNode()->getGluedNode())
922 return NULL;
923
Evan Cheng79e97132007-10-05 01:39:18 +0000924 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000925 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000926 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000927 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000928 if (VT == MVT::Glue)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000929 return NULL;
Owen Anderson9f944592009-08-11 20:47:22 +0000930 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000931 TryUnfold = true;
932 }
Evan Cheng79e97132007-10-05 01:39:18 +0000933 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000934 const SDValue &Op = N->getOperand(i);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000935 EVT VT = Op.getNode()->getValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000936 if (VT == MVT::Glue)
Evan Cheng79e97132007-10-05 01:39:18 +0000937 return NULL;
Evan Cheng79e97132007-10-05 01:39:18 +0000938 }
939
940 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000941 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000942 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Evan Cheng79e97132007-10-05 01:39:18 +0000943 return NULL;
944
Pete Cooper7c7ba1b2011-11-15 21:57:53 +0000945 // unfolding an x86 DEC64m operation results in store, dec, load which
946 // can't be handled here so quit
947 if (NewNodes.size() == 3)
948 return NULL;
949
Evan Chengbdd062d2010-05-20 06:13:19 +0000950 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000951 assert(NewNodes.size() == 2 && "Expected a load folding node!");
952
953 N = NewNodes[1];
954 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000955 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000956 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000957 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000958 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
959 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000960 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000961
Dan Gohmane52e0892008-11-11 21:34:44 +0000962 // LoadNode may already exist. This can happen when there is another
963 // load from the same location and producing the same type of value
964 // but it has different alignment or volatileness.
965 bool isNewLoad = true;
966 SUnit *LoadSU;
967 if (LoadNode->getNodeId() != -1) {
968 LoadSU = &SUnits[LoadNode->getNodeId()];
969 isNewLoad = false;
970 } else {
971 LoadSU = CreateNewSUnit(LoadNode);
972 LoadNode->setNodeId(LoadSU->NodeNum);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000973
974 InitNumRegDefsLeft(LoadSU);
Andrew Trick52226d42012-03-07 23:00:49 +0000975 computeLatency(LoadSU);
Dan Gohmane52e0892008-11-11 21:34:44 +0000976 }
977
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000978 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +0000979 assert(N->getNodeId() == -1 && "Node already inserted!");
980 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +0000981
Evan Cheng6cc775f2011-06-28 19:10:37 +0000982 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
983 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
984 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +0000985 NewSU->isTwoAddress = true;
986 break;
987 }
988 }
Evan Cheng6cc775f2011-06-28 19:10:37 +0000989 if (MCID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +0000990 NewSU->isCommutable = true;
Andrew Trickd0548ae2011-02-04 03:18:17 +0000991
992 InitNumRegDefsLeft(NewSU);
Andrew Trick52226d42012-03-07 23:00:49 +0000993 computeLatency(NewSU);
Evan Cheng79e97132007-10-05 01:39:18 +0000994
Dan Gohmaned0e8d42009-03-23 20:20:43 +0000995 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +0000996 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +0000997 SmallVector<SDep, 4> ChainSuccs;
998 SmallVector<SDep, 4> LoadPreds;
999 SmallVector<SDep, 4> NodePreds;
1000 SmallVector<SDep, 4> NodeSuccs;
1001 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1002 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001003 if (I->isCtrl())
Dan Gohman15af5522009-03-06 02:23:01 +00001004 ChainPreds.push_back(*I);
Evan Cheng3b245872010-02-05 01:27:11 +00001005 else if (isOperandOf(I->getSUnit(), LoadNode))
Dan Gohman2d170892008-12-09 22:54:47 +00001006 LoadPreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +00001007 else
Dan Gohman2d170892008-12-09 22:54:47 +00001008 NodePreds.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +00001009 }
1010 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1011 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001012 if (I->isCtrl())
1013 ChainSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +00001014 else
Dan Gohman2d170892008-12-09 22:54:47 +00001015 NodeSuccs.push_back(*I);
Evan Cheng79e97132007-10-05 01:39:18 +00001016 }
1017
Dan Gohmaned0e8d42009-03-23 20:20:43 +00001018 // Now assign edges to the newly-created nodes.
Dan Gohman15af5522009-03-06 02:23:01 +00001019 for (unsigned i = 0, e = ChainPreds.size(); i != e; ++i) {
1020 const SDep &Pred = ChainPreds[i];
1021 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +00001022 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +00001023 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001024 }
Evan Cheng79e97132007-10-05 01:39:18 +00001025 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +00001026 const SDep &Pred = LoadPreds[i];
1027 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +00001028 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +00001029 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +00001030 }
1031 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +00001032 const SDep &Pred = NodePreds[i];
1033 RemovePred(SU, Pred);
1034 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +00001035 }
1036 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +00001037 SDep D = NodeSuccs[i];
1038 SUnit *SuccDep = D.getSUnit();
1039 D.setSUnit(SU);
1040 RemovePred(SuccDep, D);
1041 D.setSUnit(NewSU);
1042 AddPred(SuccDep, D);
Andrew Trickd0548ae2011-02-04 03:18:17 +00001043 // Balance register pressure.
1044 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
1045 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
1046 --NewSU->NumRegDefsLeft;
Evan Cheng79e97132007-10-05 01:39:18 +00001047 }
1048 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
Dan Gohman2d170892008-12-09 22:54:47 +00001049 SDep D = ChainSuccs[i];
1050 SUnit *SuccDep = D.getSUnit();
1051 D.setSUnit(SU);
1052 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001053 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +00001054 D.setSUnit(LoadSU);
1055 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001056 }
Andrew Trick2085a962010-12-21 22:25:04 +00001057 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +00001058
1059 // Add a data dependency to reflect that NewSU reads the value defined
1060 // by LoadSU.
1061 AddPred(NewSU, SDep(LoadSU, SDep::Data, LoadSU->Latency));
Evan Cheng79e97132007-10-05 01:39:18 +00001062
Evan Cheng91e0fc92007-12-18 08:42:10 +00001063 if (isNewLoad)
1064 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +00001065 AvailableQueue->addNode(NewSU);
1066
1067 ++NumUnfolds;
1068
1069 if (NewSU->NumSuccsLeft == 0) {
1070 NewSU->isAvailable = true;
1071 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +00001072 }
1073 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +00001074 }
1075
Evan Chengbdd062d2010-05-20 06:13:19 +00001076 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001077 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +00001078
1079 // New SUnit has the exact same predecessors.
1080 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1081 I != E; ++I)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001082 if (!I->isArtificial())
Dan Gohman2d170892008-12-09 22:54:47 +00001083 AddPred(NewSU, *I);
Evan Cheng5924bf72007-09-25 01:54:36 +00001084
1085 // Only copy scheduled successors. Cut them from old node's successor
1086 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +00001087 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng5924bf72007-09-25 01:54:36 +00001088 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1089 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001090 if (I->isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +00001091 continue;
Dan Gohman2d170892008-12-09 22:54:47 +00001092 SUnit *SuccSU = I->getSUnit();
1093 if (SuccSU->isScheduled) {
Dan Gohman2d170892008-12-09 22:54:47 +00001094 SDep D = *I;
1095 D.setSUnit(NewSU);
1096 AddPred(SuccSU, D);
1097 D.setSUnit(SU);
1098 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +00001099 }
1100 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00001101 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +00001102 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng5924bf72007-09-25 01:54:36 +00001103
1104 AvailableQueue->updateNode(SU);
1105 AvailableQueue->addNode(NewSU);
1106
Evan Cheng1ec79b42007-09-27 07:09:03 +00001107 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +00001108 return NewSU;
1109}
1110
Evan Chengb2c42c62009-01-12 03:19:55 +00001111/// InsertCopiesAndMoveSuccs - Insert register copies and move all
1112/// scheduled successors of the given SUnit to the last copy.
1113void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
1114 const TargetRegisterClass *DestRC,
1115 const TargetRegisterClass *SrcRC,
Evan Cheng1ec79b42007-09-27 07:09:03 +00001116 SmallVector<SUnit*, 2> &Copies) {
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001117 SUnit *CopyFromSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +00001118 CopyFromSU->CopySrcRC = SrcRC;
1119 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +00001120
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001121 SUnit *CopyToSU = CreateNewSUnit(NULL);
Evan Cheng8e136a92007-09-26 21:36:17 +00001122 CopyToSU->CopySrcRC = DestRC;
1123 CopyToSU->CopyDstRC = SrcRC;
1124
1125 // Only copy scheduled successors. Cut them from old node's successor
1126 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +00001127 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Evan Cheng8e136a92007-09-26 21:36:17 +00001128 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1129 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001130 if (I->isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +00001131 continue;
Dan Gohman2d170892008-12-09 22:54:47 +00001132 SUnit *SuccSU = I->getSUnit();
1133 if (SuccSU->isScheduled) {
1134 SDep D = *I;
1135 D.setSUnit(CopyToSU);
1136 AddPred(SuccSU, D);
1137 DelDeps.push_back(std::make_pair(SuccSU, *I));
Evan Cheng8e136a92007-09-26 21:36:17 +00001138 }
Andrew Trick13acae02011-03-23 20:42:39 +00001139 else {
1140 // Avoid scheduling the def-side copy before other successors. Otherwise
1141 // we could introduce another physreg interference on the copy and
1142 // continue inserting copies indefinitely.
1143 SDep D(CopyFromSU, SDep::Order, /*Latency=*/0,
1144 /*Reg=*/0, /*isNormalMemory=*/false,
1145 /*isMustAlias=*/false, /*isArtificial=*/true);
1146 AddPred(SuccSU, D);
1147 }
Evan Cheng8e136a92007-09-26 21:36:17 +00001148 }
Evan Chengb2c42c62009-01-12 03:19:55 +00001149 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
Dan Gohman2d170892008-12-09 22:54:47 +00001150 RemovePred(DelDeps[i].first, DelDeps[i].second);
Evan Cheng8e136a92007-09-26 21:36:17 +00001151
Dan Gohman2d170892008-12-09 22:54:47 +00001152 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
1153 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
Evan Cheng8e136a92007-09-26 21:36:17 +00001154
1155 AvailableQueue->updateNode(SU);
1156 AvailableQueue->addNode(CopyFromSU);
1157 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001158 Copies.push_back(CopyFromSU);
1159 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +00001160
Evan Chengb2c42c62009-01-12 03:19:55 +00001161 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +00001162}
1163
1164/// getPhysicalRegisterVT - Returns the ValueType of the physical register
1165/// definition of the specified node.
1166/// FIXME: Move to SelectionDAG?
Owen Anderson53aa7a92009-08-10 22:56:29 +00001167static EVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +00001168 const TargetInstrInfo *TII) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001169 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1170 assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
1171 unsigned NumRes = MCID.getNumDefs();
Craig Topper5a4bcc72012-03-08 08:22:45 +00001172 for (const uint16_t *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Evan Cheng8e136a92007-09-26 21:36:17 +00001173 if (Reg == *ImpDef)
1174 break;
1175 ++NumRes;
1176 }
1177 return N->getValueType(NumRes);
1178}
1179
Evan Chengb8905c42009-03-04 01:41:49 +00001180/// CheckForLiveRegDef - Return true and update live register vector if the
1181/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001182static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Evan Chengb8905c42009-03-04 01:41:49 +00001183 std::vector<SUnit*> &LiveRegDefs,
1184 SmallSet<unsigned, 4> &RegAdded,
1185 SmallVector<unsigned, 4> &LRegs,
1186 const TargetRegisterInfo *TRI) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001187 for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
Andrew Trick12acde112010-12-23 03:43:21 +00001188
1189 // Check if Ref is live.
Andrew Trick0af2e472011-06-07 00:38:12 +00001190 if (!LiveRegDefs[*AliasI]) continue;
Andrew Trick12acde112010-12-23 03:43:21 +00001191
1192 // Allow multiple uses of the same def.
Andrew Trick0af2e472011-06-07 00:38:12 +00001193 if (LiveRegDefs[*AliasI] == SU) continue;
Andrew Trick12acde112010-12-23 03:43:21 +00001194
1195 // Add Reg to the set of interfering live regs.
Andrew Trick0af2e472011-06-07 00:38:12 +00001196 if (RegAdded.insert(*AliasI)) {
Andrew Trick0af2e472011-06-07 00:38:12 +00001197 LRegs.push_back(*AliasI);
1198 }
Evan Chengb8905c42009-03-04 01:41:49 +00001199 }
Evan Chengb8905c42009-03-04 01:41:49 +00001200}
1201
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001202/// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
1203/// by RegMask, and add them to LRegs.
1204static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
1205 std::vector<SUnit*> &LiveRegDefs,
1206 SmallSet<unsigned, 4> &RegAdded,
1207 SmallVector<unsigned, 4> &LRegs) {
1208 // Look at all live registers. Skip Reg0 and the special CallResource.
1209 for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
1210 if (!LiveRegDefs[i]) continue;
1211 if (LiveRegDefs[i] == SU) continue;
1212 if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
1213 if (RegAdded.insert(i))
1214 LRegs.push_back(i);
1215 }
1216}
1217
1218/// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
1219static const uint32_t *getNodeRegMask(const SDNode *N) {
1220 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1221 if (const RegisterMaskSDNode *Op =
1222 dyn_cast<RegisterMaskSDNode>(N->getOperand(i).getNode()))
1223 return Op->getRegMask();
1224 return NULL;
1225}
1226
Evan Cheng5924bf72007-09-25 01:54:36 +00001227/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1228/// scheduling of the given node to satisfy live physical register dependencies.
1229/// If the specific node is the last one that's available to schedule, do
1230/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001231bool ScheduleDAGRRList::
1232DelayForLiveRegsBottomUp(SUnit *SU, SmallVector<unsigned, 4> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +00001233 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +00001234 return false;
1235
Evan Chenge6f92252007-09-27 18:46:06 +00001236 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +00001237 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001238 //
1239 // If SU is the currently live definition of the same register that it uses,
1240 // then we are free to schedule it.
Evan Cheng5924bf72007-09-25 01:54:36 +00001241 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1242 I != E; ++I) {
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001243 if (I->isAssignedRegDep() && LiveRegDefs[I->getReg()] != SU)
Evan Chengb8905c42009-03-04 01:41:49 +00001244 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
1245 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001246 }
1247
Chris Lattner11a33812010-12-23 17:24:32 +00001248 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +00001249 if (Node->getOpcode() == ISD::INLINEASM) {
1250 // Inline asm can clobber physical defs.
1251 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +00001252 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +00001253 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +00001254
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001255 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +00001256 unsigned Flags =
1257 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001258 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +00001259
1260 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001261 if (InlineAsm::isRegDefKind(Flags) ||
Jakob Stoklund Olesen537a3022011-06-27 04:08:33 +00001262 InlineAsm::isRegDefEarlyClobberKind(Flags) ||
1263 InlineAsm::isClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +00001264 // Check for def of register or earlyclobber register.
1265 for (; NumVals; --NumVals, ++i) {
1266 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1267 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1268 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
1269 }
1270 } else
1271 i += NumVals;
1272 }
1273 continue;
1274 }
1275
Dan Gohman072734e2008-11-13 23:24:17 +00001276 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +00001277 continue;
Dan Gohman198b7ff2011-11-03 21:49:52 +00001278 // If we're in the middle of scheduling a call, don't begin scheduling
1279 // another call. Also, don't allow any physical registers to be live across
1280 // the call.
1281 if (Node->getMachineOpcode() == (unsigned)TII->getCallFrameDestroyOpcode()) {
1282 // Check the special calling-sequence resource.
1283 unsigned CallResource = TRI->getNumRegs();
1284 if (LiveRegDefs[CallResource]) {
1285 SDNode *Gen = LiveRegGens[CallResource]->getNode();
1286 while (SDNode *Glued = Gen->getGluedNode())
1287 Gen = Glued;
1288 if (!IsChainDependent(Gen, Node, 0, TII) && RegAdded.insert(CallResource))
1289 LRegs.push_back(CallResource);
1290 }
1291 }
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001292 if (const uint32_t *RegMask = getNodeRegMask(Node))
1293 CheckForLiveRegDefMasked(SU, RegMask, LiveRegDefs, RegAdded, LRegs);
1294
Evan Cheng6cc775f2011-06-28 19:10:37 +00001295 const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
1296 if (!MCID.ImplicitDefs)
Evan Cheng5924bf72007-09-25 01:54:36 +00001297 continue;
Craig Topper5a4bcc72012-03-08 08:22:45 +00001298 for (const uint16_t *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
Evan Chengb8905c42009-03-04 01:41:49 +00001299 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001300 }
Andrew Trick2085a962010-12-21 22:25:04 +00001301
Evan Cheng5924bf72007-09-25 01:54:36 +00001302 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +00001303}
1304
Andrew Trick528fad92010-12-23 05:42:20 +00001305/// Return a node that can be scheduled in this cycle. Requirements:
1306/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001307/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +00001308/// (3) No Interferences: may unschedule to break register interferences.
1309SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1310 SmallVector<SUnit*, 4> Interferences;
1311 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
1312
1313 SUnit *CurSU = AvailableQueue->pop();
1314 while (CurSU) {
1315 SmallVector<unsigned, 4> LRegs;
1316 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1317 break;
1318 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1319
1320 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1321 Interferences.push_back(CurSU);
1322 CurSU = AvailableQueue->pop();
1323 }
1324 if (CurSU) {
1325 // Add the nodes that aren't ready back onto the available list.
1326 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1327 Interferences[i]->isPending = false;
1328 assert(Interferences[i]->isAvailable && "must still be available");
1329 AvailableQueue->push(Interferences[i]);
1330 }
1331 return CurSU;
1332 }
1333
1334 // All candidates are delayed due to live physical reg dependencies.
1335 // Try backtracking, code duplication, or inserting cross class copies
1336 // to resolve it.
1337 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1338 SUnit *TrySU = Interferences[i];
1339 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1340
1341 // Try unscheduling up to the point where it's safe to schedule
1342 // this node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001343 SUnit *BtSU = NULL;
1344 unsigned LiveCycle = UINT_MAX;
Andrew Trick528fad92010-12-23 05:42:20 +00001345 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
1346 unsigned Reg = LRegs[j];
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001347 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1348 BtSU = LiveRegGens[Reg];
1349 LiveCycle = BtSU->getHeight();
1350 }
Andrew Trick528fad92010-12-23 05:42:20 +00001351 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001352 if (!WillCreateCycle(TrySU, BtSU)) {
1353 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001354
1355 // Force the current node to be scheduled before the node that
1356 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001357 if (BtSU->isAvailable) {
1358 BtSU->isAvailable = false;
1359 if (!BtSU->isPending)
1360 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001361 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001362 AddPred(TrySU, SDep(BtSU, SDep::Order, /*Latency=*/1,
Andrew Trick528fad92010-12-23 05:42:20 +00001363 /*Reg=*/0, /*isNormalMemory=*/false,
1364 /*isMustAlias=*/false, /*isArtificial=*/true));
1365
1366 // If one or more successors has been unscheduled, then the current
1367 // node is no longer avaialable. Schedule a successor that's now
1368 // available instead.
1369 if (!TrySU->isAvailable) {
1370 CurSU = AvailableQueue->pop();
1371 }
1372 else {
1373 CurSU = TrySU;
1374 TrySU->isPending = false;
1375 Interferences.erase(Interferences.begin()+i);
1376 }
1377 break;
1378 }
1379 }
1380
1381 if (!CurSU) {
1382 // Can't backtrack. If it's too expensive to copy the value, then try
1383 // duplicate the nodes that produces these "too expensive to copy"
1384 // values to break the dependency. In case even that doesn't work,
1385 // insert cross class copies.
1386 // If it's not too expensive, i.e. cost != -1, issue copies.
1387 SUnit *TrySU = Interferences[0];
1388 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1389 assert(LRegs.size() == 1 && "Can't handle this yet!");
1390 unsigned Reg = LRegs[0];
1391 SUnit *LRDef = LiveRegDefs[Reg];
1392 EVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1393 const TargetRegisterClass *RC =
1394 TRI->getMinimalPhysRegClass(Reg, VT);
1395 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1396
Evan Chengb4c6a342011-03-10 00:16:32 +00001397 // If cross copy register class is the same as RC, then it must be possible
1398 // copy the value directly. Do not try duplicate the def.
1399 // If cross copy register class is not the same as RC, then it's possible to
1400 // copy the value but it require cross register class copies and it is
1401 // expensive.
1402 // If cross copy register class is null, then it's not possible to copy
1403 // the value at all.
Andrew Trick528fad92010-12-23 05:42:20 +00001404 SUnit *NewDef = 0;
Evan Chengb4c6a342011-03-10 00:16:32 +00001405 if (DestRC != RC) {
Andrew Trick528fad92010-12-23 05:42:20 +00001406 NewDef = CopyAndMoveSuccessors(LRDef);
Evan Chengb4c6a342011-03-10 00:16:32 +00001407 if (!DestRC && !NewDef)
1408 report_fatal_error("Can't handle live physical register dependency!");
1409 }
Andrew Trick528fad92010-12-23 05:42:20 +00001410 if (!NewDef) {
1411 // Issue copies, these can be expensive cross register class copies.
1412 SmallVector<SUnit*, 2> Copies;
1413 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1414 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1415 << " to SU #" << Copies.front()->NodeNum << "\n");
1416 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
1417 /*Reg=*/0, /*isNormalMemory=*/false,
1418 /*isMustAlias=*/false,
1419 /*isArtificial=*/true));
1420 NewDef = Copies.back();
1421 }
1422
1423 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1424 << " to SU #" << TrySU->NodeNum << "\n");
1425 LiveRegDefs[Reg] = NewDef;
1426 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
1427 /*Reg=*/0, /*isNormalMemory=*/false,
1428 /*isMustAlias=*/false,
1429 /*isArtificial=*/true));
1430 TrySU->isAvailable = false;
1431 CurSU = NewDef;
1432 }
1433
1434 assert(CurSU && "Unable to resolve live physical register dependencies!");
1435
1436 // Add the nodes that aren't ready back onto the available list.
1437 for (unsigned i = 0, e = Interferences.size(); i != e; ++i) {
1438 Interferences[i]->isPending = false;
1439 // May no longer be available due to backtracking.
1440 if (Interferences[i]->isAvailable) {
1441 AvailableQueue->push(Interferences[i]);
1442 }
1443 }
1444 return CurSU;
1445}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001446
Evan Chengd38c22b2006-05-11 23:55:42 +00001447/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1448/// schedulers.
1449void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001450 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001451 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001452
Evan Chengd38c22b2006-05-11 23:55:42 +00001453 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001454 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001455 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001456 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1457 RootSU->isAvailable = true;
1458 AvailableQueue->push(RootSU);
1459 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001460
1461 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001462 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001463 Sequence.reserve(SUnits.size());
Evan Chengd38c22b2006-05-11 23:55:42 +00001464 while (!AvailableQueue->empty()) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00001465 DEBUG(dbgs() << "\nExamining Available:\n";
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001466 AvailableQueue->dump(this));
1467
Andrew Trick528fad92010-12-23 05:42:20 +00001468 // Pick the best node to schedule taking all constraints into
1469 // consideration.
1470 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001471
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001472 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001473
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001474 ScheduleNodeBottomUp(SU);
1475
1476 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1477 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1478 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1479 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1480 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001481 }
1482
Evan Chengd38c22b2006-05-11 23:55:42 +00001483 // Reverse the order if it is bottom up.
1484 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001485
Evan Chengd38c22b2006-05-11 23:55:42 +00001486#ifndef NDEBUG
Andrew Trick46a58662012-03-07 05:21:36 +00001487 VerifyScheduledSequence(/*isBottomUp=*/true);
Evan Chengd38c22b2006-05-11 23:55:42 +00001488#endif
1489}
1490
1491//===----------------------------------------------------------------------===//
Andrew Trick9ccce772011-01-14 21:11:41 +00001492// RegReductionPriorityQueue Definition
Evan Chengd38c22b2006-05-11 23:55:42 +00001493//===----------------------------------------------------------------------===//
1494//
1495// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1496// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001497//
Evan Chengd38c22b2006-05-11 23:55:42 +00001498namespace {
Andrew Trick9ccce772011-01-14 21:11:41 +00001499class RegReductionPQBase;
Andrew Trick2085a962010-12-21 22:25:04 +00001500
Andrew Trick9ccce772011-01-14 21:11:41 +00001501struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1502 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1503};
1504
Andrew Trick3013b6a2011-06-15 17:16:12 +00001505#ifndef NDEBUG
1506template<class SF>
1507struct reverse_sort : public queue_sort {
1508 SF &SortFunc;
1509 reverse_sort(SF &sf) : SortFunc(sf) {}
1510 reverse_sort(const reverse_sort &RHS) : SortFunc(RHS.SortFunc) {}
1511
1512 bool operator()(SUnit* left, SUnit* right) const {
1513 // reverse left/right rather than simply !SortFunc(left, right)
1514 // to expose different paths in the comparison logic.
1515 return SortFunc(right, left);
1516 }
1517};
1518#endif // NDEBUG
1519
Andrew Trick9ccce772011-01-14 21:11:41 +00001520/// bu_ls_rr_sort - Priority function for bottom up register pressure
1521// reduction scheduler.
1522struct bu_ls_rr_sort : public queue_sort {
1523 enum {
1524 IsBottomUp = true,
1525 HasReadyFilter = false
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001526 };
1527
Andrew Trick9ccce772011-01-14 21:11:41 +00001528 RegReductionPQBase *SPQ;
1529 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1530 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001531
Andrew Trick9ccce772011-01-14 21:11:41 +00001532 bool operator()(SUnit* left, SUnit* right) const;
1533};
Andrew Trick2085a962010-12-21 22:25:04 +00001534
Andrew Trick9ccce772011-01-14 21:11:41 +00001535// src_ls_rr_sort - Priority function for source order scheduler.
1536struct src_ls_rr_sort : public queue_sort {
1537 enum {
1538 IsBottomUp = true,
1539 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001540 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001541
Andrew Trick9ccce772011-01-14 21:11:41 +00001542 RegReductionPQBase *SPQ;
1543 src_ls_rr_sort(RegReductionPQBase *spq)
1544 : SPQ(spq) {}
1545 src_ls_rr_sort(const src_ls_rr_sort &RHS)
1546 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001547
Andrew Trick9ccce772011-01-14 21:11:41 +00001548 bool operator()(SUnit* left, SUnit* right) const;
1549};
Andrew Trick2085a962010-12-21 22:25:04 +00001550
Andrew Trick9ccce772011-01-14 21:11:41 +00001551// hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1552struct hybrid_ls_rr_sort : public queue_sort {
1553 enum {
1554 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001555 HasReadyFilter = false
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001556 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001557
Andrew Trick9ccce772011-01-14 21:11:41 +00001558 RegReductionPQBase *SPQ;
1559 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1560 : SPQ(spq) {}
1561 hybrid_ls_rr_sort(const hybrid_ls_rr_sort &RHS)
1562 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001563
Andrew Trick9ccce772011-01-14 21:11:41 +00001564 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Chenga77f3d32010-07-21 06:09:07 +00001565
Andrew Trick9ccce772011-01-14 21:11:41 +00001566 bool operator()(SUnit* left, SUnit* right) const;
1567};
1568
1569// ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1570// scheduler.
1571struct ilp_ls_rr_sort : public queue_sort {
1572 enum {
1573 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001574 HasReadyFilter = false
Evan Chengbdd062d2010-05-20 06:13:19 +00001575 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001576
Andrew Trick9ccce772011-01-14 21:11:41 +00001577 RegReductionPQBase *SPQ;
1578 ilp_ls_rr_sort(RegReductionPQBase *spq)
1579 : SPQ(spq) {}
1580 ilp_ls_rr_sort(const ilp_ls_rr_sort &RHS)
1581 : SPQ(RHS.SPQ) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001582
Andrew Trick9ccce772011-01-14 21:11:41 +00001583 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Cheng37b740c2010-07-24 00:39:05 +00001584
Andrew Trick9ccce772011-01-14 21:11:41 +00001585 bool operator()(SUnit* left, SUnit* right) const;
1586};
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001587
Andrew Trick9ccce772011-01-14 21:11:41 +00001588class RegReductionPQBase : public SchedulingPriorityQueue {
1589protected:
1590 std::vector<SUnit*> Queue;
1591 unsigned CurQueueId;
1592 bool TracksRegPressure;
Evan Cheng8ab58a22012-03-22 19:31:17 +00001593 bool SrcOrder;
Andrew Trick9ccce772011-01-14 21:11:41 +00001594
1595 // SUnits - The SUnits for the current graph.
1596 std::vector<SUnit> *SUnits;
1597
1598 MachineFunction &MF;
1599 const TargetInstrInfo *TII;
1600 const TargetRegisterInfo *TRI;
1601 const TargetLowering *TLI;
1602 ScheduleDAGRRList *scheduleDAG;
1603
1604 // SethiUllmanNumbers - The SethiUllman number for each node.
1605 std::vector<unsigned> SethiUllmanNumbers;
1606
1607 /// RegPressure - Tracking current reg pressure per register class.
1608 ///
1609 std::vector<unsigned> RegPressure;
1610
1611 /// RegLimit - Tracking the number of allocatable registers per register
1612 /// class.
1613 std::vector<unsigned> RegLimit;
1614
1615public:
1616 RegReductionPQBase(MachineFunction &mf,
1617 bool hasReadyFilter,
1618 bool tracksrp,
Evan Cheng8ab58a22012-03-22 19:31:17 +00001619 bool srcorder,
Andrew Trick9ccce772011-01-14 21:11:41 +00001620 const TargetInstrInfo *tii,
1621 const TargetRegisterInfo *tri,
1622 const TargetLowering *tli)
1623 : SchedulingPriorityQueue(hasReadyFilter),
Evan Cheng8ab58a22012-03-22 19:31:17 +00001624 CurQueueId(0), TracksRegPressure(tracksrp), SrcOrder(srcorder),
Andrew Trick9ccce772011-01-14 21:11:41 +00001625 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
1626 if (TracksRegPressure) {
1627 unsigned NumRC = TRI->getNumRegClasses();
1628 RegLimit.resize(NumRC);
1629 RegPressure.resize(NumRC);
1630 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1631 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1632 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1633 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichdf616942011-03-07 21:56:36 +00001634 RegLimit[(*I)->getID()] = tri->getRegPressureLimit(*I, MF);
Andrew Trick9ccce772011-01-14 21:11:41 +00001635 }
1636 }
1637
1638 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1639 scheduleDAG = scheduleDag;
1640 }
1641
1642 ScheduleHazardRecognizer* getHazardRec() {
1643 return scheduleDAG->getHazardRec();
1644 }
1645
1646 void initNodes(std::vector<SUnit> &sunits);
1647
1648 void addNode(const SUnit *SU);
1649
1650 void updateNode(const SUnit *SU);
1651
1652 void releaseState() {
1653 SUnits = 0;
1654 SethiUllmanNumbers.clear();
1655 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1656 }
1657
1658 unsigned getNodePriority(const SUnit *SU) const;
1659
1660 unsigned getNodeOrdering(const SUnit *SU) const {
Andrew Trick3bd8b7a2011-03-25 06:40:55 +00001661 if (!SU->getNode()) return 0;
1662
Andrew Trick9ccce772011-01-14 21:11:41 +00001663 return scheduleDAG->DAG->GetOrdering(SU->getNode());
1664 }
1665
1666 bool empty() const { return Queue.empty(); }
1667
1668 void push(SUnit *U) {
1669 assert(!U->NodeQueueId && "Node in the queue already");
1670 U->NodeQueueId = ++CurQueueId;
1671 Queue.push_back(U);
1672 }
1673
1674 void remove(SUnit *SU) {
1675 assert(!Queue.empty() && "Queue is empty!");
1676 assert(SU->NodeQueueId != 0 && "Not in queue!");
1677 std::vector<SUnit *>::iterator I = std::find(Queue.begin(), Queue.end(),
1678 SU);
1679 if (I != prior(Queue.end()))
1680 std::swap(*I, Queue.back());
1681 Queue.pop_back();
1682 SU->NodeQueueId = 0;
1683 }
1684
Andrew Trickd0548ae2011-02-04 03:18:17 +00001685 bool tracksRegPressure() const { return TracksRegPressure; }
1686
Andrew Trick9ccce772011-01-14 21:11:41 +00001687 void dumpRegPressure() const;
1688
1689 bool HighRegPressure(const SUnit *SU) const;
1690
Andrew Trick641e2d42011-03-05 08:00:22 +00001691 bool MayReduceRegPressure(SUnit *SU) const;
1692
1693 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
Andrew Trick9ccce772011-01-14 21:11:41 +00001694
Andrew Trick52226d42012-03-07 23:00:49 +00001695 void scheduledNode(SUnit *SU);
Andrew Trick9ccce772011-01-14 21:11:41 +00001696
Andrew Trick52226d42012-03-07 23:00:49 +00001697 void unscheduledNode(SUnit *SU);
Andrew Trick9ccce772011-01-14 21:11:41 +00001698
1699protected:
1700 bool canClobber(const SUnit *SU, const SUnit *Op);
Duncan Sands635e4ef2011-11-09 14:20:48 +00001701 void AddPseudoTwoAddrDeps();
Andrew Trick9ccce772011-01-14 21:11:41 +00001702 void PrescheduleNodesWithMultipleUses();
1703 void CalculateSethiUllmanNumbers();
1704};
1705
1706template<class SF>
Andrew Trick3013b6a2011-06-15 17:16:12 +00001707static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
1708 std::vector<SUnit *>::iterator Best = Q.begin();
1709 for (std::vector<SUnit *>::iterator I = llvm::next(Q.begin()),
1710 E = Q.end(); I != E; ++I)
1711 if (Picker(*Best, *I))
1712 Best = I;
1713 SUnit *V = *Best;
1714 if (Best != prior(Q.end()))
1715 std::swap(*Best, Q.back());
1716 Q.pop_back();
1717 return V;
1718}
Andrew Trick9ccce772011-01-14 21:11:41 +00001719
Andrew Trick3013b6a2011-06-15 17:16:12 +00001720template<class SF>
1721SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
1722#ifndef NDEBUG
1723 if (DAG->StressSched) {
1724 reverse_sort<SF> RPicker(Picker);
1725 return popFromQueueImpl(Q, RPicker);
1726 }
1727#endif
1728 (void)DAG;
1729 return popFromQueueImpl(Q, Picker);
1730}
1731
1732template<class SF>
1733class RegReductionPriorityQueue : public RegReductionPQBase {
Andrew Trick9ccce772011-01-14 21:11:41 +00001734 SF Picker;
1735
1736public:
1737 RegReductionPriorityQueue(MachineFunction &mf,
1738 bool tracksrp,
Evan Cheng8ab58a22012-03-22 19:31:17 +00001739 bool srcorder,
Andrew Trick9ccce772011-01-14 21:11:41 +00001740 const TargetInstrInfo *tii,
1741 const TargetRegisterInfo *tri,
1742 const TargetLowering *tli)
Evan Cheng8ab58a22012-03-22 19:31:17 +00001743 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
1744 tii, tri, tli),
Andrew Trick9ccce772011-01-14 21:11:41 +00001745 Picker(this) {}
1746
1747 bool isBottomUp() const { return SF::IsBottomUp; }
1748
1749 bool isReady(SUnit *U) const {
1750 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1751 }
1752
1753 SUnit *pop() {
1754 if (Queue.empty()) return NULL;
1755
Andrew Trick3013b6a2011-06-15 17:16:12 +00001756 SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
Andrew Trick9ccce772011-01-14 21:11:41 +00001757 V->NodeQueueId = 0;
1758 return V;
1759 }
1760
1761 void dump(ScheduleDAG *DAG) const {
1762 // Emulate pop() without clobbering NodeQueueIds.
1763 std::vector<SUnit*> DumpQueue = Queue;
1764 SF DumpPicker = Picker;
1765 while (!DumpQueue.empty()) {
Andrew Trick3013b6a2011-06-15 17:16:12 +00001766 SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
Dan Gohman90fb5522011-10-20 21:44:34 +00001767 dbgs() << "Height " << SU->getHeight() << ": ";
Andrew Trick9ccce772011-01-14 21:11:41 +00001768 SU->dump(DAG);
1769 }
1770 }
1771};
1772
1773typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1774BURegReductionPriorityQueue;
1775
Andrew Trick9ccce772011-01-14 21:11:41 +00001776typedef RegReductionPriorityQueue<src_ls_rr_sort>
1777SrcRegReductionPriorityQueue;
1778
1779typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1780HybridBURRPriorityQueue;
1781
1782typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1783ILPBURRPriorityQueue;
1784} // end anonymous namespace
1785
1786//===----------------------------------------------------------------------===//
1787// Static Node Priority for Register Pressure Reduction
1788//===----------------------------------------------------------------------===//
Evan Chengd38c22b2006-05-11 23:55:42 +00001789
Andrew Trickbfbd9722011-04-14 05:15:06 +00001790// Check for special nodes that bypass scheduling heuristics.
1791// Currently this pushes TokenFactor nodes down, but may be used for other
1792// pseudo-ops as well.
1793//
1794// Return -1 to schedule right above left, 1 for left above right.
1795// Return 0 if no bias exists.
1796static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
1797 bool LSchedLow = left->isScheduleLow;
1798 bool RSchedLow = right->isScheduleLow;
1799 if (LSchedLow != RSchedLow)
1800 return LSchedLow < RSchedLow ? 1 : -1;
1801 return 0;
1802}
1803
Dan Gohman186f65d2008-11-20 03:30:37 +00001804/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1805/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001806static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001807CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001808 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1809 if (SethiUllmanNumber != 0)
1810 return SethiUllmanNumber;
1811
1812 unsigned Extra = 0;
1813 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1814 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00001815 if (I->isCtrl()) continue; // ignore chain preds
1816 SUnit *PredSU = I->getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001817 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001818 if (PredSethiUllman > SethiUllmanNumber) {
1819 SethiUllmanNumber = PredSethiUllman;
1820 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001821 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001822 ++Extra;
1823 }
1824
1825 SethiUllmanNumber += Extra;
1826
1827 if (SethiUllmanNumber == 0)
1828 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001829
Evan Cheng7e4abde2008-07-02 09:23:51 +00001830 return SethiUllmanNumber;
1831}
1832
Andrew Trick9ccce772011-01-14 21:11:41 +00001833/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1834/// scheduling units.
1835void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1836 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001837
Andrew Trick9ccce772011-01-14 21:11:41 +00001838 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1839 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
Evan Chengd38c22b2006-05-11 23:55:42 +00001840}
1841
Andrew Trick9ccce772011-01-14 21:11:41 +00001842void RegReductionPQBase::addNode(const SUnit *SU) {
1843 unsigned SUSize = SethiUllmanNumbers.size();
1844 if (SUnits->size() > SUSize)
1845 SethiUllmanNumbers.resize(SUSize*2, 0);
1846 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1847}
1848
1849void RegReductionPQBase::updateNode(const SUnit *SU) {
1850 SethiUllmanNumbers[SU->NodeNum] = 0;
1851 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1852}
1853
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001854// Lower priority means schedule further down. For bottom-up scheduling, lower
1855// priority SUs are scheduled before higher priority SUs.
Andrew Trick9ccce772011-01-14 21:11:41 +00001856unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1857 assert(SU->NodeNum < SethiUllmanNumbers.size());
1858 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1859 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1860 // CopyToReg should be close to its uses to facilitate coalescing and
1861 // avoid spilling.
1862 return 0;
1863 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1864 Opc == TargetOpcode::SUBREG_TO_REG ||
1865 Opc == TargetOpcode::INSERT_SUBREG)
1866 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1867 // close to their uses to facilitate coalescing.
1868 return 0;
1869 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1870 // If SU does not have a register use, i.e. it doesn't produce a value
1871 // that would be consumed (e.g. store), then it terminates a chain of
1872 // computation. Give it a large SethiUllman number so it will be
1873 // scheduled right before its predecessors that it doesn't lengthen
1874 // their live ranges.
1875 return 0xffff;
1876 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1877 // If SU does not have a register def, schedule it close to its uses
1878 // because it does not lengthen any live ranges.
1879 return 0;
Evan Cheng1355bbd2011-04-26 21:31:35 +00001880#if 1
Andrew Trick9ccce772011-01-14 21:11:41 +00001881 return SethiUllmanNumbers[SU->NodeNum];
Evan Cheng1355bbd2011-04-26 21:31:35 +00001882#else
1883 unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
1884 if (SU->isCallOp) {
1885 // FIXME: This assumes all of the defs are used as call operands.
1886 int NP = (int)Priority - SU->getNode()->getNumValues();
1887 return (NP > 0) ? NP : 0;
1888 }
1889 return Priority;
1890#endif
Andrew Trick9ccce772011-01-14 21:11:41 +00001891}
1892
1893//===----------------------------------------------------------------------===//
1894// Register Pressure Tracking
1895//===----------------------------------------------------------------------===//
1896
1897void RegReductionPQBase::dumpRegPressure() const {
1898 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
1899 E = TRI->regclass_end(); I != E; ++I) {
1900 const TargetRegisterClass *RC = *I;
1901 unsigned Id = RC->getID();
1902 unsigned RP = RegPressure[Id];
1903 if (!RP) continue;
1904 DEBUG(dbgs() << RC->getName() << ": " << RP << " / " << RegLimit[Id]
1905 << '\n');
1906 }
1907}
1908
1909bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1910 if (!TLI)
1911 return false;
1912
1913 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1914 I != E; ++I) {
1915 if (I->isCtrl())
1916 continue;
1917 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001918 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1919 // to cover the number of registers defined (they are all live).
1920 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001921 continue;
1922 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001923 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1924 RegDefPos.IsValid(); RegDefPos.Advance()) {
Owen Anderson96adc4a2011-06-15 23:35:18 +00001925 unsigned RCId, Cost;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001926 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
Owen Anderson96adc4a2011-06-15 23:35:18 +00001927
Andrew Trick9ccce772011-01-14 21:11:41 +00001928 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1929 return true;
1930 }
1931 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001932 return false;
1933}
1934
Andrew Trick641e2d42011-03-05 08:00:22 +00001935bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00001936 const SDNode *N = SU->getNode();
1937
1938 if (!N->isMachineOpcode() || !SU->NumSuccs)
1939 return false;
1940
1941 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1942 for (unsigned i = 0; i != NumDefs; ++i) {
1943 EVT VT = N->getValueType(i);
1944 if (!N->hasAnyUseOfValue(i))
1945 continue;
1946 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1947 if (RegPressure[RCId] >= RegLimit[RCId])
1948 return true;
1949 }
1950 return false;
1951}
1952
Andrew Trick641e2d42011-03-05 08:00:22 +00001953// Compute the register pressure contribution by this instruction by count up
1954// for uses that are not live and down for defs. Only count register classes
1955// that are already under high pressure. As a side effect, compute the number of
1956// uses of registers that are already live.
1957//
1958// FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1959// so could probably be factored.
1960int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1961 LiveUses = 0;
1962 int PDiff = 0;
1963 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
1964 I != E; ++I) {
1965 if (I->isCtrl())
1966 continue;
1967 SUnit *PredSU = I->getSUnit();
1968 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1969 // to cover the number of registers defined (they are all live).
1970 if (PredSU->NumRegDefsLeft == 0) {
1971 if (PredSU->getNode()->isMachineOpcode())
1972 ++LiveUses;
1973 continue;
1974 }
1975 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1976 RegDefPos.IsValid(); RegDefPos.Advance()) {
1977 EVT VT = RegDefPos.GetValue();
1978 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1979 if (RegPressure[RCId] >= RegLimit[RCId])
1980 ++PDiff;
1981 }
1982 }
1983 const SDNode *N = SU->getNode();
1984
Eric Christopher7238cba2011-03-08 19:35:47 +00001985 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
Andrew Trick641e2d42011-03-05 08:00:22 +00001986 return PDiff;
1987
1988 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1989 for (unsigned i = 0; i != NumDefs; ++i) {
1990 EVT VT = N->getValueType(i);
1991 if (!N->hasAnyUseOfValue(i))
1992 continue;
1993 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1994 if (RegPressure[RCId] >= RegLimit[RCId])
1995 --PDiff;
1996 }
1997 return PDiff;
1998}
1999
Andrew Trick52226d42012-03-07 23:00:49 +00002000void RegReductionPQBase::scheduledNode(SUnit *SU) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002001 if (!TracksRegPressure)
2002 return;
2003
Eric Christopher7238cba2011-03-08 19:35:47 +00002004 if (!SU->getNode())
2005 return;
Andrew Tricka8846e02011-03-23 20:40:18 +00002006
Andrew Trick9ccce772011-01-14 21:11:41 +00002007 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2008 I != E; ++I) {
2009 if (I->isCtrl())
2010 continue;
2011 SUnit *PredSU = I->getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00002012 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2013 // to cover the number of registers defined (they are all live).
2014 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002015 continue;
2016 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00002017 // FIXME: The ScheduleDAG currently loses information about which of a
2018 // node's values is consumed by each dependence. Consequently, if the node
2019 // defines multiple register classes, we don't know which to pressurize
2020 // here. Instead the following loop consumes the register defs in an
2021 // arbitrary order. At least it handles the common case of clustered loads
2022 // to the same class. For precise liveness, each SDep needs to indicate the
2023 // result number. But that tightly couples the ScheduleDAG with the
2024 // SelectionDAG making updates tricky. A simpler hack would be to attach a
2025 // value type or register class to SDep.
2026 //
2027 // The most important aspect of register tracking is balancing the increase
2028 // here with the reduction further below. Note that this SU may use multiple
2029 // defs in PredSU. The can't be determined here, but we've already
2030 // compensated by reducing NumRegDefsLeft in PredSU during
2031 // ScheduleDAGSDNodes::AddSchedEdges.
2032 --PredSU->NumRegDefsLeft;
2033 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
2034 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2035 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2036 if (SkipRegDefs)
Andrew Trick9ccce772011-01-14 21:11:41 +00002037 continue;
Owen Anderson96adc4a2011-06-15 23:35:18 +00002038
2039 unsigned RCId, Cost;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00002040 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
Owen Anderson96adc4a2011-06-15 23:35:18 +00002041 RegPressure[RCId] += Cost;
Andrew Trickd0548ae2011-02-04 03:18:17 +00002042 break;
Andrew Trick9ccce772011-01-14 21:11:41 +00002043 }
2044 }
2045
Andrew Trickd0548ae2011-02-04 03:18:17 +00002046 // We should have this assert, but there may be dead SDNodes that never
2047 // materialize as SUnits, so they don't appear to generate liveness.
2048 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
2049 int SkipRegDefs = (int)SU->NumRegDefsLeft;
2050 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
2051 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2052 if (SkipRegDefs > 0)
2053 continue;
Owen Anderson96adc4a2011-06-15 23:35:18 +00002054 unsigned RCId, Cost;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00002055 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
Owen Anderson96adc4a2011-06-15 23:35:18 +00002056 if (RegPressure[RCId] < Cost) {
Andrew Trickd0548ae2011-02-04 03:18:17 +00002057 // Register pressure tracking is imprecise. This can happen. But we try
2058 // hard not to let it happen because it likely results in poor scheduling.
2059 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
2060 RegPressure[RCId] = 0;
2061 }
2062 else {
Owen Anderson96adc4a2011-06-15 23:35:18 +00002063 RegPressure[RCId] -= Cost;
Andrew Trick9ccce772011-01-14 21:11:41 +00002064 }
2065 }
Andrew Trick9ccce772011-01-14 21:11:41 +00002066 dumpRegPressure();
2067}
2068
Andrew Trick52226d42012-03-07 23:00:49 +00002069void RegReductionPQBase::unscheduledNode(SUnit *SU) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002070 if (!TracksRegPressure)
2071 return;
2072
2073 const SDNode *N = SU->getNode();
Eric Christopher7238cba2011-03-08 19:35:47 +00002074 if (!N) return;
Andrew Tricka8846e02011-03-23 20:40:18 +00002075
Andrew Trick9ccce772011-01-14 21:11:41 +00002076 if (!N->isMachineOpcode()) {
2077 if (N->getOpcode() != ISD::CopyToReg)
2078 return;
2079 } else {
2080 unsigned Opc = N->getMachineOpcode();
2081 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2082 Opc == TargetOpcode::INSERT_SUBREG ||
2083 Opc == TargetOpcode::SUBREG_TO_REG ||
2084 Opc == TargetOpcode::REG_SEQUENCE ||
2085 Opc == TargetOpcode::IMPLICIT_DEF)
2086 return;
2087 }
2088
2089 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2090 I != E; ++I) {
2091 if (I->isCtrl())
2092 continue;
2093 SUnit *PredSU = I->getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002094 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
2095 // counts data deps.
2096 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00002097 continue;
2098 const SDNode *PN = PredSU->getNode();
2099 if (!PN->isMachineOpcode()) {
2100 if (PN->getOpcode() == ISD::CopyFromReg) {
2101 EVT VT = PN->getValueType(0);
2102 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2103 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2104 }
2105 continue;
2106 }
2107 unsigned POpc = PN->getMachineOpcode();
2108 if (POpc == TargetOpcode::IMPLICIT_DEF)
2109 continue;
Andrew Trick31f25bc2011-06-27 18:01:20 +00002110 if (POpc == TargetOpcode::EXTRACT_SUBREG ||
2111 POpc == TargetOpcode::INSERT_SUBREG ||
2112 POpc == TargetOpcode::SUBREG_TO_REG) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002113 EVT VT = PN->getValueType(0);
2114 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2115 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2116 continue;
2117 }
2118 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
2119 for (unsigned i = 0; i != NumDefs; ++i) {
2120 EVT VT = PN->getValueType(i);
2121 if (!PN->hasAnyUseOfValue(i))
2122 continue;
2123 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2124 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
2125 // Register pressure tracking is imprecise. This can happen.
2126 RegPressure[RCId] = 0;
2127 else
2128 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
2129 }
2130 }
2131
2132 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
2133 // may transfer data dependencies to CopyToReg.
2134 if (SU->NumSuccs && N->isMachineOpcode()) {
2135 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2136 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2137 EVT VT = N->getValueType(i);
2138 if (VT == MVT::Glue || VT == MVT::Other)
2139 continue;
2140 if (!N->hasAnyUseOfValue(i))
2141 continue;
2142 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2143 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2144 }
2145 }
2146
2147 dumpRegPressure();
2148}
2149
2150//===----------------------------------------------------------------------===//
2151// Dynamic Node Priority for Register Pressure Reduction
2152//===----------------------------------------------------------------------===//
2153
Evan Chengb9e3db62007-03-14 22:43:40 +00002154/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00002155/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00002156static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002157 unsigned MaxHeight = 0;
Evan Cheng28748552007-03-13 23:25:11 +00002158 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
Evan Chengb9e3db62007-03-14 22:43:40 +00002159 I != E; ++I) {
Evan Chengce3bbe52009-02-10 08:30:11 +00002160 if (I->isCtrl()) continue; // ignore chain succs
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002161 unsigned Height = I->getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00002162 // If there are bunch of CopyToRegs stacked up, they should be considered
2163 // to be at the same position.
Dan Gohman2d170892008-12-09 22:54:47 +00002164 if (I->getSUnit()->getNode() &&
2165 I->getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002166 Height = closestSucc(I->getSUnit())+1;
2167 if (Height > MaxHeight)
2168 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00002169 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002170 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00002171}
2172
Evan Cheng61bc51e2007-12-20 02:22:36 +00002173/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00002174/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00002175static unsigned calcMaxScratches(const SUnit *SU) {
2176 unsigned Scratches = 0;
2177 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Evan Chengb5704992009-02-12 09:52:13 +00002178 I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002179 if (I->isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00002180 Scratches++;
2181 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00002182 return Scratches;
2183}
2184
Andrew Trickb53a00d2011-04-13 00:38:32 +00002185/// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2186/// CopyFromReg from a virtual register.
2187static bool hasOnlyLiveInOpers(const SUnit *SU) {
2188 bool RetVal = false;
2189 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
2190 I != E; ++I) {
2191 if (I->isCtrl()) continue;
2192 const SUnit *PredSU = I->getSUnit();
2193 if (PredSU->getNode() &&
2194 PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2195 unsigned Reg =
2196 cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2197 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2198 RetVal = true;
2199 continue;
2200 }
2201 }
2202 return false;
2203 }
2204 return RetVal;
2205}
2206
2207/// hasOnlyLiveOutUses - Return true if SU has only value successors that are
Evan Cheng6c1414f2010-10-29 18:09:28 +00002208/// CopyToReg to a virtual register. This SU def is probably a liveout and
2209/// it has no other use. It should be scheduled closer to the terminator.
2210static bool hasOnlyLiveOutUses(const SUnit *SU) {
2211 bool RetVal = false;
2212 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
2213 I != E; ++I) {
2214 if (I->isCtrl()) continue;
2215 const SUnit *SuccSU = I->getSUnit();
2216 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2217 unsigned Reg =
2218 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2219 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2220 RetVal = true;
2221 continue;
2222 }
2223 }
2224 return false;
2225 }
2226 return RetVal;
2227}
2228
Andrew Trickb53a00d2011-04-13 00:38:32 +00002229// Set isVRegCycle for a node with only live in opers and live out uses. Also
2230// set isVRegCycle for its CopyFromReg operands.
2231//
2232// This is only relevant for single-block loops, in which case the VRegCycle
2233// node is likely an induction variable in which the operand and target virtual
2234// registers should be coalesced (e.g. pre/post increment values). Setting the
2235// isVRegCycle flag helps the scheduler prioritize other uses of the same
2236// CopyFromReg so that this node becomes the virtual register "kill". This
2237// avoids interference between the values live in and out of the block and
2238// eliminates a copy inside the loop.
2239static void initVRegCycle(SUnit *SU) {
2240 if (DisableSchedVRegCycle)
2241 return;
2242
2243 if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2244 return;
2245
2246 DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
2247
2248 SU->isVRegCycle = true;
2249
2250 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002251 I != E; ++I) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002252 if (I->isCtrl()) continue;
2253 I->getSUnit()->isVRegCycle = true;
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002254 }
Andrew Trick1b60ad62011-04-12 20:14:07 +00002255}
2256
Andrew Trickb53a00d2011-04-13 00:38:32 +00002257// After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2258// CopyFromReg operands. We should no longer penalize other uses of this VReg.
2259static void resetVRegCycle(SUnit *SU) {
2260 if (!SU->isVRegCycle)
2261 return;
2262
2263 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2264 I != E; ++I) {
Andrew Trick1b60ad62011-04-12 20:14:07 +00002265 if (I->isCtrl()) continue; // ignore chain preds
Andrew Trickb53a00d2011-04-13 00:38:32 +00002266 SUnit *PredSU = I->getSUnit();
2267 if (PredSU->isVRegCycle) {
2268 assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2269 "VRegCycle def must be CopyFromReg");
2270 I->getSUnit()->isVRegCycle = 0;
2271 }
2272 }
2273}
2274
2275// Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2276// means a node that defines the VRegCycle has not been scheduled yet.
2277static bool hasVRegCycleUse(const SUnit *SU) {
2278 // If this SU also defines the VReg, don't hoist it as a "use".
2279 if (SU->isVRegCycle)
2280 return false;
2281
2282 for (SUnit::const_pred_iterator I = SU->Preds.begin(),E = SU->Preds.end();
2283 I != E; ++I) {
2284 if (I->isCtrl()) continue; // ignore chain preds
2285 if (I->getSUnit()->isVRegCycle &&
2286 I->getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
2287 DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
2288 return true;
Andrew Trick2ad0b372011-04-07 19:54:57 +00002289 }
2290 }
2291 return false;
2292}
2293
Andrew Trick9ccce772011-01-14 21:11:41 +00002294// Check for either a dependence (latency) or resource (hazard) stall.
2295//
2296// Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2297static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2298 if ((int)SPQ->getCurCycle() < Height) return true;
2299 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2300 != ScheduleHazardRecognizer::NoHazard)
2301 return true;
2302 return false;
2303}
2304
2305// Return -1 if left has higher priority, 1 if right has higher priority.
2306// Return 0 if latency-based priority is equivalent.
2307static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2308 RegReductionPQBase *SPQ) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002309 // Scheduling an instruction that uses a VReg whose postincrement has not yet
2310 // been scheduled will induce a copy. Model this as an extra cycle of latency.
2311 int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2312 int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2313 int LHeight = (int)left->getHeight() + LPenalty;
2314 int RHeight = (int)right->getHeight() + RPenalty;
Andrew Trick9ccce772011-01-14 21:11:41 +00002315
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002316 bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
Andrew Trick9ccce772011-01-14 21:11:41 +00002317 BUHasStall(left, LHeight, SPQ);
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002318 bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
Andrew Trick9ccce772011-01-14 21:11:41 +00002319 BUHasStall(right, RHeight, SPQ);
2320
2321 // If scheduling one of the node will cause a pipeline stall, delay it.
2322 // If scheduling either one of the node will cause a pipeline stall, sort
2323 // them according to their height.
2324 if (LStall) {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002325 if (!RStall)
Andrew Trick9ccce772011-01-14 21:11:41 +00002326 return 1;
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002327 if (LHeight != RHeight)
Andrew Trick9ccce772011-01-14 21:11:41 +00002328 return LHeight > RHeight ? 1 : -1;
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002329 } else if (RStall)
Andrew Trick9ccce772011-01-14 21:11:41 +00002330 return -1;
2331
Andrew Trick47ff14b2011-01-21 05:51:33 +00002332 // If either node is scheduling for latency, sort them by height/depth
Andrew Trick9ccce772011-01-14 21:11:41 +00002333 // and latency.
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002334 if (!checkPref || (left->SchedulingPref == Sched::ILP ||
2335 right->SchedulingPref == Sched::ILP)) {
Andrew Tricka88d46e2012-06-05 03:44:34 +00002336 // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
2337 // is enabled, grouping instructions by cycle, then its height is already
2338 // covered so only its depth matters. We also reach this point if both stall
2339 // but have the same height.
2340 if (!SPQ->getHazardRec()->isEnabled()) {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002341 if (LHeight != RHeight)
Andrew Trick9ccce772011-01-14 21:11:41 +00002342 return LHeight > RHeight ? 1 : -1;
2343 }
Andrew Tricka88d46e2012-06-05 03:44:34 +00002344 int LDepth = left->getDepth() - LPenalty;
2345 int RDepth = right->getDepth() - RPenalty;
2346 if (LDepth != RDepth) {
2347 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2348 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2349 << ") depth " << RDepth << "\n");
2350 return LDepth < RDepth ? 1 : -1;
Andrew Trick47ff14b2011-01-21 05:51:33 +00002351 }
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002352 if (left->Latency != right->Latency)
Andrew Trick9ccce772011-01-14 21:11:41 +00002353 return left->Latency > right->Latency ? 1 : -1;
2354 }
2355 return 0;
2356}
2357
2358static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002359 // Schedule physical register definitions close to their use. This is
2360 // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
2361 // long as shortening physreg live ranges is generally good, we can defer
2362 // creating a subtarget hook.
2363 if (!DisableSchedPhysRegJoin) {
2364 bool LHasPhysReg = left->hasPhysRegDefs;
2365 bool RHasPhysReg = right->hasPhysRegDefs;
2366 if (LHasPhysReg != RHasPhysReg) {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002367 #ifndef NDEBUG
Craig Topper95207192012-05-24 06:35:32 +00002368 const char *const PhysRegMsg[] = {" has no physreg"," defines a physreg"};
Andrew Trickbfbd9722011-04-14 05:15:06 +00002369 #endif
2370 DEBUG(dbgs() << " SU (" << left->NodeNum << ") "
2371 << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
2372 << PhysRegMsg[RHasPhysReg] << "\n");
2373 return LHasPhysReg < RHasPhysReg;
2374 }
2375 }
2376
Evan Cheng2f647542011-04-26 04:57:37 +00002377 // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
Evan Cheng6730f032007-01-08 23:55:53 +00002378 unsigned LPriority = SPQ->getNodePriority(left);
2379 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng1355bbd2011-04-26 21:31:35 +00002380
2381 // Be really careful about hoisting call operands above previous calls.
2382 // Only allows it if it would reduce register pressure.
2383 if (left->isCall && right->isCallOp) {
2384 unsigned RNumVals = right->getNode()->getNumValues();
2385 RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2386 }
2387 if (right->isCall && left->isCallOp) {
2388 unsigned LNumVals = left->getNode()->getNumValues();
2389 LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2390 }
2391
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002392 if (LPriority != RPriority)
Evan Cheng73bdf042008-03-01 00:39:47 +00002393 return LPriority > RPriority;
Andrew Trick52b3e382011-03-08 01:51:56 +00002394
Evan Cheng1355bbd2011-04-26 21:31:35 +00002395 // One or both of the nodes are calls and their sethi-ullman numbers are the
2396 // same, then keep source order.
2397 if (left->isCall || right->isCall) {
2398 unsigned LOrder = SPQ->getNodeOrdering(left);
2399 unsigned ROrder = SPQ->getNodeOrdering(right);
2400
2401 // Prefer an ordering where the lower the non-zero order number, the higher
2402 // the preference.
2403 if ((LOrder || ROrder) && LOrder != ROrder)
2404 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2405 }
2406
Evan Cheng73bdf042008-03-01 00:39:47 +00002407 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2408 // e.g.
2409 // t1 = op t2, c1
2410 // t3 = op t4, c2
2411 //
2412 // and the following instructions are both ready.
2413 // t2 = op c3
2414 // t4 = op c4
2415 //
2416 // Then schedule t2 = op first.
2417 // i.e.
2418 // t4 = op c4
2419 // t2 = op c3
2420 // t1 = op t2, c1
2421 // t3 = op t4, c2
2422 //
2423 // This creates more short live intervals.
2424 unsigned LDist = closestSucc(left);
2425 unsigned RDist = closestSucc(right);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002426 if (LDist != RDist)
Evan Cheng73bdf042008-03-01 00:39:47 +00002427 return LDist < RDist;
2428
Evan Cheng3a14efa2009-02-12 08:59:45 +00002429 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00002430 unsigned LScratch = calcMaxScratches(left);
2431 unsigned RScratch = calcMaxScratches(right);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002432 if (LScratch != RScratch)
Evan Cheng73bdf042008-03-01 00:39:47 +00002433 return LScratch > RScratch;
2434
Evan Cheng1355bbd2011-04-26 21:31:35 +00002435 // Comparing latency against a call makes little sense unless the node
2436 // is register pressure-neutral.
2437 if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
2438 return (left->NodeQueueId > right->NodeQueueId);
2439
2440 // Do not compare latencies when one or both of the nodes are calls.
2441 if (!DisableSchedCycles &&
2442 !(left->isCall || right->isCall)) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002443 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2444 if (result != 0)
2445 return result > 0;
2446 }
2447 else {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002448 if (left->getHeight() != right->getHeight())
Andrew Trick9ccce772011-01-14 21:11:41 +00002449 return left->getHeight() > right->getHeight();
Andrew Trick2085a962010-12-21 22:25:04 +00002450
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002451 if (left->getDepth() != right->getDepth())
Andrew Trick9ccce772011-01-14 21:11:41 +00002452 return left->getDepth() < right->getDepth();
2453 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002454
Andrew Trick2085a962010-12-21 22:25:04 +00002455 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002456 "NodeQueueId cannot be zero");
2457 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002458}
2459
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002460// Bottom up
Andrew Trick9ccce772011-01-14 21:11:41 +00002461bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002462 if (int res = checkSpecialNodes(left, right))
2463 return res > 0;
2464
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002465 return BURRSort(left, right, SPQ);
2466}
2467
2468// Source order, otherwise bottom up.
Andrew Trick9ccce772011-01-14 21:11:41 +00002469bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002470 if (int res = checkSpecialNodes(left, right))
2471 return res > 0;
2472
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002473 unsigned LOrder = SPQ->getNodeOrdering(left);
2474 unsigned ROrder = SPQ->getNodeOrdering(right);
2475
2476 // Prefer an ordering where the lower the non-zero order number, the higher
2477 // the preference.
2478 if ((LOrder || ROrder) && LOrder != ROrder)
2479 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2480
2481 return BURRSort(left, right, SPQ);
2482}
2483
Andrew Trick9ccce772011-01-14 21:11:41 +00002484// If the time between now and when the instruction will be ready can cover
2485// the spill code, then avoid adding it to the ready queue. This gives long
2486// stalls highest priority and allows hoisting across calls. It should also
2487// speed up processing the available queue.
2488bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2489 static const unsigned ReadyDelay = 3;
2490
2491 if (SPQ->MayReduceRegPressure(SU)) return true;
2492
2493 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2494
2495 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2496 != ScheduleHazardRecognizer::NoHazard)
2497 return false;
2498
2499 return true;
2500}
2501
2502// Return true if right should be scheduled with higher priority than left.
2503bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002504 if (int res = checkSpecialNodes(left, right))
2505 return res > 0;
2506
Evan Chengdebf9c52010-11-03 00:45:17 +00002507 if (left->isCall || right->isCall)
2508 // No way to compute latency of calls.
2509 return BURRSort(left, right, SPQ);
2510
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002511 bool LHigh = SPQ->HighRegPressure(left);
2512 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002513 // Avoid causing spills. If register pressure is high, schedule for
2514 // register pressure reduction.
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002515 if (LHigh && !RHigh) {
2516 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2517 << right->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002518 return true;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002519 }
2520 else if (!LHigh && RHigh) {
2521 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2522 << left->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002523 return false;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002524 }
Andrew Trickb53a00d2011-04-13 00:38:32 +00002525 if (!LHigh && !RHigh) {
2526 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2527 if (result != 0)
2528 return result > 0;
Evan Chengcc2efe12010-05-28 23:26:21 +00002529 }
Evan Chengbdd062d2010-05-20 06:13:19 +00002530 return BURRSort(left, right, SPQ);
2531}
2532
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002533// Schedule as many instructions in each cycle as possible. So don't make an
2534// instruction available unless it is ready in the current cycle.
2535bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00002536 if (SU->getHeight() > CurCycle) return false;
2537
2538 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2539 != ScheduleHazardRecognizer::NoHazard)
2540 return false;
2541
Andrew Trickc88b7ec2011-03-04 02:03:45 +00002542 return true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002543}
2544
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002545static bool canEnableCoalescing(SUnit *SU) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002546 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2547 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2548 // CopyToReg should be close to its uses to facilitate coalescing and
2549 // avoid spilling.
2550 return true;
2551
2552 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2553 Opc == TargetOpcode::SUBREG_TO_REG ||
2554 Opc == TargetOpcode::INSERT_SUBREG)
2555 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2556 // close to their uses to facilitate coalescing.
2557 return true;
2558
2559 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2560 // If SU does not have a register def, schedule it close to its uses
2561 // because it does not lengthen any live ranges.
2562 return true;
2563
2564 return false;
2565}
2566
Andrew Trickb8390b72011-03-05 08:04:11 +00002567// list-ilp is currently an experimental scheduler that allows various
2568// heuristics to be enabled prior to the normal register reduction logic.
Andrew Trick9ccce772011-01-14 21:11:41 +00002569bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002570 if (int res = checkSpecialNodes(left, right))
2571 return res > 0;
2572
Evan Chengdebf9c52010-11-03 00:45:17 +00002573 if (left->isCall || right->isCall)
2574 // No way to compute latency of calls.
2575 return BURRSort(left, right, SPQ);
2576
Andrew Trick52b3e382011-03-08 01:51:56 +00002577 unsigned LLiveUses = 0, RLiveUses = 0;
2578 int LPDiff = 0, RPDiff = 0;
2579 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2580 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2581 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2582 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002583 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002584 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2585 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002586 return LPDiff > RPDiff;
2587 }
2588
Andrew Trick52b3e382011-03-08 01:51:56 +00002589 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002590 bool LReduce = canEnableCoalescing(left);
2591 bool RReduce = canEnableCoalescing(right);
Andrew Trick52b3e382011-03-08 01:51:56 +00002592 if (LReduce && !RReduce) return false;
2593 if (RReduce && !LReduce) return true;
2594 }
2595
2596 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2597 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2598 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002599 return LLiveUses < RLiveUses;
2600 }
2601
Andrew Trick52b3e382011-03-08 01:51:56 +00002602 if (!DisableSchedStalls) {
2603 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2604 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002605 if (LStall != RStall)
Andrew Trick52b3e382011-03-08 01:51:56 +00002606 return left->getHeight() > right->getHeight();
Andrew Trick641e2d42011-03-05 08:00:22 +00002607 }
2608
Andrew Trick25cedf32011-03-05 10:29:25 +00002609 if (!DisableSchedCriticalPath) {
2610 int spread = (int)left->getDepth() - (int)right->getDepth();
2611 if (std::abs(spread) > MaxReorderWindow) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002612 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2613 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2614 << right->getDepth() << "\n");
Andrew Trick25cedf32011-03-05 10:29:25 +00002615 return left->getDepth() < right->getDepth();
2616 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002617 }
2618
2619 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002620 int spread = (int)left->getHeight() - (int)right->getHeight();
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002621 if (std::abs(spread) > MaxReorderWindow)
Andrew Trick52b3e382011-03-08 01:51:56 +00002622 return left->getHeight() > right->getHeight();
Evan Cheng37b740c2010-07-24 00:39:05 +00002623 }
2624
2625 return BURRSort(left, right, SPQ);
2626}
2627
Andrew Trickb53a00d2011-04-13 00:38:32 +00002628void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2629 SUnits = &sunits;
2630 // Add pseudo dependency edges for two-address nodes.
Evan Chengd33b2d62011-11-10 07:43:16 +00002631 if (!Disable2AddrHack)
2632 AddPseudoTwoAddrDeps();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002633 // Reroute edges to nodes with multiple uses.
Evan Cheng8ab58a22012-03-22 19:31:17 +00002634 if (!TracksRegPressure && !SrcOrder)
Andrew Trickb53a00d2011-04-13 00:38:32 +00002635 PrescheduleNodesWithMultipleUses();
2636 // Calculate node priorities.
2637 CalculateSethiUllmanNumbers();
2638
2639 // For single block loops, mark nodes that look like canonical IV increments.
2640 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB)) {
2641 for (unsigned i = 0, e = sunits.size(); i != e; ++i) {
2642 initVRegCycle(&sunits[i]);
2643 }
2644 }
2645}
2646
Andrew Trick9ccce772011-01-14 21:11:41 +00002647//===----------------------------------------------------------------------===//
2648// Preschedule for Register Pressure
2649//===----------------------------------------------------------------------===//
2650
2651bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002652 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002653 unsigned Opc = SU->getNode()->getMachineOpcode();
Evan Cheng6cc775f2011-06-28 19:10:37 +00002654 const MCInstrDesc &MCID = TII->get(Opc);
2655 unsigned NumRes = MCID.getNumDefs();
2656 unsigned NumOps = MCID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002657 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00002658 if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002659 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002660 if (DU->getNodeId() != -1 &&
2661 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002662 return true;
2663 }
2664 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002665 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002666 return false;
2667}
2668
Andrew Trick832a6a192011-09-01 00:54:31 +00002669/// canClobberReachingPhysRegUse - True if SU would clobber one of it's
2670/// successor's explicit physregs whose definition can reach DepSU.
2671/// i.e. DepSU should not be scheduled above SU.
2672static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
2673 ScheduleDAGRRList *scheduleDAG,
2674 const TargetInstrInfo *TII,
2675 const TargetRegisterInfo *TRI) {
Craig Topper5a4bcc72012-03-08 08:22:45 +00002676 const uint16_t *ImpDefs
Andrew Trick832a6a192011-09-01 00:54:31 +00002677 = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002678 const uint32_t *RegMask = getNodeRegMask(SU->getNode());
2679 if(!ImpDefs && !RegMask)
Andrew Trick832a6a192011-09-01 00:54:31 +00002680 return false;
2681
2682 for (SUnit::const_succ_iterator SI = SU->Succs.begin(), SE = SU->Succs.end();
2683 SI != SE; ++SI) {
2684 SUnit *SuccSU = SI->getSUnit();
2685 for (SUnit::const_pred_iterator PI = SuccSU->Preds.begin(),
2686 PE = SuccSU->Preds.end(); PI != PE; ++PI) {
2687 if (!PI->isAssignedRegDep())
2688 continue;
2689
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002690 if (RegMask && MachineOperand::clobbersPhysReg(RegMask, PI->getReg()) &&
2691 scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
2692 return true;
2693
2694 if (ImpDefs)
Craig Topper5a4bcc72012-03-08 08:22:45 +00002695 for (const uint16_t *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002696 // Return true if SU clobbers this physical register use and the
2697 // definition of the register reaches from DepSU. IsReachable queries
2698 // a topological forward sort of the DAG (following the successors).
2699 if (TRI->regsOverlap(*ImpDef, PI->getReg()) &&
2700 scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
2701 return true;
Andrew Trick832a6a192011-09-01 00:54:31 +00002702 }
2703 }
2704 return false;
2705}
2706
Evan Chengf9891412007-12-20 09:25:31 +00002707/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002708/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002709static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002710 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002711 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002712 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002713 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
Craig Topper5a4bcc72012-03-08 08:22:45 +00002714 const uint16_t *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002715 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002716 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002717 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002718 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002719 continue;
Craig Topper5a4bcc72012-03-08 08:22:45 +00002720 const uint16_t *SUImpDefs =
Dan Gohmana366da12009-03-23 16:23:01 +00002721 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002722 const uint32_t *SURegMask = getNodeRegMask(SUNode);
2723 if (!SUImpDefs && !SURegMask)
2724 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002725 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002726 EVT VT = N->getValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002727 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002728 continue;
2729 if (!N->hasAnyUseOfValue(i))
2730 continue;
2731 unsigned Reg = ImpDefs[i - NumDefs];
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002732 if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
2733 return true;
2734 if (!SUImpDefs)
2735 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002736 for (;*SUImpDefs; ++SUImpDefs) {
2737 unsigned SUReg = *SUImpDefs;
2738 if (TRI->regsOverlap(Reg, SUReg))
2739 return true;
2740 }
Evan Chengf9891412007-12-20 09:25:31 +00002741 }
2742 }
2743 return false;
2744}
2745
Dan Gohman9a658d72009-03-24 00:49:12 +00002746/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2747/// are not handled well by the general register pressure reduction
2748/// heuristics. When presented with code like this:
2749///
2750/// N
2751/// / |
2752/// / |
2753/// U store
2754/// |
2755/// ...
2756///
2757/// the heuristics tend to push the store up, but since the
2758/// operand of the store has another use (U), this would increase
2759/// the length of that other use (the U->N edge).
2760///
2761/// This function transforms code like the above to route U's
2762/// dependence through the store when possible, like this:
2763///
2764/// N
2765/// ||
2766/// ||
2767/// store
2768/// |
2769/// U
2770/// |
2771/// ...
2772///
2773/// This results in the store being scheduled immediately
2774/// after N, which shortens the U->N live range, reducing
2775/// register pressure.
2776///
Andrew Trick9ccce772011-01-14 21:11:41 +00002777void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
Dan Gohman9a658d72009-03-24 00:49:12 +00002778 // Visit all the nodes in topological order, working top-down.
2779 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
2780 SUnit *SU = &(*SUnits)[i];
2781 // For now, only look at nodes with no data successors, such as stores.
2782 // These are especially important, due to the heuristics in
2783 // getNodePriority for nodes with no data successors.
2784 if (SU->NumSuccs != 0)
2785 continue;
2786 // For now, only look at nodes with exactly one data predecessor.
2787 if (SU->NumPreds != 1)
2788 continue;
2789 // Avoid prescheduling copies to virtual registers, which don't behave
2790 // like other nodes from the perspective of scheduling heuristics.
2791 if (SDNode *N = SU->getNode())
2792 if (N->getOpcode() == ISD::CopyToReg &&
2793 TargetRegisterInfo::isVirtualRegister
2794 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2795 continue;
2796
2797 // Locate the single data predecessor.
2798 SUnit *PredSU = 0;
2799 for (SUnit::const_pred_iterator II = SU->Preds.begin(),
2800 EE = SU->Preds.end(); II != EE; ++II)
2801 if (!II->isCtrl()) {
2802 PredSU = II->getSUnit();
2803 break;
2804 }
2805 assert(PredSU);
2806
2807 // Don't rewrite edges that carry physregs, because that requires additional
2808 // support infrastructure.
2809 if (PredSU->hasPhysRegDefs)
2810 continue;
2811 // Short-circuit the case where SU is PredSU's only data successor.
2812 if (PredSU->NumSuccs == 1)
2813 continue;
2814 // Avoid prescheduling to copies from virtual registers, which don't behave
Andrew Trickd0548ae2011-02-04 03:18:17 +00002815 // like other nodes from the perspective of scheduling heuristics.
Dan Gohman9a658d72009-03-24 00:49:12 +00002816 if (SDNode *N = SU->getNode())
2817 if (N->getOpcode() == ISD::CopyFromReg &&
2818 TargetRegisterInfo::isVirtualRegister
2819 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2820 continue;
2821
2822 // Perform checks on the successors of PredSU.
2823 for (SUnit::const_succ_iterator II = PredSU->Succs.begin(),
2824 EE = PredSU->Succs.end(); II != EE; ++II) {
2825 SUnit *PredSuccSU = II->getSUnit();
2826 if (PredSuccSU == SU) continue;
2827 // If PredSU has another successor with no data successors, for
2828 // now don't attempt to choose either over the other.
2829 if (PredSuccSU->NumSuccs == 0)
2830 goto outer_loop_continue;
2831 // Don't break physical register dependencies.
2832 if (SU->hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2833 if (canClobberPhysRegDefs(PredSuccSU, SU, TII, TRI))
2834 goto outer_loop_continue;
2835 // Don't introduce graph cycles.
2836 if (scheduleDAG->IsReachable(SU, PredSuccSU))
2837 goto outer_loop_continue;
2838 }
2839
2840 // Ok, the transformation is safe and the heuristics suggest it is
2841 // profitable. Update the graph.
Evan Chengbdd062d2010-05-20 06:13:19 +00002842 DEBUG(dbgs() << " Prescheduling SU #" << SU->NodeNum
2843 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002844 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002845 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2846 SDep Edge = PredSU->Succs[i];
2847 assert(!Edge.isAssignedRegDep());
2848 SUnit *SuccSU = Edge.getSUnit();
2849 if (SuccSU != SU) {
2850 Edge.setSUnit(PredSU);
2851 scheduleDAG->RemovePred(SuccSU, Edge);
2852 scheduleDAG->AddPred(SU, Edge);
2853 Edge.setSUnit(SU);
2854 scheduleDAG->AddPred(SuccSU, Edge);
2855 --i;
2856 }
2857 }
2858 outer_loop_continue:;
2859 }
2860}
2861
Evan Chengd38c22b2006-05-11 23:55:42 +00002862/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2863/// it as a def&use operand. Add a pseudo control edge from it to the other
2864/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002865/// first (lower in the schedule). If both nodes are two-address, favor the
2866/// one that has a CopyToReg use (more likely to be a loop induction update).
2867/// If both are two-address, but one is commutable while the other is not
2868/// commutable, favor the one that's not commutable.
Duncan Sands635e4ef2011-11-09 14:20:48 +00002869void RegReductionPQBase::AddPseudoTwoAddrDeps() {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002870 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
Dan Gohmane955c482008-08-05 14:45:15 +00002871 SUnit *SU = &(*SUnits)[i];
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002872 if (!SU->isTwoAddress)
2873 continue;
2874
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002875 SDNode *Node = SU->getNode();
Chris Lattner11a33812010-12-23 17:24:32 +00002876 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002877 continue;
2878
Evan Cheng6c1414f2010-10-29 18:09:28 +00002879 bool isLiveOut = hasOnlyLiveOutUses(SU);
Dan Gohman17059682008-07-17 19:10:17 +00002880 unsigned Opc = Node->getMachineOpcode();
Evan Cheng6cc775f2011-06-28 19:10:37 +00002881 const MCInstrDesc &MCID = TII->get(Opc);
2882 unsigned NumRes = MCID.getNumDefs();
2883 unsigned NumOps = MCID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002884 for (unsigned j = 0; j != NumOps; ++j) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00002885 if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
Dan Gohman82016c22008-11-19 02:00:32 +00002886 continue;
2887 SDNode *DU = SU->getNode()->getOperand(j).getNode();
2888 if (DU->getNodeId() == -1)
2889 continue;
2890 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
2891 if (!DUSU) continue;
2892 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
2893 E = DUSU->Succs.end(); I != E; ++I) {
Dan Gohman2d170892008-12-09 22:54:47 +00002894 if (I->isCtrl()) continue;
2895 SUnit *SuccSU = I->getSUnit();
Dan Gohman82016c22008-11-19 02:00:32 +00002896 if (SuccSU == SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002897 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002898 // Be conservative. Ignore if nodes aren't at roughly the same
2899 // depth and height.
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002900 if (SuccSU->getHeight() < SU->getHeight() &&
2901 (SU->getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002902 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002903 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2904 // constrains whatever is using the copy, instead of the copy
2905 // itself. In the case that the copy is coalesced, this
2906 // preserves the intent of the pseudo two-address heurietics.
2907 while (SuccSU->Succs.size() == 1 &&
2908 SuccSU->getNode()->isMachineOpcode() &&
2909 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002910 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002911 SuccSU = SuccSU->Succs.front().getSUnit();
2912 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002913 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2914 continue;
2915 // Don't constrain nodes with physical register defs if the
2916 // predecessor can clobber them.
Dan Gohmanf3746cb2009-03-24 00:50:07 +00002917 if (SuccSU->hasPhysRegDefs && SU->hasPhysRegClobbers) {
Dan Gohman82016c22008-11-19 02:00:32 +00002918 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002919 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002920 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002921 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2922 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002923 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002924 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2925 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2926 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002927 continue;
Andrew Trick832a6a192011-09-01 00:54:31 +00002928 if (!canClobberReachingPhysRegUse(SuccSU, SU, scheduleDAG, TII, TRI) &&
2929 (!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002930 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Dan Gohman82016c22008-11-19 02:00:32 +00002931 (!SU->isCommutable && SuccSU->isCommutable)) &&
2932 !scheduleDAG->IsReachable(SuccSU, SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002933 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002934 << SU->NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
Dan Gohman79c35162009-01-06 01:19:04 +00002935 scheduleDAG->AddPred(SU, SDep(SuccSU, SDep::Order, /*Latency=*/0,
Dan Gohmanbf8e5202009-01-06 01:28:56 +00002936 /*Reg=*/0, /*isNormalMemory=*/false,
2937 /*isMustAlias=*/false,
Dan Gohman2d170892008-12-09 22:54:47 +00002938 /*isArtificial=*/true));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002939 }
2940 }
2941 }
2942 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002943}
2944
Evan Chengd38c22b2006-05-11 23:55:42 +00002945//===----------------------------------------------------------------------===//
2946// Public Constructor Functions
2947//===----------------------------------------------------------------------===//
2948
Dan Gohmandfaf6462009-02-11 04:27:20 +00002949llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002950llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2951 CodeGenOpt::Level OptLevel) {
Dan Gohman619ef482009-01-15 19:20:50 +00002952 const TargetMachine &TM = IS->TM;
2953 const TargetInstrInfo *TII = TM.getInstrInfo();
2954 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002955
Evan Chenga77f3d32010-07-21 06:09:07 +00002956 BURegReductionPriorityQueue *PQ =
Evan Cheng8ab58a22012-03-22 19:31:17 +00002957 new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002958 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002959 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002960 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002961}
2962
Dan Gohmandfaf6462009-02-11 04:27:20 +00002963llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002964llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2965 CodeGenOpt::Level OptLevel) {
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002966 const TargetMachine &TM = IS->TM;
2967 const TargetInstrInfo *TII = TM.getInstrInfo();
2968 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002969
Evan Chenga77f3d32010-07-21 06:09:07 +00002970 SrcRegReductionPriorityQueue *PQ =
Evan Cheng8ab58a22012-03-22 19:31:17 +00002971 new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002972 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002973 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002974 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002975}
2976
2977llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002978llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2979 CodeGenOpt::Level OptLevel) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002980 const TargetMachine &TM = IS->TM;
2981 const TargetInstrInfo *TII = TM.getInstrInfo();
2982 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
Evan Chenga77f3d32010-07-21 06:09:07 +00002983 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00002984
Evan Chenga77f3d32010-07-21 06:09:07 +00002985 HybridBURRPriorityQueue *PQ =
Evan Cheng8ab58a22012-03-22 19:31:17 +00002986 new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002987
2988 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002989 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002990 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002991}
Evan Cheng37b740c2010-07-24 00:39:05 +00002992
2993llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002994llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
2995 CodeGenOpt::Level OptLevel) {
Evan Cheng37b740c2010-07-24 00:39:05 +00002996 const TargetMachine &TM = IS->TM;
2997 const TargetInstrInfo *TII = TM.getInstrInfo();
2998 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
2999 const TargetLowering *TLI = &IS->getTargetLowering();
Andrew Trick2085a962010-12-21 22:25:04 +00003000
Evan Cheng37b740c2010-07-24 00:39:05 +00003001 ILPBURRPriorityQueue *PQ =
Evan Cheng8ab58a22012-03-22 19:31:17 +00003002 new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00003003 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00003004 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00003005 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00003006}