blob: 4f4025d8ae6ada7c637010fbd08005ba0341fad2 [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
Jim Laskey29e635d2006-08-02 12:30:23 +000018#include "llvm/CodeGen/SchedulerRegistry.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "ScheduleDAGSDNodes.h"
20#include "llvm/ADT/STLExtras.h"
Evan Cheng5924bf72007-09-25 01:54:36 +000021#include "llvm/ADT/SmallSet.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000022#include "llvm/ADT/Statistic.h"
Weiming Zhao4a0b4fb2013-01-29 21:18:43 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
25#include "llvm/CodeGen/SelectionDAGISel.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
Chris Lattner3b9f02a2010-04-07 05:20:54 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000030#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000034#include "llvm/Target/TargetSubtargetInfo.h"
Evan Chengd38c22b2006-05-11 23:55:42 +000035#include <climits>
Evan Chengd38c22b2006-05-11 23:55:42 +000036using namespace llvm;
37
Chandler Carruth1b9dde02014-04-22 02:02:50 +000038#define DEBUG_TYPE "pre-RA-sched"
39
Dan Gohmanfd227e92008-03-25 17:10:29 +000040STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
Evan Cheng79e97132007-10-05 01:39:18 +000041STATISTIC(NumUnfolds, "Number of nodes unfolded");
Evan Cheng1ec79b42007-09-27 07:09:03 +000042STATISTIC(NumDups, "Number of duplicated nodes");
Evan Chengb2c42c62009-01-12 03:19:55 +000043STATISTIC(NumPRCopies, "Number of physical register copies");
Evan Cheng1ec79b42007-09-27 07:09:03 +000044
Jim Laskey95eda5b2006-08-01 14:21:23 +000045static RegisterScheduler
46 burrListDAGScheduler("list-burr",
Dan Gohman9c4b7d52008-10-14 20:25:08 +000047 "Bottom-up register reduction list scheduling",
Jim Laskey95eda5b2006-08-01 14:21:23 +000048 createBURRListDAGScheduler);
49static RegisterScheduler
Bill Wendling8cbc25d2010-01-23 10:26:57 +000050 sourceListDAGScheduler("source",
51 "Similar to list-burr but schedules in source "
52 "order when possible",
53 createSourceListDAGScheduler);
Jim Laskey95eda5b2006-08-01 14:21:23 +000054
Evan Chengbdd062d2010-05-20 06:13:19 +000055static RegisterScheduler
Evan Cheng725211e2010-05-21 00:42:32 +000056 hybridListDAGScheduler("list-hybrid",
Evan Cheng37b740c2010-07-24 00:39:05 +000057 "Bottom-up register pressure aware list scheduling "
58 "which tries to balance latency and register pressure",
Evan Chengbdd062d2010-05-20 06:13:19 +000059 createHybridListDAGScheduler);
60
Evan Cheng37b740c2010-07-24 00:39:05 +000061static RegisterScheduler
62 ILPListDAGScheduler("list-ilp",
63 "Bottom-up register pressure aware list scheduling "
64 "which tries to balance ILP and register pressure",
65 createILPListDAGScheduler);
66
Andrew Trick47ff14b2011-01-21 05:51:33 +000067static cl::opt<bool> DisableSchedCycles(
Andrew Trickbd428ec2011-01-21 06:19:05 +000068 "disable-sched-cycles", cl::Hidden, cl::init(false),
Andrew Trick47ff14b2011-01-21 05:51:33 +000069 cl::desc("Disable cycle-level precision during preRA scheduling"));
Andrew Trick10ffc2b2010-12-24 05:03:26 +000070
Andrew Trick641e2d42011-03-05 08:00:22 +000071// Temporary sched=list-ilp flags until the heuristics are robust.
Andrew Trickbfbd9722011-04-14 05:15:06 +000072// Some options are also available under sched=list-hybrid.
Andrew Trick641e2d42011-03-05 08:00:22 +000073static cl::opt<bool> DisableSchedRegPressure(
74 "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
75 cl::desc("Disable regpressure priority in sched=list-ilp"));
76static cl::opt<bool> DisableSchedLiveUses(
Andrew Trickdd017322011-03-06 00:03:32 +000077 "disable-sched-live-uses", cl::Hidden, cl::init(true),
Andrew Trick641e2d42011-03-05 08:00:22 +000078 cl::desc("Disable live use priority in sched=list-ilp"));
Andrew Trick2ad0b372011-04-07 19:54:57 +000079static cl::opt<bool> DisableSchedVRegCycle(
80 "disable-sched-vrcycle", cl::Hidden, cl::init(false),
81 cl::desc("Disable virtual register cycle interference checks"));
Andrew Trickbfbd9722011-04-14 05:15:06 +000082static cl::opt<bool> DisableSchedPhysRegJoin(
83 "disable-sched-physreg-join", cl::Hidden, cl::init(false),
84 cl::desc("Disable physreg def-use affinity"));
Andrew Trick641e2d42011-03-05 08:00:22 +000085static cl::opt<bool> DisableSchedStalls(
Andrew Trickdd017322011-03-06 00:03:32 +000086 "disable-sched-stalls", cl::Hidden, cl::init(true),
Andrew Trick641e2d42011-03-05 08:00:22 +000087 cl::desc("Disable no-stall priority in sched=list-ilp"));
88static cl::opt<bool> DisableSchedCriticalPath(
89 "disable-sched-critical-path", cl::Hidden, cl::init(false),
90 cl::desc("Disable critical path priority in sched=list-ilp"));
91static cl::opt<bool> DisableSchedHeight(
92 "disable-sched-height", cl::Hidden, cl::init(false),
93 cl::desc("Disable scheduled-height priority in sched=list-ilp"));
Evan Chengd33b2d62011-11-10 07:43:16 +000094static cl::opt<bool> Disable2AddrHack(
95 "disable-2addr-hack", cl::Hidden, cl::init(true),
96 cl::desc("Disable scheduler's two-address hack"));
Andrew Trick641e2d42011-03-05 08:00:22 +000097
98static cl::opt<int> MaxReorderWindow(
99 "max-sched-reorder", cl::Hidden, cl::init(6),
100 cl::desc("Number of instructions to allow ahead of the critical path "
101 "in sched=list-ilp"));
102
103static cl::opt<unsigned> AvgIPC(
104 "sched-avg-ipc", cl::Hidden, cl::init(1),
105 cl::desc("Average inst/cycle whan no target itinerary exists."));
106
Evan Chengd38c22b2006-05-11 23:55:42 +0000107namespace {
Evan Chengd38c22b2006-05-11 23:55:42 +0000108//===----------------------------------------------------------------------===//
109/// ScheduleDAGRRList - The actual register reduction list scheduler
110/// implementation. This supports both top-down and bottom-up scheduling.
111///
Nick Lewycky02d5f772009-10-25 06:33:48 +0000112class ScheduleDAGRRList : public ScheduleDAGSDNodes {
Evan Chengd38c22b2006-05-11 23:55:42 +0000113private:
Evan Chengbdd062d2010-05-20 06:13:19 +0000114 /// NeedLatency - True if the scheduler will make use of latency information.
115 ///
116 bool NeedLatency;
117
Evan Chengd38c22b2006-05-11 23:55:42 +0000118 /// AvailableQueue - The priority queue to use for the available SUnits.
Evan Chengd38c22b2006-05-11 23:55:42 +0000119 SchedulingPriorityQueue *AvailableQueue;
120
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000121 /// PendingQueue - This contains all of the instructions whose operands have
122 /// been issued, but their results are not ready yet (due to the latency of
123 /// the operation). Once the operands becomes available, the instruction is
124 /// added to the AvailableQueue.
125 std::vector<SUnit*> PendingQueue;
126
127 /// HazardRec - The hazard recognizer to use.
128 ScheduleHazardRecognizer *HazardRec;
129
Andrew Trick528fad92010-12-23 05:42:20 +0000130 /// CurCycle - The current scheduler state corresponds to this cycle.
131 unsigned CurCycle;
132
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000133 /// MinAvailableCycle - Cycle of the soonest available instruction.
134 unsigned MinAvailableCycle;
135
Andrew Trick641e2d42011-03-05 08:00:22 +0000136 /// IssueCount - Count instructions issued in this cycle
137 /// Currently valid only for bottom-up scheduling.
138 unsigned IssueCount;
139
Dan Gohmanc07f6862008-09-23 18:50:48 +0000140 /// LiveRegDefs - A set of physical registers and their definition
Evan Cheng5924bf72007-09-25 01:54:36 +0000141 /// that are "live". These nodes must be scheduled before any other nodes that
142 /// modifies the registers can be scheduled.
Dan Gohmanc07f6862008-09-23 18:50:48 +0000143 unsigned NumLiveRegs;
Fiona Glasere25b06f2015-12-02 18:32:59 +0000144 std::unique_ptr<SUnit*[]> LiveRegDefs;
145 std::unique_ptr<SUnit*[]> LiveRegGens;
Evan Cheng5924bf72007-09-25 01:54:36 +0000146
Andrew Trick7cf43612013-02-25 19:11:48 +0000147 // Collect interferences between physical register use/defs.
148 // Each interference is an SUnit and set of physical registers.
149 SmallVector<SUnit*, 4> Interferences;
150 typedef DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMapT;
151 LRegsMapT LRegsMap;
152
Dan Gohmanad2134d2008-11-25 00:52:40 +0000153 /// Topo - A topological ordering for SUnits which permits fast IsReachable
154 /// and similar queries.
155 ScheduleDAGTopologicalSort Topo;
156
Eli Friedmand5c173f2011-12-07 22:24:28 +0000157 // Hack to keep track of the inverse of FindCallSeqStart without more crazy
158 // DAG crawling.
159 DenseMap<SUnit*, SUnit*> CallSeqEndForStart;
160
Evan Chengd38c22b2006-05-11 23:55:42 +0000161public:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000162 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
163 SchedulingPriorityQueue *availqueue,
164 CodeGenOpt::Level OptLevel)
Dan Gohman90fb5522011-10-20 21:44:34 +0000165 : ScheduleDAGSDNodes(mf),
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000166 NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
Craig Topperc0196b12014-04-14 00:51:57 +0000167 Topo(SUnits, nullptr) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000168
Eric Christopheredba30c2014-10-09 06:28:06 +0000169 const TargetSubtargetInfo &STI = mf.getSubtarget();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000170 if (DisableSchedCycles || !NeedLatency)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000171 HazardRec = new ScheduleHazardRecognizer();
Andrew Trick47ff14b2011-01-21 05:51:33 +0000172 else
Eric Christopheredba30c2014-10-09 06:28:06 +0000173 HazardRec = STI.getInstrInfo()->CreateTargetHazardRecognizer(&STI, this);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000174 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000175
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000176 ~ScheduleDAGRRList() override {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000177 delete HazardRec;
Evan Chengd38c22b2006-05-11 23:55:42 +0000178 delete AvailableQueue;
179 }
180
Craig Topper7b883b32014-03-08 06:31:39 +0000181 void Schedule() override;
Evan Chengd38c22b2006-05-11 23:55:42 +0000182
Andrew Trick9ccce772011-01-14 21:11:41 +0000183 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
184
Roman Levenstein733a4d62008-03-26 11:23:38 +0000185 /// IsReachable - Checks if SU is reachable from TargetSU.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000186 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
187 return Topo.IsReachable(SU, TargetSU);
188 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000189
Dan Gohman60d68442009-01-29 19:49:27 +0000190 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000191 /// create a cycle.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000192 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
193 return Topo.WillCreateCycle(SU, TargetSU);
194 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000195
Dan Gohman2d170892008-12-09 22:54:47 +0000196 /// AddPred - adds a predecessor edge to SUnit SU.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000197 /// This returns true if this is a new predecessor.
198 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000199 void AddPred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000200 Topo.AddPred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000201 SU->addPred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000202 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000203
Dan Gohman2d170892008-12-09 22:54:47 +0000204 /// RemovePred - removes a predecessor edge from SUnit SU.
205 /// This returns true if an edge was removed.
206 /// Updates the topological ordering if required.
Dan Gohman17214e62008-12-16 01:00:55 +0000207 void RemovePred(SUnit *SU, const SDep &D) {
Dan Gohman2d170892008-12-09 22:54:47 +0000208 Topo.RemovePred(SU, D.getSUnit());
Dan Gohman17214e62008-12-16 01:00:55 +0000209 SU->removePred(D);
Dan Gohmanad2134d2008-11-25 00:52:40 +0000210 }
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000211
Evan Chengd38c22b2006-05-11 23:55:42 +0000212private:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000213 bool isReady(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000214 return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000215 AvailableQueue->isReady(SU);
216 }
217
Dan Gohman60d68442009-01-29 19:49:27 +0000218 void ReleasePred(SUnit *SU, const SDep *PredEdge);
Andrew Tricka52f3252010-12-23 04:16:14 +0000219 void ReleasePredecessors(SUnit *SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000220 void ReleasePending();
221 void AdvanceToCycle(unsigned NextCycle);
222 void AdvancePastStalls(SUnit *SU);
223 void EmitNode(SUnit *SU);
Andrew Trick528fad92010-12-23 05:42:20 +0000224 void ScheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000225 void CapturePred(SDep *PredEdge);
Evan Cheng8e136a92007-09-26 21:36:17 +0000226 void UnscheduleNodeBottomUp(SUnit*);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000227 void RestoreHazardCheckerBottomUp();
228 void BacktrackBottomUp(SUnit*, SUnit*);
Evan Cheng8e136a92007-09-26 21:36:17 +0000229 SUnit *CopyAndMoveSuccessors(SUnit*);
Evan Chengb2c42c62009-01-12 03:19:55 +0000230 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
231 const TargetRegisterClass*,
232 const TargetRegisterClass*,
Craig Topperb94011f2013-07-14 04:42:23 +0000233 SmallVectorImpl<SUnit*>&);
234 bool DelayForLiveRegsBottomUp(SUnit*, SmallVectorImpl<unsigned>&);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000235
Andrew Trick7cf43612013-02-25 19:11:48 +0000236 void releaseInterferences(unsigned Reg = 0);
237
Andrew Trick528fad92010-12-23 05:42:20 +0000238 SUnit *PickNodeToScheduleBottomUp();
Evan Chengd38c22b2006-05-11 23:55:42 +0000239 void ListScheduleBottomUp();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000240
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000241 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
Roman Levenstein733a4d62008-03-26 11:23:38 +0000242 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000243 SUnit *CreateNewSUnit(SDNode *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000244 unsigned NumSUnits = SUnits.size();
Andrew Trick52226d42012-03-07 23:00:49 +0000245 SUnit *NewNode = newSUnit(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000246 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000247 if (NewNode->NodeNum >= NumSUnits)
248 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000249 return NewNode;
250 }
251
Roman Levenstein733a4d62008-03-26 11:23:38 +0000252 /// CreateClone - Creates a new SUnit from an existing one.
253 /// Updates the topological ordering if required.
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000254 SUnit *CreateClone(SUnit *N) {
Dan Gohmanad2134d2008-11-25 00:52:40 +0000255 unsigned NumSUnits = SUnits.size();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000256 SUnit *NewNode = Clone(N);
Roman Levenstein733a4d62008-03-26 11:23:38 +0000257 // Update the topological ordering.
Dan Gohmanad2134d2008-11-25 00:52:40 +0000258 if (NewNode->NodeNum >= NumSUnits)
259 Topo.InitDAGTopologicalSorting();
Roman Levenstein7e71b4b2008-03-26 09:18:09 +0000260 return NewNode;
261 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000262
Andrew Trick52226d42012-03-07 23:00:49 +0000263 /// forceUnitLatencies - Register-pressure-reducing scheduling doesn't
Evan Chengbdd062d2010-05-20 06:13:19 +0000264 /// need actual latency information but the hybrid scheduler does.
Craig Topper7b883b32014-03-08 06:31:39 +0000265 bool forceUnitLatencies() const override {
Evan Chengbdd062d2010-05-20 06:13:19 +0000266 return !NeedLatency;
267 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000268};
269} // end anonymous namespace
270
Owen Anderson96adc4a2011-06-15 23:35:18 +0000271/// GetCostForDef - Looks up the register class and cost for a given definition.
272/// Typically this just means looking up the representative register class,
Owen Andersonca2f78a2011-11-16 01:02:57 +0000273/// but for untyped values (MVT::Untyped) it means inspecting the node's
Owen Anderson96adc4a2011-06-15 23:35:18 +0000274/// opcode to determine what register class is being generated.
275static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos,
276 const TargetLowering *TLI,
277 const TargetInstrInfo *TII,
278 const TargetRegisterInfo *TRI,
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +0000279 unsigned &RegClass, unsigned &Cost,
280 const MachineFunction &MF) {
Patrik Hagglund05394352012-12-13 18:45:35 +0000281 MVT VT = RegDefPos.GetValue();
Owen Anderson96adc4a2011-06-15 23:35:18 +0000282
283 // Special handling for untyped values. These values can only come from
284 // the expansion of custom DAG-to-DAG patterns.
Owen Andersonca2f78a2011-11-16 01:02:57 +0000285 if (VT == MVT::Untyped) {
Owen Andersond1955e72011-06-21 22:54:23 +0000286 const SDNode *Node = RegDefPos.GetNode();
Owen Andersond1955e72011-06-21 22:54:23 +0000287
Weiming Zhao4a0b4fb2013-01-29 21:18:43 +0000288 // Special handling for CopyFromReg of untyped values.
289 if (!Node->isMachineOpcode() && Node->getOpcode() == ISD::CopyFromReg) {
290 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
291 const TargetRegisterClass *RC = MF.getRegInfo().getRegClass(Reg);
292 RegClass = RC->getID();
293 Cost = 1;
294 return;
295 }
296
297 unsigned Opcode = Node->getMachineOpcode();
Owen Andersond1955e72011-06-21 22:54:23 +0000298 if (Opcode == TargetOpcode::REG_SEQUENCE) {
299 unsigned DstRCIdx = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
300 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
301 RegClass = RC->getID();
302 Cost = 1;
303 return;
304 }
305
Owen Anderson96adc4a2011-06-15 23:35:18 +0000306 unsigned Idx = RegDefPos.GetIdx();
Evan Cheng6cc775f2011-06-28 19:10:37 +0000307 const MCInstrDesc Desc = TII->get(Opcode);
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +0000308 const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx, TRI, MF);
Owen Anderson96adc4a2011-06-15 23:35:18 +0000309 RegClass = RC->getID();
310 // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
311 // better way to determine it.
312 Cost = 1;
313 } else {
314 RegClass = TLI->getRepRegClassFor(VT)->getID();
315 Cost = TLI->getRepRegClassCostFor(VT);
316 }
317}
Evan Chengd38c22b2006-05-11 23:55:42 +0000318
319/// Schedule - Schedule the DAG using list scheduling.
320void ScheduleDAGRRList::Schedule() {
Evan Chenga77f3d32010-07-21 06:09:07 +0000321 DEBUG(dbgs()
322 << "********** List Scheduling BB#" << BB->getNumber()
Evan Cheng6c1414f2010-10-29 18:09:28 +0000323 << " '" << BB->getName() << "' **********\n");
Evan Cheng5924bf72007-09-25 01:54:36 +0000324
Andrew Trick528fad92010-12-23 05:42:20 +0000325 CurCycle = 0;
Andrew Trick641e2d42011-03-05 08:00:22 +0000326 IssueCount = 0;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000327 MinAvailableCycle = DisableSchedCycles ? 0 : UINT_MAX;
Dan Gohmanc07f6862008-09-23 18:50:48 +0000328 NumLiveRegs = 0;
Dan Gohman198b7ff2011-11-03 21:49:52 +0000329 // Allocate slots for each physical register, plus one for a special register
330 // to track the virtual resource of a calling sequence.
Fiona Glasere25b06f2015-12-02 18:32:59 +0000331 LiveRegDefs.reset(new SUnit*[TRI->getNumRegs() + 1]());
332 LiveRegGens.reset(new SUnit*[TRI->getNumRegs() + 1]());
Eli Friedmand5c173f2011-12-07 22:24:28 +0000333 CallSeqEndForStart.clear();
Andrew Trick7cf43612013-02-25 19:11:48 +0000334 assert(Interferences.empty() && LRegsMap.empty() && "stale Interferences");
Evan Cheng5924bf72007-09-25 01:54:36 +0000335
Dan Gohman04543e72008-12-23 18:36:58 +0000336 // Build the scheduling graph.
Craig Topperc0196b12014-04-14 00:51:57 +0000337 BuildSchedGraph(nullptr);
Evan Chengd38c22b2006-05-11 23:55:42 +0000338
Sanjay Patele9fa3362016-02-03 22:44:14 +0000339 DEBUG(for (SUnit &SU : SUnits)
340 SU.dumpAll(this));
Dan Gohmanad2134d2008-11-25 00:52:40 +0000341 Topo.InitDAGTopologicalSorting();
Evan Chengd38c22b2006-05-11 23:55:42 +0000342
Dan Gohman46520a22008-06-21 19:18:17 +0000343 AvailableQueue->initNodes(SUnits);
Andrew Trick2085a962010-12-21 22:25:04 +0000344
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000345 HazardRec->Reset();
346
Dan Gohman90fb5522011-10-20 21:44:34 +0000347 // Execute the actual scheduling loop.
348 ListScheduleBottomUp();
Andrew Trick2085a962010-12-21 22:25:04 +0000349
Evan Chengd38c22b2006-05-11 23:55:42 +0000350 AvailableQueue->releaseState();
Andrew Trickedee68c2012-03-07 05:21:40 +0000351
352 DEBUG({
353 dbgs() << "*** Final schedule ***\n";
354 dumpSchedule();
355 dbgs() << '\n';
356 });
Evan Chengafed73e2006-05-12 01:58:24 +0000357}
Evan Chengd38c22b2006-05-11 23:55:42 +0000358
359//===----------------------------------------------------------------------===//
360// Bottom-Up Scheduling
361//===----------------------------------------------------------------------===//
362
Evan Chengd38c22b2006-05-11 23:55:42 +0000363/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
Dan Gohman54a187e2007-08-20 19:28:38 +0000364/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman60d68442009-01-29 19:49:27 +0000365void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000366 SUnit *PredSU = PredEdge->getSUnit();
Reid Klecknercea8dab2009-09-30 20:43:07 +0000367
Evan Chengd38c22b2006-05-11 23:55:42 +0000368#ifndef NDEBUG
Reid Klecknercea8dab2009-09-30 20:43:07 +0000369 if (PredSU->NumSuccsLeft == 0) {
David Greenef34d7ac2010-01-05 01:24:54 +0000370 dbgs() << "*** Scheduling failed! ***\n";
Dan Gohman22d07b12008-11-18 02:06:40 +0000371 PredSU->dump(this);
David Greenef34d7ac2010-01-05 01:24:54 +0000372 dbgs() << " has been released too many times!\n";
Craig Topperc0196b12014-04-14 00:51:57 +0000373 llvm_unreachable(nullptr);
Evan Chengd38c22b2006-05-11 23:55:42 +0000374 }
375#endif
Reid Klecknercea8dab2009-09-30 20:43:07 +0000376 --PredSU->NumSuccsLeft;
377
Andrew Trick52226d42012-03-07 23:00:49 +0000378 if (!forceUnitLatencies()) {
Evan Chengbdd062d2010-05-20 06:13:19 +0000379 // Updating predecessor's height. This is now the cycle when the
380 // predecessor can be scheduled without causing a pipeline stall.
381 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
382 }
383
Dan Gohmanb9543432009-02-10 23:27:53 +0000384 // If all the node's successors are scheduled, this node is ready
385 // to be scheduled. Ignore the special EntrySU node.
386 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
Dan Gohman4370f262008-04-15 01:22:18 +0000387 PredSU->isAvailable = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000388
389 unsigned Height = PredSU->getHeight();
390 if (Height < MinAvailableCycle)
391 MinAvailableCycle = Height;
392
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000393 if (isReady(PredSU)) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000394 AvailableQueue->push(PredSU);
395 }
396 // CapturePred and others may have left the node in the pending queue, avoid
397 // adding it twice.
398 else if (!PredSU->isPending) {
399 PredSU->isPending = true;
400 PendingQueue.push_back(PredSU);
401 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000402 }
403}
404
Dan Gohman198b7ff2011-11-03 21:49:52 +0000405/// IsChainDependent - Test if Outer is reachable from Inner through
406/// chain dependencies.
407static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
408 unsigned NestLevel,
409 const TargetInstrInfo *TII) {
410 SDNode *N = Outer;
411 for (;;) {
412 if (N == Inner)
413 return true;
414 // For a TokenFactor, examine each operand. There may be multiple ways
415 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
416 // most nesting in order to ensure that we find the corresponding match.
417 if (N->getOpcode() == ISD::TokenFactor) {
Pete Cooper9271ccc2015-06-26 19:18:49 +0000418 for (const SDValue &Op : N->op_values())
419 if (IsChainDependent(Op.getNode(), Inner, NestLevel, TII))
Dan Gohman198b7ff2011-11-03 21:49:52 +0000420 return true;
421 return false;
422 }
423 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
424 if (N->isMachineOpcode()) {
Serge Pavlov2757afd2017-04-12 14:13:00 +0000425 if (N->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
Dan Gohman198b7ff2011-11-03 21:49:52 +0000426 ++NestLevel;
Serge Pavlov2757afd2017-04-12 14:13:00 +0000427 } else if (N->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
Dan Gohman198b7ff2011-11-03 21:49:52 +0000428 if (NestLevel == 0)
429 return false;
430 --NestLevel;
431 }
432 }
433 // Otherwise, find the chain and continue climbing.
Pete Cooper9271ccc2015-06-26 19:18:49 +0000434 for (const SDValue &Op : N->op_values())
435 if (Op.getValueType() == MVT::Other) {
436 N = Op.getNode();
Dan Gohman198b7ff2011-11-03 21:49:52 +0000437 goto found_chain_operand;
438 }
439 return false;
440 found_chain_operand:;
441 if (N->getOpcode() == ISD::EntryToken)
442 return false;
443 }
444}
445
446/// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
447/// the corresponding (lowered) CALLSEQ_BEGIN node.
448///
449/// NestLevel and MaxNested are used in recursion to indcate the current level
450/// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
451/// level seen so far.
452///
453/// TODO: It would be better to give CALLSEQ_END an explicit operand to point
454/// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
455static SDNode *
456FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
457 const TargetInstrInfo *TII) {
458 for (;;) {
459 // For a TokenFactor, examine each operand. There may be multiple ways
460 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
461 // most nesting in order to ensure that we find the corresponding match.
462 if (N->getOpcode() == ISD::TokenFactor) {
Craig Topperc0196b12014-04-14 00:51:57 +0000463 SDNode *Best = nullptr;
Dan Gohman198b7ff2011-11-03 21:49:52 +0000464 unsigned BestMaxNest = MaxNest;
Pete Cooper9271ccc2015-06-26 19:18:49 +0000465 for (const SDValue &Op : N->op_values()) {
Dan Gohman198b7ff2011-11-03 21:49:52 +0000466 unsigned MyNestLevel = NestLevel;
467 unsigned MyMaxNest = MaxNest;
Pete Cooper9271ccc2015-06-26 19:18:49 +0000468 if (SDNode *New = FindCallSeqStart(Op.getNode(),
Dan Gohman198b7ff2011-11-03 21:49:52 +0000469 MyNestLevel, MyMaxNest, TII))
470 if (!Best || (MyMaxNest > BestMaxNest)) {
471 Best = New;
472 BestMaxNest = MyMaxNest;
473 }
474 }
475 assert(Best);
476 MaxNest = BestMaxNest;
477 return Best;
478 }
479 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
480 if (N->isMachineOpcode()) {
Serge Pavlov2757afd2017-04-12 14:13:00 +0000481 if (N->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
Dan Gohman198b7ff2011-11-03 21:49:52 +0000482 ++NestLevel;
483 MaxNest = std::max(MaxNest, NestLevel);
Serge Pavlov2757afd2017-04-12 14:13:00 +0000484 } else if (N->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
Dan Gohman198b7ff2011-11-03 21:49:52 +0000485 assert(NestLevel != 0);
486 --NestLevel;
487 if (NestLevel == 0)
488 return N;
489 }
490 }
491 // Otherwise, find the chain and continue climbing.
Pete Cooper9271ccc2015-06-26 19:18:49 +0000492 for (const SDValue &Op : N->op_values())
493 if (Op.getValueType() == MVT::Other) {
494 N = Op.getNode();
Dan Gohman198b7ff2011-11-03 21:49:52 +0000495 goto found_chain_operand;
496 }
Craig Topperc0196b12014-04-14 00:51:57 +0000497 return nullptr;
Dan Gohman198b7ff2011-11-03 21:49:52 +0000498 found_chain_operand:;
499 if (N->getOpcode() == ISD::EntryToken)
Craig Topperc0196b12014-04-14 00:51:57 +0000500 return nullptr;
Dan Gohman198b7ff2011-11-03 21:49:52 +0000501 }
502}
503
Andrew Trick033efdf2010-12-23 03:15:51 +0000504/// Call ReleasePred for each predecessor, then update register live def/gen.
505/// Always update LiveRegDefs for a register dependence even if the current SU
506/// also defines the register. This effectively create one large live range
507/// across a sequence of two-address node. This is important because the
508/// entire chain must be scheduled together. Example:
509///
510/// flags = (3) add
511/// flags = (2) addc flags
512/// flags = (1) addc flags
513///
514/// results in
515///
516/// LiveRegDefs[flags] = 3
Andrew Tricka52f3252010-12-23 04:16:14 +0000517/// LiveRegGens[flags] = 1
Andrew Trick033efdf2010-12-23 03:15:51 +0000518///
519/// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
520/// interference on flags.
Andrew Tricka52f3252010-12-23 04:16:14 +0000521void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
Evan Chengd38c22b2006-05-11 23:55:42 +0000522 // Bottom up: release predecessors
Krzysztof Parzyszek41b6e142017-05-04 13:35:17 +0000523 for (SDep &Pred : SU->Preds) {
524 ReleasePred(SU, &Pred);
525 if (Pred.isAssignedRegDep()) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000526 // This is a physical register dependency and it's impossible or
Andrew Trick2085a962010-12-21 22:25:04 +0000527 // expensive to copy the register. Make sure nothing that can
Evan Cheng5924bf72007-09-25 01:54:36 +0000528 // clobber the register is scheduled between the predecessor and
529 // this node.
Krzysztof Parzyszek41b6e142017-05-04 13:35:17 +0000530 SUnit *RegDef = LiveRegDefs[Pred.getReg()]; (void)RegDef;
531 assert((!RegDef || RegDef == SU || RegDef == Pred.getSUnit()) &&
Andrew Trick033efdf2010-12-23 03:15:51 +0000532 "interference on register dependence");
Krzysztof Parzyszek41b6e142017-05-04 13:35:17 +0000533 LiveRegDefs[Pred.getReg()] = Pred.getSUnit();
534 if (!LiveRegGens[Pred.getReg()]) {
Dan Gohmanc07f6862008-09-23 18:50:48 +0000535 ++NumLiveRegs;
Krzysztof Parzyszek41b6e142017-05-04 13:35:17 +0000536 LiveRegGens[Pred.getReg()] = SU;
Evan Cheng5924bf72007-09-25 01:54:36 +0000537 }
538 }
539 }
Dan Gohman198b7ff2011-11-03 21:49:52 +0000540
541 // If we're scheduling a lowered CALLSEQ_END, find the corresponding
542 // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
543 // these nodes, to prevent other calls from being interscheduled with them.
544 unsigned CallResource = TRI->getNumRegs();
545 if (!LiveRegDefs[CallResource])
546 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
547 if (Node->isMachineOpcode() &&
Serge Pavlov2757afd2017-04-12 14:13:00 +0000548 Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
Dan Gohman198b7ff2011-11-03 21:49:52 +0000549 unsigned NestLevel = 0;
550 unsigned MaxNest = 0;
551 SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
552
553 SUnit *Def = &SUnits[N->getNodeId()];
Eli Friedmand5c173f2011-12-07 22:24:28 +0000554 CallSeqEndForStart[Def] = SU;
555
Dan Gohman198b7ff2011-11-03 21:49:52 +0000556 ++NumLiveRegs;
557 LiveRegDefs[CallResource] = Def;
558 LiveRegGens[CallResource] = SU;
559 break;
560 }
Dan Gohmanb9543432009-02-10 23:27:53 +0000561}
562
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000563/// Check to see if any of the pending instructions are ready to issue. If
564/// so, add them to the available queue.
565void ScheduleDAGRRList::ReleasePending() {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000566 if (DisableSchedCycles) {
Andrew Trick5ce945c2010-12-24 07:10:19 +0000567 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
568 return;
569 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000570
571 // If the available queue is empty, it is safe to reset MinAvailableCycle.
572 if (AvailableQueue->empty())
573 MinAvailableCycle = UINT_MAX;
574
575 // Check to see if any of the pending instructions are ready to issue. If
576 // so, add them to the available queue.
577 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman90fb5522011-10-20 21:44:34 +0000578 unsigned ReadyCycle = PendingQueue[i]->getHeight();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000579 if (ReadyCycle < MinAvailableCycle)
580 MinAvailableCycle = ReadyCycle;
581
582 if (PendingQueue[i]->isAvailable) {
583 if (!isReady(PendingQueue[i]))
584 continue;
585 AvailableQueue->push(PendingQueue[i]);
586 }
587 PendingQueue[i]->isPending = false;
588 PendingQueue[i] = PendingQueue.back();
589 PendingQueue.pop_back();
590 --i; --e;
591 }
592}
593
594/// Move the scheduler state forward by the specified number of Cycles.
595void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
596 if (NextCycle <= CurCycle)
597 return;
598
Andrew Trick641e2d42011-03-05 08:00:22 +0000599 IssueCount = 0;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000600 AvailableQueue->setCurCycle(NextCycle);
Andrew Trick47ff14b2011-01-21 05:51:33 +0000601 if (!HazardRec->isEnabled()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000602 // Bypass lots of virtual calls in case of long latency.
603 CurCycle = NextCycle;
604 }
605 else {
606 for (; CurCycle != NextCycle; ++CurCycle) {
Dan Gohman90fb5522011-10-20 21:44:34 +0000607 HazardRec->RecedeCycle();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000608 }
609 }
610 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
611 // available Q to release pending nodes at least once before popping.
612 ReleasePending();
613}
614
615/// Move the scheduler state forward until the specified node's dependents are
616/// ready and can be scheduled with no resource conflicts.
617void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000618 if (DisableSchedCycles)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000619 return;
620
Andrew Trickb53a00d2011-04-13 00:38:32 +0000621 // FIXME: Nodes such as CopyFromReg probably should not advance the current
622 // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
623 // has predecessors the cycle will be advanced when they are scheduled.
624 // But given the crude nature of modeling latency though such nodes, we
625 // currently need to treat these nodes like real instructions.
626 // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
627
Dan Gohman90fb5522011-10-20 21:44:34 +0000628 unsigned ReadyCycle = SU->getHeight();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000629
630 // Bump CurCycle to account for latency. We assume the latency of other
631 // available instructions may be hidden by the stall (not a full pipe stall).
632 // This updates the hazard recognizer's cycle before reserving resources for
633 // this instruction.
634 AdvanceToCycle(ReadyCycle);
635
636 // Calls are scheduled in their preceding cycle, so don't conflict with
637 // hazards from instructions after the call. EmitNode will reset the
638 // scoreboard state before emitting the call.
Dan Gohman90fb5522011-10-20 21:44:34 +0000639 if (SU->isCall)
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000640 return;
641
642 // FIXME: For resource conflicts in very long non-pipelined stages, we
643 // should probably skip ahead here to avoid useless scoreboard checks.
644 int Stalls = 0;
645 while (true) {
646 ScheduleHazardRecognizer::HazardType HT =
Dan Gohman90fb5522011-10-20 21:44:34 +0000647 HazardRec->getHazardType(SU, -Stalls);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000648
649 if (HT == ScheduleHazardRecognizer::NoHazard)
650 break;
651
652 ++Stalls;
653 }
654 AdvanceToCycle(CurCycle + Stalls);
655}
656
657/// Record this SUnit in the HazardRecognizer.
658/// Does not update CurCycle.
659void ScheduleDAGRRList::EmitNode(SUnit *SU) {
Andrew Trick47ff14b2011-01-21 05:51:33 +0000660 if (!HazardRec->isEnabled())
Andrew Trickc9405662010-12-24 06:46:50 +0000661 return;
662
663 // Check for phys reg copy.
664 if (!SU->getNode())
665 return;
666
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000667 switch (SU->getNode()->getOpcode()) {
668 default:
669 assert(SU->getNode()->isMachineOpcode() &&
670 "This target-independent node should not be scheduled.");
671 break;
672 case ISD::MERGE_VALUES:
673 case ISD::TokenFactor:
Nadav Rotem7c277da2012-09-06 09:17:37 +0000674 case ISD::LIFETIME_START:
675 case ISD::LIFETIME_END:
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000676 case ISD::CopyToReg:
677 case ISD::CopyFromReg:
678 case ISD::EH_LABEL:
679 // Noops don't affect the scoreboard state. Copies are likely to be
680 // removed.
681 return;
682 case ISD::INLINEASM:
683 // For inline asm, clear the pipeline state.
684 HazardRec->Reset();
685 return;
686 }
Dan Gohman90fb5522011-10-20 21:44:34 +0000687 if (SU->isCall) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000688 // Calls are scheduled with their preceding instructions. For bottom-up
689 // scheduling, clear the pipeline state before emitting.
690 HazardRec->Reset();
691 }
692
693 HazardRec->EmitInstruction(SU);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000694}
695
Andrew Trickb53a00d2011-04-13 00:38:32 +0000696static void resetVRegCycle(SUnit *SU);
697
Dan Gohmanb9543432009-02-10 23:27:53 +0000698/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
699/// count of its predecessors. If a predecessor pending count is zero, add it to
700/// the Available queue.
Andrew Trick528fad92010-12-23 05:42:20 +0000701void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
Andrew Trick1b60ad62011-04-12 20:14:07 +0000702 DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
Dan Gohmanb9543432009-02-10 23:27:53 +0000703 DEBUG(SU->dump(this));
704
Evan Chengbdd062d2010-05-20 06:13:19 +0000705#ifndef NDEBUG
706 if (CurCycle < SU->getHeight())
Andrew Trickb53a00d2011-04-13 00:38:32 +0000707 DEBUG(dbgs() << " Height [" << SU->getHeight()
708 << "] pipeline stall!\n");
Evan Chengbdd062d2010-05-20 06:13:19 +0000709#endif
710
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000711 // FIXME: Do not modify node height. It may interfere with
712 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
Eric Christopher1b4b1e52011-03-21 18:06:21 +0000713 // node its ready cycle can aid heuristics, and after scheduling it can
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000714 // indicate the scheduled cycle.
Dan Gohmanb9543432009-02-10 23:27:53 +0000715 SU->setHeightToAtLeast(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000716
Robert Wilhelmf0cfb832013-09-28 11:46:15 +0000717 // Reserve resources for the scheduled instruction.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000718 EmitNode(SU);
719
Dan Gohmanb9543432009-02-10 23:27:53 +0000720 Sequence.push_back(SU);
721
Andrew Trick52226d42012-03-07 23:00:49 +0000722 AvailableQueue->scheduledNode(SU);
Chris Lattner981afd22010-12-20 00:55:43 +0000723
Andrew Trick641e2d42011-03-05 08:00:22 +0000724 // If HazardRec is disabled, and each inst counts as one cycle, then
Andrew Trickb53a00d2011-04-13 00:38:32 +0000725 // advance CurCycle before ReleasePredecessors to avoid useless pushes to
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000726 // PendingQueue for schedulers that implement HasReadyFilter.
Andrew Trick641e2d42011-03-05 08:00:22 +0000727 if (!HazardRec->isEnabled() && AvgIPC < 2)
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000728 AdvanceToCycle(CurCycle + 1);
729
Andrew Trick033efdf2010-12-23 03:15:51 +0000730 // Update liveness of predecessors before successors to avoid treating a
731 // two-address node as a live range def.
Andrew Tricka52f3252010-12-23 04:16:14 +0000732 ReleasePredecessors(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000733
734 // Release all the implicit physical register defs that are live.
Krzysztof Parzyszek41b6e142017-05-04 13:35:17 +0000735 for (SDep &Succ : SU->Succs) {
736 // LiveRegDegs[Succ.getReg()] != SU when SU is a two-address node.
737 if (Succ.isAssignedRegDep() && LiveRegDefs[Succ.getReg()] == SU) {
Andrew Trick033efdf2010-12-23 03:15:51 +0000738 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
739 --NumLiveRegs;
Krzysztof Parzyszek41b6e142017-05-04 13:35:17 +0000740 LiveRegDefs[Succ.getReg()] = nullptr;
741 LiveRegGens[Succ.getReg()] = nullptr;
742 releaseInterferences(Succ.getReg());
Evan Cheng5924bf72007-09-25 01:54:36 +0000743 }
744 }
Dan Gohman198b7ff2011-11-03 21:49:52 +0000745 // Release the special call resource dependence, if this is the beginning
746 // of a call.
747 unsigned CallResource = TRI->getNumRegs();
748 if (LiveRegDefs[CallResource] == SU)
749 for (const SDNode *SUNode = SU->getNode(); SUNode;
750 SUNode = SUNode->getGluedNode()) {
751 if (SUNode->isMachineOpcode() &&
Serge Pavlov2757afd2017-04-12 14:13:00 +0000752 SUNode->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
Dan Gohman198b7ff2011-11-03 21:49:52 +0000753 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
754 --NumLiveRegs;
Craig Topperc0196b12014-04-14 00:51:57 +0000755 LiveRegDefs[CallResource] = nullptr;
756 LiveRegGens[CallResource] = nullptr;
Andrew Trick7cf43612013-02-25 19:11:48 +0000757 releaseInterferences(CallResource);
Dan Gohman198b7ff2011-11-03 21:49:52 +0000758 }
759 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000760
Andrew Trickb53a00d2011-04-13 00:38:32 +0000761 resetVRegCycle(SU);
762
Evan Chengd38c22b2006-05-11 23:55:42 +0000763 SU->isScheduled = true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000764
765 // Conditions under which the scheduler should eagerly advance the cycle:
766 // (1) No available instructions
767 // (2) All pipelines full, so available instructions must have hazards.
768 //
Andrew Trickb53a00d2011-04-13 00:38:32 +0000769 // If HazardRec is disabled, the cycle was pre-advanced before calling
770 // ReleasePredecessors. In that case, IssueCount should remain 0.
Andrew Trickc88b7ec2011-03-04 02:03:45 +0000771 //
772 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
Andrew Trickb53a00d2011-04-13 00:38:32 +0000773 if (HazardRec->isEnabled() || AvgIPC > 1) {
774 if (SU->getNode() && SU->getNode()->isMachineOpcode())
775 ++IssueCount;
776 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
777 || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
778 AdvanceToCycle(CurCycle + 1);
779 }
Evan Chengd38c22b2006-05-11 23:55:42 +0000780}
781
Evan Cheng5924bf72007-09-25 01:54:36 +0000782/// CapturePred - This does the opposite of ReleasePred. Since SU is being
783/// unscheduled, incrcease the succ left count of its predecessors. Remove
784/// them from AvailableQueue if necessary.
Andrew Trick2085a962010-12-21 22:25:04 +0000785void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
Dan Gohman2d170892008-12-09 22:54:47 +0000786 SUnit *PredSU = PredEdge->getSUnit();
Evan Cheng5924bf72007-09-25 01:54:36 +0000787 if (PredSU->isAvailable) {
788 PredSU->isAvailable = false;
789 if (!PredSU->isPending)
790 AvailableQueue->remove(PredSU);
791 }
792
Reid Kleckner8ff5c192009-09-30 20:15:38 +0000793 assert(PredSU->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
Evan Cheng038dcc52007-09-28 19:24:24 +0000794 ++PredSU->NumSuccsLeft;
Evan Cheng5924bf72007-09-25 01:54:36 +0000795}
796
797/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
798/// its predecessor states to reflect the change.
799void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
David Greenef34d7ac2010-01-05 01:24:54 +0000800 DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
Dan Gohman22d07b12008-11-18 02:06:40 +0000801 DEBUG(SU->dump(this));
Evan Cheng5924bf72007-09-25 01:54:36 +0000802
Krzysztof Parzyszek41b6e142017-05-04 13:35:17 +0000803 for (SDep &Pred : SU->Preds) {
804 CapturePred(&Pred);
805 if (Pred.isAssignedRegDep() && SU == LiveRegGens[Pred.getReg()]){
Dan Gohmanc07f6862008-09-23 18:50:48 +0000806 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
Krzysztof Parzyszek41b6e142017-05-04 13:35:17 +0000807 assert(LiveRegDefs[Pred.getReg()] == Pred.getSUnit() &&
Evan Cheng5924bf72007-09-25 01:54:36 +0000808 "Physical register dependency violated?");
Dan Gohmanc07f6862008-09-23 18:50:48 +0000809 --NumLiveRegs;
Krzysztof Parzyszek41b6e142017-05-04 13:35:17 +0000810 LiveRegDefs[Pred.getReg()] = nullptr;
811 LiveRegGens[Pred.getReg()] = nullptr;
812 releaseInterferences(Pred.getReg());
Evan Cheng5924bf72007-09-25 01:54:36 +0000813 }
814 }
815
Dan Gohman198b7ff2011-11-03 21:49:52 +0000816 // Reclaim the special call resource dependence, if this is the beginning
817 // of a call.
818 unsigned CallResource = TRI->getNumRegs();
819 for (const SDNode *SUNode = SU->getNode(); SUNode;
820 SUNode = SUNode->getGluedNode()) {
821 if (SUNode->isMachineOpcode() &&
Serge Pavlov2757afd2017-04-12 14:13:00 +0000822 SUNode->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
Dan Gohman198b7ff2011-11-03 21:49:52 +0000823 ++NumLiveRegs;
824 LiveRegDefs[CallResource] = SU;
Eli Friedmand5c173f2011-12-07 22:24:28 +0000825 LiveRegGens[CallResource] = CallSeqEndForStart[SU];
Dan Gohman198b7ff2011-11-03 21:49:52 +0000826 }
827 }
828
829 // Release the special call resource dependence, if this is the end
830 // of a call.
831 if (LiveRegGens[CallResource] == SU)
832 for (const SDNode *SUNode = SU->getNode(); SUNode;
833 SUNode = SUNode->getGluedNode()) {
834 if (SUNode->isMachineOpcode() &&
Serge Pavlov2757afd2017-04-12 14:13:00 +0000835 SUNode->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
Dan Gohman198b7ff2011-11-03 21:49:52 +0000836 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
837 --NumLiveRegs;
Craig Topperc0196b12014-04-14 00:51:57 +0000838 LiveRegDefs[CallResource] = nullptr;
839 LiveRegGens[CallResource] = nullptr;
Andrew Trick7cf43612013-02-25 19:11:48 +0000840 releaseInterferences(CallResource);
Dan Gohman198b7ff2011-11-03 21:49:52 +0000841 }
842 }
843
Pawel Bylicacc358122015-06-24 12:49:42 +0000844 for (auto &Succ : SU->Succs) {
845 if (Succ.isAssignedRegDep()) {
846 auto Reg = Succ.getReg();
847 if (!LiveRegDefs[Reg])
Eli Friedman0bdc0832011-12-07 22:06:02 +0000848 ++NumLiveRegs;
Andrew Trick033efdf2010-12-23 03:15:51 +0000849 // This becomes the nearest def. Note that an earlier def may still be
850 // pending if this is a two-address node.
Pawel Bylicacc358122015-06-24 12:49:42 +0000851 LiveRegDefs[Reg] = SU;
852
853 // Update LiveRegGen only if was empty before this unscheduling.
854 // This is to avoid incorrect updating LiveRegGen set in previous run.
855 if (!LiveRegGens[Reg]) {
856 // Find the successor with the lowest height.
857 LiveRegGens[Reg] = Succ.getSUnit();
858 for (auto &Succ2 : SU->Succs) {
859 if (Succ2.isAssignedRegDep() && Succ2.getReg() == Reg &&
860 Succ2.getSUnit()->getHeight() < LiveRegGens[Reg]->getHeight())
861 LiveRegGens[Reg] = Succ2.getSUnit();
862 }
863 }
Evan Cheng5924bf72007-09-25 01:54:36 +0000864 }
865 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000866 if (SU->getHeight() < MinAvailableCycle)
867 MinAvailableCycle = SU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000868
Dan Gohmandddc1ac2008-12-16 03:25:46 +0000869 SU->setHeightDirty();
Evan Cheng5924bf72007-09-25 01:54:36 +0000870 SU->isScheduled = false;
871 SU->isAvailable = true;
Andrew Trick47ff14b2011-01-21 05:51:33 +0000872 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000873 // Don't make available until backtracking is complete.
874 SU->isPending = true;
875 PendingQueue.push_back(SU);
876 }
877 else {
878 AvailableQueue->push(SU);
879 }
Andrew Trick52226d42012-03-07 23:00:49 +0000880 AvailableQueue->unscheduledNode(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +0000881}
882
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000883/// After backtracking, the hazard checker needs to be restored to a state
Sylvestre Ledru35521e22012-07-23 08:51:15 +0000884/// corresponding the current cycle.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000885void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
886 HazardRec->Reset();
887
888 unsigned LookAhead = std::min((unsigned)Sequence.size(),
889 HazardRec->getMaxLookAhead());
890 if (LookAhead == 0)
891 return;
892
893 std::vector<SUnit*>::const_iterator I = (Sequence.end() - LookAhead);
894 unsigned HazardCycle = (*I)->getHeight();
Krzysztof Parzyszek41b6e142017-05-04 13:35:17 +0000895 for (auto E = Sequence.end(); I != E; ++I) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000896 SUnit *SU = *I;
897 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
898 HazardRec->RecedeCycle();
899 }
900 EmitNode(SU);
901 }
902}
903
Evan Cheng8e136a92007-09-26 21:36:17 +0000904/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
Dan Gohman60d68442009-01-29 19:49:27 +0000905/// BTCycle in order to schedule a specific node.
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000906void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
907 SUnit *OldSU = Sequence.back();
908 while (true) {
Evan Cheng5924bf72007-09-25 01:54:36 +0000909 Sequence.pop_back();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000910 // FIXME: use ready cycle instead of height
911 CurCycle = OldSU->getHeight();
Evan Cheng5924bf72007-09-25 01:54:36 +0000912 UnscheduleNodeBottomUp(OldSU);
Evan Chengbdd062d2010-05-20 06:13:19 +0000913 AvailableQueue->setCurCycle(CurCycle);
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000914 if (OldSU == BtSU)
915 break;
916 OldSU = Sequence.back();
Evan Cheng5924bf72007-09-25 01:54:36 +0000917 }
918
Dan Gohman60d68442009-01-29 19:49:27 +0000919 assert(!SU->isSucc(OldSU) && "Something is wrong!");
Evan Cheng1ec79b42007-09-27 07:09:03 +0000920
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000921 RestoreHazardCheckerBottomUp();
922
Andrew Trick5ce945c2010-12-24 07:10:19 +0000923 ReleasePending();
Andrew Trick10ffc2b2010-12-24 05:03:26 +0000924
Evan Cheng1ec79b42007-09-27 07:09:03 +0000925 ++NumBacktracks;
Evan Cheng5924bf72007-09-25 01:54:36 +0000926}
927
Evan Cheng3b245872010-02-05 01:27:11 +0000928static bool isOperandOf(const SUnit *SU, SDNode *N) {
929 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +0000930 SUNode = SUNode->getGluedNode()) {
Evan Cheng3b245872010-02-05 01:27:11 +0000931 if (SUNode->isOperandOf(N))
932 return true;
933 }
934 return false;
935}
936
Evan Cheng5924bf72007-09-25 01:54:36 +0000937/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
938/// successors to the newly created node.
939SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000940 SDNode *N = SU->getNode();
Evan Cheng79e97132007-10-05 01:39:18 +0000941 if (!N)
Craig Topperc0196b12014-04-14 00:51:57 +0000942 return nullptr;
Evan Cheng79e97132007-10-05 01:39:18 +0000943
Andrew Trickc9405662010-12-24 06:46:50 +0000944 if (SU->getNode()->getGluedNode())
Craig Topperc0196b12014-04-14 00:51:57 +0000945 return nullptr;
Andrew Trickc9405662010-12-24 06:46:50 +0000946
Evan Cheng79e97132007-10-05 01:39:18 +0000947 SUnit *NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +0000948 bool TryUnfold = false;
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000949 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
Craig Topper7f416c82014-11-16 21:17:18 +0000950 MVT VT = N->getSimpleValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000951 if (VT == MVT::Glue)
Craig Topperc0196b12014-04-14 00:51:57 +0000952 return nullptr;
Owen Anderson9f944592009-08-11 20:47:22 +0000953 else if (VT == MVT::Other)
Evan Cheng84d0ebc2007-10-05 01:42:35 +0000954 TryUnfold = true;
955 }
Pete Cooper9271ccc2015-06-26 19:18:49 +0000956 for (const SDValue &Op : N->op_values()) {
Craig Topper7f416c82014-11-16 21:17:18 +0000957 MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
Chris Lattner3e5fbd72010-12-21 02:38:05 +0000958 if (VT == MVT::Glue)
Craig Topperc0196b12014-04-14 00:51:57 +0000959 return nullptr;
Evan Cheng79e97132007-10-05 01:39:18 +0000960 }
961
962 if (TryUnfold) {
Dan Gohmane6e13482008-06-21 15:52:51 +0000963 SmallVector<SDNode*, 2> NewNodes;
Dan Gohman5a390b92008-11-13 21:21:28 +0000964 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
Craig Topperc0196b12014-04-14 00:51:57 +0000965 return nullptr;
Evan Cheng79e97132007-10-05 01:39:18 +0000966
Pete Cooper7c7ba1b2011-11-15 21:57:53 +0000967 // unfolding an x86 DEC64m operation results in store, dec, load which
968 // can't be handled here so quit
969 if (NewNodes.size() == 3)
Craig Topperc0196b12014-04-14 00:51:57 +0000970 return nullptr;
Pete Cooper7c7ba1b2011-11-15 21:57:53 +0000971
Evan Chengbdd062d2010-05-20 06:13:19 +0000972 DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
Evan Cheng79e97132007-10-05 01:39:18 +0000973 assert(NewNodes.size() == 2 && "Expected a load folding node!");
974
975 N = NewNodes[1];
976 SDNode *LoadNode = NewNodes[0];
Evan Cheng79e97132007-10-05 01:39:18 +0000977 unsigned NumVals = N->getNumValues();
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000978 unsigned OldNumVals = SU->getNode()->getNumValues();
Evan Cheng79e97132007-10-05 01:39:18 +0000979 for (unsigned i = 0; i != NumVals; ++i)
Dan Gohman1ddfcba2008-11-13 21:36:12 +0000980 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
981 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
Dan Gohman5a390b92008-11-13 21:21:28 +0000982 SDValue(LoadNode, 1));
Evan Cheng79e97132007-10-05 01:39:18 +0000983
Dan Gohmane52e0892008-11-11 21:34:44 +0000984 // LoadNode may already exist. This can happen when there is another
985 // load from the same location and producing the same type of value
986 // but it has different alignment or volatileness.
987 bool isNewLoad = true;
988 SUnit *LoadSU;
989 if (LoadNode->getNodeId() != -1) {
990 LoadSU = &SUnits[LoadNode->getNodeId()];
991 isNewLoad = false;
992 } else {
993 LoadSU = CreateNewSUnit(LoadNode);
994 LoadNode->setNodeId(LoadSU->NodeNum);
Andrew Trickd0548ae2011-02-04 03:18:17 +0000995
996 InitNumRegDefsLeft(LoadSU);
Andrew Trick52226d42012-03-07 23:00:49 +0000997 computeLatency(LoadSU);
Dan Gohmane52e0892008-11-11 21:34:44 +0000998 }
999
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001000 SUnit *NewSU = CreateNewSUnit(N);
Dan Gohman46520a22008-06-21 19:18:17 +00001001 assert(N->getNodeId() == -1 && "Node already inserted!");
1002 N->setNodeId(NewSU->NodeNum);
Andrew Trick2085a962010-12-21 22:25:04 +00001003
Evan Cheng6cc775f2011-06-28 19:10:37 +00001004 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1005 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
1006 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
Evan Cheng79e97132007-10-05 01:39:18 +00001007 NewSU->isTwoAddress = true;
1008 break;
1009 }
1010 }
Evan Cheng6cc775f2011-06-28 19:10:37 +00001011 if (MCID.isCommutable())
Evan Cheng79e97132007-10-05 01:39:18 +00001012 NewSU->isCommutable = true;
Andrew Trickd0548ae2011-02-04 03:18:17 +00001013
1014 InitNumRegDefsLeft(NewSU);
Andrew Trick52226d42012-03-07 23:00:49 +00001015 computeLatency(NewSU);
Evan Cheng79e97132007-10-05 01:39:18 +00001016
Dan Gohmaned0e8d42009-03-23 20:20:43 +00001017 // Record all the edges to and from the old SU, by category.
Dan Gohman15af5522009-03-06 02:23:01 +00001018 SmallVector<SDep, 4> ChainPreds;
Evan Cheng79e97132007-10-05 01:39:18 +00001019 SmallVector<SDep, 4> ChainSuccs;
1020 SmallVector<SDep, 4> LoadPreds;
1021 SmallVector<SDep, 4> NodePreds;
1022 SmallVector<SDep, 4> NodeSuccs;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001023 for (SDep &Pred : SU->Preds) {
1024 if (Pred.isCtrl())
1025 ChainPreds.push_back(Pred);
1026 else if (isOperandOf(Pred.getSUnit(), LoadNode))
1027 LoadPreds.push_back(Pred);
Evan Cheng79e97132007-10-05 01:39:18 +00001028 else
Sanjay Patele9fa3362016-02-03 22:44:14 +00001029 NodePreds.push_back(Pred);
Evan Cheng79e97132007-10-05 01:39:18 +00001030 }
Sanjay Patele9fa3362016-02-03 22:44:14 +00001031 for (SDep &Succ : SU->Succs) {
1032 if (Succ.isCtrl())
1033 ChainSuccs.push_back(Succ);
Evan Cheng79e97132007-10-05 01:39:18 +00001034 else
Sanjay Patele9fa3362016-02-03 22:44:14 +00001035 NodeSuccs.push_back(Succ);
Evan Cheng79e97132007-10-05 01:39:18 +00001036 }
1037
Dan Gohmaned0e8d42009-03-23 20:20:43 +00001038 // Now assign edges to the newly-created nodes.
Sanjay Patele9fa3362016-02-03 22:44:14 +00001039 for (const SDep &Pred : ChainPreds) {
Dan Gohman15af5522009-03-06 02:23:01 +00001040 RemovePred(SU, Pred);
Dan Gohman4370f262008-04-15 01:22:18 +00001041 if (isNewLoad)
Dan Gohman15af5522009-03-06 02:23:01 +00001042 AddPred(LoadSU, Pred);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001043 }
Sanjay Patele9fa3362016-02-03 22:44:14 +00001044 for (const SDep &Pred : LoadPreds) {
Dan Gohman2d170892008-12-09 22:54:47 +00001045 RemovePred(SU, Pred);
Dan Gohman15af5522009-03-06 02:23:01 +00001046 if (isNewLoad)
Dan Gohman2d170892008-12-09 22:54:47 +00001047 AddPred(LoadSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +00001048 }
Sanjay Patele9fa3362016-02-03 22:44:14 +00001049 for (const SDep &Pred : NodePreds) {
Dan Gohman2d170892008-12-09 22:54:47 +00001050 RemovePred(SU, Pred);
1051 AddPred(NewSU, Pred);
Evan Cheng79e97132007-10-05 01:39:18 +00001052 }
Sanjay Patele9fa3362016-02-03 22:44:14 +00001053 for (SDep D : NodeSuccs) {
Dan Gohman2d170892008-12-09 22:54:47 +00001054 SUnit *SuccDep = D.getSUnit();
1055 D.setSUnit(SU);
1056 RemovePred(SuccDep, D);
1057 D.setSUnit(NewSU);
1058 AddPred(SuccDep, D);
Andrew Trickd0548ae2011-02-04 03:18:17 +00001059 // Balance register pressure.
1060 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled
1061 && !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
1062 --NewSU->NumRegDefsLeft;
Evan Cheng79e97132007-10-05 01:39:18 +00001063 }
Sanjay Patele9fa3362016-02-03 22:44:14 +00001064 for (SDep D : ChainSuccs) {
Dan Gohman2d170892008-12-09 22:54:47 +00001065 SUnit *SuccDep = D.getSUnit();
1066 D.setSUnit(SU);
1067 RemovePred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001068 if (isNewLoad) {
Dan Gohman2d170892008-12-09 22:54:47 +00001069 D.setSUnit(LoadSU);
1070 AddPred(SuccDep, D);
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001071 }
Andrew Trick2085a962010-12-21 22:25:04 +00001072 }
Dan Gohmaned0e8d42009-03-23 20:20:43 +00001073
1074 // Add a data dependency to reflect that NewSU reads the value defined
1075 // by LoadSU.
Andrew Trickbaeaabb2012-11-06 03:13:46 +00001076 SDep D(LoadSU, SDep::Data, 0);
1077 D.setLatency(LoadSU->Latency);
1078 AddPred(NewSU, D);
Evan Cheng79e97132007-10-05 01:39:18 +00001079
Evan Cheng91e0fc92007-12-18 08:42:10 +00001080 if (isNewLoad)
1081 AvailableQueue->addNode(LoadSU);
Evan Cheng79e97132007-10-05 01:39:18 +00001082 AvailableQueue->addNode(NewSU);
1083
1084 ++NumUnfolds;
1085
1086 if (NewSU->NumSuccsLeft == 0) {
1087 NewSU->isAvailable = true;
1088 return NewSU;
Evan Cheng91e0fc92007-12-18 08:42:10 +00001089 }
1090 SU = NewSU;
Evan Cheng79e97132007-10-05 01:39:18 +00001091 }
1092
Evan Chengbdd062d2010-05-20 06:13:19 +00001093 DEBUG(dbgs() << " Duplicating SU #" << SU->NodeNum << "\n");
Roman Levenstein7e71b4b2008-03-26 09:18:09 +00001094 NewSU = CreateClone(SU);
Evan Cheng5924bf72007-09-25 01:54:36 +00001095
1096 // New SUnit has the exact same predecessors.
Sanjay Patele9fa3362016-02-03 22:44:14 +00001097 for (SDep &Pred : SU->Preds)
1098 if (!Pred.isArtificial())
1099 AddPred(NewSU, Pred);
Evan Cheng5924bf72007-09-25 01:54:36 +00001100
1101 // Only copy scheduled successors. Cut them from old node's successor
1102 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +00001103 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001104 for (SDep &Succ : SU->Succs) {
1105 if (Succ.isArtificial())
Evan Cheng5924bf72007-09-25 01:54:36 +00001106 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001107 SUnit *SuccSU = Succ.getSUnit();
Dan Gohman2d170892008-12-09 22:54:47 +00001108 if (SuccSU->isScheduled) {
Sanjay Patele9fa3362016-02-03 22:44:14 +00001109 SDep D = Succ;
Dan Gohman2d170892008-12-09 22:54:47 +00001110 D.setSUnit(NewSU);
1111 AddPred(SuccSU, D);
1112 D.setSUnit(SU);
1113 DelDeps.push_back(std::make_pair(SuccSU, D));
Evan Cheng5924bf72007-09-25 01:54:36 +00001114 }
1115 }
Sanjay Patele9fa3362016-02-03 22:44:14 +00001116 for (auto &DelDep : DelDeps)
1117 RemovePred(DelDep.first, DelDep.second);
Evan Cheng5924bf72007-09-25 01:54:36 +00001118
1119 AvailableQueue->updateNode(SU);
1120 AvailableQueue->addNode(NewSU);
1121
Evan Cheng1ec79b42007-09-27 07:09:03 +00001122 ++NumDups;
Evan Cheng5924bf72007-09-25 01:54:36 +00001123 return NewSU;
1124}
1125
Evan Chengb2c42c62009-01-12 03:19:55 +00001126/// InsertCopiesAndMoveSuccs - Insert register copies and move all
1127/// scheduled successors of the given SUnit to the last copy.
1128void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
Craig Topperb94011f2013-07-14 04:42:23 +00001129 const TargetRegisterClass *DestRC,
1130 const TargetRegisterClass *SrcRC,
1131 SmallVectorImpl<SUnit*> &Copies) {
Craig Topperc0196b12014-04-14 00:51:57 +00001132 SUnit *CopyFromSU = CreateNewSUnit(nullptr);
Evan Cheng8e136a92007-09-26 21:36:17 +00001133 CopyFromSU->CopySrcRC = SrcRC;
1134 CopyFromSU->CopyDstRC = DestRC;
Evan Cheng8e136a92007-09-26 21:36:17 +00001135
Craig Topperc0196b12014-04-14 00:51:57 +00001136 SUnit *CopyToSU = CreateNewSUnit(nullptr);
Evan Cheng8e136a92007-09-26 21:36:17 +00001137 CopyToSU->CopySrcRC = DestRC;
1138 CopyToSU->CopyDstRC = SrcRC;
1139
1140 // Only copy scheduled successors. Cut them from old node's successor
1141 // list and move them over.
Dan Gohman2d170892008-12-09 22:54:47 +00001142 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001143 for (SDep &Succ : SU->Succs) {
1144 if (Succ.isArtificial())
Evan Cheng8e136a92007-09-26 21:36:17 +00001145 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001146 SUnit *SuccSU = Succ.getSUnit();
Dan Gohman2d170892008-12-09 22:54:47 +00001147 if (SuccSU->isScheduled) {
Sanjay Patele9fa3362016-02-03 22:44:14 +00001148 SDep D = Succ;
Dan Gohman2d170892008-12-09 22:54:47 +00001149 D.setSUnit(CopyToSU);
1150 AddPred(SuccSU, D);
Sanjay Patele9fa3362016-02-03 22:44:14 +00001151 DelDeps.push_back(std::make_pair(SuccSU, Succ));
Evan Cheng8e136a92007-09-26 21:36:17 +00001152 }
Andrew Trick13acae02011-03-23 20:42:39 +00001153 else {
1154 // Avoid scheduling the def-side copy before other successors. Otherwise
1155 // we could introduce another physreg interference on the copy and
1156 // continue inserting copies indefinitely.
Andrew Trickbaeaabb2012-11-06 03:13:46 +00001157 AddPred(SuccSU, SDep(CopyFromSU, SDep::Artificial));
Andrew Trick13acae02011-03-23 20:42:39 +00001158 }
Evan Cheng8e136a92007-09-26 21:36:17 +00001159 }
Sanjay Patele9fa3362016-02-03 22:44:14 +00001160 for (auto &DelDep : DelDeps)
1161 RemovePred(DelDep.first, DelDep.second);
Evan Cheng8e136a92007-09-26 21:36:17 +00001162
Andrew Trickbaeaabb2012-11-06 03:13:46 +00001163 SDep FromDep(SU, SDep::Data, Reg);
1164 FromDep.setLatency(SU->Latency);
1165 AddPred(CopyFromSU, FromDep);
1166 SDep ToDep(CopyFromSU, SDep::Data, 0);
1167 ToDep.setLatency(CopyFromSU->Latency);
1168 AddPred(CopyToSU, ToDep);
Evan Cheng8e136a92007-09-26 21:36:17 +00001169
1170 AvailableQueue->updateNode(SU);
1171 AvailableQueue->addNode(CopyFromSU);
1172 AvailableQueue->addNode(CopyToSU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001173 Copies.push_back(CopyFromSU);
1174 Copies.push_back(CopyToSU);
Evan Cheng8e136a92007-09-26 21:36:17 +00001175
Evan Chengb2c42c62009-01-12 03:19:55 +00001176 ++NumPRCopies;
Evan Cheng8e136a92007-09-26 21:36:17 +00001177}
1178
1179/// getPhysicalRegisterVT - Returns the ValueType of the physical register
1180/// definition of the specified node.
1181/// FIXME: Move to SelectionDAG?
Craig Topper7f416c82014-11-16 21:17:18 +00001182static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
Duncan Sands13237ac2008-06-06 12:08:01 +00001183 const TargetInstrInfo *TII) {
Tim Northovere4c7be52014-10-23 22:31:48 +00001184 unsigned NumRes;
1185 if (N->getOpcode() == ISD::CopyFromReg) {
1186 // CopyFromReg has: "chain, Val, glue" so operand 1 gives the type.
1187 NumRes = 1;
1188 } else {
1189 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1190 assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
1191 NumRes = MCID.getNumDefs();
Craig Toppere5e035a32015-12-05 07:13:35 +00001192 for (const MCPhysReg *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
Tim Northovere4c7be52014-10-23 22:31:48 +00001193 if (Reg == *ImpDef)
1194 break;
1195 ++NumRes;
1196 }
Evan Cheng8e136a92007-09-26 21:36:17 +00001197 }
Craig Topper7f416c82014-11-16 21:17:18 +00001198 return N->getSimpleValueType(NumRes);
Evan Cheng8e136a92007-09-26 21:36:17 +00001199}
1200
Evan Chengb8905c42009-03-04 01:41:49 +00001201/// CheckForLiveRegDef - Return true and update live register vector if the
1202/// specified register def of the specified SUnit clobbers any "live" registers.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001203static void CheckForLiveRegDef(SUnit *SU, unsigned Reg,
Fiona Glasere25b06f2015-12-02 18:32:59 +00001204 SUnit **LiveRegDefs,
Evan Chengb8905c42009-03-04 01:41:49 +00001205 SmallSet<unsigned, 4> &RegAdded,
Craig Topperb94011f2013-07-14 04:42:23 +00001206 SmallVectorImpl<unsigned> &LRegs,
Evan Chengb8905c42009-03-04 01:41:49 +00001207 const TargetRegisterInfo *TRI) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +00001208 for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
Andrew Trick12acde112010-12-23 03:43:21 +00001209
1210 // Check if Ref is live.
Andrew Trick0af2e472011-06-07 00:38:12 +00001211 if (!LiveRegDefs[*AliasI]) continue;
Andrew Trick12acde112010-12-23 03:43:21 +00001212
1213 // Allow multiple uses of the same def.
Andrew Trick0af2e472011-06-07 00:38:12 +00001214 if (LiveRegDefs[*AliasI] == SU) continue;
Andrew Trick12acde112010-12-23 03:43:21 +00001215
1216 // Add Reg to the set of interfering live regs.
David Blaikie70573dc2014-11-19 07:49:26 +00001217 if (RegAdded.insert(*AliasI).second) {
Andrew Trick0af2e472011-06-07 00:38:12 +00001218 LRegs.push_back(*AliasI);
1219 }
Evan Chengb8905c42009-03-04 01:41:49 +00001220 }
Evan Chengb8905c42009-03-04 01:41:49 +00001221}
1222
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001223/// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
1224/// by RegMask, and add them to LRegs.
1225static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
Fiona Glasere25b06f2015-12-02 18:32:59 +00001226 ArrayRef<SUnit*> LiveRegDefs,
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001227 SmallSet<unsigned, 4> &RegAdded,
Craig Topperb94011f2013-07-14 04:42:23 +00001228 SmallVectorImpl<unsigned> &LRegs) {
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001229 // Look at all live registers. Skip Reg0 and the special CallResource.
Fiona Glaser1075f632015-12-02 18:46:23 +00001230 for (unsigned i = 1, e = LiveRegDefs.size()-1; i != e; ++i) {
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001231 if (!LiveRegDefs[i]) continue;
1232 if (LiveRegDefs[i] == SU) continue;
1233 if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
David Blaikie70573dc2014-11-19 07:49:26 +00001234 if (RegAdded.insert(i).second)
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001235 LRegs.push_back(i);
1236 }
1237}
1238
1239/// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
1240static const uint32_t *getNodeRegMask(const SDNode *N) {
Pete Cooper9271ccc2015-06-26 19:18:49 +00001241 for (const SDValue &Op : N->op_values())
1242 if (const auto *RegOp = dyn_cast<RegisterMaskSDNode>(Op.getNode()))
1243 return RegOp->getRegMask();
Craig Topperc0196b12014-04-14 00:51:57 +00001244 return nullptr;
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001245}
1246
Evan Cheng5924bf72007-09-25 01:54:36 +00001247/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1248/// scheduling of the given node to satisfy live physical register dependencies.
1249/// If the specific node is the last one that's available to schedule, do
1250/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
Chris Lattner0cfe8842010-12-20 00:51:56 +00001251bool ScheduleDAGRRList::
Craig Topperb94011f2013-07-14 04:42:23 +00001252DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) {
Dan Gohmanc07f6862008-09-23 18:50:48 +00001253 if (NumLiveRegs == 0)
Evan Cheng5924bf72007-09-25 01:54:36 +00001254 return false;
1255
Evan Chenge6f92252007-09-27 18:46:06 +00001256 SmallSet<unsigned, 4> RegAdded;
Evan Cheng5924bf72007-09-25 01:54:36 +00001257 // If this node would clobber any "live" register, then it's not ready.
Andrew Trickfbb3ed82010-12-21 22:27:44 +00001258 //
1259 // If SU is the currently live definition of the same register that it uses,
1260 // then we are free to schedule it.
Krzysztof Parzyszek41b6e142017-05-04 13:35:17 +00001261 for (SDep &Pred : SU->Preds) {
1262 if (Pred.isAssignedRegDep() && LiveRegDefs[Pred.getReg()] != SU)
1263 CheckForLiveRegDef(Pred.getSUnit(), Pred.getReg(), LiveRegDefs.get(),
Evan Chengb8905c42009-03-04 01:41:49 +00001264 RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001265 }
1266
Chris Lattner11a33812010-12-23 17:24:32 +00001267 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
Evan Chengb8905c42009-03-04 01:41:49 +00001268 if (Node->getOpcode() == ISD::INLINEASM) {
1269 // Inline asm can clobber physical defs.
1270 unsigned NumOps = Node->getNumOperands();
Chris Lattner3e5fbd72010-12-21 02:38:05 +00001271 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
Chris Lattner11a33812010-12-23 17:24:32 +00001272 --NumOps; // Ignore the glue operand.
Evan Chengb8905c42009-03-04 01:41:49 +00001273
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001274 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
Evan Chengb8905c42009-03-04 01:41:49 +00001275 unsigned Flags =
1276 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001277 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
Evan Chengb8905c42009-03-04 01:41:49 +00001278
1279 ++i; // Skip the ID value.
Chris Lattner3b9f02a2010-04-07 05:20:54 +00001280 if (InlineAsm::isRegDefKind(Flags) ||
Jakob Stoklund Olesen537a3022011-06-27 04:08:33 +00001281 InlineAsm::isRegDefEarlyClobberKind(Flags) ||
1282 InlineAsm::isClobberKind(Flags)) {
Evan Chengb8905c42009-03-04 01:41:49 +00001283 // Check for def of register or earlyclobber register.
1284 for (; NumVals; --NumVals, ++i) {
1285 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1286 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Fiona Glasere25b06f2015-12-02 18:32:59 +00001287 CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
Evan Chengb8905c42009-03-04 01:41:49 +00001288 }
1289 } else
1290 i += NumVals;
1291 }
1292 continue;
1293 }
1294
Dan Gohman072734e2008-11-13 23:24:17 +00001295 if (!Node->isMachineOpcode())
Evan Cheng5924bf72007-09-25 01:54:36 +00001296 continue;
Dan Gohman198b7ff2011-11-03 21:49:52 +00001297 // If we're in the middle of scheduling a call, don't begin scheduling
1298 // another call. Also, don't allow any physical registers to be live across
1299 // the call.
Sam Parker4fc5f3c2017-04-11 08:43:32 +00001300 if ((Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) ||
1301 (Node->getMachineOpcode() == TII->getCallFrameSetupOpcode())) {
Dan Gohman198b7ff2011-11-03 21:49:52 +00001302 // Check the special calling-sequence resource.
1303 unsigned CallResource = TRI->getNumRegs();
1304 if (LiveRegDefs[CallResource]) {
1305 SDNode *Gen = LiveRegGens[CallResource]->getNode();
1306 while (SDNode *Glued = Gen->getGluedNode())
1307 Gen = Glued;
David Blaikie70573dc2014-11-19 07:49:26 +00001308 if (!IsChainDependent(Gen, Node, 0, TII) &&
1309 RegAdded.insert(CallResource).second)
Dan Gohman198b7ff2011-11-03 21:49:52 +00001310 LRegs.push_back(CallResource);
1311 }
1312 }
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001313 if (const uint32_t *RegMask = getNodeRegMask(Node))
Fiona Glasere25b06f2015-12-02 18:32:59 +00001314 CheckForLiveRegDefMasked(SU, RegMask,
1315 makeArrayRef(LiveRegDefs.get(), TRI->getNumRegs()),
1316 RegAdded, LRegs);
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00001317
Evan Cheng6cc775f2011-06-28 19:10:37 +00001318 const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
Artyom Skrobov53cf1892017-04-23 06:58:08 +00001319 if (MCID.hasOptionalDef()) {
1320 // Most ARM instructions have an OptionalDef for CPSR, to model the S-bit.
1321 // This operand can be either a def of CPSR, if the S bit is set; or a use
1322 // of %noreg. When the OptionalDef is set to a valid register, we need to
1323 // handle it in the same way as an ImplicitDef.
1324 for (unsigned i = 0; i < MCID.getNumDefs(); ++i)
1325 if (MCID.OpInfo[i].isOptionalDef()) {
1326 const SDValue &OptionalDef = Node->getOperand(i - Node->getNumValues());
1327 unsigned Reg = cast<RegisterSDNode>(OptionalDef)->getReg();
1328 CheckForLiveRegDef(SU, Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
1329 }
1330 }
Evan Cheng6cc775f2011-06-28 19:10:37 +00001331 if (!MCID.ImplicitDefs)
Evan Cheng5924bf72007-09-25 01:54:36 +00001332 continue;
Craig Toppere5e035a32015-12-05 07:13:35 +00001333 for (const MCPhysReg *Reg = MCID.getImplicitDefs(); *Reg; ++Reg)
Fiona Glasere25b06f2015-12-02 18:32:59 +00001334 CheckForLiveRegDef(SU, *Reg, LiveRegDefs.get(), RegAdded, LRegs, TRI);
Evan Cheng5924bf72007-09-25 01:54:36 +00001335 }
Andrew Trick2085a962010-12-21 22:25:04 +00001336
Evan Cheng5924bf72007-09-25 01:54:36 +00001337 return !LRegs.empty();
Evan Chengd38c22b2006-05-11 23:55:42 +00001338}
1339
Andrew Trick7cf43612013-02-25 19:11:48 +00001340void ScheduleDAGRRList::releaseInterferences(unsigned Reg) {
1341 // Add the nodes that aren't ready back onto the available list.
1342 for (unsigned i = Interferences.size(); i > 0; --i) {
1343 SUnit *SU = Interferences[i-1];
1344 LRegsMapT::iterator LRegsPos = LRegsMap.find(SU);
1345 if (Reg) {
Craig Topperb94011f2013-07-14 04:42:23 +00001346 SmallVectorImpl<unsigned> &LRegs = LRegsPos->second;
David Majnemer0d955d02016-08-11 22:21:41 +00001347 if (!is_contained(LRegs, Reg))
Andrew Trick7cf43612013-02-25 19:11:48 +00001348 continue;
1349 }
1350 SU->isPending = false;
1351 // The interfering node may no longer be available due to backtracking.
1352 // Furthermore, it may have been made available again, in which case it is
1353 // now already in the AvailableQueue.
1354 if (SU->isAvailable && !SU->NodeQueueId) {
1355 DEBUG(dbgs() << " Repushing SU #" << SU->NodeNum << '\n');
1356 AvailableQueue->push(SU);
1357 }
1358 if (i < Interferences.size())
1359 Interferences[i-1] = Interferences.back();
1360 Interferences.pop_back();
1361 LRegsMap.erase(LRegsPos);
1362 }
1363}
1364
Andrew Trick528fad92010-12-23 05:42:20 +00001365/// Return a node that can be scheduled in this cycle. Requirements:
1366/// (1) Ready: latency has been satisfied
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001367/// (2) No Hazards: resources are available
Andrew Trick528fad92010-12-23 05:42:20 +00001368/// (3) No Interferences: may unschedule to break register interferences.
1369SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
Craig Topperc0196b12014-04-14 00:51:57 +00001370 SUnit *CurSU = AvailableQueue->empty() ? nullptr : AvailableQueue->pop();
Andrew Trick528fad92010-12-23 05:42:20 +00001371 while (CurSU) {
1372 SmallVector<unsigned, 4> LRegs;
1373 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1374 break;
Andrew Trick0f23b762013-03-07 19:21:08 +00001375 DEBUG(dbgs() << " Interfering reg " <<
1376 (LRegs[0] == TRI->getNumRegs() ? "CallResource"
1377 : TRI->getName(LRegs[0]))
1378 << " SU #" << CurSU->NodeNum << '\n');
Andrew Trick7cf43612013-02-25 19:11:48 +00001379 std::pair<LRegsMapT::iterator, bool> LRegsPair =
1380 LRegsMap.insert(std::make_pair(CurSU, LRegs));
1381 if (LRegsPair.second) {
1382 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1383 Interferences.push_back(CurSU);
1384 }
1385 else {
Sanjay Patelb49bf162014-07-14 18:21:07 +00001386 assert(CurSU->isPending && "Interferences are pending");
Andrew Trick7cf43612013-02-25 19:11:48 +00001387 // Update the interference with current live regs.
1388 LRegsPair.first->second = LRegs;
1389 }
Andrew Trick528fad92010-12-23 05:42:20 +00001390 CurSU = AvailableQueue->pop();
1391 }
Andrew Trick7cf43612013-02-25 19:11:48 +00001392 if (CurSU)
Andrew Trick528fad92010-12-23 05:42:20 +00001393 return CurSU;
Andrew Trick528fad92010-12-23 05:42:20 +00001394
1395 // All candidates are delayed due to live physical reg dependencies.
1396 // Try backtracking, code duplication, or inserting cross class copies
1397 // to resolve it.
Sanjay Patele9fa3362016-02-03 22:44:14 +00001398 for (SUnit *TrySU : Interferences) {
Craig Topperb94011f2013-07-14 04:42:23 +00001399 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
Andrew Trick528fad92010-12-23 05:42:20 +00001400
1401 // Try unscheduling up to the point where it's safe to schedule
1402 // this node.
Craig Topperc0196b12014-04-14 00:51:57 +00001403 SUnit *BtSU = nullptr;
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001404 unsigned LiveCycle = UINT_MAX;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001405 for (unsigned Reg : LRegs) {
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001406 if (LiveRegGens[Reg]->getHeight() < LiveCycle) {
1407 BtSU = LiveRegGens[Reg];
1408 LiveCycle = BtSU->getHeight();
1409 }
Andrew Trick528fad92010-12-23 05:42:20 +00001410 }
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001411 if (!WillCreateCycle(TrySU, BtSU)) {
Andrew Trick7cf43612013-02-25 19:11:48 +00001412 // BacktrackBottomUp mutates Interferences!
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001413 BacktrackBottomUp(TrySU, BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001414
1415 // Force the current node to be scheduled before the node that
1416 // requires the physical reg dep.
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001417 if (BtSU->isAvailable) {
1418 BtSU->isAvailable = false;
1419 if (!BtSU->isPending)
1420 AvailableQueue->remove(BtSU);
Andrew Trick528fad92010-12-23 05:42:20 +00001421 }
Andrew Trick7cf43612013-02-25 19:11:48 +00001422 DEBUG(dbgs() << "ARTIFICIAL edge from SU(" << BtSU->NodeNum << ") to SU("
1423 << TrySU->NodeNum << ")\n");
Andrew Trickbaeaabb2012-11-06 03:13:46 +00001424 AddPred(TrySU, SDep(BtSU, SDep::Artificial));
Andrew Trick528fad92010-12-23 05:42:20 +00001425
1426 // If one or more successors has been unscheduled, then the current
Andrew Trick7cf43612013-02-25 19:11:48 +00001427 // node is no longer available.
Andrew Tricke97ff5a2015-03-27 03:44:13 +00001428 if (!TrySU->isAvailable || !TrySU->NodeQueueId)
Andrew Trick528fad92010-12-23 05:42:20 +00001429 CurSU = AvailableQueue->pop();
Andrew Trick528fad92010-12-23 05:42:20 +00001430 else {
Andrew Tricke97ff5a2015-03-27 03:44:13 +00001431 // Available and in AvailableQueue
Andrew Trick7cf43612013-02-25 19:11:48 +00001432 AvailableQueue->remove(TrySU);
Andrew Trick528fad92010-12-23 05:42:20 +00001433 CurSU = TrySU;
Andrew Trick528fad92010-12-23 05:42:20 +00001434 }
Andrew Trick7cf43612013-02-25 19:11:48 +00001435 // Interferences has been mutated. We must break.
Andrew Trick528fad92010-12-23 05:42:20 +00001436 break;
1437 }
1438 }
1439
1440 if (!CurSU) {
1441 // Can't backtrack. If it's too expensive to copy the value, then try
1442 // duplicate the nodes that produces these "too expensive to copy"
1443 // values to break the dependency. In case even that doesn't work,
1444 // insert cross class copies.
1445 // If it's not too expensive, i.e. cost != -1, issue copies.
1446 SUnit *TrySU = Interferences[0];
Craig Topperb94011f2013-07-14 04:42:23 +00001447 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
Andrew Trick528fad92010-12-23 05:42:20 +00001448 assert(LRegs.size() == 1 && "Can't handle this yet!");
1449 unsigned Reg = LRegs[0];
1450 SUnit *LRDef = LiveRegDefs[Reg];
Craig Topper7f416c82014-11-16 21:17:18 +00001451 MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
Andrew Trick528fad92010-12-23 05:42:20 +00001452 const TargetRegisterClass *RC =
1453 TRI->getMinimalPhysRegClass(Reg, VT);
1454 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1455
Evan Chengb4c6a342011-03-10 00:16:32 +00001456 // If cross copy register class is the same as RC, then it must be possible
1457 // copy the value directly. Do not try duplicate the def.
1458 // If cross copy register class is not the same as RC, then it's possible to
1459 // copy the value but it require cross register class copies and it is
1460 // expensive.
1461 // If cross copy register class is null, then it's not possible to copy
1462 // the value at all.
Craig Topperc0196b12014-04-14 00:51:57 +00001463 SUnit *NewDef = nullptr;
Evan Chengb4c6a342011-03-10 00:16:32 +00001464 if (DestRC != RC) {
Andrew Trick528fad92010-12-23 05:42:20 +00001465 NewDef = CopyAndMoveSuccessors(LRDef);
Evan Chengb4c6a342011-03-10 00:16:32 +00001466 if (!DestRC && !NewDef)
1467 report_fatal_error("Can't handle live physical register dependency!");
1468 }
Andrew Trick528fad92010-12-23 05:42:20 +00001469 if (!NewDef) {
1470 // Issue copies, these can be expensive cross register class copies.
1471 SmallVector<SUnit*, 2> Copies;
1472 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1473 DEBUG(dbgs() << " Adding an edge from SU #" << TrySU->NodeNum
1474 << " to SU #" << Copies.front()->NodeNum << "\n");
Andrew Trickbaeaabb2012-11-06 03:13:46 +00001475 AddPred(TrySU, SDep(Copies.front(), SDep::Artificial));
Andrew Trick528fad92010-12-23 05:42:20 +00001476 NewDef = Copies.back();
1477 }
1478
1479 DEBUG(dbgs() << " Adding an edge from SU #" << NewDef->NodeNum
1480 << " to SU #" << TrySU->NodeNum << "\n");
1481 LiveRegDefs[Reg] = NewDef;
Andrew Trickbaeaabb2012-11-06 03:13:46 +00001482 AddPred(NewDef, SDep(TrySU, SDep::Artificial));
Andrew Trick528fad92010-12-23 05:42:20 +00001483 TrySU->isAvailable = false;
1484 CurSU = NewDef;
1485 }
Andrew Trick528fad92010-12-23 05:42:20 +00001486 assert(CurSU && "Unable to resolve live physical register dependencies!");
Andrew Trick528fad92010-12-23 05:42:20 +00001487 return CurSU;
1488}
Evan Cheng1ec79b42007-09-27 07:09:03 +00001489
Evan Chengd38c22b2006-05-11 23:55:42 +00001490/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1491/// schedulers.
1492void ScheduleDAGRRList::ListScheduleBottomUp() {
Dan Gohmanb9543432009-02-10 23:27:53 +00001493 // Release any predecessors of the special Exit node.
Andrew Tricka52f3252010-12-23 04:16:14 +00001494 ReleasePredecessors(&ExitSU);
Dan Gohmanb9543432009-02-10 23:27:53 +00001495
Evan Chengd38c22b2006-05-11 23:55:42 +00001496 // Add root to Available queue.
Dan Gohman4370f262008-04-15 01:22:18 +00001497 if (!SUnits.empty()) {
Dan Gohman5a390b92008-11-13 21:21:28 +00001498 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
Dan Gohman4370f262008-04-15 01:22:18 +00001499 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1500 RootSU->isAvailable = true;
1501 AvailableQueue->push(RootSU);
1502 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001503
1504 // While Available queue is not empty, grab the node with the highest
Dan Gohman54a187e2007-08-20 19:28:38 +00001505 // priority. If it is not ready put it back. Schedule the node.
Dan Gohmane6e13482008-06-21 15:52:51 +00001506 Sequence.reserve(SUnits.size());
Andrew Trick7cf43612013-02-25 19:11:48 +00001507 while (!AvailableQueue->empty() || !Interferences.empty()) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00001508 DEBUG(dbgs() << "\nExamining Available:\n";
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001509 AvailableQueue->dump(this));
1510
Andrew Trick528fad92010-12-23 05:42:20 +00001511 // Pick the best node to schedule taking all constraints into
1512 // consideration.
1513 SUnit *SU = PickNodeToScheduleBottomUp();
Evan Cheng1ec79b42007-09-27 07:09:03 +00001514
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001515 AdvancePastStalls(SU);
Evan Cheng1ec79b42007-09-27 07:09:03 +00001516
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001517 ScheduleNodeBottomUp(SU);
1518
1519 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1520 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1521 assert(MinAvailableCycle < UINT_MAX && "MinAvailableCycle uninitialized");
1522 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1523 }
Evan Chengd38c22b2006-05-11 23:55:42 +00001524 }
1525
Evan Chengd38c22b2006-05-11 23:55:42 +00001526 // Reverse the order if it is bottom up.
1527 std::reverse(Sequence.begin(), Sequence.end());
Andrew Trick2085a962010-12-21 22:25:04 +00001528
Evan Chengd38c22b2006-05-11 23:55:42 +00001529#ifndef NDEBUG
Andrew Trick46a58662012-03-07 05:21:36 +00001530 VerifyScheduledSequence(/*isBottomUp=*/true);
Evan Chengd38c22b2006-05-11 23:55:42 +00001531#endif
1532}
1533
1534//===----------------------------------------------------------------------===//
Andrew Trick9ccce772011-01-14 21:11:41 +00001535// RegReductionPriorityQueue Definition
Evan Chengd38c22b2006-05-11 23:55:42 +00001536//===----------------------------------------------------------------------===//
1537//
1538// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1539// to reduce register pressure.
Andrew Trick2085a962010-12-21 22:25:04 +00001540//
Evan Chengd38c22b2006-05-11 23:55:42 +00001541namespace {
Andrew Trick9ccce772011-01-14 21:11:41 +00001542class RegReductionPQBase;
Andrew Trick2085a962010-12-21 22:25:04 +00001543
Andrew Trick9ccce772011-01-14 21:11:41 +00001544struct queue_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1545 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1546};
1547
Andrew Trick3013b6a2011-06-15 17:16:12 +00001548#ifndef NDEBUG
1549template<class SF>
1550struct reverse_sort : public queue_sort {
1551 SF &SortFunc;
1552 reverse_sort(SF &sf) : SortFunc(sf) {}
Andrew Trick3013b6a2011-06-15 17:16:12 +00001553
1554 bool operator()(SUnit* left, SUnit* right) const {
1555 // reverse left/right rather than simply !SortFunc(left, right)
1556 // to expose different paths in the comparison logic.
1557 return SortFunc(right, left);
1558 }
1559};
1560#endif // NDEBUG
1561
Andrew Trick9ccce772011-01-14 21:11:41 +00001562/// bu_ls_rr_sort - Priority function for bottom up register pressure
1563// reduction scheduler.
1564struct bu_ls_rr_sort : public queue_sort {
1565 enum {
1566 IsBottomUp = true,
1567 HasReadyFilter = false
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001568 };
1569
Andrew Trick9ccce772011-01-14 21:11:41 +00001570 RegReductionPQBase *SPQ;
1571 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001572
Andrew Trick9ccce772011-01-14 21:11:41 +00001573 bool operator()(SUnit* left, SUnit* right) const;
1574};
Andrew Trick2085a962010-12-21 22:25:04 +00001575
Andrew Trick9ccce772011-01-14 21:11:41 +00001576// src_ls_rr_sort - Priority function for source order scheduler.
1577struct src_ls_rr_sort : public queue_sort {
1578 enum {
1579 IsBottomUp = true,
1580 HasReadyFilter = false
Evan Chengd38c22b2006-05-11 23:55:42 +00001581 };
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001582
Andrew Trick9ccce772011-01-14 21:11:41 +00001583 RegReductionPQBase *SPQ;
1584 src_ls_rr_sort(RegReductionPQBase *spq)
1585 : SPQ(spq) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001586
Andrew Trick9ccce772011-01-14 21:11:41 +00001587 bool operator()(SUnit* left, SUnit* right) const;
1588};
Andrew Trick2085a962010-12-21 22:25:04 +00001589
Andrew Trick9ccce772011-01-14 21:11:41 +00001590// hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1591struct hybrid_ls_rr_sort : public queue_sort {
1592 enum {
1593 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001594 HasReadyFilter = false
Bill Wendling8cbc25d2010-01-23 10:26:57 +00001595 };
Evan Chengbdd062d2010-05-20 06:13:19 +00001596
Andrew Trick9ccce772011-01-14 21:11:41 +00001597 RegReductionPQBase *SPQ;
1598 hybrid_ls_rr_sort(RegReductionPQBase *spq)
1599 : SPQ(spq) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001600
Andrew Trick9ccce772011-01-14 21:11:41 +00001601 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Chenga77f3d32010-07-21 06:09:07 +00001602
Andrew Trick9ccce772011-01-14 21:11:41 +00001603 bool operator()(SUnit* left, SUnit* right) const;
1604};
1605
1606// ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1607// scheduler.
1608struct ilp_ls_rr_sort : public queue_sort {
1609 enum {
1610 IsBottomUp = true,
Andrew Trickc88b7ec2011-03-04 02:03:45 +00001611 HasReadyFilter = false
Evan Chengbdd062d2010-05-20 06:13:19 +00001612 };
Evan Cheng37b740c2010-07-24 00:39:05 +00001613
Andrew Trick9ccce772011-01-14 21:11:41 +00001614 RegReductionPQBase *SPQ;
1615 ilp_ls_rr_sort(RegReductionPQBase *spq)
1616 : SPQ(spq) {}
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001617
Andrew Trick9ccce772011-01-14 21:11:41 +00001618 bool isReady(SUnit *SU, unsigned CurCycle) const;
Evan Cheng37b740c2010-07-24 00:39:05 +00001619
Andrew Trick9ccce772011-01-14 21:11:41 +00001620 bool operator()(SUnit* left, SUnit* right) const;
1621};
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001622
Andrew Trick9ccce772011-01-14 21:11:41 +00001623class RegReductionPQBase : public SchedulingPriorityQueue {
1624protected:
1625 std::vector<SUnit*> Queue;
1626 unsigned CurQueueId;
1627 bool TracksRegPressure;
Evan Cheng8ab58a22012-03-22 19:31:17 +00001628 bool SrcOrder;
Andrew Trick9ccce772011-01-14 21:11:41 +00001629
1630 // SUnits - The SUnits for the current graph.
1631 std::vector<SUnit> *SUnits;
1632
1633 MachineFunction &MF;
1634 const TargetInstrInfo *TII;
1635 const TargetRegisterInfo *TRI;
1636 const TargetLowering *TLI;
1637 ScheduleDAGRRList *scheduleDAG;
1638
1639 // SethiUllmanNumbers - The SethiUllman number for each node.
1640 std::vector<unsigned> SethiUllmanNumbers;
1641
1642 /// RegPressure - Tracking current reg pressure per register class.
1643 ///
1644 std::vector<unsigned> RegPressure;
1645
1646 /// RegLimit - Tracking the number of allocatable registers per register
1647 /// class.
1648 std::vector<unsigned> RegLimit;
1649
1650public:
1651 RegReductionPQBase(MachineFunction &mf,
1652 bool hasReadyFilter,
1653 bool tracksrp,
Evan Cheng8ab58a22012-03-22 19:31:17 +00001654 bool srcorder,
Andrew Trick9ccce772011-01-14 21:11:41 +00001655 const TargetInstrInfo *tii,
1656 const TargetRegisterInfo *tri,
1657 const TargetLowering *tli)
1658 : SchedulingPriorityQueue(hasReadyFilter),
Evan Cheng8ab58a22012-03-22 19:31:17 +00001659 CurQueueId(0), TracksRegPressure(tracksrp), SrcOrder(srcorder),
Craig Topperc0196b12014-04-14 00:51:57 +00001660 MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(nullptr) {
Andrew Trick9ccce772011-01-14 21:11:41 +00001661 if (TracksRegPressure) {
1662 unsigned NumRC = TRI->getNumRegClasses();
1663 RegLimit.resize(NumRC);
1664 RegPressure.resize(NumRC);
1665 std::fill(RegLimit.begin(), RegLimit.end(), 0);
1666 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Krzysztof Parzyszekee9aa3f2017-01-25 19:29:04 +00001667 for (const TargetRegisterClass *RC : TRI->regclasses())
1668 RegLimit[RC->getID()] = tri->getRegPressureLimit(RC, MF);
Andrew Trick9ccce772011-01-14 21:11:41 +00001669 }
1670 }
1671
1672 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1673 scheduleDAG = scheduleDag;
1674 }
1675
1676 ScheduleHazardRecognizer* getHazardRec() {
1677 return scheduleDAG->getHazardRec();
1678 }
1679
Craig Topper7b883b32014-03-08 06:31:39 +00001680 void initNodes(std::vector<SUnit> &sunits) override;
Andrew Trick9ccce772011-01-14 21:11:41 +00001681
Craig Topper7b883b32014-03-08 06:31:39 +00001682 void addNode(const SUnit *SU) override;
Andrew Trick9ccce772011-01-14 21:11:41 +00001683
Craig Topper7b883b32014-03-08 06:31:39 +00001684 void updateNode(const SUnit *SU) override;
Andrew Trick9ccce772011-01-14 21:11:41 +00001685
Craig Topper7b883b32014-03-08 06:31:39 +00001686 void releaseState() override {
Craig Topperc0196b12014-04-14 00:51:57 +00001687 SUnits = nullptr;
Andrew Trick9ccce772011-01-14 21:11:41 +00001688 SethiUllmanNumbers.clear();
1689 std::fill(RegPressure.begin(), RegPressure.end(), 0);
1690 }
1691
1692 unsigned getNodePriority(const SUnit *SU) const;
1693
1694 unsigned getNodeOrdering(const SUnit *SU) const {
Andrew Trick3bd8b7a2011-03-25 06:40:55 +00001695 if (!SU->getNode()) return 0;
1696
Andrew Tricke2431c62013-05-25 03:08:10 +00001697 return SU->getNode()->getIROrder();
Andrew Trick9ccce772011-01-14 21:11:41 +00001698 }
1699
Craig Topper7b883b32014-03-08 06:31:39 +00001700 bool empty() const override { return Queue.empty(); }
Andrew Trick9ccce772011-01-14 21:11:41 +00001701
Craig Topper7b883b32014-03-08 06:31:39 +00001702 void push(SUnit *U) override {
Andrew Trick9ccce772011-01-14 21:11:41 +00001703 assert(!U->NodeQueueId && "Node in the queue already");
1704 U->NodeQueueId = ++CurQueueId;
1705 Queue.push_back(U);
1706 }
1707
Craig Topper7b883b32014-03-08 06:31:39 +00001708 void remove(SUnit *SU) override {
Andrew Trick9ccce772011-01-14 21:11:41 +00001709 assert(!Queue.empty() && "Queue is empty!");
1710 assert(SU->NodeQueueId != 0 && "Not in queue!");
David Majnemer0d955d02016-08-11 22:21:41 +00001711 std::vector<SUnit *>::iterator I = find(Queue, SU);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001712 if (I != std::prev(Queue.end()))
Andrew Trick9ccce772011-01-14 21:11:41 +00001713 std::swap(*I, Queue.back());
1714 Queue.pop_back();
1715 SU->NodeQueueId = 0;
1716 }
1717
Craig Topper7b883b32014-03-08 06:31:39 +00001718 bool tracksRegPressure() const override { return TracksRegPressure; }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001719
Andrew Trick9ccce772011-01-14 21:11:41 +00001720 void dumpRegPressure() const;
1721
1722 bool HighRegPressure(const SUnit *SU) const;
1723
Andrew Trick641e2d42011-03-05 08:00:22 +00001724 bool MayReduceRegPressure(SUnit *SU) const;
1725
1726 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
Andrew Trick9ccce772011-01-14 21:11:41 +00001727
Craig Topper7b883b32014-03-08 06:31:39 +00001728 void scheduledNode(SUnit *SU) override;
Andrew Trick9ccce772011-01-14 21:11:41 +00001729
Craig Topper7b883b32014-03-08 06:31:39 +00001730 void unscheduledNode(SUnit *SU) override;
Andrew Trick9ccce772011-01-14 21:11:41 +00001731
1732protected:
1733 bool canClobber(const SUnit *SU, const SUnit *Op);
Duncan Sands635e4ef2011-11-09 14:20:48 +00001734 void AddPseudoTwoAddrDeps();
Andrew Trick9ccce772011-01-14 21:11:41 +00001735 void PrescheduleNodesWithMultipleUses();
1736 void CalculateSethiUllmanNumbers();
1737};
1738
1739template<class SF>
Andrew Trick3013b6a2011-06-15 17:16:12 +00001740static SUnit *popFromQueueImpl(std::vector<SUnit*> &Q, SF &Picker) {
1741 std::vector<SUnit *>::iterator Best = Q.begin();
Krzysztof Parzyszek41b6e142017-05-04 13:35:17 +00001742 for (auto I = std::next(Q.begin()), E = Q.end(); I != E; ++I)
Andrew Trick3013b6a2011-06-15 17:16:12 +00001743 if (Picker(*Best, *I))
1744 Best = I;
1745 SUnit *V = *Best;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001746 if (Best != std::prev(Q.end()))
Andrew Trick3013b6a2011-06-15 17:16:12 +00001747 std::swap(*Best, Q.back());
1748 Q.pop_back();
1749 return V;
1750}
Andrew Trick9ccce772011-01-14 21:11:41 +00001751
Andrew Trick3013b6a2011-06-15 17:16:12 +00001752template<class SF>
1753SUnit *popFromQueue(std::vector<SUnit*> &Q, SF &Picker, ScheduleDAG *DAG) {
1754#ifndef NDEBUG
1755 if (DAG->StressSched) {
1756 reverse_sort<SF> RPicker(Picker);
1757 return popFromQueueImpl(Q, RPicker);
1758 }
1759#endif
1760 (void)DAG;
1761 return popFromQueueImpl(Q, Picker);
1762}
1763
1764template<class SF>
1765class RegReductionPriorityQueue : public RegReductionPQBase {
Andrew Trick9ccce772011-01-14 21:11:41 +00001766 SF Picker;
1767
1768public:
1769 RegReductionPriorityQueue(MachineFunction &mf,
1770 bool tracksrp,
Evan Cheng8ab58a22012-03-22 19:31:17 +00001771 bool srcorder,
Andrew Trick9ccce772011-01-14 21:11:41 +00001772 const TargetInstrInfo *tii,
1773 const TargetRegisterInfo *tri,
1774 const TargetLowering *tli)
Evan Cheng8ab58a22012-03-22 19:31:17 +00001775 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
1776 tii, tri, tli),
Andrew Trick9ccce772011-01-14 21:11:41 +00001777 Picker(this) {}
1778
Craig Topper7b883b32014-03-08 06:31:39 +00001779 bool isBottomUp() const override { return SF::IsBottomUp; }
Andrew Trick9ccce772011-01-14 21:11:41 +00001780
Craig Topper7b883b32014-03-08 06:31:39 +00001781 bool isReady(SUnit *U) const override {
Andrew Trick9ccce772011-01-14 21:11:41 +00001782 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1783 }
1784
Craig Topper7b883b32014-03-08 06:31:39 +00001785 SUnit *pop() override {
Craig Topperc0196b12014-04-14 00:51:57 +00001786 if (Queue.empty()) return nullptr;
Andrew Trick9ccce772011-01-14 21:11:41 +00001787
Andrew Trick3013b6a2011-06-15 17:16:12 +00001788 SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
Andrew Trick9ccce772011-01-14 21:11:41 +00001789 V->NodeQueueId = 0;
1790 return V;
1791 }
1792
Manman Ren19f49ac2012-09-11 22:23:19 +00001793#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +00001794 LLVM_DUMP_METHOD void dump(ScheduleDAG *DAG) const override {
Andrew Trick9ccce772011-01-14 21:11:41 +00001795 // Emulate pop() without clobbering NodeQueueIds.
1796 std::vector<SUnit*> DumpQueue = Queue;
1797 SF DumpPicker = Picker;
1798 while (!DumpQueue.empty()) {
Andrew Trick3013b6a2011-06-15 17:16:12 +00001799 SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
Dan Gohman90fb5522011-10-20 21:44:34 +00001800 dbgs() << "Height " << SU->getHeight() << ": ";
Andrew Trick9ccce772011-01-14 21:11:41 +00001801 SU->dump(DAG);
1802 }
1803 }
Manman Ren742534c2012-09-06 19:06:06 +00001804#endif
Andrew Trick9ccce772011-01-14 21:11:41 +00001805};
1806
1807typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1808BURegReductionPriorityQueue;
1809
Andrew Trick9ccce772011-01-14 21:11:41 +00001810typedef RegReductionPriorityQueue<src_ls_rr_sort>
1811SrcRegReductionPriorityQueue;
1812
1813typedef RegReductionPriorityQueue<hybrid_ls_rr_sort>
1814HybridBURRPriorityQueue;
1815
1816typedef RegReductionPriorityQueue<ilp_ls_rr_sort>
1817ILPBURRPriorityQueue;
1818} // end anonymous namespace
1819
1820//===----------------------------------------------------------------------===//
1821// Static Node Priority for Register Pressure Reduction
1822//===----------------------------------------------------------------------===//
Evan Chengd38c22b2006-05-11 23:55:42 +00001823
Andrew Trickbfbd9722011-04-14 05:15:06 +00001824// Check for special nodes that bypass scheduling heuristics.
1825// Currently this pushes TokenFactor nodes down, but may be used for other
1826// pseudo-ops as well.
1827//
1828// Return -1 to schedule right above left, 1 for left above right.
1829// Return 0 if no bias exists.
1830static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
1831 bool LSchedLow = left->isScheduleLow;
1832 bool RSchedLow = right->isScheduleLow;
1833 if (LSchedLow != RSchedLow)
1834 return LSchedLow < RSchedLow ? 1 : -1;
1835 return 0;
1836}
1837
Dan Gohman186f65d2008-11-20 03:30:37 +00001838/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1839/// Smaller number is the higher priority.
Evan Cheng7e4abde2008-07-02 09:23:51 +00001840static unsigned
Dan Gohman186f65d2008-11-20 03:30:37 +00001841CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
Evan Cheng7e4abde2008-07-02 09:23:51 +00001842 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1843 if (SethiUllmanNumber != 0)
1844 return SethiUllmanNumber;
1845
1846 unsigned Extra = 0;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001847 for (const SDep &Pred : SU->Preds) {
1848 if (Pred.isCtrl()) continue; // ignore chain preds
1849 SUnit *PredSU = Pred.getSUnit();
Dan Gohman186f65d2008-11-20 03:30:37 +00001850 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
Evan Cheng7e4abde2008-07-02 09:23:51 +00001851 if (PredSethiUllman > SethiUllmanNumber) {
1852 SethiUllmanNumber = PredSethiUllman;
1853 Extra = 0;
Evan Cheng3a14efa2009-02-12 08:59:45 +00001854 } else if (PredSethiUllman == SethiUllmanNumber)
Evan Cheng7e4abde2008-07-02 09:23:51 +00001855 ++Extra;
1856 }
1857
1858 SethiUllmanNumber += Extra;
1859
1860 if (SethiUllmanNumber == 0)
1861 SethiUllmanNumber = 1;
Andrew Trick2085a962010-12-21 22:25:04 +00001862
Evan Cheng7e4abde2008-07-02 09:23:51 +00001863 return SethiUllmanNumber;
1864}
1865
Andrew Trick9ccce772011-01-14 21:11:41 +00001866/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1867/// scheduling units.
1868void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1869 SethiUllmanNumbers.assign(SUnits->size(), 0);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00001870
Sanjay Patele9fa3362016-02-03 22:44:14 +00001871 for (const SUnit &SU : *SUnits)
1872 CalcNodeSethiUllmanNumber(&SU, SethiUllmanNumbers);
Evan Chengd38c22b2006-05-11 23:55:42 +00001873}
1874
Andrew Trick9ccce772011-01-14 21:11:41 +00001875void RegReductionPQBase::addNode(const SUnit *SU) {
1876 unsigned SUSize = SethiUllmanNumbers.size();
1877 if (SUnits->size() > SUSize)
1878 SethiUllmanNumbers.resize(SUSize*2, 0);
1879 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1880}
1881
1882void RegReductionPQBase::updateNode(const SUnit *SU) {
1883 SethiUllmanNumbers[SU->NodeNum] = 0;
1884 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1885}
1886
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001887// Lower priority means schedule further down. For bottom-up scheduling, lower
1888// priority SUs are scheduled before higher priority SUs.
Andrew Trick9ccce772011-01-14 21:11:41 +00001889unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
1890 assert(SU->NodeNum < SethiUllmanNumbers.size());
1891 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1892 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1893 // CopyToReg should be close to its uses to facilitate coalescing and
1894 // avoid spilling.
1895 return 0;
Christian Koniged34d0e2013-03-20 15:43:00 +00001896 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
1897 Opc == TargetOpcode::SUBREG_TO_REG ||
1898 Opc == TargetOpcode::INSERT_SUBREG)
1899 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
1900 // close to their uses to facilitate coalescing.
1901 return 0;
Andrew Trick9ccce772011-01-14 21:11:41 +00001902 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
1903 // If SU does not have a register use, i.e. it doesn't produce a value
1904 // that would be consumed (e.g. store), then it terminates a chain of
1905 // computation. Give it a large SethiUllman number so it will be
1906 // scheduled right before its predecessors that it doesn't lengthen
1907 // their live ranges.
1908 return 0xffff;
1909 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
1910 // If SU does not have a register def, schedule it close to its uses
1911 // because it does not lengthen any live ranges.
1912 return 0;
Evan Cheng1355bbd2011-04-26 21:31:35 +00001913#if 1
Andrew Trick9ccce772011-01-14 21:11:41 +00001914 return SethiUllmanNumbers[SU->NodeNum];
Evan Cheng1355bbd2011-04-26 21:31:35 +00001915#else
1916 unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
1917 if (SU->isCallOp) {
1918 // FIXME: This assumes all of the defs are used as call operands.
1919 int NP = (int)Priority - SU->getNode()->getNumValues();
1920 return (NP > 0) ? NP : 0;
1921 }
1922 return Priority;
1923#endif
Andrew Trick9ccce772011-01-14 21:11:41 +00001924}
1925
1926//===----------------------------------------------------------------------===//
1927// Register Pressure Tracking
1928//===----------------------------------------------------------------------===//
1929
Manman Ren19f49ac2012-09-11 22:23:19 +00001930#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +00001931LLVM_DUMP_METHOD void RegReductionPQBase::dumpRegPressure() const {
Krzysztof Parzyszekee9aa3f2017-01-25 19:29:04 +00001932 for (const TargetRegisterClass *RC : TRI->regclasses()) {
Andrew Trick9ccce772011-01-14 21:11:41 +00001933 unsigned Id = RC->getID();
1934 unsigned RP = RegPressure[Id];
1935 if (!RP) continue;
Craig Toppercf0444b2014-11-17 05:50:14 +00001936 DEBUG(dbgs() << TRI->getRegClassName(RC) << ": " << RP << " / "
1937 << RegLimit[Id] << '\n');
Andrew Trick9ccce772011-01-14 21:11:41 +00001938 }
1939}
Matthias Braun8c209aa2017-01-28 02:02:38 +00001940#endif
Andrew Trick9ccce772011-01-14 21:11:41 +00001941
1942bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
1943 if (!TLI)
1944 return false;
1945
Sanjay Patele9fa3362016-02-03 22:44:14 +00001946 for (const SDep &Pred : SU->Preds) {
1947 if (Pred.isCtrl())
Andrew Trick9ccce772011-01-14 21:11:41 +00001948 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001949 SUnit *PredSU = Pred.getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00001950 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
1951 // to cover the number of registers defined (they are all live).
1952 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00001953 continue;
1954 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00001955 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
1956 RegDefPos.IsValid(); RegDefPos.Advance()) {
Owen Anderson96adc4a2011-06-15 23:35:18 +00001957 unsigned RCId, Cost;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001958 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
Owen Anderson96adc4a2011-06-15 23:35:18 +00001959
Andrew Trick9ccce772011-01-14 21:11:41 +00001960 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
1961 return true;
1962 }
1963 }
Andrew Trick9ccce772011-01-14 21:11:41 +00001964 return false;
1965}
1966
Andrew Trick641e2d42011-03-05 08:00:22 +00001967bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00001968 const SDNode *N = SU->getNode();
1969
1970 if (!N->isMachineOpcode() || !SU->NumSuccs)
1971 return false;
1972
1973 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1974 for (unsigned i = 0; i != NumDefs; ++i) {
Patrik Hagglund05394352012-12-13 18:45:35 +00001975 MVT VT = N->getSimpleValueType(i);
Andrew Trick9ccce772011-01-14 21:11:41 +00001976 if (!N->hasAnyUseOfValue(i))
1977 continue;
1978 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
1979 if (RegPressure[RCId] >= RegLimit[RCId])
1980 return true;
1981 }
1982 return false;
1983}
1984
Andrew Trick641e2d42011-03-05 08:00:22 +00001985// Compute the register pressure contribution by this instruction by count up
1986// for uses that are not live and down for defs. Only count register classes
1987// that are already under high pressure. As a side effect, compute the number of
1988// uses of registers that are already live.
1989//
1990// FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
1991// so could probably be factored.
1992int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
1993 LiveUses = 0;
1994 int PDiff = 0;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001995 for (const SDep &Pred : SU->Preds) {
1996 if (Pred.isCtrl())
Andrew Trick641e2d42011-03-05 08:00:22 +00001997 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00001998 SUnit *PredSU = Pred.getSUnit();
Andrew Trick641e2d42011-03-05 08:00:22 +00001999 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2000 // to cover the number of registers defined (they are all live).
2001 if (PredSU->NumRegDefsLeft == 0) {
2002 if (PredSU->getNode()->isMachineOpcode())
2003 ++LiveUses;
2004 continue;
2005 }
2006 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2007 RegDefPos.IsValid(); RegDefPos.Advance()) {
Patrik Hagglund05394352012-12-13 18:45:35 +00002008 MVT VT = RegDefPos.GetValue();
Andrew Trick641e2d42011-03-05 08:00:22 +00002009 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2010 if (RegPressure[RCId] >= RegLimit[RCId])
2011 ++PDiff;
2012 }
2013 }
2014 const SDNode *N = SU->getNode();
2015
Eric Christopher7238cba2011-03-08 19:35:47 +00002016 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
Andrew Trick641e2d42011-03-05 08:00:22 +00002017 return PDiff;
2018
2019 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2020 for (unsigned i = 0; i != NumDefs; ++i) {
Patrik Hagglund05394352012-12-13 18:45:35 +00002021 MVT VT = N->getSimpleValueType(i);
Andrew Trick641e2d42011-03-05 08:00:22 +00002022 if (!N->hasAnyUseOfValue(i))
2023 continue;
2024 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2025 if (RegPressure[RCId] >= RegLimit[RCId])
2026 --PDiff;
2027 }
2028 return PDiff;
2029}
2030
Andrew Trick52226d42012-03-07 23:00:49 +00002031void RegReductionPQBase::scheduledNode(SUnit *SU) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002032 if (!TracksRegPressure)
2033 return;
2034
Eric Christopher7238cba2011-03-08 19:35:47 +00002035 if (!SU->getNode())
2036 return;
Andrew Tricka8846e02011-03-23 20:40:18 +00002037
Sanjay Patele9fa3362016-02-03 22:44:14 +00002038 for (const SDep &Pred : SU->Preds) {
2039 if (Pred.isCtrl())
Andrew Trick9ccce772011-01-14 21:11:41 +00002040 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002041 SUnit *PredSU = Pred.getSUnit();
Andrew Trickd0548ae2011-02-04 03:18:17 +00002042 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2043 // to cover the number of registers defined (they are all live).
2044 if (PredSU->NumRegDefsLeft == 0) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002045 continue;
2046 }
Andrew Trickd0548ae2011-02-04 03:18:17 +00002047 // FIXME: The ScheduleDAG currently loses information about which of a
2048 // node's values is consumed by each dependence. Consequently, if the node
2049 // defines multiple register classes, we don't know which to pressurize
2050 // here. Instead the following loop consumes the register defs in an
2051 // arbitrary order. At least it handles the common case of clustered loads
2052 // to the same class. For precise liveness, each SDep needs to indicate the
2053 // result number. But that tightly couples the ScheduleDAG with the
2054 // SelectionDAG making updates tricky. A simpler hack would be to attach a
2055 // value type or register class to SDep.
2056 //
2057 // The most important aspect of register tracking is balancing the increase
2058 // here with the reduction further below. Note that this SU may use multiple
2059 // defs in PredSU. The can't be determined here, but we've already
2060 // compensated by reducing NumRegDefsLeft in PredSU during
2061 // ScheduleDAGSDNodes::AddSchedEdges.
2062 --PredSU->NumRegDefsLeft;
2063 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
2064 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2065 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2066 if (SkipRegDefs)
Andrew Trick9ccce772011-01-14 21:11:41 +00002067 continue;
Owen Anderson96adc4a2011-06-15 23:35:18 +00002068
2069 unsigned RCId, Cost;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00002070 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
Owen Anderson96adc4a2011-06-15 23:35:18 +00002071 RegPressure[RCId] += Cost;
Andrew Trickd0548ae2011-02-04 03:18:17 +00002072 break;
Andrew Trick9ccce772011-01-14 21:11:41 +00002073 }
2074 }
2075
Andrew Trickd0548ae2011-02-04 03:18:17 +00002076 // We should have this assert, but there may be dead SDNodes that never
2077 // materialize as SUnits, so they don't appear to generate liveness.
2078 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
2079 int SkipRegDefs = (int)SU->NumRegDefsLeft;
2080 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
2081 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2082 if (SkipRegDefs > 0)
2083 continue;
Owen Anderson96adc4a2011-06-15 23:35:18 +00002084 unsigned RCId, Cost;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00002085 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
Owen Anderson96adc4a2011-06-15 23:35:18 +00002086 if (RegPressure[RCId] < Cost) {
Andrew Trickd0548ae2011-02-04 03:18:17 +00002087 // Register pressure tracking is imprecise. This can happen. But we try
2088 // hard not to let it happen because it likely results in poor scheduling.
2089 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") has too many regdefs\n");
2090 RegPressure[RCId] = 0;
2091 }
2092 else {
Owen Anderson96adc4a2011-06-15 23:35:18 +00002093 RegPressure[RCId] -= Cost;
Andrew Trick9ccce772011-01-14 21:11:41 +00002094 }
2095 }
Matthias Braun8c209aa2017-01-28 02:02:38 +00002096 DEBUG(dumpRegPressure());
Andrew Trick9ccce772011-01-14 21:11:41 +00002097}
2098
Andrew Trick52226d42012-03-07 23:00:49 +00002099void RegReductionPQBase::unscheduledNode(SUnit *SU) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002100 if (!TracksRegPressure)
2101 return;
2102
2103 const SDNode *N = SU->getNode();
Eric Christopher7238cba2011-03-08 19:35:47 +00002104 if (!N) return;
Andrew Tricka8846e02011-03-23 20:40:18 +00002105
Andrew Trick9ccce772011-01-14 21:11:41 +00002106 if (!N->isMachineOpcode()) {
2107 if (N->getOpcode() != ISD::CopyToReg)
2108 return;
2109 } else {
2110 unsigned Opc = N->getMachineOpcode();
2111 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2112 Opc == TargetOpcode::INSERT_SUBREG ||
2113 Opc == TargetOpcode::SUBREG_TO_REG ||
2114 Opc == TargetOpcode::REG_SEQUENCE ||
2115 Opc == TargetOpcode::IMPLICIT_DEF)
2116 return;
2117 }
2118
Sanjay Patele9fa3362016-02-03 22:44:14 +00002119 for (const SDep &Pred : SU->Preds) {
2120 if (Pred.isCtrl())
Andrew Trick9ccce772011-01-14 21:11:41 +00002121 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002122 SUnit *PredSU = Pred.getSUnit();
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002123 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
2124 // counts data deps.
2125 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
Andrew Trick9ccce772011-01-14 21:11:41 +00002126 continue;
2127 const SDNode *PN = PredSU->getNode();
2128 if (!PN->isMachineOpcode()) {
2129 if (PN->getOpcode() == ISD::CopyFromReg) {
Patrik Hagglund05394352012-12-13 18:45:35 +00002130 MVT VT = PN->getSimpleValueType(0);
Andrew Trick9ccce772011-01-14 21:11:41 +00002131 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2132 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2133 }
2134 continue;
2135 }
2136 unsigned POpc = PN->getMachineOpcode();
2137 if (POpc == TargetOpcode::IMPLICIT_DEF)
2138 continue;
Andrew Trick31f25bc2011-06-27 18:01:20 +00002139 if (POpc == TargetOpcode::EXTRACT_SUBREG ||
2140 POpc == TargetOpcode::INSERT_SUBREG ||
2141 POpc == TargetOpcode::SUBREG_TO_REG) {
Patrik Hagglund05394352012-12-13 18:45:35 +00002142 MVT VT = PN->getSimpleValueType(0);
Andrew Trick9ccce772011-01-14 21:11:41 +00002143 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2144 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2145 continue;
2146 }
2147 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
2148 for (unsigned i = 0; i != NumDefs; ++i) {
Patrik Hagglund05394352012-12-13 18:45:35 +00002149 MVT VT = PN->getSimpleValueType(i);
Andrew Trick9ccce772011-01-14 21:11:41 +00002150 if (!PN->hasAnyUseOfValue(i))
2151 continue;
2152 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2153 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
2154 // Register pressure tracking is imprecise. This can happen.
2155 RegPressure[RCId] = 0;
2156 else
2157 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
2158 }
2159 }
2160
2161 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
2162 // may transfer data dependencies to CopyToReg.
2163 if (SU->NumSuccs && N->isMachineOpcode()) {
2164 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2165 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Patrik Hagglund05394352012-12-13 18:45:35 +00002166 MVT VT = N->getSimpleValueType(i);
Andrew Trick9ccce772011-01-14 21:11:41 +00002167 if (VT == MVT::Glue || VT == MVT::Other)
2168 continue;
2169 if (!N->hasAnyUseOfValue(i))
2170 continue;
2171 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2172 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
2173 }
2174 }
2175
Matthias Braun8c209aa2017-01-28 02:02:38 +00002176 DEBUG(dumpRegPressure());
Andrew Trick9ccce772011-01-14 21:11:41 +00002177}
2178
2179//===----------------------------------------------------------------------===//
2180// Dynamic Node Priority for Register Pressure Reduction
2181//===----------------------------------------------------------------------===//
2182
Evan Chengb9e3db62007-03-14 22:43:40 +00002183/// closestSucc - Returns the scheduled cycle of the successor which is
Dan Gohmana19c6622009-03-12 23:55:10 +00002184/// closest to the current cycle.
Evan Cheng28748552007-03-13 23:25:11 +00002185static unsigned closestSucc(const SUnit *SU) {
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002186 unsigned MaxHeight = 0;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002187 for (const SDep &Succ : SU->Succs) {
2188 if (Succ.isCtrl()) continue; // ignore chain succs
2189 unsigned Height = Succ.getSUnit()->getHeight();
Evan Chengb9e3db62007-03-14 22:43:40 +00002190 // If there are bunch of CopyToRegs stacked up, they should be considered
2191 // to be at the same position.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002192 if (Succ.getSUnit()->getNode() &&
2193 Succ.getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
2194 Height = closestSucc(Succ.getSUnit())+1;
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002195 if (Height > MaxHeight)
2196 MaxHeight = Height;
Evan Chengb9e3db62007-03-14 22:43:40 +00002197 }
Dan Gohmandddc1ac2008-12-16 03:25:46 +00002198 return MaxHeight;
Evan Cheng28748552007-03-13 23:25:11 +00002199}
2200
Evan Cheng61bc51e2007-12-20 02:22:36 +00002201/// calcMaxScratches - Returns an cost estimate of the worse case requirement
Evan Cheng3a14efa2009-02-12 08:59:45 +00002202/// for scratch registers, i.e. number of data dependencies.
Evan Cheng61bc51e2007-12-20 02:22:36 +00002203static unsigned calcMaxScratches(const SUnit *SU) {
2204 unsigned Scratches = 0;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002205 for (const SDep &Pred : SU->Preds) {
2206 if (Pred.isCtrl()) continue; // ignore chain preds
Evan Chengb5704992009-02-12 09:52:13 +00002207 Scratches++;
2208 }
Evan Cheng61bc51e2007-12-20 02:22:36 +00002209 return Scratches;
2210}
2211
Andrew Trickb53a00d2011-04-13 00:38:32 +00002212/// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2213/// CopyFromReg from a virtual register.
2214static bool hasOnlyLiveInOpers(const SUnit *SU) {
2215 bool RetVal = false;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002216 for (const SDep &Pred : SU->Preds) {
2217 if (Pred.isCtrl()) continue;
2218 const SUnit *PredSU = Pred.getSUnit();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002219 if (PredSU->getNode() &&
2220 PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2221 unsigned Reg =
2222 cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2223 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2224 RetVal = true;
2225 continue;
2226 }
2227 }
2228 return false;
2229 }
2230 return RetVal;
2231}
2232
2233/// hasOnlyLiveOutUses - Return true if SU has only value successors that are
Evan Cheng6c1414f2010-10-29 18:09:28 +00002234/// CopyToReg to a virtual register. This SU def is probably a liveout and
2235/// it has no other use. It should be scheduled closer to the terminator.
2236static bool hasOnlyLiveOutUses(const SUnit *SU) {
2237 bool RetVal = false;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002238 for (const SDep &Succ : SU->Succs) {
2239 if (Succ.isCtrl()) continue;
2240 const SUnit *SuccSU = Succ.getSUnit();
Evan Cheng6c1414f2010-10-29 18:09:28 +00002241 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2242 unsigned Reg =
2243 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2244 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2245 RetVal = true;
2246 continue;
2247 }
2248 }
2249 return false;
2250 }
2251 return RetVal;
2252}
2253
Andrew Trickb53a00d2011-04-13 00:38:32 +00002254// Set isVRegCycle for a node with only live in opers and live out uses. Also
2255// set isVRegCycle for its CopyFromReg operands.
2256//
2257// This is only relevant for single-block loops, in which case the VRegCycle
2258// node is likely an induction variable in which the operand and target virtual
2259// registers should be coalesced (e.g. pre/post increment values). Setting the
2260// isVRegCycle flag helps the scheduler prioritize other uses of the same
2261// CopyFromReg so that this node becomes the virtual register "kill". This
2262// avoids interference between the values live in and out of the block and
2263// eliminates a copy inside the loop.
2264static void initVRegCycle(SUnit *SU) {
2265 if (DisableSchedVRegCycle)
2266 return;
2267
2268 if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2269 return;
2270
2271 DEBUG(dbgs() << "VRegCycle: SU(" << SU->NodeNum << ")\n");
2272
2273 SU->isVRegCycle = true;
2274
Sanjay Patele9fa3362016-02-03 22:44:14 +00002275 for (const SDep &Pred : SU->Preds) {
2276 if (Pred.isCtrl()) continue;
2277 Pred.getSUnit()->isVRegCycle = true;
Andrew Trickc5dd24a2011-04-12 19:54:36 +00002278 }
Andrew Trick1b60ad62011-04-12 20:14:07 +00002279}
2280
Andrew Trickb53a00d2011-04-13 00:38:32 +00002281// After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2282// CopyFromReg operands. We should no longer penalize other uses of this VReg.
2283static void resetVRegCycle(SUnit *SU) {
2284 if (!SU->isVRegCycle)
2285 return;
2286
Sanjay Patele9fa3362016-02-03 22:44:14 +00002287 for (const SDep &Pred : SU->Preds) {
2288 if (Pred.isCtrl()) continue; // ignore chain preds
2289 SUnit *PredSU = Pred.getSUnit();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002290 if (PredSU->isVRegCycle) {
2291 assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2292 "VRegCycle def must be CopyFromReg");
Sanjay Patele9fa3362016-02-03 22:44:14 +00002293 Pred.getSUnit()->isVRegCycle = false;
Andrew Trickb53a00d2011-04-13 00:38:32 +00002294 }
2295 }
2296}
2297
2298// Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2299// means a node that defines the VRegCycle has not been scheduled yet.
2300static bool hasVRegCycleUse(const SUnit *SU) {
2301 // If this SU also defines the VReg, don't hoist it as a "use".
2302 if (SU->isVRegCycle)
2303 return false;
2304
Sanjay Patele9fa3362016-02-03 22:44:14 +00002305 for (const SDep &Pred : SU->Preds) {
2306 if (Pred.isCtrl()) continue; // ignore chain preds
2307 if (Pred.getSUnit()->isVRegCycle &&
2308 Pred.getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002309 DEBUG(dbgs() << " VReg cycle use: SU (" << SU->NodeNum << ")\n");
2310 return true;
Andrew Trick2ad0b372011-04-07 19:54:57 +00002311 }
2312 }
2313 return false;
2314}
2315
Andrew Trick9ccce772011-01-14 21:11:41 +00002316// Check for either a dependence (latency) or resource (hazard) stall.
2317//
2318// Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2319static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2320 if ((int)SPQ->getCurCycle() < Height) return true;
2321 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2322 != ScheduleHazardRecognizer::NoHazard)
2323 return true;
2324 return false;
2325}
2326
2327// Return -1 if left has higher priority, 1 if right has higher priority.
2328// Return 0 if latency-based priority is equivalent.
2329static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2330 RegReductionPQBase *SPQ) {
Andrew Trickb53a00d2011-04-13 00:38:32 +00002331 // Scheduling an instruction that uses a VReg whose postincrement has not yet
2332 // been scheduled will induce a copy. Model this as an extra cycle of latency.
2333 int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2334 int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2335 int LHeight = (int)left->getHeight() + LPenalty;
2336 int RHeight = (int)right->getHeight() + RPenalty;
Andrew Trick9ccce772011-01-14 21:11:41 +00002337
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002338 bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
Andrew Trick9ccce772011-01-14 21:11:41 +00002339 BUHasStall(left, LHeight, SPQ);
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002340 bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
Andrew Trick9ccce772011-01-14 21:11:41 +00002341 BUHasStall(right, RHeight, SPQ);
2342
2343 // If scheduling one of the node will cause a pipeline stall, delay it.
2344 // If scheduling either one of the node will cause a pipeline stall, sort
2345 // them according to their height.
2346 if (LStall) {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002347 if (!RStall)
Andrew Trick9ccce772011-01-14 21:11:41 +00002348 return 1;
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002349 if (LHeight != RHeight)
Andrew Trick9ccce772011-01-14 21:11:41 +00002350 return LHeight > RHeight ? 1 : -1;
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002351 } else if (RStall)
Andrew Trick9ccce772011-01-14 21:11:41 +00002352 return -1;
2353
Andrew Trick47ff14b2011-01-21 05:51:33 +00002354 // If either node is scheduling for latency, sort them by height/depth
Andrew Trick9ccce772011-01-14 21:11:41 +00002355 // and latency.
Dan Gohman4ed1afa2011-10-24 17:55:11 +00002356 if (!checkPref || (left->SchedulingPref == Sched::ILP ||
2357 right->SchedulingPref == Sched::ILP)) {
Andrew Tricka88d46e2012-06-05 03:44:34 +00002358 // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
2359 // is enabled, grouping instructions by cycle, then its height is already
2360 // covered so only its depth matters. We also reach this point if both stall
2361 // but have the same height.
2362 if (!SPQ->getHazardRec()->isEnabled()) {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002363 if (LHeight != RHeight)
Andrew Trick9ccce772011-01-14 21:11:41 +00002364 return LHeight > RHeight ? 1 : -1;
2365 }
Andrew Tricka88d46e2012-06-05 03:44:34 +00002366 int LDepth = left->getDepth() - LPenalty;
2367 int RDepth = right->getDepth() - RPenalty;
2368 if (LDepth != RDepth) {
2369 DEBUG(dbgs() << " Comparing latency of SU (" << left->NodeNum
2370 << ") depth " << LDepth << " vs SU (" << right->NodeNum
2371 << ") depth " << RDepth << "\n");
2372 return LDepth < RDepth ? 1 : -1;
Andrew Trick47ff14b2011-01-21 05:51:33 +00002373 }
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002374 if (left->Latency != right->Latency)
Andrew Trick9ccce772011-01-14 21:11:41 +00002375 return left->Latency > right->Latency ? 1 : -1;
2376 }
2377 return 0;
2378}
2379
2380static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002381 // Schedule physical register definitions close to their use. This is
2382 // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
2383 // long as shortening physreg live ranges is generally good, we can defer
2384 // creating a subtarget hook.
2385 if (!DisableSchedPhysRegJoin) {
2386 bool LHasPhysReg = left->hasPhysRegDefs;
2387 bool RHasPhysReg = right->hasPhysRegDefs;
2388 if (LHasPhysReg != RHasPhysReg) {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002389 #ifndef NDEBUG
Craig Topper06b3b662013-07-15 08:02:13 +00002390 static const char *const PhysRegMsg[] = { " has no physreg",
2391 " defines a physreg" };
Andrew Trickbfbd9722011-04-14 05:15:06 +00002392 #endif
2393 DEBUG(dbgs() << " SU (" << left->NodeNum << ") "
2394 << PhysRegMsg[LHasPhysReg] << " SU(" << right->NodeNum << ") "
2395 << PhysRegMsg[RHasPhysReg] << "\n");
2396 return LHasPhysReg < RHasPhysReg;
2397 }
2398 }
2399
Evan Cheng2f647542011-04-26 04:57:37 +00002400 // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
Evan Cheng6730f032007-01-08 23:55:53 +00002401 unsigned LPriority = SPQ->getNodePriority(left);
2402 unsigned RPriority = SPQ->getNodePriority(right);
Evan Cheng1355bbd2011-04-26 21:31:35 +00002403
2404 // Be really careful about hoisting call operands above previous calls.
2405 // Only allows it if it would reduce register pressure.
2406 if (left->isCall && right->isCallOp) {
2407 unsigned RNumVals = right->getNode()->getNumValues();
2408 RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2409 }
2410 if (right->isCall && left->isCallOp) {
2411 unsigned LNumVals = left->getNode()->getNumValues();
2412 LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2413 }
2414
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002415 if (LPriority != RPriority)
Evan Cheng73bdf042008-03-01 00:39:47 +00002416 return LPriority > RPriority;
Andrew Trick52b3e382011-03-08 01:51:56 +00002417
Evan Cheng1355bbd2011-04-26 21:31:35 +00002418 // One or both of the nodes are calls and their sethi-ullman numbers are the
2419 // same, then keep source order.
2420 if (left->isCall || right->isCall) {
2421 unsigned LOrder = SPQ->getNodeOrdering(left);
2422 unsigned ROrder = SPQ->getNodeOrdering(right);
2423
2424 // Prefer an ordering where the lower the non-zero order number, the higher
2425 // the preference.
2426 if ((LOrder || ROrder) && LOrder != ROrder)
2427 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2428 }
2429
Evan Cheng73bdf042008-03-01 00:39:47 +00002430 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2431 // e.g.
2432 // t1 = op t2, c1
2433 // t3 = op t4, c2
2434 //
2435 // and the following instructions are both ready.
2436 // t2 = op c3
2437 // t4 = op c4
2438 //
2439 // Then schedule t2 = op first.
2440 // i.e.
2441 // t4 = op c4
2442 // t2 = op c3
2443 // t1 = op t2, c1
2444 // t3 = op t4, c2
2445 //
2446 // This creates more short live intervals.
2447 unsigned LDist = closestSucc(left);
2448 unsigned RDist = closestSucc(right);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002449 if (LDist != RDist)
Evan Cheng73bdf042008-03-01 00:39:47 +00002450 return LDist < RDist;
2451
Evan Cheng3a14efa2009-02-12 08:59:45 +00002452 // How many registers becomes live when the node is scheduled.
Evan Cheng73bdf042008-03-01 00:39:47 +00002453 unsigned LScratch = calcMaxScratches(left);
2454 unsigned RScratch = calcMaxScratches(right);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002455 if (LScratch != RScratch)
Evan Cheng73bdf042008-03-01 00:39:47 +00002456 return LScratch > RScratch;
2457
Evan Cheng1355bbd2011-04-26 21:31:35 +00002458 // Comparing latency against a call makes little sense unless the node
2459 // is register pressure-neutral.
2460 if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
2461 return (left->NodeQueueId > right->NodeQueueId);
2462
2463 // Do not compare latencies when one or both of the nodes are calls.
2464 if (!DisableSchedCycles &&
2465 !(left->isCall || right->isCall)) {
Andrew Trick9ccce772011-01-14 21:11:41 +00002466 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2467 if (result != 0)
2468 return result > 0;
2469 }
2470 else {
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002471 if (left->getHeight() != right->getHeight())
Andrew Trick9ccce772011-01-14 21:11:41 +00002472 return left->getHeight() > right->getHeight();
Andrew Trick2085a962010-12-21 22:25:04 +00002473
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002474 if (left->getDepth() != right->getDepth())
Andrew Trick9ccce772011-01-14 21:11:41 +00002475 return left->getDepth() < right->getDepth();
2476 }
Evan Cheng73bdf042008-03-01 00:39:47 +00002477
Andrew Trick2085a962010-12-21 22:25:04 +00002478 assert(left->NodeQueueId && right->NodeQueueId &&
Roman Levenstein6b371142008-04-29 09:07:59 +00002479 "NodeQueueId cannot be zero");
2480 return (left->NodeQueueId > right->NodeQueueId);
Evan Chengd38c22b2006-05-11 23:55:42 +00002481}
2482
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002483// Bottom up
Andrew Trick9ccce772011-01-14 21:11:41 +00002484bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002485 if (int res = checkSpecialNodes(left, right))
2486 return res > 0;
2487
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002488 return BURRSort(left, right, SPQ);
2489}
2490
2491// Source order, otherwise bottom up.
Andrew Trick9ccce772011-01-14 21:11:41 +00002492bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002493 if (int res = checkSpecialNodes(left, right))
2494 return res > 0;
2495
Bill Wendling8cbc25d2010-01-23 10:26:57 +00002496 unsigned LOrder = SPQ->getNodeOrdering(left);
2497 unsigned ROrder = SPQ->getNodeOrdering(right);
2498
2499 // Prefer an ordering where the lower the non-zero order number, the higher
2500 // the preference.
2501 if ((LOrder || ROrder) && LOrder != ROrder)
2502 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2503
2504 return BURRSort(left, right, SPQ);
2505}
2506
Andrew Trick9ccce772011-01-14 21:11:41 +00002507// If the time between now and when the instruction will be ready can cover
2508// the spill code, then avoid adding it to the ready queue. This gives long
2509// stalls highest priority and allows hoisting across calls. It should also
2510// speed up processing the available queue.
2511bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2512 static const unsigned ReadyDelay = 3;
2513
2514 if (SPQ->MayReduceRegPressure(SU)) return true;
2515
2516 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2517
2518 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2519 != ScheduleHazardRecognizer::NoHazard)
2520 return false;
2521
2522 return true;
2523}
2524
2525// Return true if right should be scheduled with higher priority than left.
2526bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002527 if (int res = checkSpecialNodes(left, right))
2528 return res > 0;
2529
Evan Chengdebf9c52010-11-03 00:45:17 +00002530 if (left->isCall || right->isCall)
2531 // No way to compute latency of calls.
2532 return BURRSort(left, right, SPQ);
2533
Evan Chenge6d6c5d2010-07-26 21:49:07 +00002534 bool LHigh = SPQ->HighRegPressure(left);
2535 bool RHigh = SPQ->HighRegPressure(right);
Evan Cheng37b740c2010-07-24 00:39:05 +00002536 // Avoid causing spills. If register pressure is high, schedule for
2537 // register pressure reduction.
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002538 if (LHigh && !RHigh) {
2539 DEBUG(dbgs() << " pressure SU(" << left->NodeNum << ") > SU("
2540 << right->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002541 return true;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002542 }
2543 else if (!LHigh && RHigh) {
2544 DEBUG(dbgs() << " pressure SU(" << right->NodeNum << ") > SU("
2545 << left->NodeNum << ")\n");
Evan Cheng28590382010-07-21 23:53:58 +00002546 return false;
Andrew Trick2cd1f0b2011-01-20 06:21:59 +00002547 }
Andrew Trickb53a00d2011-04-13 00:38:32 +00002548 if (!LHigh && !RHigh) {
2549 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2550 if (result != 0)
2551 return result > 0;
Evan Chengcc2efe12010-05-28 23:26:21 +00002552 }
Evan Chengbdd062d2010-05-20 06:13:19 +00002553 return BURRSort(left, right, SPQ);
2554}
2555
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002556// Schedule as many instructions in each cycle as possible. So don't make an
2557// instruction available unless it is ready in the current cycle.
2558bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
Andrew Trick9ccce772011-01-14 21:11:41 +00002559 if (SU->getHeight() > CurCycle) return false;
2560
2561 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2562 != ScheduleHazardRecognizer::NoHazard)
2563 return false;
2564
Andrew Trickc88b7ec2011-03-04 02:03:45 +00002565 return true;
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002566}
2567
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002568static bool canEnableCoalescing(SUnit *SU) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002569 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2570 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
2571 // CopyToReg should be close to its uses to facilitate coalescing and
2572 // avoid spilling.
2573 return true;
2574
Christian Koniged34d0e2013-03-20 15:43:00 +00002575 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2576 Opc == TargetOpcode::SUBREG_TO_REG ||
2577 Opc == TargetOpcode::INSERT_SUBREG)
2578 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2579 // close to their uses to facilitate coalescing.
2580 return true;
Andrew Trick52b3e382011-03-08 01:51:56 +00002581
2582 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2583 // If SU does not have a register def, schedule it close to its uses
2584 // because it does not lengthen any live ranges.
2585 return true;
2586
2587 return false;
2588}
2589
Andrew Trickb8390b72011-03-05 08:04:11 +00002590// list-ilp is currently an experimental scheduler that allows various
2591// heuristics to be enabled prior to the normal register reduction logic.
Andrew Trick9ccce772011-01-14 21:11:41 +00002592bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
Andrew Trickbfbd9722011-04-14 05:15:06 +00002593 if (int res = checkSpecialNodes(left, right))
2594 return res > 0;
2595
Evan Chengdebf9c52010-11-03 00:45:17 +00002596 if (left->isCall || right->isCall)
2597 // No way to compute latency of calls.
2598 return BURRSort(left, right, SPQ);
2599
Andrew Trick52b3e382011-03-08 01:51:56 +00002600 unsigned LLiveUses = 0, RLiveUses = 0;
2601 int LPDiff = 0, RPDiff = 0;
2602 if (!DisableSchedRegPressure || !DisableSchedLiveUses) {
2603 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2604 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2605 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002606 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002607 DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPDiff
2608 << " != SU(" << right->NodeNum << "): " << RPDiff << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002609 return LPDiff > RPDiff;
2610 }
2611
Andrew Trick52b3e382011-03-08 01:51:56 +00002612 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
Benjamin Kramerb2e4d842011-03-09 16:19:12 +00002613 bool LReduce = canEnableCoalescing(left);
2614 bool RReduce = canEnableCoalescing(right);
Andrew Trick52b3e382011-03-08 01:51:56 +00002615 if (LReduce && !RReduce) return false;
2616 if (RReduce && !LReduce) return true;
2617 }
2618
2619 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2620 DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
2621 << " != SU(" << right->NodeNum << "): " << RLiveUses << "\n");
Andrew Trick641e2d42011-03-05 08:00:22 +00002622 return LLiveUses < RLiveUses;
2623 }
2624
Andrew Trick52b3e382011-03-08 01:51:56 +00002625 if (!DisableSchedStalls) {
2626 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2627 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002628 if (LStall != RStall)
Andrew Trick52b3e382011-03-08 01:51:56 +00002629 return left->getHeight() > right->getHeight();
Andrew Trick641e2d42011-03-05 08:00:22 +00002630 }
2631
Andrew Trick25cedf32011-03-05 10:29:25 +00002632 if (!DisableSchedCriticalPath) {
2633 int spread = (int)left->getDepth() - (int)right->getDepth();
2634 if (std::abs(spread) > MaxReorderWindow) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002635 DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
2636 << left->getDepth() << " != SU(" << right->NodeNum << "): "
2637 << right->getDepth() << "\n");
Andrew Trick25cedf32011-03-05 10:29:25 +00002638 return left->getDepth() < right->getDepth();
2639 }
Andrew Trick641e2d42011-03-05 08:00:22 +00002640 }
2641
2642 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
Andrew Trick52b3e382011-03-08 01:51:56 +00002643 int spread = (int)left->getHeight() - (int)right->getHeight();
Nick Lewyckyd63851e2011-12-07 21:35:59 +00002644 if (std::abs(spread) > MaxReorderWindow)
Andrew Trick52b3e382011-03-08 01:51:56 +00002645 return left->getHeight() > right->getHeight();
Evan Cheng37b740c2010-07-24 00:39:05 +00002646 }
2647
2648 return BURRSort(left, right, SPQ);
2649}
2650
Andrew Trickb53a00d2011-04-13 00:38:32 +00002651void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2652 SUnits = &sunits;
2653 // Add pseudo dependency edges for two-address nodes.
Evan Chengd33b2d62011-11-10 07:43:16 +00002654 if (!Disable2AddrHack)
2655 AddPseudoTwoAddrDeps();
Andrew Trickb53a00d2011-04-13 00:38:32 +00002656 // Reroute edges to nodes with multiple uses.
Evan Cheng8ab58a22012-03-22 19:31:17 +00002657 if (!TracksRegPressure && !SrcOrder)
Andrew Trickb53a00d2011-04-13 00:38:32 +00002658 PrescheduleNodesWithMultipleUses();
2659 // Calculate node priorities.
2660 CalculateSethiUllmanNumbers();
2661
2662 // For single block loops, mark nodes that look like canonical IV increments.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002663 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB))
2664 for (SUnit &SU : sunits)
2665 initVRegCycle(&SU);
Andrew Trickb53a00d2011-04-13 00:38:32 +00002666}
2667
Andrew Trick9ccce772011-01-14 21:11:41 +00002668//===----------------------------------------------------------------------===//
2669// Preschedule for Register Pressure
2670//===----------------------------------------------------------------------===//
2671
2672bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002673 if (SU->isTwoAddress) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002674 unsigned Opc = SU->getNode()->getMachineOpcode();
Evan Cheng6cc775f2011-06-28 19:10:37 +00002675 const MCInstrDesc &MCID = TII->get(Opc);
2676 unsigned NumRes = MCID.getNumDefs();
2677 unsigned NumOps = MCID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002678 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00002679 if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002680 SDNode *DU = SU->getNode()->getOperand(i).getNode();
Dan Gohman46520a22008-06-21 19:18:17 +00002681 if (DU->getNodeId() != -1 &&
2682 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002683 return true;
2684 }
2685 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002686 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002687 return false;
2688}
2689
Andrew Trick832a6a192011-09-01 00:54:31 +00002690/// canClobberReachingPhysRegUse - True if SU would clobber one of it's
2691/// successor's explicit physregs whose definition can reach DepSU.
2692/// i.e. DepSU should not be scheduled above SU.
2693static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
2694 ScheduleDAGRRList *scheduleDAG,
2695 const TargetInstrInfo *TII,
2696 const TargetRegisterInfo *TRI) {
Craig Toppere5e035a32015-12-05 07:13:35 +00002697 const MCPhysReg *ImpDefs
Andrew Trick832a6a192011-09-01 00:54:31 +00002698 = TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002699 const uint32_t *RegMask = getNodeRegMask(SU->getNode());
2700 if(!ImpDefs && !RegMask)
Andrew Trick832a6a192011-09-01 00:54:31 +00002701 return false;
2702
Sanjay Patele9fa3362016-02-03 22:44:14 +00002703 for (const SDep &Succ : SU->Succs) {
2704 SUnit *SuccSU = Succ.getSUnit();
2705 for (const SDep &SuccPred : SuccSU->Preds) {
2706 if (!SuccPred.isAssignedRegDep())
Andrew Trick832a6a192011-09-01 00:54:31 +00002707 continue;
2708
Sanjay Patele9fa3362016-02-03 22:44:14 +00002709 if (RegMask &&
2710 MachineOperand::clobbersPhysReg(RegMask, SuccPred.getReg()) &&
2711 scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002712 return true;
2713
2714 if (ImpDefs)
Craig Toppere5e035a32015-12-05 07:13:35 +00002715 for (const MCPhysReg *ImpDef = ImpDefs; *ImpDef; ++ImpDef)
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002716 // Return true if SU clobbers this physical register use and the
2717 // definition of the register reaches from DepSU. IsReachable queries
2718 // a topological forward sort of the DAG (following the successors).
Sanjay Patele9fa3362016-02-03 22:44:14 +00002719 if (TRI->regsOverlap(*ImpDef, SuccPred.getReg()) &&
2720 scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002721 return true;
Andrew Trick832a6a192011-09-01 00:54:31 +00002722 }
2723 }
2724 return false;
2725}
2726
Evan Chengf9891412007-12-20 09:25:31 +00002727/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
Dan Gohmanea045202008-06-21 22:05:24 +00002728/// physical register defs.
Dan Gohmane955c482008-08-05 14:45:15 +00002729static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
Evan Chengf9891412007-12-20 09:25:31 +00002730 const TargetInstrInfo *TII,
Dan Gohman3a4be0f2008-02-10 18:45:23 +00002731 const TargetRegisterInfo *TRI) {
Dan Gohman1ddfcba2008-11-13 21:36:12 +00002732 SDNode *N = SuccSU->getNode();
Dan Gohman17059682008-07-17 19:10:17 +00002733 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
Craig Toppere5e035a32015-12-05 07:13:35 +00002734 const MCPhysReg *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
Dan Gohmanea045202008-06-21 22:05:24 +00002735 assert(ImpDefs && "Caller should check hasPhysRegDefs");
Dan Gohmana366da12009-03-23 16:23:01 +00002736 for (const SDNode *SUNode = SU->getNode(); SUNode;
Chris Lattner11a33812010-12-23 17:24:32 +00002737 SUNode = SUNode->getGluedNode()) {
Dan Gohmana366da12009-03-23 16:23:01 +00002738 if (!SUNode->isMachineOpcode())
Evan Chengf9891412007-12-20 09:25:31 +00002739 continue;
Craig Toppere5e035a32015-12-05 07:13:35 +00002740 const MCPhysReg *SUImpDefs =
Dan Gohmana366da12009-03-23 16:23:01 +00002741 TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002742 const uint32_t *SURegMask = getNodeRegMask(SUNode);
2743 if (!SUImpDefs && !SURegMask)
2744 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002745 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
Craig Topper7f416c82014-11-16 21:17:18 +00002746 MVT VT = N->getSimpleValueType(i);
Chris Lattner3e5fbd72010-12-21 02:38:05 +00002747 if (VT == MVT::Glue || VT == MVT::Other)
Dan Gohmana366da12009-03-23 16:23:01 +00002748 continue;
2749 if (!N->hasAnyUseOfValue(i))
2750 continue;
2751 unsigned Reg = ImpDefs[i - NumDefs];
Jakob Stoklund Olesen2ceea932012-02-13 23:25:24 +00002752 if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
2753 return true;
2754 if (!SUImpDefs)
2755 continue;
Dan Gohmana366da12009-03-23 16:23:01 +00002756 for (;*SUImpDefs; ++SUImpDefs) {
2757 unsigned SUReg = *SUImpDefs;
2758 if (TRI->regsOverlap(Reg, SUReg))
2759 return true;
2760 }
Evan Chengf9891412007-12-20 09:25:31 +00002761 }
2762 }
2763 return false;
2764}
2765
Dan Gohman9a658d72009-03-24 00:49:12 +00002766/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2767/// are not handled well by the general register pressure reduction
2768/// heuristics. When presented with code like this:
2769///
2770/// N
2771/// / |
2772/// / |
2773/// U store
2774/// |
2775/// ...
2776///
2777/// the heuristics tend to push the store up, but since the
2778/// operand of the store has another use (U), this would increase
2779/// the length of that other use (the U->N edge).
2780///
2781/// This function transforms code like the above to route U's
2782/// dependence through the store when possible, like this:
2783///
2784/// N
2785/// ||
2786/// ||
2787/// store
2788/// |
2789/// U
2790/// |
2791/// ...
2792///
2793/// This results in the store being scheduled immediately
2794/// after N, which shortens the U->N live range, reducing
2795/// register pressure.
2796///
Andrew Trick9ccce772011-01-14 21:11:41 +00002797void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
Dan Gohman9a658d72009-03-24 00:49:12 +00002798 // Visit all the nodes in topological order, working top-down.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002799 for (SUnit &SU : *SUnits) {
Dan Gohman9a658d72009-03-24 00:49:12 +00002800 // For now, only look at nodes with no data successors, such as stores.
2801 // These are especially important, due to the heuristics in
2802 // getNodePriority for nodes with no data successors.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002803 if (SU.NumSuccs != 0)
Dan Gohman9a658d72009-03-24 00:49:12 +00002804 continue;
2805 // For now, only look at nodes with exactly one data predecessor.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002806 if (SU.NumPreds != 1)
Dan Gohman9a658d72009-03-24 00:49:12 +00002807 continue;
2808 // Avoid prescheduling copies to virtual registers, which don't behave
2809 // like other nodes from the perspective of scheduling heuristics.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002810 if (SDNode *N = SU.getNode())
Dan Gohman9a658d72009-03-24 00:49:12 +00002811 if (N->getOpcode() == ISD::CopyToReg &&
2812 TargetRegisterInfo::isVirtualRegister
2813 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2814 continue;
2815
2816 // Locate the single data predecessor.
Craig Topperc0196b12014-04-14 00:51:57 +00002817 SUnit *PredSU = nullptr;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002818 for (const SDep &Pred : SU.Preds)
2819 if (!Pred.isCtrl()) {
2820 PredSU = Pred.getSUnit();
Dan Gohman9a658d72009-03-24 00:49:12 +00002821 break;
2822 }
2823 assert(PredSU);
2824
2825 // Don't rewrite edges that carry physregs, because that requires additional
2826 // support infrastructure.
2827 if (PredSU->hasPhysRegDefs)
2828 continue;
2829 // Short-circuit the case where SU is PredSU's only data successor.
2830 if (PredSU->NumSuccs == 1)
2831 continue;
2832 // Avoid prescheduling to copies from virtual registers, which don't behave
Andrew Trickd0548ae2011-02-04 03:18:17 +00002833 // like other nodes from the perspective of scheduling heuristics.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002834 if (SDNode *N = SU.getNode())
Dan Gohman9a658d72009-03-24 00:49:12 +00002835 if (N->getOpcode() == ISD::CopyFromReg &&
2836 TargetRegisterInfo::isVirtualRegister
2837 (cast<RegisterSDNode>(N->getOperand(1))->getReg()))
2838 continue;
2839
2840 // Perform checks on the successors of PredSU.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002841 for (const SDep &PredSucc : PredSU->Succs) {
2842 SUnit *PredSuccSU = PredSucc.getSUnit();
2843 if (PredSuccSU == &SU) continue;
Dan Gohman9a658d72009-03-24 00:49:12 +00002844 // If PredSU has another successor with no data successors, for
2845 // now don't attempt to choose either over the other.
2846 if (PredSuccSU->NumSuccs == 0)
2847 goto outer_loop_continue;
2848 // Don't break physical register dependencies.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002849 if (SU.hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
2850 if (canClobberPhysRegDefs(PredSuccSU, &SU, TII, TRI))
Dan Gohman9a658d72009-03-24 00:49:12 +00002851 goto outer_loop_continue;
2852 // Don't introduce graph cycles.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002853 if (scheduleDAG->IsReachable(&SU, PredSuccSU))
Dan Gohman9a658d72009-03-24 00:49:12 +00002854 goto outer_loop_continue;
2855 }
2856
2857 // Ok, the transformation is safe and the heuristics suggest it is
2858 // profitable. Update the graph.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002859 DEBUG(dbgs() << " Prescheduling SU #" << SU.NodeNum
Evan Chengbdd062d2010-05-20 06:13:19 +00002860 << " next to PredSU #" << PredSU->NodeNum
Chris Lattner4dc3edd2009-08-23 06:35:02 +00002861 << " to guide scheduling in the presence of multiple uses\n");
Dan Gohman9a658d72009-03-24 00:49:12 +00002862 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
2863 SDep Edge = PredSU->Succs[i];
2864 assert(!Edge.isAssignedRegDep());
2865 SUnit *SuccSU = Edge.getSUnit();
Sanjay Patele9fa3362016-02-03 22:44:14 +00002866 if (SuccSU != &SU) {
Dan Gohman9a658d72009-03-24 00:49:12 +00002867 Edge.setSUnit(PredSU);
2868 scheduleDAG->RemovePred(SuccSU, Edge);
Sanjay Patele9fa3362016-02-03 22:44:14 +00002869 scheduleDAG->AddPred(&SU, Edge);
2870 Edge.setSUnit(&SU);
Dan Gohman9a658d72009-03-24 00:49:12 +00002871 scheduleDAG->AddPred(SuccSU, Edge);
2872 --i;
2873 }
2874 }
2875 outer_loop_continue:;
2876 }
2877}
2878
Evan Chengd38c22b2006-05-11 23:55:42 +00002879/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
2880/// it as a def&use operand. Add a pseudo control edge from it to the other
2881/// node (if it won't create a cycle) so the two-address one will be scheduled
Evan Chenga5e595d2007-09-28 22:32:30 +00002882/// first (lower in the schedule). If both nodes are two-address, favor the
2883/// one that has a CopyToReg use (more likely to be a loop induction update).
2884/// If both are two-address, but one is commutable while the other is not
2885/// commutable, favor the one that's not commutable.
Duncan Sands635e4ef2011-11-09 14:20:48 +00002886void RegReductionPQBase::AddPseudoTwoAddrDeps() {
Sanjay Patele9fa3362016-02-03 22:44:14 +00002887 for (SUnit &SU : *SUnits) {
2888 if (!SU.isTwoAddress)
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002889 continue;
2890
Sanjay Patele9fa3362016-02-03 22:44:14 +00002891 SDNode *Node = SU.getNode();
2892 if (!Node || !Node->isMachineOpcode() || SU.getNode()->getGluedNode())
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002893 continue;
2894
Sanjay Patele9fa3362016-02-03 22:44:14 +00002895 bool isLiveOut = hasOnlyLiveOutUses(&SU);
Dan Gohman17059682008-07-17 19:10:17 +00002896 unsigned Opc = Node->getMachineOpcode();
Evan Cheng6cc775f2011-06-28 19:10:37 +00002897 const MCInstrDesc &MCID = TII->get(Opc);
2898 unsigned NumRes = MCID.getNumDefs();
2899 unsigned NumOps = MCID.getNumOperands() - NumRes;
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002900 for (unsigned j = 0; j != NumOps; ++j) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00002901 if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
Dan Gohman82016c22008-11-19 02:00:32 +00002902 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002903 SDNode *DU = SU.getNode()->getOperand(j).getNode();
Dan Gohman82016c22008-11-19 02:00:32 +00002904 if (DU->getNodeId() == -1)
2905 continue;
2906 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
Sanjay Patele9fa3362016-02-03 22:44:14 +00002907 if (!DUSU)
2908 continue;
2909 for (const SDep &Succ : DUSU->Succs) {
2910 if (Succ.isCtrl())
2911 continue;
2912 SUnit *SuccSU = Succ.getSUnit();
2913 if (SuccSU == &SU)
Evan Cheng1bf166312007-11-09 01:27:11 +00002914 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002915 // Be conservative. Ignore if nodes aren't at roughly the same
2916 // depth and height.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002917 if (SuccSU->getHeight() < SU.getHeight() &&
2918 (SU.getHeight() - SuccSU->getHeight()) > 1)
Dan Gohman82016c22008-11-19 02:00:32 +00002919 continue;
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002920 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
2921 // constrains whatever is using the copy, instead of the copy
2922 // itself. In the case that the copy is coalesced, this
2923 // preserves the intent of the pseudo two-address heurietics.
2924 while (SuccSU->Succs.size() == 1 &&
2925 SuccSU->getNode()->isMachineOpcode() &&
2926 SuccSU->getNode()->getMachineOpcode() ==
Chris Lattnerb06015a2010-02-09 19:54:29 +00002927 TargetOpcode::COPY_TO_REGCLASS)
Dan Gohmaneefba6b2009-04-16 20:59:02 +00002928 SuccSU = SuccSU->Succs.front().getSUnit();
2929 // Don't constrain non-instruction nodes.
Dan Gohman82016c22008-11-19 02:00:32 +00002930 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
2931 continue;
2932 // Don't constrain nodes with physical register defs if the
2933 // predecessor can clobber them.
Sanjay Patele9fa3362016-02-03 22:44:14 +00002934 if (SuccSU->hasPhysRegDefs && SU.hasPhysRegClobbers) {
2935 if (canClobberPhysRegDefs(SuccSU, &SU, TII, TRI))
Evan Cheng5924bf72007-09-25 01:54:36 +00002936 continue;
Dan Gohman82016c22008-11-19 02:00:32 +00002937 }
Dan Gohman3027bb62009-04-16 20:57:10 +00002938 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
2939 // these may be coalesced away. We want them close to their uses.
Dan Gohman82016c22008-11-19 02:00:32 +00002940 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
Chris Lattnerb06015a2010-02-09 19:54:29 +00002941 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
2942 SuccOpc == TargetOpcode::INSERT_SUBREG ||
2943 SuccOpc == TargetOpcode::SUBREG_TO_REG)
Dan Gohman82016c22008-11-19 02:00:32 +00002944 continue;
Sanjay Patele9fa3362016-02-03 22:44:14 +00002945 if (!canClobberReachingPhysRegUse(SuccSU, &SU, scheduleDAG, TII, TRI) &&
Andrew Trick832a6a192011-09-01 00:54:31 +00002946 (!canClobber(SuccSU, DUSU) ||
Evan Cheng6c1414f2010-10-29 18:09:28 +00002947 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
Sanjay Patele9fa3362016-02-03 22:44:14 +00002948 (!SU.isCommutable && SuccSU->isCommutable)) &&
2949 !scheduleDAG->IsReachable(SuccSU, &SU)) {
Evan Chengbdd062d2010-05-20 06:13:19 +00002950 DEBUG(dbgs() << " Adding a pseudo-two-addr edge from SU #"
Sanjay Patele9fa3362016-02-03 22:44:14 +00002951 << SU.NodeNum << " to SU #" << SuccSU->NodeNum << "\n");
2952 scheduleDAG->AddPred(&SU, SDep(SuccSU, SDep::Artificial));
Evan Chengfd2c5dd2006-11-04 09:44:31 +00002953 }
2954 }
2955 }
2956 }
Evan Chengd38c22b2006-05-11 23:55:42 +00002957}
2958
Evan Chengd38c22b2006-05-11 23:55:42 +00002959//===----------------------------------------------------------------------===//
2960// Public Constructor Functions
2961//===----------------------------------------------------------------------===//
2962
Dan Gohmandfaf6462009-02-11 04:27:20 +00002963llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002964llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
2965 CodeGenOpt::Level OptLevel) {
Eric Christopheredba30c2014-10-09 06:28:06 +00002966 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
2967 const TargetInstrInfo *TII = STI.getInstrInfo();
2968 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002969
Evan Chenga77f3d32010-07-21 06:09:07 +00002970 BURegReductionPriorityQueue *PQ =
Craig Topperc0196b12014-04-14 00:51:57 +00002971 new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, nullptr);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002972 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Cheng7e4abde2008-07-02 09:23:51 +00002973 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002974 return SD;
Evan Chengd38c22b2006-05-11 23:55:42 +00002975}
2976
Dan Gohmandfaf6462009-02-11 04:27:20 +00002977llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002978llvm::createSourceListDAGScheduler(SelectionDAGISel *IS,
2979 CodeGenOpt::Level OptLevel) {
Eric Christopheredba30c2014-10-09 06:28:06 +00002980 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
2981 const TargetInstrInfo *TII = STI.getInstrInfo();
2982 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
Andrew Trick2085a962010-12-21 22:25:04 +00002983
Evan Chenga77f3d32010-07-21 06:09:07 +00002984 SrcRegReductionPriorityQueue *PQ =
Craig Topperc0196b12014-04-14 00:51:57 +00002985 new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, nullptr);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002986 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
Evan Chengbdd062d2010-05-20 06:13:19 +00002987 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00002988 return SD;
Evan Chengbdd062d2010-05-20 06:13:19 +00002989}
2990
2991llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00002992llvm::createHybridListDAGScheduler(SelectionDAGISel *IS,
2993 CodeGenOpt::Level OptLevel) {
Eric Christopheredba30c2014-10-09 06:28:06 +00002994 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
2995 const TargetInstrInfo *TII = STI.getInstrInfo();
2996 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
Eric Christopherb17140d2014-10-08 07:32:17 +00002997 const TargetLowering *TLI = IS->TLI;
Andrew Trick2085a962010-12-21 22:25:04 +00002998
Evan Chenga77f3d32010-07-21 06:09:07 +00002999 HybridBURRPriorityQueue *PQ =
Evan Cheng8ab58a22012-03-22 19:31:17 +00003000 new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00003001
3002 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Bill Wendling8cbc25d2010-01-23 10:26:57 +00003003 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00003004 return SD;
Bill Wendling8cbc25d2010-01-23 10:26:57 +00003005}
Evan Cheng37b740c2010-07-24 00:39:05 +00003006
3007llvm::ScheduleDAGSDNodes *
Andrew Trick10ffc2b2010-12-24 05:03:26 +00003008llvm::createILPListDAGScheduler(SelectionDAGISel *IS,
3009 CodeGenOpt::Level OptLevel) {
Eric Christopheredba30c2014-10-09 06:28:06 +00003010 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
3011 const TargetInstrInfo *TII = STI.getInstrInfo();
3012 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
Eric Christopherb17140d2014-10-08 07:32:17 +00003013 const TargetLowering *TLI = IS->TLI;
Andrew Trick2085a962010-12-21 22:25:04 +00003014
Evan Cheng37b740c2010-07-24 00:39:05 +00003015 ILPBURRPriorityQueue *PQ =
Evan Cheng8ab58a22012-03-22 19:31:17 +00003016 new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
Andrew Trick10ffc2b2010-12-24 05:03:26 +00003017 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
Evan Cheng37b740c2010-07-24 00:39:05 +00003018 PQ->setScheduleDAG(SD);
Andrew Trick2085a962010-12-21 22:25:04 +00003019 return SD;
Evan Cheng37b740c2010-07-24 00:39:05 +00003020}