blob: 8fe20876bccde41bc3bc629a303e09464e295790 [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 Goodwin34877712009-10-26 19:32:42 +000022#include "AggressiveAntiDepBreaker.h"
David Goodwin2e7be612009-10-26 16:59:04 +000023#include "CriticalAntiDepBreaker.h"
David Goodwind94a4e52009-08-10 15:55:25 +000024#include "ExactHazardRecognizer.h"
25#include "SimpleHazardRecognizer.h"
Dan Gohman6dc75fe2009-02-06 17:12:10 +000026#include "ScheduleDAGInstrs.h"
David Goodwinada0ef82009-10-26 19:41:00 +000027#include "llvm/CodeGen/AntiDepBreaker.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000028#include "llvm/CodeGen/Passes.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000029#include "llvm/CodeGen/LatencyPriorityQueue.h"
30#include "llvm/CodeGen/SchedulerRegistry.h"
Dan Gohman3f237442008-12-16 03:25:46 +000031#include "llvm/CodeGen/MachineDominators.h"
David Goodwinc7951f82009-10-01 19:45:32 +000032#include "llvm/CodeGen/MachineFrameInfo.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000033#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohman3f237442008-12-16 03:25:46 +000034#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman21d90032008-11-25 00:52:40 +000035#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman2836c282009-01-16 01:33:36 +000036#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Dan Gohmana70dca12009-10-09 23:27:56 +000037#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohmanbed353d2009-02-10 23:29:38 +000038#include "llvm/Target/TargetLowering.h"
Dan Gohman79ce2762009-01-15 19:20:50 +000039#include "llvm/Target/TargetMachine.h"
Dan Gohman21d90032008-11-25 00:52:40 +000040#include "llvm/Target/TargetInstrInfo.h"
41#include "llvm/Target/TargetRegisterInfo.h"
David Goodwin0dad89f2009-09-30 00:10:16 +000042#include "llvm/Target/TargetSubtarget.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000043#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000044#include "llvm/Support/ErrorHandling.h"
David Goodwin3a5f0d42009-08-11 01:44:26 +000045#include "llvm/Support/raw_ostream.h"
David Goodwin2e7be612009-10-26 16:59:04 +000046#include "llvm/ADT/BitVector.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000047#include "llvm/ADT/Statistic.h"
Dan Gohman21d90032008-11-25 00:52:40 +000048#include <map>
David Goodwin88a589c2009-08-25 17:03:05 +000049#include <set>
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000050using namespace llvm;
51
Dan Gohman2836c282009-01-16 01:33:36 +000052STATISTIC(NumNoops, "Number of noops inserted");
Dan Gohman343f0c02008-11-19 23:18:57 +000053STATISTIC(NumStalls, "Number of pipeline stalls");
David Goodwin2e7be612009-10-26 16:59:04 +000054STATISTIC(NumFixedAnti, "Number of fixed anti-dependencies");
Dan Gohman343f0c02008-11-19 23:18:57 +000055
David Goodwin471850a2009-10-01 21:46:35 +000056// Post-RA scheduling is enabled with
57// TargetSubtarget.enablePostRAScheduler(). This flag can be used to
58// override the target.
59static cl::opt<bool>
60EnablePostRAScheduler("post-RA-scheduler",
61 cl::desc("Enable scheduling after register allocation"),
David Goodwin9843a932009-10-01 22:19:57 +000062 cl::init(false), cl::Hidden);
David Goodwin2e7be612009-10-26 16:59:04 +000063static cl::opt<std::string>
Dan Gohman21d90032008-11-25 00:52:40 +000064EnableAntiDepBreaking("break-anti-dependencies",
David Goodwin2e7be612009-10-26 16:59:04 +000065 cl::desc("Break post-RA scheduling anti-dependencies: "
66 "\"critical\", \"all\", or \"none\""),
67 cl::init("none"), cl::Hidden);
Dan Gohman2836c282009-01-16 01:33:36 +000068static cl::opt<bool>
69EnablePostRAHazardAvoidance("avoid-hazards",
David Goodwind94a4e52009-08-10 15:55:25 +000070 cl::desc("Enable exact hazard avoidance"),
David Goodwin5e411782009-09-03 22:15:25 +000071 cl::init(true), cl::Hidden);
Dan Gohman2836c282009-01-16 01:33:36 +000072
David Goodwin1f152282009-09-01 18:34:03 +000073// If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
74static cl::opt<int>
75DebugDiv("postra-sched-debugdiv",
76 cl::desc("Debug control MBBs that are scheduled"),
77 cl::init(0), cl::Hidden);
78static cl::opt<int>
79DebugMod("postra-sched-debugmod",
80 cl::desc("Debug control MBBs that are scheduled"),
81 cl::init(0), cl::Hidden);
82
David Goodwinada0ef82009-10-26 19:41:00 +000083AntiDepBreaker::~AntiDepBreaker() { }
84
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000085namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000086 class PostRAScheduler : public MachineFunctionPass {
Dan Gohmana70dca12009-10-09 23:27:56 +000087 AliasAnalysis *AA;
Evan Chengfa163542009-10-16 21:06:15 +000088 CodeGenOpt::Level OptLevel;
Dan Gohmana70dca12009-10-09 23:27:56 +000089
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000090 public:
91 static char ID;
Evan Chengfa163542009-10-16 21:06:15 +000092 PostRAScheduler(CodeGenOpt::Level ol) :
93 MachineFunctionPass(&ID), OptLevel(ol) {}
Dan Gohman21d90032008-11-25 00:52:40 +000094
Dan Gohman3f237442008-12-16 03:25:46 +000095 void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000096 AU.setPreservesCFG();
Dan Gohmana70dca12009-10-09 23:27:56 +000097 AU.addRequired<AliasAnalysis>();
Dan Gohman3f237442008-12-16 03:25:46 +000098 AU.addRequired<MachineDominatorTree>();
99 AU.addPreserved<MachineDominatorTree>();
100 AU.addRequired<MachineLoopInfo>();
101 AU.addPreserved<MachineLoopInfo>();
102 MachineFunctionPass::getAnalysisUsage(AU);
103 }
104
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000105 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +0000106 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000107 }
108
109 bool runOnMachineFunction(MachineFunction &Fn);
110 };
Dan Gohman343f0c02008-11-19 23:18:57 +0000111 char PostRAScheduler::ID = 0;
112
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000113 class SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +0000114 /// AvailableQueue - The priority queue to use for the available SUnits.
Dan Gohmanc1ae8c92009-10-21 01:44:44 +0000115 ///
Dan Gohman343f0c02008-11-19 23:18:57 +0000116 LatencyPriorityQueue AvailableQueue;
117
118 /// PendingQueue - This contains all of the instructions whose operands have
119 /// been issued, but their results are not ready yet (due to the latency of
120 /// the operation). Once the operands becomes available, the instruction is
121 /// added to the AvailableQueue.
122 std::vector<SUnit*> PendingQueue;
123
Dan Gohman21d90032008-11-25 00:52:40 +0000124 /// Topo - A topological ordering for SUnits.
125 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +0000126
Dan Gohman2836c282009-01-16 01:33:36 +0000127 /// HazardRec - The hazard recognizer to use.
128 ScheduleHazardRecognizer *HazardRec;
129
David Goodwin2e7be612009-10-26 16:59:04 +0000130 /// AntiDepBreak - Anti-dependence breaking object, or NULL if none
131 AntiDepBreaker *AntiDepBreak;
132
Dan Gohmana70dca12009-10-09 23:27:56 +0000133 /// AA - AliasAnalysis for making memory reference queries.
134 AliasAnalysis *AA;
135
Dan Gohmanc1ae8c92009-10-21 01:44:44 +0000136 /// KillIndices - The index of the most recent kill (proceding bottom-up),
137 /// or ~0u if the register is not live.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000138 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
139
Dan Gohman21d90032008-11-25 00:52:40 +0000140 public:
Dan Gohman79ce2762009-01-15 19:20:50 +0000141 SchedulePostRATDList(MachineFunction &MF,
Dan Gohman3f237442008-12-16 03:25:46 +0000142 const MachineLoopInfo &MLI,
Dan Gohman2836c282009-01-16 01:33:36 +0000143 const MachineDominatorTree &MDT,
Dan Gohmana70dca12009-10-09 23:27:56 +0000144 ScheduleHazardRecognizer *HR,
David Goodwin2e7be612009-10-26 16:59:04 +0000145 AntiDepBreaker *ADB,
146 AliasAnalysis *aa)
Dan Gohman79ce2762009-01-15 19:20:50 +0000147 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
David Goodwin2e7be612009-10-26 16:59:04 +0000148 HazardRec(HR), AntiDepBreak(ADB), AA(aa) {}
Dan Gohman2836c282009-01-16 01:33:36 +0000149
150 ~SchedulePostRATDList() {
Dan Gohman2836c282009-01-16 01:33:36 +0000151 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000152
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000153 /// StartBlock - Initialize register live-range state for scheduling in
154 /// this block.
155 ///
156 void StartBlock(MachineBasicBlock *BB);
157
158 /// Schedule - Schedule the instruction range using list scheduling.
159 ///
Dan Gohman343f0c02008-11-19 23:18:57 +0000160 void Schedule();
David Goodwin88a589c2009-08-25 17:03:05 +0000161
Dan Gohmanc1ae8c92009-10-21 01:44:44 +0000162 /// Observe - Update liveness information to account for the current
163 /// instruction, which will not be scheduled.
164 ///
165 void Observe(MachineInstr *MI, unsigned Count);
166
167 /// FinishBlock - Clean up register live-range state.
168 ///
169 void FinishBlock();
170
David Goodwin2e7be612009-10-26 16:59:04 +0000171 /// FixupKills - Fix register kill flags that have been made
172 /// invalid due to scheduling
173 ///
174 void FixupKills(MachineBasicBlock *MBB);
175
Dan Gohman343f0c02008-11-19 23:18:57 +0000176 private:
Dan Gohman54e4c362008-12-09 22:54:47 +0000177 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000178 void ReleaseSuccessors(SUnit *SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000179 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
180 void ListScheduleTopDown();
David Goodwin5e411782009-09-03 22:15:25 +0000181 void StartBlockForKills(MachineBasicBlock *BB);
David Goodwin8f909342009-09-23 16:35:25 +0000182
183 // ToggleKillFlag - Toggle a register operand kill flag. Other
184 // adjustments may be made to the instruction if necessary. Return
185 // true if the operand has been deleted, false if not.
186 bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
Dan Gohman343f0c02008-11-19 23:18:57 +0000187 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000188}
189
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000190/// isSchedulingBoundary - Test if the given instruction should be
191/// considered a scheduling boundary. This primarily includes labels
192/// and terminators.
193///
194static bool isSchedulingBoundary(const MachineInstr *MI,
195 const MachineFunction &MF) {
196 // Terminators and labels can't be scheduled around.
197 if (MI->getDesc().isTerminator() || MI->isLabel())
198 return true;
199
Dan Gohmanbed353d2009-02-10 23:29:38 +0000200 // Don't attempt to schedule around any instruction that modifies
201 // a stack-oriented pointer, as it's unlikely to be profitable. This
202 // saves compile time, because it doesn't require every single
203 // stack slot reference to depend on the instruction that does the
204 // modification.
205 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
206 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
207 return true;
208
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000209 return false;
210}
211
Dan Gohman343f0c02008-11-19 23:18:57 +0000212bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
Dan Gohman5bf7c2a2009-10-10 00:15:38 +0000213 AA = &getAnalysis<AliasAnalysis>();
214
David Goodwin471850a2009-10-01 21:46:35 +0000215 // Check for explicit enable/disable of post-ra scheduling.
David Goodwin4c3715c2009-10-22 23:19:17 +0000216 TargetSubtarget::AntiDepBreakMode AntiDepMode = TargetSubtarget::ANTIDEP_NONE;
David Goodwin471850a2009-10-01 21:46:35 +0000217 if (EnablePostRAScheduler.getPosition() > 0) {
218 if (!EnablePostRAScheduler)
Evan Chengc83da2f92009-10-16 06:10:34 +0000219 return false;
David Goodwin471850a2009-10-01 21:46:35 +0000220 } else {
Evan Chengc83da2f92009-10-16 06:10:34 +0000221 // Check that post-RA scheduling is enabled for this target.
David Goodwin471850a2009-10-01 21:46:35 +0000222 const TargetSubtarget &ST = Fn.getTarget().getSubtarget<TargetSubtarget>();
David Goodwin4c3715c2009-10-22 23:19:17 +0000223 if (!ST.enablePostRAScheduler(OptLevel, AntiDepMode))
Evan Chengc83da2f92009-10-16 06:10:34 +0000224 return false;
David Goodwin471850a2009-10-01 21:46:35 +0000225 }
David Goodwin0dad89f2009-09-30 00:10:16 +0000226
David Goodwin4c3715c2009-10-22 23:19:17 +0000227 // Check for antidep breaking override...
228 if (EnableAntiDepBreaking.getPosition() > 0) {
David Goodwin2e7be612009-10-26 16:59:04 +0000229 AntiDepMode = (EnableAntiDepBreaking == "all") ? TargetSubtarget::ANTIDEP_ALL :
230 (EnableAntiDepBreaking == "critical") ? TargetSubtarget::ANTIDEP_CRITICAL :
231 TargetSubtarget::ANTIDEP_NONE;
David Goodwin4c3715c2009-10-22 23:19:17 +0000232 }
233
David Goodwin3a5f0d42009-08-11 01:44:26 +0000234 DEBUG(errs() << "PostRAScheduler\n");
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000235
Dan Gohman3f237442008-12-16 03:25:46 +0000236 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
237 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
David Goodwind94a4e52009-08-10 15:55:25 +0000238 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
Dan Gohman2836c282009-01-16 01:33:36 +0000239 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
David Goodwind94a4e52009-08-10 15:55:25 +0000240 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
241 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
David Goodwin2e7be612009-10-26 16:59:04 +0000242 AntiDepBreaker *ADB =
David Goodwin34877712009-10-26 19:32:42 +0000243 ((AntiDepMode == TargetSubtarget::ANTIDEP_ALL) ?
244 (AntiDepBreaker *)new AggressiveAntiDepBreaker(Fn) :
245 ((AntiDepMode == TargetSubtarget::ANTIDEP_CRITICAL) ?
246 (AntiDepBreaker *)new CriticalAntiDepBreaker(Fn) : NULL));
Dan Gohman3f237442008-12-16 03:25:46 +0000247
David Goodwin2e7be612009-10-26 16:59:04 +0000248 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR, ADB, AA);
Dan Gohman79ce2762009-01-15 19:20:50 +0000249
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000250 // Loop over all of the basic blocks
251 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000252 MBB != MBBe; ++MBB) {
David Goodwin1f152282009-09-01 18:34:03 +0000253#ifndef NDEBUG
254 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
255 if (DebugDiv > 0) {
256 static int bbcnt = 0;
257 if (bbcnt++ % DebugDiv != DebugMod)
258 continue;
259 errs() << "*** DEBUG scheduling " << Fn.getFunction()->getNameStr() <<
260 ":MBB ID#" << MBB->getNumber() << " ***\n";
261 }
262#endif
263
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000264 // Initialize register live-range state for scheduling in this block.
265 Scheduler.StartBlock(MBB);
266
Dan Gohmanf7119392009-01-16 22:10:20 +0000267 // Schedule each sequence of instructions not interrupted by a label
268 // or anything else that effectively needs to shut down scheduling.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000269 MachineBasicBlock::iterator Current = MBB->end();
Dan Gohman47ac0f02009-02-11 04:27:20 +0000270 unsigned Count = MBB->size(), CurrentCount = Count;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000271 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
272 MachineInstr *MI = prior(I);
273 if (isSchedulingBoundary(MI, Fn)) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000274 Scheduler.Run(MBB, I, Current, CurrentCount);
Evan Chengfb2e7522009-09-18 21:02:19 +0000275 Scheduler.EmitSchedule(0);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000276 Current = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000277 CurrentCount = Count - 1;
Dan Gohman1274ced2009-03-10 18:10:43 +0000278 Scheduler.Observe(MI, CurrentCount);
Dan Gohmanf7119392009-01-16 22:10:20 +0000279 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000280 I = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000281 --Count;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000282 }
Dan Gohman47ac0f02009-02-11 04:27:20 +0000283 assert(Count == 0 && "Instruction count mismatch!");
Duncan Sands9e8bd0b2009-03-11 09:04:34 +0000284 assert((MBB->begin() == Current || CurrentCount != 0) &&
Dan Gohman1274ced2009-03-10 18:10:43 +0000285 "Instruction count mismatch!");
286 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
Evan Chengfb2e7522009-09-18 21:02:19 +0000287 Scheduler.EmitSchedule(0);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000288
289 // Clean up register live-range state.
290 Scheduler.FinishBlock();
David Goodwin88a589c2009-08-25 17:03:05 +0000291
David Goodwin5e411782009-09-03 22:15:25 +0000292 // Update register kills
David Goodwin88a589c2009-08-25 17:03:05 +0000293 Scheduler.FixupKills(MBB);
Dan Gohman343f0c02008-11-19 23:18:57 +0000294 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000295
David Goodwin2e7be612009-10-26 16:59:04 +0000296 delete HR;
297 delete ADB;
298
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000299 return true;
300}
301
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000302/// StartBlock - Initialize register live-range state for scheduling in
303/// this block.
Dan Gohman21d90032008-11-25 00:52:40 +0000304///
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000305void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
306 // Call the superclass.
307 ScheduleDAGInstrs::StartBlock(BB);
Dan Gohman21d90032008-11-25 00:52:40 +0000308
David Goodwin2e7be612009-10-26 16:59:04 +0000309 // Reset the hazard recognizer and anti-dep breaker.
David Goodwind94a4e52009-08-10 15:55:25 +0000310 HazardRec->Reset();
David Goodwin2e7be612009-10-26 16:59:04 +0000311 if (AntiDepBreak != NULL)
312 AntiDepBreak->StartBlock(BB);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000313}
314
315/// Schedule - Schedule the instruction range using list scheduling.
316///
317void SchedulePostRATDList::Schedule() {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000318 DEBUG(errs() << "********** List Scheduling **********\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000319
320 // Build the scheduling graph.
Dan Gohmana70dca12009-10-09 23:27:56 +0000321 BuildSchedGraph(AA);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000322
David Goodwin2e7be612009-10-26 16:59:04 +0000323 if (AntiDepBreak != NULL) {
324 unsigned Broken =
325 AntiDepBreak->BreakAntiDependencies(SUnits, Begin, InsertPos,
326 InsertPosIndex);
327 if (Broken > 0) {
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000328 // We made changes. Update the dependency graph.
329 // Theoretically we could update the graph in place:
330 // When a live range is changed to use a different register, remove
331 // the def's anti-dependence *and* output-dependence edges due to
332 // that register, and add new anti-dependence and output-dependence
333 // edges based on the next live range of the register.
334 SUnits.clear();
335 EntrySU = SUnit();
336 ExitSU = SUnit();
Dan Gohmana70dca12009-10-09 23:27:56 +0000337 BuildSchedGraph(AA);
David Goodwin2e7be612009-10-26 16:59:04 +0000338
339 NumFixedAnti += Broken;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000340 }
341 }
342
David Goodwind94a4e52009-08-10 15:55:25 +0000343 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
344 SUnits[su].dumpAll(this));
345
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000346 AvailableQueue.initNodes(SUnits);
347
348 ListScheduleTopDown();
349
350 AvailableQueue.releaseState();
351}
352
353/// Observe - Update liveness information to account for the current
354/// instruction, which will not be scheduled.
355///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000356void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
David Goodwin2e7be612009-10-26 16:59:04 +0000357 if (AntiDepBreak != NULL)
358 AntiDepBreak->Observe(MI, Count, InsertPosIndex);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000359}
360
361/// FinishBlock - Clean up register live-range state.
362///
363void SchedulePostRATDList::FinishBlock() {
David Goodwin2e7be612009-10-26 16:59:04 +0000364 if (AntiDepBreak != NULL)
365 AntiDepBreak->FinishBlock();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000366
367 // Call the superclass.
368 ScheduleDAGInstrs::FinishBlock();
369}
370
David Goodwin5e411782009-09-03 22:15:25 +0000371/// StartBlockForKills - Initialize register live-range state for updating kills
372///
373void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
374 // Initialize the indices to indicate that no registers are live.
375 std::fill(KillIndices, array_endof(KillIndices), ~0u);
376
377 // Determine the live-out physregs for this block.
378 if (!BB->empty() && BB->back().getDesc().isReturn()) {
379 // In a return block, examine the function live-out regs.
380 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
381 E = MRI.liveout_end(); I != E; ++I) {
382 unsigned Reg = *I;
383 KillIndices[Reg] = BB->size();
384 // Repeat, for all subregs.
385 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
386 *Subreg; ++Subreg) {
387 KillIndices[*Subreg] = BB->size();
388 }
389 }
390 }
391 else {
392 // In a non-return block, examine the live-in regs of all successors.
393 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
394 SE = BB->succ_end(); SI != SE; ++SI) {
395 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
396 E = (*SI)->livein_end(); I != E; ++I) {
397 unsigned Reg = *I;
398 KillIndices[Reg] = BB->size();
399 // Repeat, for all subregs.
400 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
401 *Subreg; ++Subreg) {
402 KillIndices[*Subreg] = BB->size();
403 }
404 }
405 }
406 }
407}
408
David Goodwin8f909342009-09-23 16:35:25 +0000409bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
410 MachineOperand &MO) {
411 // Setting kill flag...
412 if (!MO.isKill()) {
413 MO.setIsKill(true);
414 return false;
415 }
416
417 // If MO itself is live, clear the kill flag...
418 if (KillIndices[MO.getReg()] != ~0u) {
419 MO.setIsKill(false);
420 return false;
421 }
422
423 // If any subreg of MO is live, then create an imp-def for that
424 // subreg and keep MO marked as killed.
Benjamin Kramer8bff4af2009-10-02 15:59:52 +0000425 MO.setIsKill(false);
David Goodwin8f909342009-09-23 16:35:25 +0000426 bool AllDead = true;
427 const unsigned SuperReg = MO.getReg();
428 for (const unsigned *Subreg = TRI->getSubRegisters(SuperReg);
429 *Subreg; ++Subreg) {
430 if (KillIndices[*Subreg] != ~0u) {
431 MI->addOperand(MachineOperand::CreateReg(*Subreg,
432 true /*IsDef*/,
433 true /*IsImp*/,
434 false /*IsKill*/,
435 false /*IsDead*/));
436 AllDead = false;
437 }
438 }
439
Dan Gohmanc1ae8c92009-10-21 01:44:44 +0000440 if(AllDead)
Benjamin Kramer8bff4af2009-10-02 15:59:52 +0000441 MO.setIsKill(true);
David Goodwin8f909342009-09-23 16:35:25 +0000442 return false;
443}
444
David Goodwin88a589c2009-08-25 17:03:05 +0000445/// FixupKills - Fix the register kill flags, they may have been made
446/// incorrect by instruction reordering.
447///
448void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
449 DEBUG(errs() << "Fixup kills for BB ID#" << MBB->getNumber() << '\n');
450
451 std::set<unsigned> killedRegs;
452 BitVector ReservedRegs = TRI->getReservedRegs(MF);
David Goodwin5e411782009-09-03 22:15:25 +0000453
454 StartBlockForKills(MBB);
David Goodwin7886cd82009-08-29 00:11:13 +0000455
456 // Examine block from end to start...
David Goodwin88a589c2009-08-25 17:03:05 +0000457 unsigned Count = MBB->size();
458 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
459 I != E; --Count) {
460 MachineInstr *MI = --I;
461
David Goodwin7886cd82009-08-29 00:11:13 +0000462 // Update liveness. Registers that are defed but not used in this
463 // instruction are now dead. Mark register and all subregs as they
464 // are completely defined.
465 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
466 MachineOperand &MO = MI->getOperand(i);
467 if (!MO.isReg()) continue;
468 unsigned Reg = MO.getReg();
469 if (Reg == 0) continue;
470 if (!MO.isDef()) continue;
471 // Ignore two-addr defs.
472 if (MI->isRegTiedToUseOperand(i)) continue;
473
David Goodwin7886cd82009-08-29 00:11:13 +0000474 KillIndices[Reg] = ~0u;
475
476 // Repeat for all subregs.
477 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
478 *Subreg; ++Subreg) {
479 KillIndices[*Subreg] = ~0u;
480 }
481 }
David Goodwin88a589c2009-08-25 17:03:05 +0000482
David Goodwin8f909342009-09-23 16:35:25 +0000483 // Examine all used registers and set/clear kill flag. When a
484 // register is used multiple times we only set the kill flag on
485 // the first use.
David Goodwin88a589c2009-08-25 17:03:05 +0000486 killedRegs.clear();
487 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
488 MachineOperand &MO = MI->getOperand(i);
489 if (!MO.isReg() || !MO.isUse()) continue;
490 unsigned Reg = MO.getReg();
491 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
492
David Goodwin7886cd82009-08-29 00:11:13 +0000493 bool kill = false;
494 if (killedRegs.find(Reg) == killedRegs.end()) {
495 kill = true;
496 // A register is not killed if any subregs are live...
497 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
498 *Subreg; ++Subreg) {
499 if (KillIndices[*Subreg] != ~0u) {
500 kill = false;
501 break;
502 }
503 }
504
505 // If subreg is not live, then register is killed if it became
506 // live in this instruction
507 if (kill)
508 kill = (KillIndices[Reg] == ~0u);
509 }
510
David Goodwin88a589c2009-08-25 17:03:05 +0000511 if (MO.isKill() != kill) {
David Goodwin8f909342009-09-23 16:35:25 +0000512 bool removed = ToggleKillFlag(MI, MO);
513 if (removed) {
514 DEBUG(errs() << "Fixed <removed> in ");
515 } else {
516 DEBUG(errs() << "Fixed " << MO << " in ");
517 }
David Goodwin88a589c2009-08-25 17:03:05 +0000518 DEBUG(MI->dump());
519 }
David Goodwin7886cd82009-08-29 00:11:13 +0000520
David Goodwin88a589c2009-08-25 17:03:05 +0000521 killedRegs.insert(Reg);
522 }
David Goodwin7886cd82009-08-29 00:11:13 +0000523
David Goodwina3251db2009-08-31 20:47:02 +0000524 // Mark any used register (that is not using undef) and subregs as
525 // now live...
David Goodwin7886cd82009-08-29 00:11:13 +0000526 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
527 MachineOperand &MO = MI->getOperand(i);
David Goodwina3251db2009-08-31 20:47:02 +0000528 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
David Goodwin7886cd82009-08-29 00:11:13 +0000529 unsigned Reg = MO.getReg();
530 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
531
David Goodwin7886cd82009-08-29 00:11:13 +0000532 KillIndices[Reg] = Count;
533
534 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
535 *Subreg; ++Subreg) {
536 KillIndices[*Subreg] = Count;
537 }
538 }
David Goodwin88a589c2009-08-25 17:03:05 +0000539 }
540}
541
Dan Gohman343f0c02008-11-19 23:18:57 +0000542//===----------------------------------------------------------------------===//
543// Top-Down Scheduling
544//===----------------------------------------------------------------------===//
545
546/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
547/// the PendingQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman54e4c362008-12-09 22:54:47 +0000548void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
549 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Klecknerc277ab02009-09-30 20:15:38 +0000550
Dan Gohman343f0c02008-11-19 23:18:57 +0000551#ifndef NDEBUG
Reid Klecknerc277ab02009-09-30 20:15:38 +0000552 if (SuccSU->NumPredsLeft == 0) {
Chris Lattner103289e2009-08-23 07:19:13 +0000553 errs() << "*** Scheduling failed! ***\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000554 SuccSU->dump(this);
Chris Lattner103289e2009-08-23 07:19:13 +0000555 errs() << " has been released too many times!\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000556 llvm_unreachable(0);
Dan Gohman343f0c02008-11-19 23:18:57 +0000557 }
558#endif
Reid Klecknerc277ab02009-09-30 20:15:38 +0000559 --SuccSU->NumPredsLeft;
560
Dan Gohman343f0c02008-11-19 23:18:57 +0000561 // Compute how many cycles it will be before this actually becomes
562 // available. This is the max of the start time of all predecessors plus
563 // their latencies.
Dan Gohman3f237442008-12-16 03:25:46 +0000564 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
Dan Gohman343f0c02008-11-19 23:18:57 +0000565
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000566 // If all the node's predecessors are scheduled, this node is ready
567 // to be scheduled. Ignore the special ExitSU node.
568 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Dan Gohman343f0c02008-11-19 23:18:57 +0000569 PendingQueue.push_back(SuccSU);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000570}
571
572/// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
573void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
574 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
575 I != E; ++I)
576 ReleaseSucc(SU, &*I);
Dan Gohman343f0c02008-11-19 23:18:57 +0000577}
578
579/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
580/// count of its successors. If a successor pending count is zero, add it to
581/// the Available queue.
582void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000583 DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman343f0c02008-11-19 23:18:57 +0000584 DEBUG(SU->dump(this));
585
586 Sequence.push_back(SU);
Dan Gohman3f237442008-12-16 03:25:46 +0000587 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
588 SU->setDepthToAtLeast(CurCycle);
Dan Gohman343f0c02008-11-19 23:18:57 +0000589
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000590 ReleaseSuccessors(SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000591 SU->isScheduled = true;
592 AvailableQueue.ScheduledNode(SU);
593}
594
595/// ListScheduleTopDown - The main loop of list scheduling for top-down
596/// schedulers.
597void SchedulePostRATDList::ListScheduleTopDown() {
598 unsigned CurCycle = 0;
599
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000600 // Release any successors of the special Entry node.
601 ReleaseSuccessors(&EntrySU);
602
Dan Gohman343f0c02008-11-19 23:18:57 +0000603 // All leaves to Available queue.
604 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
605 // It is available if it has no predecessors.
606 if (SUnits[i].Preds.empty()) {
607 AvailableQueue.push(&SUnits[i]);
608 SUnits[i].isAvailable = true;
609 }
610 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000611
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000612 // In any cycle where we can't schedule any instructions, we must
613 // stall or emit a noop, depending on the target.
Benjamin Kramerbe441c02009-09-06 12:10:17 +0000614 bool CycleHasInsts = false;
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000615
Dan Gohman343f0c02008-11-19 23:18:57 +0000616 // While Available queue is not empty, grab the node with the highest
617 // priority. If it is not ready put it back. Schedule the node.
Dan Gohman2836c282009-01-16 01:33:36 +0000618 std::vector<SUnit*> NotReady;
Dan Gohman343f0c02008-11-19 23:18:57 +0000619 Sequence.reserve(SUnits.size());
620 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
621 // Check to see if any of the pending instructions are ready to issue. If
622 // so, add them to the available queue.
Dan Gohman3f237442008-12-16 03:25:46 +0000623 unsigned MinDepth = ~0u;
Dan Gohman343f0c02008-11-19 23:18:57 +0000624 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman3f237442008-12-16 03:25:46 +0000625 if (PendingQueue[i]->getDepth() <= CurCycle) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000626 AvailableQueue.push(PendingQueue[i]);
627 PendingQueue[i]->isAvailable = true;
628 PendingQueue[i] = PendingQueue.back();
629 PendingQueue.pop_back();
630 --i; --e;
Dan Gohman3f237442008-12-16 03:25:46 +0000631 } else if (PendingQueue[i]->getDepth() < MinDepth)
632 MinDepth = PendingQueue[i]->getDepth();
Dan Gohman343f0c02008-11-19 23:18:57 +0000633 }
David Goodwinc93d8372009-08-11 17:35:23 +0000634
David Goodwin7cd01182009-08-11 17:56:42 +0000635 DEBUG(errs() << "\n*** Examining Available\n";
636 LatencyPriorityQueue q = AvailableQueue;
637 while (!q.empty()) {
638 SUnit *su = q.pop();
639 errs() << "Height " << su->getHeight() << ": ";
640 su->dump(this);
641 });
David Goodwinc93d8372009-08-11 17:35:23 +0000642
Dan Gohman2836c282009-01-16 01:33:36 +0000643 SUnit *FoundSUnit = 0;
644
645 bool HasNoopHazards = false;
646 while (!AvailableQueue.empty()) {
647 SUnit *CurSUnit = AvailableQueue.pop();
648
649 ScheduleHazardRecognizer::HazardType HT =
650 HazardRec->getHazardType(CurSUnit);
651 if (HT == ScheduleHazardRecognizer::NoHazard) {
652 FoundSUnit = CurSUnit;
653 break;
654 }
655
656 // Remember if this is a noop hazard.
657 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
658
659 NotReady.push_back(CurSUnit);
660 }
661
662 // Add the nodes that aren't ready back onto the available list.
663 if (!NotReady.empty()) {
664 AvailableQueue.push_all(NotReady);
665 NotReady.clear();
666 }
667
Dan Gohman343f0c02008-11-19 23:18:57 +0000668 // If we found a node to schedule, do it now.
669 if (FoundSUnit) {
670 ScheduleNodeTopDown(FoundSUnit, CurCycle);
Dan Gohman2836c282009-01-16 01:33:36 +0000671 HazardRec->EmitInstruction(FoundSUnit);
Benjamin Kramerbe441c02009-09-06 12:10:17 +0000672 CycleHasInsts = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000673
David Goodwind94a4e52009-08-10 15:55:25 +0000674 // If we are using the target-specific hazards, then don't
675 // advance the cycle time just because we schedule a node. If
676 // the target allows it we can schedule multiple nodes in the
677 // same cycle.
678 if (!EnablePostRAHazardAvoidance) {
679 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
680 ++CurCycle;
681 }
Dan Gohman2836c282009-01-16 01:33:36 +0000682 } else {
Benjamin Kramerbe441c02009-09-06 12:10:17 +0000683 if (CycleHasInsts) {
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000684 DEBUG(errs() << "*** Finished cycle " << CurCycle << '\n');
685 HazardRec->AdvanceCycle();
686 } else if (!HasNoopHazards) {
687 // Otherwise, we have a pipeline stall, but no other problem,
688 // just advance the current cycle and try again.
689 DEBUG(errs() << "*** Stall in cycle " << CurCycle << '\n');
690 HazardRec->AdvanceCycle();
691 ++NumStalls;
692 } else {
693 // Otherwise, we have no instructions to issue and we have instructions
694 // that will fault if we don't do this right. This is the case for
695 // processors without pipeline interlocks and other cases.
696 DEBUG(errs() << "*** Emitting noop in cycle " << CurCycle << '\n');
697 HazardRec->EmitNoop();
698 Sequence.push_back(0); // NULL here means noop
699 ++NumNoops;
700 }
701
Dan Gohman2836c282009-01-16 01:33:36 +0000702 ++CurCycle;
Benjamin Kramerbe441c02009-09-06 12:10:17 +0000703 CycleHasInsts = false;
Dan Gohman343f0c02008-11-19 23:18:57 +0000704 }
705 }
706
707#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +0000708 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +0000709#endif
710}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000711
712//===----------------------------------------------------------------------===//
713// Public Constructor Functions
714//===----------------------------------------------------------------------===//
715
Evan Chengfa163542009-10-16 21:06:15 +0000716FunctionPass *llvm::createPostRAScheduler(CodeGenOpt::Level OptLevel) {
717 return new PostRAScheduler(OptLevel);
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000718}