blob: ea66f02a4b458f97cb3a1f74451f36c1e72ed1c4 [file] [log] [blame]
Dale Johannesen72f15962007-07-13 17:31:29 +00001//===----- SchedulePostRAList.cpp - list scheduler ------------------------===//
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This implements a top-down list scheduler, using standard algorithms.
11// The basic approach uses a priority queue of available nodes to schedule.
12// One at a time, nodes are taken from the priority queue (thus in priority
13// order), checked for legality to schedule, and emitted if legal.
14//
15// Nodes may not be legal to schedule either due to structural hazards (e.g.
16// pipeline or resource constraints) or because an input to the instruction has
17// not completed execution.
18//
19//===----------------------------------------------------------------------===//
20
21#define DEBUG_TYPE "post-RA-sched"
David Goodwin2e7be612009-10-26 16:59:04 +000022#include "CriticalAntiDepBreaker.h"
David Goodwind94a4e52009-08-10 15:55:25 +000023#include "ExactHazardRecognizer.h"
24#include "SimpleHazardRecognizer.h"
Dan Gohman6dc75fe2009-02-06 17:12:10 +000025#include "ScheduleDAGInstrs.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000026#include "llvm/CodeGen/Passes.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000027#include "llvm/CodeGen/LatencyPriorityQueue.h"
28#include "llvm/CodeGen/SchedulerRegistry.h"
Dan Gohman3f237442008-12-16 03:25:46 +000029#include "llvm/CodeGen/MachineDominators.h"
David Goodwinc7951f82009-10-01 19:45:32 +000030#include "llvm/CodeGen/MachineFrameInfo.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000031#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohman3f237442008-12-16 03:25:46 +000032#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman21d90032008-11-25 00:52:40 +000033#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman2836c282009-01-16 01:33:36 +000034#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Dan Gohmana70dca12009-10-09 23:27:56 +000035#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohmanbed353d2009-02-10 23:29:38 +000036#include "llvm/Target/TargetLowering.h"
Dan Gohman79ce2762009-01-15 19:20:50 +000037#include "llvm/Target/TargetMachine.h"
Dan Gohman21d90032008-11-25 00:52:40 +000038#include "llvm/Target/TargetInstrInfo.h"
39#include "llvm/Target/TargetRegisterInfo.h"
David Goodwin0dad89f2009-09-30 00:10:16 +000040#include "llvm/Target/TargetSubtarget.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000041#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000042#include "llvm/Support/ErrorHandling.h"
David Goodwin3a5f0d42009-08-11 01:44:26 +000043#include "llvm/Support/raw_ostream.h"
David Goodwin2e7be612009-10-26 16:59:04 +000044#include "llvm/ADT/BitVector.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000045#include "llvm/ADT/Statistic.h"
Dan Gohman21d90032008-11-25 00:52:40 +000046#include <map>
David Goodwin88a589c2009-08-25 17:03:05 +000047#include <set>
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000048using namespace llvm;
49
Dan Gohman2836c282009-01-16 01:33:36 +000050STATISTIC(NumNoops, "Number of noops inserted");
Dan Gohman343f0c02008-11-19 23:18:57 +000051STATISTIC(NumStalls, "Number of pipeline stalls");
David Goodwin2e7be612009-10-26 16:59:04 +000052STATISTIC(NumFixedAnti, "Number of fixed anti-dependencies");
Dan Gohman343f0c02008-11-19 23:18:57 +000053
David Goodwin471850a2009-10-01 21:46:35 +000054// Post-RA scheduling is enabled with
55// TargetSubtarget.enablePostRAScheduler(). This flag can be used to
56// override the target.
57static cl::opt<bool>
58EnablePostRAScheduler("post-RA-scheduler",
59 cl::desc("Enable scheduling after register allocation"),
David Goodwin9843a932009-10-01 22:19:57 +000060 cl::init(false), cl::Hidden);
David Goodwin2e7be612009-10-26 16:59:04 +000061static cl::opt<std::string>
Dan Gohman21d90032008-11-25 00:52:40 +000062EnableAntiDepBreaking("break-anti-dependencies",
David Goodwin2e7be612009-10-26 16:59:04 +000063 cl::desc("Break post-RA scheduling anti-dependencies: "
64 "\"critical\", \"all\", or \"none\""),
65 cl::init("none"), cl::Hidden);
Dan Gohman2836c282009-01-16 01:33:36 +000066static cl::opt<bool>
67EnablePostRAHazardAvoidance("avoid-hazards",
David Goodwind94a4e52009-08-10 15:55:25 +000068 cl::desc("Enable exact hazard avoidance"),
David Goodwin5e411782009-09-03 22:15:25 +000069 cl::init(true), cl::Hidden);
Dan Gohman2836c282009-01-16 01:33:36 +000070
David Goodwin1f152282009-09-01 18:34:03 +000071// If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
72static cl::opt<int>
73DebugDiv("postra-sched-debugdiv",
74 cl::desc("Debug control MBBs that are scheduled"),
75 cl::init(0), cl::Hidden);
76static cl::opt<int>
77DebugMod("postra-sched-debugmod",
78 cl::desc("Debug control MBBs that are scheduled"),
79 cl::init(0), cl::Hidden);
80
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000081namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000082 class PostRAScheduler : public MachineFunctionPass {
Dan Gohmana70dca12009-10-09 23:27:56 +000083 AliasAnalysis *AA;
Evan Chengfa163542009-10-16 21:06:15 +000084 CodeGenOpt::Level OptLevel;
Dan Gohmana70dca12009-10-09 23:27:56 +000085
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000086 public:
87 static char ID;
Evan Chengfa163542009-10-16 21:06:15 +000088 PostRAScheduler(CodeGenOpt::Level ol) :
89 MachineFunctionPass(&ID), OptLevel(ol) {}
Dan Gohman21d90032008-11-25 00:52:40 +000090
Dan Gohman3f237442008-12-16 03:25:46 +000091 void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000092 AU.setPreservesCFG();
Dan Gohmana70dca12009-10-09 23:27:56 +000093 AU.addRequired<AliasAnalysis>();
Dan Gohman3f237442008-12-16 03:25:46 +000094 AU.addRequired<MachineDominatorTree>();
95 AU.addPreserved<MachineDominatorTree>();
96 AU.addRequired<MachineLoopInfo>();
97 AU.addPreserved<MachineLoopInfo>();
98 MachineFunctionPass::getAnalysisUsage(AU);
99 }
100
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000101 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +0000102 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000103 }
104
105 bool runOnMachineFunction(MachineFunction &Fn);
106 };
Dan Gohman343f0c02008-11-19 23:18:57 +0000107 char PostRAScheduler::ID = 0;
108
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000109 class SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +0000110 /// AvailableQueue - The priority queue to use for the available SUnits.
Dan Gohmanc1ae8c92009-10-21 01:44:44 +0000111 ///
Dan Gohman343f0c02008-11-19 23:18:57 +0000112 LatencyPriorityQueue AvailableQueue;
113
114 /// PendingQueue - This contains all of the instructions whose operands have
115 /// been issued, but their results are not ready yet (due to the latency of
116 /// the operation). Once the operands becomes available, the instruction is
117 /// added to the AvailableQueue.
118 std::vector<SUnit*> PendingQueue;
119
Dan Gohman21d90032008-11-25 00:52:40 +0000120 /// Topo - A topological ordering for SUnits.
121 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +0000122
Dan Gohman2836c282009-01-16 01:33:36 +0000123 /// HazardRec - The hazard recognizer to use.
124 ScheduleHazardRecognizer *HazardRec;
125
David Goodwin2e7be612009-10-26 16:59:04 +0000126 /// AntiDepBreak - Anti-dependence breaking object, or NULL if none
127 AntiDepBreaker *AntiDepBreak;
128
Dan Gohmana70dca12009-10-09 23:27:56 +0000129 /// AA - AliasAnalysis for making memory reference queries.
130 AliasAnalysis *AA;
131
Dan Gohmanc1ae8c92009-10-21 01:44:44 +0000132 /// KillIndices - The index of the most recent kill (proceding bottom-up),
133 /// or ~0u if the register is not live.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000134 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
135
Dan Gohman21d90032008-11-25 00:52:40 +0000136 public:
Dan Gohman79ce2762009-01-15 19:20:50 +0000137 SchedulePostRATDList(MachineFunction &MF,
Dan Gohman3f237442008-12-16 03:25:46 +0000138 const MachineLoopInfo &MLI,
Dan Gohman2836c282009-01-16 01:33:36 +0000139 const MachineDominatorTree &MDT,
Dan Gohmana70dca12009-10-09 23:27:56 +0000140 ScheduleHazardRecognizer *HR,
David Goodwin2e7be612009-10-26 16:59:04 +0000141 AntiDepBreaker *ADB,
142 AliasAnalysis *aa)
Dan Gohman79ce2762009-01-15 19:20:50 +0000143 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
David Goodwin2e7be612009-10-26 16:59:04 +0000144 HazardRec(HR), AntiDepBreak(ADB), AA(aa) {}
Dan Gohman2836c282009-01-16 01:33:36 +0000145
146 ~SchedulePostRATDList() {
Dan Gohman2836c282009-01-16 01:33:36 +0000147 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000148
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000149 /// StartBlock - Initialize register live-range state for scheduling in
150 /// this block.
151 ///
152 void StartBlock(MachineBasicBlock *BB);
153
154 /// Schedule - Schedule the instruction range using list scheduling.
155 ///
Dan Gohman343f0c02008-11-19 23:18:57 +0000156 void Schedule();
David Goodwin88a589c2009-08-25 17:03:05 +0000157
Dan Gohmanc1ae8c92009-10-21 01:44:44 +0000158 /// Observe - Update liveness information to account for the current
159 /// instruction, which will not be scheduled.
160 ///
161 void Observe(MachineInstr *MI, unsigned Count);
162
163 /// FinishBlock - Clean up register live-range state.
164 ///
165 void FinishBlock();
166
David Goodwin2e7be612009-10-26 16:59:04 +0000167 /// FixupKills - Fix register kill flags that have been made
168 /// invalid due to scheduling
169 ///
170 void FixupKills(MachineBasicBlock *MBB);
171
Dan Gohman343f0c02008-11-19 23:18:57 +0000172 private:
Dan Gohman54e4c362008-12-09 22:54:47 +0000173 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000174 void ReleaseSuccessors(SUnit *SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000175 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
176 void ListScheduleTopDown();
David Goodwin5e411782009-09-03 22:15:25 +0000177 void StartBlockForKills(MachineBasicBlock *BB);
David Goodwin8f909342009-09-23 16:35:25 +0000178
179 // ToggleKillFlag - Toggle a register operand kill flag. Other
180 // adjustments may be made to the instruction if necessary. Return
181 // true if the operand has been deleted, false if not.
182 bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
Dan Gohman343f0c02008-11-19 23:18:57 +0000183 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000184}
185
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000186/// isSchedulingBoundary - Test if the given instruction should be
187/// considered a scheduling boundary. This primarily includes labels
188/// and terminators.
189///
190static bool isSchedulingBoundary(const MachineInstr *MI,
191 const MachineFunction &MF) {
192 // Terminators and labels can't be scheduled around.
193 if (MI->getDesc().isTerminator() || MI->isLabel())
194 return true;
195
Dan Gohmanbed353d2009-02-10 23:29:38 +0000196 // Don't attempt to schedule around any instruction that modifies
197 // a stack-oriented pointer, as it's unlikely to be profitable. This
198 // saves compile time, because it doesn't require every single
199 // stack slot reference to depend on the instruction that does the
200 // modification.
201 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
202 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
203 return true;
204
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000205 return false;
206}
207
Dan Gohman343f0c02008-11-19 23:18:57 +0000208bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
Dan Gohman5bf7c2a2009-10-10 00:15:38 +0000209 AA = &getAnalysis<AliasAnalysis>();
210
David Goodwin471850a2009-10-01 21:46:35 +0000211 // Check for explicit enable/disable of post-ra scheduling.
David Goodwin4c3715c2009-10-22 23:19:17 +0000212 TargetSubtarget::AntiDepBreakMode AntiDepMode = TargetSubtarget::ANTIDEP_NONE;
David Goodwin471850a2009-10-01 21:46:35 +0000213 if (EnablePostRAScheduler.getPosition() > 0) {
214 if (!EnablePostRAScheduler)
Evan Chengc83da2f92009-10-16 06:10:34 +0000215 return false;
David Goodwin471850a2009-10-01 21:46:35 +0000216 } else {
Evan Chengc83da2f92009-10-16 06:10:34 +0000217 // Check that post-RA scheduling is enabled for this target.
David Goodwin471850a2009-10-01 21:46:35 +0000218 const TargetSubtarget &ST = Fn.getTarget().getSubtarget<TargetSubtarget>();
David Goodwin4c3715c2009-10-22 23:19:17 +0000219 if (!ST.enablePostRAScheduler(OptLevel, AntiDepMode))
Evan Chengc83da2f92009-10-16 06:10:34 +0000220 return false;
David Goodwin471850a2009-10-01 21:46:35 +0000221 }
David Goodwin0dad89f2009-09-30 00:10:16 +0000222
David Goodwin4c3715c2009-10-22 23:19:17 +0000223 // Check for antidep breaking override...
224 if (EnableAntiDepBreaking.getPosition() > 0) {
David Goodwin2e7be612009-10-26 16:59:04 +0000225 AntiDepMode = (EnableAntiDepBreaking == "all") ? TargetSubtarget::ANTIDEP_ALL :
226 (EnableAntiDepBreaking == "critical") ? TargetSubtarget::ANTIDEP_CRITICAL :
227 TargetSubtarget::ANTIDEP_NONE;
David Goodwin4c3715c2009-10-22 23:19:17 +0000228 }
229
David Goodwin3a5f0d42009-08-11 01:44:26 +0000230 DEBUG(errs() << "PostRAScheduler\n");
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000231
Dan Gohman3f237442008-12-16 03:25:46 +0000232 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
233 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
David Goodwind94a4e52009-08-10 15:55:25 +0000234 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
Dan Gohman2836c282009-01-16 01:33:36 +0000235 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
David Goodwind94a4e52009-08-10 15:55:25 +0000236 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
237 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
David Goodwin2e7be612009-10-26 16:59:04 +0000238 AntiDepBreaker *ADB =
239 (AntiDepMode == TargetSubtarget::ANTIDEP_ALL) ? NULL /* FIXME */ :
240 (AntiDepMode == TargetSubtarget::ANTIDEP_CRITICAL) ?
241 new CriticalAntiDepBreaker(Fn) : NULL;
Dan Gohman3f237442008-12-16 03:25:46 +0000242
David Goodwin2e7be612009-10-26 16:59:04 +0000243 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR, ADB, AA);
Dan Gohman79ce2762009-01-15 19:20:50 +0000244
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000245 // Loop over all of the basic blocks
246 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000247 MBB != MBBe; ++MBB) {
David Goodwin1f152282009-09-01 18:34:03 +0000248#ifndef NDEBUG
249 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
250 if (DebugDiv > 0) {
251 static int bbcnt = 0;
252 if (bbcnt++ % DebugDiv != DebugMod)
253 continue;
254 errs() << "*** DEBUG scheduling " << Fn.getFunction()->getNameStr() <<
255 ":MBB ID#" << MBB->getNumber() << " ***\n";
256 }
257#endif
258
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000259 // Initialize register live-range state for scheduling in this block.
260 Scheduler.StartBlock(MBB);
261
Dan Gohmanf7119392009-01-16 22:10:20 +0000262 // Schedule each sequence of instructions not interrupted by a label
263 // or anything else that effectively needs to shut down scheduling.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000264 MachineBasicBlock::iterator Current = MBB->end();
Dan Gohman47ac0f02009-02-11 04:27:20 +0000265 unsigned Count = MBB->size(), CurrentCount = Count;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000266 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
267 MachineInstr *MI = prior(I);
268 if (isSchedulingBoundary(MI, Fn)) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000269 Scheduler.Run(MBB, I, Current, CurrentCount);
Evan Chengfb2e7522009-09-18 21:02:19 +0000270 Scheduler.EmitSchedule(0);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000271 Current = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000272 CurrentCount = Count - 1;
Dan Gohman1274ced2009-03-10 18:10:43 +0000273 Scheduler.Observe(MI, CurrentCount);
Dan Gohmanf7119392009-01-16 22:10:20 +0000274 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000275 I = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000276 --Count;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000277 }
Dan Gohman47ac0f02009-02-11 04:27:20 +0000278 assert(Count == 0 && "Instruction count mismatch!");
Duncan Sands9e8bd0b2009-03-11 09:04:34 +0000279 assert((MBB->begin() == Current || CurrentCount != 0) &&
Dan Gohman1274ced2009-03-10 18:10:43 +0000280 "Instruction count mismatch!");
281 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
Evan Chengfb2e7522009-09-18 21:02:19 +0000282 Scheduler.EmitSchedule(0);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000283
284 // Clean up register live-range state.
285 Scheduler.FinishBlock();
David Goodwin88a589c2009-08-25 17:03:05 +0000286
David Goodwin5e411782009-09-03 22:15:25 +0000287 // Update register kills
David Goodwin88a589c2009-08-25 17:03:05 +0000288 Scheduler.FixupKills(MBB);
Dan Gohman343f0c02008-11-19 23:18:57 +0000289 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000290
David Goodwin2e7be612009-10-26 16:59:04 +0000291 delete HR;
292 delete ADB;
293
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000294 return true;
295}
296
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000297/// StartBlock - Initialize register live-range state for scheduling in
298/// this block.
Dan Gohman21d90032008-11-25 00:52:40 +0000299///
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000300void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
301 // Call the superclass.
302 ScheduleDAGInstrs::StartBlock(BB);
Dan Gohman21d90032008-11-25 00:52:40 +0000303
David Goodwin2e7be612009-10-26 16:59:04 +0000304 // Reset the hazard recognizer and anti-dep breaker.
David Goodwind94a4e52009-08-10 15:55:25 +0000305 HazardRec->Reset();
David Goodwin2e7be612009-10-26 16:59:04 +0000306 if (AntiDepBreak != NULL)
307 AntiDepBreak->StartBlock(BB);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000308}
309
310/// Schedule - Schedule the instruction range using list scheduling.
311///
312void SchedulePostRATDList::Schedule() {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000313 DEBUG(errs() << "********** List Scheduling **********\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000314
315 // Build the scheduling graph.
Dan Gohmana70dca12009-10-09 23:27:56 +0000316 BuildSchedGraph(AA);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000317
David Goodwin2e7be612009-10-26 16:59:04 +0000318 if (AntiDepBreak != NULL) {
319 unsigned Broken =
320 AntiDepBreak->BreakAntiDependencies(SUnits, Begin, InsertPos,
321 InsertPosIndex);
322 if (Broken > 0) {
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000323 // We made changes. Update the dependency graph.
324 // Theoretically we could update the graph in place:
325 // When a live range is changed to use a different register, remove
326 // the def's anti-dependence *and* output-dependence edges due to
327 // that register, and add new anti-dependence and output-dependence
328 // edges based on the next live range of the register.
329 SUnits.clear();
330 EntrySU = SUnit();
331 ExitSU = SUnit();
Dan Gohmana70dca12009-10-09 23:27:56 +0000332 BuildSchedGraph(AA);
David Goodwin2e7be612009-10-26 16:59:04 +0000333
334 NumFixedAnti += Broken;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000335 }
336 }
337
David Goodwind94a4e52009-08-10 15:55:25 +0000338 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
339 SUnits[su].dumpAll(this));
340
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000341 AvailableQueue.initNodes(SUnits);
342
343 ListScheduleTopDown();
344
345 AvailableQueue.releaseState();
346}
347
348/// Observe - Update liveness information to account for the current
349/// instruction, which will not be scheduled.
350///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000351void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
David Goodwin2e7be612009-10-26 16:59:04 +0000352 if (AntiDepBreak != NULL)
353 AntiDepBreak->Observe(MI, Count, InsertPosIndex);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000354}
355
356/// FinishBlock - Clean up register live-range state.
357///
358void SchedulePostRATDList::FinishBlock() {
David Goodwin2e7be612009-10-26 16:59:04 +0000359 if (AntiDepBreak != NULL)
360 AntiDepBreak->FinishBlock();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000361
362 // Call the superclass.
363 ScheduleDAGInstrs::FinishBlock();
364}
365
David Goodwin5e411782009-09-03 22:15:25 +0000366/// StartBlockForKills - Initialize register live-range state for updating kills
367///
368void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
369 // Initialize the indices to indicate that no registers are live.
370 std::fill(KillIndices, array_endof(KillIndices), ~0u);
371
372 // Determine the live-out physregs for this block.
373 if (!BB->empty() && BB->back().getDesc().isReturn()) {
374 // In a return block, examine the function live-out regs.
375 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
376 E = MRI.liveout_end(); I != E; ++I) {
377 unsigned Reg = *I;
378 KillIndices[Reg] = BB->size();
379 // Repeat, for all subregs.
380 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
381 *Subreg; ++Subreg) {
382 KillIndices[*Subreg] = BB->size();
383 }
384 }
385 }
386 else {
387 // In a non-return block, examine the live-in regs of all successors.
388 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
389 SE = BB->succ_end(); SI != SE; ++SI) {
390 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
391 E = (*SI)->livein_end(); I != E; ++I) {
392 unsigned Reg = *I;
393 KillIndices[Reg] = BB->size();
394 // Repeat, for all subregs.
395 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
396 *Subreg; ++Subreg) {
397 KillIndices[*Subreg] = BB->size();
398 }
399 }
400 }
401 }
402}
403
David Goodwin8f909342009-09-23 16:35:25 +0000404bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
405 MachineOperand &MO) {
406 // Setting kill flag...
407 if (!MO.isKill()) {
408 MO.setIsKill(true);
409 return false;
410 }
411
412 // If MO itself is live, clear the kill flag...
413 if (KillIndices[MO.getReg()] != ~0u) {
414 MO.setIsKill(false);
415 return false;
416 }
417
418 // If any subreg of MO is live, then create an imp-def for that
419 // subreg and keep MO marked as killed.
Benjamin Kramer8bff4af2009-10-02 15:59:52 +0000420 MO.setIsKill(false);
David Goodwin8f909342009-09-23 16:35:25 +0000421 bool AllDead = true;
422 const unsigned SuperReg = MO.getReg();
423 for (const unsigned *Subreg = TRI->getSubRegisters(SuperReg);
424 *Subreg; ++Subreg) {
425 if (KillIndices[*Subreg] != ~0u) {
426 MI->addOperand(MachineOperand::CreateReg(*Subreg,
427 true /*IsDef*/,
428 true /*IsImp*/,
429 false /*IsKill*/,
430 false /*IsDead*/));
431 AllDead = false;
432 }
433 }
434
Dan Gohmanc1ae8c92009-10-21 01:44:44 +0000435 if(AllDead)
Benjamin Kramer8bff4af2009-10-02 15:59:52 +0000436 MO.setIsKill(true);
David Goodwin8f909342009-09-23 16:35:25 +0000437 return false;
438}
439
David Goodwin88a589c2009-08-25 17:03:05 +0000440/// FixupKills - Fix the register kill flags, they may have been made
441/// incorrect by instruction reordering.
442///
443void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
444 DEBUG(errs() << "Fixup kills for BB ID#" << MBB->getNumber() << '\n');
445
446 std::set<unsigned> killedRegs;
447 BitVector ReservedRegs = TRI->getReservedRegs(MF);
David Goodwin5e411782009-09-03 22:15:25 +0000448
449 StartBlockForKills(MBB);
David Goodwin7886cd82009-08-29 00:11:13 +0000450
451 // Examine block from end to start...
David Goodwin88a589c2009-08-25 17:03:05 +0000452 unsigned Count = MBB->size();
453 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
454 I != E; --Count) {
455 MachineInstr *MI = --I;
456
David Goodwin7886cd82009-08-29 00:11:13 +0000457 // Update liveness. Registers that are defed but not used in this
458 // instruction are now dead. Mark register and all subregs as they
459 // are completely defined.
460 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
461 MachineOperand &MO = MI->getOperand(i);
462 if (!MO.isReg()) continue;
463 unsigned Reg = MO.getReg();
464 if (Reg == 0) continue;
465 if (!MO.isDef()) continue;
466 // Ignore two-addr defs.
467 if (MI->isRegTiedToUseOperand(i)) continue;
468
David Goodwin7886cd82009-08-29 00:11:13 +0000469 KillIndices[Reg] = ~0u;
470
471 // Repeat for all subregs.
472 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
473 *Subreg; ++Subreg) {
474 KillIndices[*Subreg] = ~0u;
475 }
476 }
David Goodwin88a589c2009-08-25 17:03:05 +0000477
David Goodwin8f909342009-09-23 16:35:25 +0000478 // Examine all used registers and set/clear kill flag. When a
479 // register is used multiple times we only set the kill flag on
480 // the first use.
David Goodwin88a589c2009-08-25 17:03:05 +0000481 killedRegs.clear();
482 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
483 MachineOperand &MO = MI->getOperand(i);
484 if (!MO.isReg() || !MO.isUse()) continue;
485 unsigned Reg = MO.getReg();
486 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
487
David Goodwin7886cd82009-08-29 00:11:13 +0000488 bool kill = false;
489 if (killedRegs.find(Reg) == killedRegs.end()) {
490 kill = true;
491 // A register is not killed if any subregs are live...
492 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
493 *Subreg; ++Subreg) {
494 if (KillIndices[*Subreg] != ~0u) {
495 kill = false;
496 break;
497 }
498 }
499
500 // If subreg is not live, then register is killed if it became
501 // live in this instruction
502 if (kill)
503 kill = (KillIndices[Reg] == ~0u);
504 }
505
David Goodwin88a589c2009-08-25 17:03:05 +0000506 if (MO.isKill() != kill) {
David Goodwin8f909342009-09-23 16:35:25 +0000507 bool removed = ToggleKillFlag(MI, MO);
508 if (removed) {
509 DEBUG(errs() << "Fixed <removed> in ");
510 } else {
511 DEBUG(errs() << "Fixed " << MO << " in ");
512 }
David Goodwin88a589c2009-08-25 17:03:05 +0000513 DEBUG(MI->dump());
514 }
David Goodwin7886cd82009-08-29 00:11:13 +0000515
David Goodwin88a589c2009-08-25 17:03:05 +0000516 killedRegs.insert(Reg);
517 }
David Goodwin7886cd82009-08-29 00:11:13 +0000518
David Goodwina3251db2009-08-31 20:47:02 +0000519 // Mark any used register (that is not using undef) and subregs as
520 // now live...
David Goodwin7886cd82009-08-29 00:11:13 +0000521 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
522 MachineOperand &MO = MI->getOperand(i);
David Goodwina3251db2009-08-31 20:47:02 +0000523 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
David Goodwin7886cd82009-08-29 00:11:13 +0000524 unsigned Reg = MO.getReg();
525 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
526
David Goodwin7886cd82009-08-29 00:11:13 +0000527 KillIndices[Reg] = Count;
528
529 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
530 *Subreg; ++Subreg) {
531 KillIndices[*Subreg] = Count;
532 }
533 }
David Goodwin88a589c2009-08-25 17:03:05 +0000534 }
535}
536
Dan Gohman343f0c02008-11-19 23:18:57 +0000537//===----------------------------------------------------------------------===//
538// Top-Down Scheduling
539//===----------------------------------------------------------------------===//
540
541/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
542/// the PendingQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman54e4c362008-12-09 22:54:47 +0000543void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
544 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Klecknerc277ab02009-09-30 20:15:38 +0000545
Dan Gohman343f0c02008-11-19 23:18:57 +0000546#ifndef NDEBUG
Reid Klecknerc277ab02009-09-30 20:15:38 +0000547 if (SuccSU->NumPredsLeft == 0) {
Chris Lattner103289e2009-08-23 07:19:13 +0000548 errs() << "*** Scheduling failed! ***\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000549 SuccSU->dump(this);
Chris Lattner103289e2009-08-23 07:19:13 +0000550 errs() << " has been released too many times!\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000551 llvm_unreachable(0);
Dan Gohman343f0c02008-11-19 23:18:57 +0000552 }
553#endif
Reid Klecknerc277ab02009-09-30 20:15:38 +0000554 --SuccSU->NumPredsLeft;
555
Dan Gohman343f0c02008-11-19 23:18:57 +0000556 // Compute how many cycles it will be before this actually becomes
557 // available. This is the max of the start time of all predecessors plus
558 // their latencies.
Dan Gohman3f237442008-12-16 03:25:46 +0000559 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
Dan Gohman343f0c02008-11-19 23:18:57 +0000560
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000561 // If all the node's predecessors are scheduled, this node is ready
562 // to be scheduled. Ignore the special ExitSU node.
563 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Dan Gohman343f0c02008-11-19 23:18:57 +0000564 PendingQueue.push_back(SuccSU);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000565}
566
567/// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
568void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
569 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
570 I != E; ++I)
571 ReleaseSucc(SU, &*I);
Dan Gohman343f0c02008-11-19 23:18:57 +0000572}
573
574/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
575/// count of its successors. If a successor pending count is zero, add it to
576/// the Available queue.
577void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000578 DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman343f0c02008-11-19 23:18:57 +0000579 DEBUG(SU->dump(this));
580
581 Sequence.push_back(SU);
Dan Gohman3f237442008-12-16 03:25:46 +0000582 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
583 SU->setDepthToAtLeast(CurCycle);
Dan Gohman343f0c02008-11-19 23:18:57 +0000584
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000585 ReleaseSuccessors(SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000586 SU->isScheduled = true;
587 AvailableQueue.ScheduledNode(SU);
588}
589
590/// ListScheduleTopDown - The main loop of list scheduling for top-down
591/// schedulers.
592void SchedulePostRATDList::ListScheduleTopDown() {
593 unsigned CurCycle = 0;
594
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000595 // Release any successors of the special Entry node.
596 ReleaseSuccessors(&EntrySU);
597
Dan Gohman343f0c02008-11-19 23:18:57 +0000598 // All leaves to Available queue.
599 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
600 // It is available if it has no predecessors.
601 if (SUnits[i].Preds.empty()) {
602 AvailableQueue.push(&SUnits[i]);
603 SUnits[i].isAvailable = true;
604 }
605 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000606
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000607 // In any cycle where we can't schedule any instructions, we must
608 // stall or emit a noop, depending on the target.
Benjamin Kramerbe441c02009-09-06 12:10:17 +0000609 bool CycleHasInsts = false;
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000610
Dan Gohman343f0c02008-11-19 23:18:57 +0000611 // While Available queue is not empty, grab the node with the highest
612 // priority. If it is not ready put it back. Schedule the node.
Dan Gohman2836c282009-01-16 01:33:36 +0000613 std::vector<SUnit*> NotReady;
Dan Gohman343f0c02008-11-19 23:18:57 +0000614 Sequence.reserve(SUnits.size());
615 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
616 // Check to see if any of the pending instructions are ready to issue. If
617 // so, add them to the available queue.
Dan Gohman3f237442008-12-16 03:25:46 +0000618 unsigned MinDepth = ~0u;
Dan Gohman343f0c02008-11-19 23:18:57 +0000619 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman3f237442008-12-16 03:25:46 +0000620 if (PendingQueue[i]->getDepth() <= CurCycle) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000621 AvailableQueue.push(PendingQueue[i]);
622 PendingQueue[i]->isAvailable = true;
623 PendingQueue[i] = PendingQueue.back();
624 PendingQueue.pop_back();
625 --i; --e;
Dan Gohman3f237442008-12-16 03:25:46 +0000626 } else if (PendingQueue[i]->getDepth() < MinDepth)
627 MinDepth = PendingQueue[i]->getDepth();
Dan Gohman343f0c02008-11-19 23:18:57 +0000628 }
David Goodwinc93d8372009-08-11 17:35:23 +0000629
David Goodwin7cd01182009-08-11 17:56:42 +0000630 DEBUG(errs() << "\n*** Examining Available\n";
631 LatencyPriorityQueue q = AvailableQueue;
632 while (!q.empty()) {
633 SUnit *su = q.pop();
634 errs() << "Height " << su->getHeight() << ": ";
635 su->dump(this);
636 });
David Goodwinc93d8372009-08-11 17:35:23 +0000637
Dan Gohman2836c282009-01-16 01:33:36 +0000638 SUnit *FoundSUnit = 0;
639
640 bool HasNoopHazards = false;
641 while (!AvailableQueue.empty()) {
642 SUnit *CurSUnit = AvailableQueue.pop();
643
644 ScheduleHazardRecognizer::HazardType HT =
645 HazardRec->getHazardType(CurSUnit);
646 if (HT == ScheduleHazardRecognizer::NoHazard) {
647 FoundSUnit = CurSUnit;
648 break;
649 }
650
651 // Remember if this is a noop hazard.
652 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
653
654 NotReady.push_back(CurSUnit);
655 }
656
657 // Add the nodes that aren't ready back onto the available list.
658 if (!NotReady.empty()) {
659 AvailableQueue.push_all(NotReady);
660 NotReady.clear();
661 }
662
Dan Gohman343f0c02008-11-19 23:18:57 +0000663 // If we found a node to schedule, do it now.
664 if (FoundSUnit) {
665 ScheduleNodeTopDown(FoundSUnit, CurCycle);
Dan Gohman2836c282009-01-16 01:33:36 +0000666 HazardRec->EmitInstruction(FoundSUnit);
Benjamin Kramerbe441c02009-09-06 12:10:17 +0000667 CycleHasInsts = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000668
David Goodwind94a4e52009-08-10 15:55:25 +0000669 // If we are using the target-specific hazards, then don't
670 // advance the cycle time just because we schedule a node. If
671 // the target allows it we can schedule multiple nodes in the
672 // same cycle.
673 if (!EnablePostRAHazardAvoidance) {
674 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
675 ++CurCycle;
676 }
Dan Gohman2836c282009-01-16 01:33:36 +0000677 } else {
Benjamin Kramerbe441c02009-09-06 12:10:17 +0000678 if (CycleHasInsts) {
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000679 DEBUG(errs() << "*** Finished cycle " << CurCycle << '\n');
680 HazardRec->AdvanceCycle();
681 } else if (!HasNoopHazards) {
682 // Otherwise, we have a pipeline stall, but no other problem,
683 // just advance the current cycle and try again.
684 DEBUG(errs() << "*** Stall in cycle " << CurCycle << '\n');
685 HazardRec->AdvanceCycle();
686 ++NumStalls;
687 } else {
688 // Otherwise, we have no instructions to issue and we have instructions
689 // that will fault if we don't do this right. This is the case for
690 // processors without pipeline interlocks and other cases.
691 DEBUG(errs() << "*** Emitting noop in cycle " << CurCycle << '\n');
692 HazardRec->EmitNoop();
693 Sequence.push_back(0); // NULL here means noop
694 ++NumNoops;
695 }
696
Dan Gohman2836c282009-01-16 01:33:36 +0000697 ++CurCycle;
Benjamin Kramerbe441c02009-09-06 12:10:17 +0000698 CycleHasInsts = false;
Dan Gohman343f0c02008-11-19 23:18:57 +0000699 }
700 }
701
702#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +0000703 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +0000704#endif
705}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000706
707//===----------------------------------------------------------------------===//
708// Public Constructor Functions
709//===----------------------------------------------------------------------===//
710
Evan Chengfa163542009-10-16 21:06:15 +0000711FunctionPass *llvm::createPostRAScheduler(CodeGenOpt::Level OptLevel) {
712 return new PostRAScheduler(OptLevel);
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000713}