blob: 5de5e7663dac48b559d44f540bdee4f09ace27fc [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 Goodwind94a4e52009-08-10 15:55:25 +000022#include "ExactHazardRecognizer.h"
23#include "SimpleHazardRecognizer.h"
Dan Gohman6dc75fe2009-02-06 17:12:10 +000024#include "ScheduleDAGInstrs.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000025#include "llvm/CodeGen/Passes.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000026#include "llvm/CodeGen/LatencyPriorityQueue.h"
27#include "llvm/CodeGen/SchedulerRegistry.h"
Dan Gohman3f237442008-12-16 03:25:46 +000028#include "llvm/CodeGen/MachineDominators.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000029#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohman3f237442008-12-16 03:25:46 +000030#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman21d90032008-11-25 00:52:40 +000031#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman2836c282009-01-16 01:33:36 +000032#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Dan Gohmanbed353d2009-02-10 23:29:38 +000033#include "llvm/Target/TargetLowering.h"
Dan Gohman79ce2762009-01-15 19:20:50 +000034#include "llvm/Target/TargetMachine.h"
Dan Gohman21d90032008-11-25 00:52:40 +000035#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner459525d2008-01-14 19:00:06 +000037#include "llvm/Support/Compiler.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000038#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000039#include "llvm/Support/ErrorHandling.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000040#include "llvm/ADT/Statistic.h"
Dan Gohman21d90032008-11-25 00:52:40 +000041#include <map>
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000042using namespace llvm;
43
Dan Gohman2836c282009-01-16 01:33:36 +000044STATISTIC(NumNoops, "Number of noops inserted");
Dan Gohman343f0c02008-11-19 23:18:57 +000045STATISTIC(NumStalls, "Number of pipeline stalls");
46
Dan Gohman21d90032008-11-25 00:52:40 +000047static cl::opt<bool>
48EnableAntiDepBreaking("break-anti-dependencies",
Dan Gohman00dc84a2008-12-16 19:27:52 +000049 cl::desc("Break post-RA scheduling anti-dependencies"),
50 cl::init(true), cl::Hidden);
Dan Gohman21d90032008-11-25 00:52:40 +000051
Dan Gohman2836c282009-01-16 01:33:36 +000052static cl::opt<bool>
53EnablePostRAHazardAvoidance("avoid-hazards",
David Goodwind94a4e52009-08-10 15:55:25 +000054 cl::desc("Enable exact hazard avoidance"),
55 cl::init(false), cl::Hidden);
Dan Gohman2836c282009-01-16 01:33:36 +000056
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000057namespace {
Dan Gohman343f0c02008-11-19 23:18:57 +000058 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000059 public:
60 static char ID;
Dan Gohman343f0c02008-11-19 23:18:57 +000061 PostRAScheduler() : MachineFunctionPass(&ID) {}
Dan Gohman21d90032008-11-25 00:52:40 +000062
Dan Gohman3f237442008-12-16 03:25:46 +000063 void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000064 AU.setPreservesCFG();
Dan Gohman3f237442008-12-16 03:25:46 +000065 AU.addRequired<MachineDominatorTree>();
66 AU.addPreserved<MachineDominatorTree>();
67 AU.addRequired<MachineLoopInfo>();
68 AU.addPreserved<MachineLoopInfo>();
69 MachineFunctionPass::getAnalysisUsage(AU);
70 }
71
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000072 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +000073 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000074 }
75
76 bool runOnMachineFunction(MachineFunction &Fn);
77 };
Dan Gohman343f0c02008-11-19 23:18:57 +000078 char PostRAScheduler::ID = 0;
79
80 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +000081 /// AvailableQueue - The priority queue to use for the available SUnits.
82 ///
83 LatencyPriorityQueue AvailableQueue;
84
85 /// PendingQueue - This contains all of the instructions whose operands have
86 /// been issued, but their results are not ready yet (due to the latency of
87 /// the operation). Once the operands becomes available, the instruction is
88 /// added to the AvailableQueue.
89 std::vector<SUnit*> PendingQueue;
90
Dan Gohman21d90032008-11-25 00:52:40 +000091 /// Topo - A topological ordering for SUnits.
92 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +000093
Dan Gohman79ce2762009-01-15 19:20:50 +000094 /// AllocatableSet - The set of allocatable registers.
95 /// We'll be ignoring anti-dependencies on non-allocatable registers,
96 /// because they may not be safe to break.
97 const BitVector AllocatableSet;
98
Dan Gohman2836c282009-01-16 01:33:36 +000099 /// HazardRec - The hazard recognizer to use.
100 ScheduleHazardRecognizer *HazardRec;
101
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000102 /// Classes - For live regs that are only used in one register class in a
103 /// live range, the register class. If the register is not live, the
104 /// corresponding value is null. If the register is live but used in
105 /// multiple register classes, the corresponding value is -1 casted to a
106 /// pointer.
107 const TargetRegisterClass *
108 Classes[TargetRegisterInfo::FirstVirtualRegister];
109
110 /// RegRegs - Map registers to all their references within a live range.
111 std::multimap<unsigned, MachineOperand *> RegRefs;
112
113 /// The index of the most recent kill (proceding bottom-up), or ~0u if
114 /// the register is not live.
115 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
116
117 /// The index of the most recent complete def (proceding bottom up), or ~0u
118 /// if the register is live.
119 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
120
Dan Gohman21d90032008-11-25 00:52:40 +0000121 public:
Dan Gohman79ce2762009-01-15 19:20:50 +0000122 SchedulePostRATDList(MachineFunction &MF,
Dan Gohman3f237442008-12-16 03:25:46 +0000123 const MachineLoopInfo &MLI,
Dan Gohman2836c282009-01-16 01:33:36 +0000124 const MachineDominatorTree &MDT,
125 ScheduleHazardRecognizer *HR)
Dan Gohman79ce2762009-01-15 19:20:50 +0000126 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
Dan Gohman2836c282009-01-16 01:33:36 +0000127 AllocatableSet(TRI->getAllocatableSet(MF)),
128 HazardRec(HR) {}
129
130 ~SchedulePostRATDList() {
131 delete HazardRec;
132 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000133
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000134 /// StartBlock - Initialize register live-range state for scheduling in
135 /// this block.
136 ///
137 void StartBlock(MachineBasicBlock *BB);
138
139 /// Schedule - Schedule the instruction range using list scheduling.
140 ///
Dan Gohman343f0c02008-11-19 23:18:57 +0000141 void Schedule();
142
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000143 /// Observe - Update liveness information to account for the current
144 /// instruction, which will not be scheduled.
145 ///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000146 void Observe(MachineInstr *MI, unsigned Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000147
148 /// FinishBlock - Clean up register live-range state.
149 ///
150 void FinishBlock();
151
Dan Gohman343f0c02008-11-19 23:18:57 +0000152 private:
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000153 void PrescanInstruction(MachineInstr *MI);
154 void ScanInstruction(MachineInstr *MI, unsigned Count);
Dan Gohman54e4c362008-12-09 22:54:47 +0000155 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000156 void ReleaseSuccessors(SUnit *SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000157 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
158 void ListScheduleTopDown();
Dan Gohman21d90032008-11-25 00:52:40 +0000159 bool BreakAntiDependencies();
Dan Gohman343f0c02008-11-19 23:18:57 +0000160 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000161}
162
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000163/// isSchedulingBoundary - Test if the given instruction should be
164/// considered a scheduling boundary. This primarily includes labels
165/// and terminators.
166///
167static bool isSchedulingBoundary(const MachineInstr *MI,
168 const MachineFunction &MF) {
169 // Terminators and labels can't be scheduled around.
170 if (MI->getDesc().isTerminator() || MI->isLabel())
171 return true;
172
Dan Gohmanbed353d2009-02-10 23:29:38 +0000173 // Don't attempt to schedule around any instruction that modifies
174 // a stack-oriented pointer, as it's unlikely to be profitable. This
175 // saves compile time, because it doesn't require every single
176 // stack slot reference to depend on the instruction that does the
177 // modification.
178 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
179 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
180 return true;
181
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000182 return false;
183}
184
Dan Gohman343f0c02008-11-19 23:18:57 +0000185bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
186 DOUT << "PostRAScheduler\n";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000187
Dan Gohman3f237442008-12-16 03:25:46 +0000188 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
189 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
David Goodwind94a4e52009-08-10 15:55:25 +0000190 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
Dan Gohman2836c282009-01-16 01:33:36 +0000191 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
David Goodwind94a4e52009-08-10 15:55:25 +0000192 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
193 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
Dan Gohman3f237442008-12-16 03:25:46 +0000194
Dan Gohman2836c282009-01-16 01:33:36 +0000195 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
Dan Gohman79ce2762009-01-15 19:20:50 +0000196
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000197 // Loop over all of the basic blocks
198 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000199 MBB != MBBe; ++MBB) {
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000200 // Initialize register live-range state for scheduling in this block.
201 Scheduler.StartBlock(MBB);
202
Dan Gohmanf7119392009-01-16 22:10:20 +0000203 // Schedule each sequence of instructions not interrupted by a label
204 // or anything else that effectively needs to shut down scheduling.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000205 MachineBasicBlock::iterator Current = MBB->end();
Dan Gohman47ac0f02009-02-11 04:27:20 +0000206 unsigned Count = MBB->size(), CurrentCount = Count;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000207 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
208 MachineInstr *MI = prior(I);
209 if (isSchedulingBoundary(MI, Fn)) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000210 Scheduler.Run(MBB, I, Current, CurrentCount);
211 Scheduler.EmitSchedule();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000212 Current = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000213 CurrentCount = Count - 1;
Dan Gohman1274ced2009-03-10 18:10:43 +0000214 Scheduler.Observe(MI, CurrentCount);
Dan Gohmanf7119392009-01-16 22:10:20 +0000215 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000216 I = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000217 --Count;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000218 }
Dan Gohman47ac0f02009-02-11 04:27:20 +0000219 assert(Count == 0 && "Instruction count mismatch!");
Duncan Sands9e8bd0b2009-03-11 09:04:34 +0000220 assert((MBB->begin() == Current || CurrentCount != 0) &&
Dan Gohman1274ced2009-03-10 18:10:43 +0000221 "Instruction count mismatch!");
222 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
Dan Gohman343f0c02008-11-19 23:18:57 +0000223 Scheduler.EmitSchedule();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000224
225 // Clean up register live-range state.
226 Scheduler.FinishBlock();
Dan Gohman343f0c02008-11-19 23:18:57 +0000227 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000228
229 return true;
230}
231
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000232/// StartBlock - Initialize register live-range state for scheduling in
233/// this block.
Dan Gohman21d90032008-11-25 00:52:40 +0000234///
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000235void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
236 // Call the superclass.
237 ScheduleDAGInstrs::StartBlock(BB);
Dan Gohman21d90032008-11-25 00:52:40 +0000238
David Goodwind94a4e52009-08-10 15:55:25 +0000239 // Reset the hazard recognizer.
240 HazardRec->Reset();
241
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000242 // Clear out the register class data.
243 std::fill(Classes, array_endof(Classes),
244 static_cast<const TargetRegisterClass *>(0));
Dan Gohman21d90032008-11-25 00:52:40 +0000245
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000246 // Initialize the indices to indicate that no registers are live.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000247 std::fill(KillIndices, array_endof(KillIndices), ~0u);
Dan Gohman21d90032008-11-25 00:52:40 +0000248 std::fill(DefIndices, array_endof(DefIndices), BB->size());
249
250 // Determine the live-out physregs for this block.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000251 if (!BB->empty() && BB->back().getDesc().isReturn())
Dan Gohman21d90032008-11-25 00:52:40 +0000252 // In a return block, examine the function live-out regs.
253 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
254 E = MRI.liveout_end(); I != E; ++I) {
255 unsigned Reg = *I;
256 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
257 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000258 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000259 // Repeat, for all aliases.
260 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
261 unsigned AliasReg = *Alias;
262 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
263 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000264 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000265 }
266 }
267 else
268 // In a non-return block, examine the live-in regs of all successors.
269 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
Dan Gohman47ac0f02009-02-11 04:27:20 +0000270 SE = BB->succ_end(); SI != SE; ++SI)
Dan Gohman21d90032008-11-25 00:52:40 +0000271 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
272 E = (*SI)->livein_end(); I != E; ++I) {
273 unsigned Reg = *I;
274 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
275 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000276 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000277 // Repeat, for all aliases.
278 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
279 unsigned AliasReg = *Alias;
280 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
281 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000282 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000283 }
284 }
285
286 // Consider callee-saved registers as live-out, since we're running after
287 // prologue/epilogue insertion so there's no way to add additional
288 // saved registers.
289 //
290 // TODO: If the callee saves and restores these, then we can potentially
291 // use them between the save and the restore. To do that, we could scan
292 // the exit blocks to see which of these registers are defined.
Dan Gohman00dc84a2008-12-16 19:27:52 +0000293 // Alternatively, callee-saved registers that aren't saved and restored
Dan Gohmanebb0a312008-12-03 19:30:13 +0000294 // could be marked live-in in every block.
Dan Gohman21d90032008-11-25 00:52:40 +0000295 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
296 unsigned Reg = *I;
297 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
298 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000299 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000300 // Repeat, for all aliases.
301 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
302 unsigned AliasReg = *Alias;
303 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
304 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000305 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000306 }
307 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000308}
309
310/// Schedule - Schedule the instruction range using list scheduling.
311///
312void SchedulePostRATDList::Schedule() {
313 DOUT << "********** List Scheduling **********\n";
314
315 // Build the scheduling graph.
316 BuildSchedGraph();
317
318 if (EnableAntiDepBreaking) {
319 if (BreakAntiDependencies()) {
320 // We made changes. Update the dependency graph.
321 // Theoretically we could update the graph in place:
322 // When a live range is changed to use a different register, remove
323 // the def's anti-dependence *and* output-dependence edges due to
324 // that register, and add new anti-dependence and output-dependence
325 // edges based on the next live range of the register.
326 SUnits.clear();
327 EntrySU = SUnit();
328 ExitSU = SUnit();
329 BuildSchedGraph();
330 }
331 }
332
David Goodwind94a4e52009-08-10 15:55:25 +0000333 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
334 SUnits[su].dumpAll(this));
335
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000336 AvailableQueue.initNodes(SUnits);
337
338 ListScheduleTopDown();
339
340 AvailableQueue.releaseState();
341}
342
343/// Observe - Update liveness information to account for the current
344/// instruction, which will not be scheduled.
345///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000346void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000347 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
348
349 // Any register which was defined within the previous scheduling region
350 // may have been rescheduled and its lifetime may overlap with registers
351 // in ways not reflected in our current liveness state. For each such
352 // register, adjust the liveness state to be conservatively correct.
353 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
354 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
355 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
356 // Mark this register to be non-renamable.
357 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
358 // Move the def index to the end of the previous region, to reflect
359 // that the def could theoretically have been scheduled at the end.
360 DefIndices[Reg] = InsertPosIndex;
361 }
362
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000363 PrescanInstruction(MI);
Dan Gohman47ac0f02009-02-11 04:27:20 +0000364 ScanInstruction(MI, Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000365}
366
367/// FinishBlock - Clean up register live-range state.
368///
369void SchedulePostRATDList::FinishBlock() {
370 RegRefs.clear();
371
372 // Call the superclass.
373 ScheduleDAGInstrs::FinishBlock();
374}
375
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000376/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
377/// critical path.
378static SDep *CriticalPathStep(SUnit *SU) {
379 SDep *Next = 0;
380 unsigned NextDepth = 0;
381 // Find the predecessor edge with the greatest depth.
382 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
383 P != PE; ++P) {
384 SUnit *PredSU = P->getSUnit();
385 unsigned PredLatency = P->getLatency();
386 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
387 // In the case of a latency tie, prefer an anti-dependency edge over
388 // other types of edges.
389 if (NextDepth < PredTotalLatency ||
390 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
391 NextDepth = PredTotalLatency;
392 Next = &*P;
393 }
394 }
395 return Next;
396}
397
398void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
399 // Scan the register operands for this instruction and update
400 // Classes and RegRefs.
401 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
402 MachineOperand &MO = MI->getOperand(i);
403 if (!MO.isReg()) continue;
404 unsigned Reg = MO.getReg();
405 if (Reg == 0) continue;
Chris Lattner2a386882009-07-29 21:36:49 +0000406 const TargetRegisterClass *NewRC = 0;
407
408 if (i < MI->getDesc().getNumOperands())
409 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000410
411 // For now, only allow the register to be changed if its register
412 // class is consistent across all uses.
413 if (!Classes[Reg] && NewRC)
414 Classes[Reg] = NewRC;
415 else if (!NewRC || Classes[Reg] != NewRC)
416 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
417
418 // Now check for aliases.
419 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
420 // If an alias of the reg is used during the live range, give up.
421 // Note that this allows us to skip checking if AntiDepReg
422 // overlaps with any of the aliases, among other things.
423 unsigned AliasReg = *Alias;
424 if (Classes[AliasReg]) {
425 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
426 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
427 }
428 }
429
430 // If we're still willing to consider this register, note the reference.
431 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
432 RegRefs.insert(std::make_pair(Reg, &MO));
433 }
434}
435
436void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
437 unsigned Count) {
438 // Update liveness.
439 // Proceding upwards, registers that are defed but not used in this
440 // instruction are now dead.
441 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
442 MachineOperand &MO = MI->getOperand(i);
443 if (!MO.isReg()) continue;
444 unsigned Reg = MO.getReg();
445 if (Reg == 0) continue;
446 if (!MO.isDef()) continue;
447 // Ignore two-addr defs.
Bob Wilsond9df5012009-04-09 17:16:43 +0000448 if (MI->isRegTiedToUseOperand(i)) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000449
450 DefIndices[Reg] = Count;
451 KillIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000452 assert(((KillIndices[Reg] == ~0u) !=
453 (DefIndices[Reg] == ~0u)) &&
454 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000455 Classes[Reg] = 0;
456 RegRefs.erase(Reg);
457 // Repeat, for all subregs.
458 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
459 *Subreg; ++Subreg) {
460 unsigned SubregReg = *Subreg;
461 DefIndices[SubregReg] = Count;
462 KillIndices[SubregReg] = ~0u;
463 Classes[SubregReg] = 0;
464 RegRefs.erase(SubregReg);
465 }
466 // Conservatively mark super-registers as unusable.
467 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
468 *Super; ++Super) {
469 unsigned SuperReg = *Super;
470 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
471 }
472 }
473 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
474 MachineOperand &MO = MI->getOperand(i);
475 if (!MO.isReg()) continue;
476 unsigned Reg = MO.getReg();
477 if (Reg == 0) continue;
478 if (!MO.isUse()) continue;
479
Chris Lattner2a386882009-07-29 21:36:49 +0000480 const TargetRegisterClass *NewRC = 0;
481 if (i < MI->getDesc().getNumOperands())
482 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000483
484 // For now, only allow the register to be changed if its register
485 // class is consistent across all uses.
486 if (!Classes[Reg] && NewRC)
487 Classes[Reg] = NewRC;
488 else if (!NewRC || Classes[Reg] != NewRC)
489 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
490
491 RegRefs.insert(std::make_pair(Reg, &MO));
492
493 // It wasn't previously live but now it is, this is a kill.
494 if (KillIndices[Reg] == ~0u) {
495 KillIndices[Reg] = Count;
496 DefIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000497 assert(((KillIndices[Reg] == ~0u) !=
498 (DefIndices[Reg] == ~0u)) &&
499 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000500 }
501 // Repeat, for all aliases.
502 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
503 unsigned AliasReg = *Alias;
504 if (KillIndices[AliasReg] == ~0u) {
505 KillIndices[AliasReg] = Count;
506 DefIndices[AliasReg] = ~0u;
507 }
508 }
509 }
510}
511
512/// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
513/// of the ScheduleDAG and break them by renaming registers.
514///
515bool SchedulePostRATDList::BreakAntiDependencies() {
516 // The code below assumes that there is at least one instruction,
517 // so just duck out immediately if the block is empty.
518 if (SUnits.empty()) return false;
519
520 // Find the node at the bottom of the critical path.
521 SUnit *Max = 0;
522 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
523 SUnit *SU = &SUnits[i];
524 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
525 Max = SU;
526 }
527
528 DOUT << "Critical path has total latency "
529 << (Max->getDepth() + Max->Latency) << "\n";
530
531 // Track progress along the critical path through the SUnit graph as we walk
532 // the instructions.
533 SUnit *CriticalPathSU = Max;
534 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
Dan Gohman21d90032008-11-25 00:52:40 +0000535
536 // Consider this pattern:
537 // A = ...
538 // ... = A
539 // A = ...
540 // ... = A
541 // A = ...
542 // ... = A
543 // A = ...
544 // ... = A
545 // There are three anti-dependencies here, and without special care,
546 // we'd break all of them using the same register:
547 // A = ...
548 // ... = A
549 // B = ...
550 // ... = B
551 // B = ...
552 // ... = B
553 // B = ...
554 // ... = B
555 // because at each anti-dependence, B is the first register that
556 // isn't A which is free. This re-introduces anti-dependencies
557 // at all but one of the original anti-dependencies that we were
558 // trying to break. To avoid this, keep track of the most recent
559 // register that each register was replaced with, avoid avoid
560 // using it to repair an anti-dependence on the same register.
561 // This lets us produce this:
562 // A = ...
563 // ... = A
564 // B = ...
565 // ... = B
566 // C = ...
567 // ... = C
568 // B = ...
569 // ... = B
570 // This still has an anti-dependence on B, but at least it isn't on the
571 // original critical path.
572 //
573 // TODO: If we tracked more than one register here, we could potentially
574 // fix that remaining critical edge too. This is a little more involved,
575 // because unlike the most recent register, less recent registers should
576 // still be considered, though only if no other registers are available.
577 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
578
Dan Gohman21d90032008-11-25 00:52:40 +0000579 // Attempt to break anti-dependence edges on the critical path. Walk the
580 // instructions from the bottom up, tracking information about liveness
581 // as we go to help determine which registers are available.
582 bool Changed = false;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000583 unsigned Count = InsertPosIndex - 1;
584 for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000585 I != E; --Count) {
586 MachineInstr *MI = --I;
Dan Gohman21d90032008-11-25 00:52:40 +0000587
Dan Gohman490b1832008-12-05 05:30:02 +0000588 // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
589 // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
590 // is left behind appearing to clobber the super-register, while the
591 // subregister needs to remain live. So we just ignore them.
592 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
593 continue;
594
Dan Gohman00dc84a2008-12-16 19:27:52 +0000595 // Check if this instruction has a dependence on the critical path that
596 // is an anti-dependence that we may be able to break. If it is, set
597 // AntiDepReg to the non-zero register associated with the anti-dependence.
598 //
599 // We limit our attention to the critical path as a heuristic to avoid
600 // breaking anti-dependence edges that aren't going to significantly
601 // impact the overall schedule. There are a limited number of registers
602 // and we want to save them for the important edges.
603 //
604 // TODO: Instructions with multiple defs could have multiple
605 // anti-dependencies. The current code here only knows how to break one
606 // edge per instruction. Note that we'd have to be able to break all of
607 // the anti-dependencies in an instruction in order to be effective.
608 unsigned AntiDepReg = 0;
609 if (MI == CriticalPathMI) {
610 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
611 SUnit *NextSU = Edge->getSUnit();
612
613 // Only consider anti-dependence edges.
614 if (Edge->getKind() == SDep::Anti) {
615 AntiDepReg = Edge->getReg();
616 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
617 // Don't break anti-dependencies on non-allocatable registers.
Dan Gohman49bb50e2009-01-16 21:57:43 +0000618 if (!AllocatableSet.test(AntiDepReg))
619 AntiDepReg = 0;
620 else {
Dan Gohman00dc84a2008-12-16 19:27:52 +0000621 // If the SUnit has other dependencies on the SUnit that it
622 // anti-depends on, don't bother breaking the anti-dependency
623 // since those edges would prevent such units from being
624 // scheduled past each other regardless.
625 //
626 // Also, if there are dependencies on other SUnits with the
627 // same register as the anti-dependency, don't attempt to
628 // break it.
629 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
630 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
631 if (P->getSUnit() == NextSU ?
632 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
633 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
634 AntiDepReg = 0;
635 break;
636 }
637 }
638 }
639 CriticalPathSU = NextSU;
640 CriticalPathMI = CriticalPathSU->getInstr();
641 } else {
642 // We've reached the end of the critical path.
643 CriticalPathSU = 0;
644 CriticalPathMI = 0;
645 }
646 }
Dan Gohman21d90032008-11-25 00:52:40 +0000647
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000648 PrescanInstruction(MI);
649
650 // If this instruction has a use of AntiDepReg, breaking it
651 // is invalid.
Dan Gohman21d90032008-11-25 00:52:40 +0000652 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
653 MachineOperand &MO = MI->getOperand(i);
654 if (!MO.isReg()) continue;
655 unsigned Reg = MO.getReg();
656 if (Reg == 0) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000657 if (MO.isUse() && AntiDepReg == Reg) {
Dan Gohman21d90032008-11-25 00:52:40 +0000658 AntiDepReg = 0;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000659 break;
Dan Gohman21d90032008-11-25 00:52:40 +0000660 }
Dan Gohman21d90032008-11-25 00:52:40 +0000661 }
662
663 // Determine AntiDepReg's register class, if it is live and is
664 // consistently used within a single class.
665 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
Nick Lewyckya89d1022008-11-27 17:29:52 +0000666 assert((AntiDepReg == 0 || RC != NULL) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000667 "Register should be live if it's causing an anti-dependence!");
668 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
669 AntiDepReg = 0;
670
671 // Look for a suitable register to use to break the anti-depenence.
672 //
673 // TODO: Instead of picking the first free register, consider which might
674 // be the best.
675 if (AntiDepReg != 0) {
Dan Gohman79ce2762009-01-15 19:20:50 +0000676 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
677 RE = RC->allocation_order_end(MF); R != RE; ++R) {
Dan Gohman21d90032008-11-25 00:52:40 +0000678 unsigned NewReg = *R;
679 // Don't replace a register with itself.
680 if (NewReg == AntiDepReg) continue;
681 // Don't replace a register with one that was recently used to repair
682 // an anti-dependence with this AntiDepReg, because that would
683 // re-introduce that anti-dependence.
684 if (NewReg == LastNewReg[AntiDepReg]) continue;
685 // If NewReg is dead and NewReg's most recent def is not before
686 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000687 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000688 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman6c3643c2008-12-19 22:23:43 +0000689 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000690 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman6c3643c2008-12-19 22:23:43 +0000691 if (KillIndices[NewReg] == ~0u &&
Dan Gohmanfde221f2008-12-16 06:20:58 +0000692 Classes[NewReg] != reinterpret_cast<TargetRegisterClass *>(-1) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000693 KillIndices[AntiDepReg] <= DefIndices[NewReg]) {
Dan Gohman80e201b2008-12-04 02:15:26 +0000694 DOUT << "Breaking anti-dependence edge on "
695 << TRI->getName(AntiDepReg)
Dan Gohmancef874a2008-12-03 23:07:27 +0000696 << " with " << RegRefs.count(AntiDepReg) << " references"
Dan Gohman80e201b2008-12-04 02:15:26 +0000697 << " using " << TRI->getName(NewReg) << "!\n";
Dan Gohman21d90032008-11-25 00:52:40 +0000698
699 // Update the references to the old register to refer to the new
700 // register.
701 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
702 std::multimap<unsigned, MachineOperand *>::iterator>
703 Range = RegRefs.equal_range(AntiDepReg);
704 for (std::multimap<unsigned, MachineOperand *>::iterator
705 Q = Range.first, QE = Range.second; Q != QE; ++Q)
706 Q->second->setReg(NewReg);
707
708 // We just went back in time and modified history; the
709 // liveness information for the anti-depenence reg is now
710 // inconsistent. Set the state as if it were dead.
711 Classes[NewReg] = Classes[AntiDepReg];
712 DefIndices[NewReg] = DefIndices[AntiDepReg];
713 KillIndices[NewReg] = KillIndices[AntiDepReg];
Dan Gohman47ac0f02009-02-11 04:27:20 +0000714 assert(((KillIndices[NewReg] == ~0u) !=
715 (DefIndices[NewReg] == ~0u)) &&
716 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000717
718 Classes[AntiDepReg] = 0;
719 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
Dan Gohman6c3643c2008-12-19 22:23:43 +0000720 KillIndices[AntiDepReg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000721 assert(((KillIndices[AntiDepReg] == ~0u) !=
722 (DefIndices[AntiDepReg] == ~0u)) &&
723 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000724
725 RegRefs.erase(AntiDepReg);
726 Changed = true;
727 LastNewReg[AntiDepReg] = NewReg;
728 break;
729 }
730 }
731 }
732
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000733 ScanInstruction(MI, Count);
Dan Gohman21d90032008-11-25 00:52:40 +0000734 }
Dan Gohman21d90032008-11-25 00:52:40 +0000735
736 return Changed;
737}
738
Dan Gohman343f0c02008-11-19 23:18:57 +0000739//===----------------------------------------------------------------------===//
740// Top-Down Scheduling
741//===----------------------------------------------------------------------===//
742
743/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
744/// the PendingQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman54e4c362008-12-09 22:54:47 +0000745void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
746 SUnit *SuccSU = SuccEdge->getSUnit();
Dan Gohman343f0c02008-11-19 23:18:57 +0000747 --SuccSU->NumPredsLeft;
748
749#ifndef NDEBUG
750 if (SuccSU->NumPredsLeft < 0) {
751 cerr << "*** Scheduling failed! ***\n";
752 SuccSU->dump(this);
753 cerr << " has been released too many times!\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000754 llvm_unreachable(0);
Dan Gohman343f0c02008-11-19 23:18:57 +0000755 }
756#endif
757
758 // Compute how many cycles it will be before this actually becomes
759 // available. This is the max of the start time of all predecessors plus
760 // their latencies.
Dan Gohman3f237442008-12-16 03:25:46 +0000761 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
Dan Gohman343f0c02008-11-19 23:18:57 +0000762
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000763 // If all the node's predecessors are scheduled, this node is ready
764 // to be scheduled. Ignore the special ExitSU node.
765 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Dan Gohman343f0c02008-11-19 23:18:57 +0000766 PendingQueue.push_back(SuccSU);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000767}
768
769/// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
770void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
771 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
772 I != E; ++I)
773 ReleaseSucc(SU, &*I);
Dan Gohman343f0c02008-11-19 23:18:57 +0000774}
775
776/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
777/// count of its successors. If a successor pending count is zero, add it to
778/// the Available queue.
779void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
780 DOUT << "*** Scheduling [" << CurCycle << "]: ";
781 DEBUG(SU->dump(this));
782
783 Sequence.push_back(SU);
Dan Gohman3f237442008-12-16 03:25:46 +0000784 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
785 SU->setDepthToAtLeast(CurCycle);
Dan Gohman343f0c02008-11-19 23:18:57 +0000786
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000787 ReleaseSuccessors(SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000788 SU->isScheduled = true;
789 AvailableQueue.ScheduledNode(SU);
790}
791
792/// ListScheduleTopDown - The main loop of list scheduling for top-down
793/// schedulers.
794void SchedulePostRATDList::ListScheduleTopDown() {
795 unsigned CurCycle = 0;
796
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000797 // Release any successors of the special Entry node.
798 ReleaseSuccessors(&EntrySU);
799
Dan Gohman343f0c02008-11-19 23:18:57 +0000800 // All leaves to Available queue.
801 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
802 // It is available if it has no predecessors.
803 if (SUnits[i].Preds.empty()) {
804 AvailableQueue.push(&SUnits[i]);
805 SUnits[i].isAvailable = true;
806 }
807 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000808
Dan Gohman343f0c02008-11-19 23:18:57 +0000809 // While Available queue is not empty, grab the node with the highest
810 // priority. If it is not ready put it back. Schedule the node.
Dan Gohman2836c282009-01-16 01:33:36 +0000811 std::vector<SUnit*> NotReady;
Dan Gohman343f0c02008-11-19 23:18:57 +0000812 Sequence.reserve(SUnits.size());
813 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
814 // Check to see if any of the pending instructions are ready to issue. If
815 // so, add them to the available queue.
Dan Gohman3f237442008-12-16 03:25:46 +0000816 unsigned MinDepth = ~0u;
Dan Gohman343f0c02008-11-19 23:18:57 +0000817 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman3f237442008-12-16 03:25:46 +0000818 if (PendingQueue[i]->getDepth() <= CurCycle) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000819 AvailableQueue.push(PendingQueue[i]);
820 PendingQueue[i]->isAvailable = true;
821 PendingQueue[i] = PendingQueue.back();
822 PendingQueue.pop_back();
823 --i; --e;
Dan Gohman3f237442008-12-16 03:25:46 +0000824 } else if (PendingQueue[i]->getDepth() < MinDepth)
825 MinDepth = PendingQueue[i]->getDepth();
Dan Gohman343f0c02008-11-19 23:18:57 +0000826 }
827
Dan Gohman2836c282009-01-16 01:33:36 +0000828 SUnit *FoundSUnit = 0;
829
830 bool HasNoopHazards = false;
831 while (!AvailableQueue.empty()) {
832 SUnit *CurSUnit = AvailableQueue.pop();
833
834 ScheduleHazardRecognizer::HazardType HT =
835 HazardRec->getHazardType(CurSUnit);
836 if (HT == ScheduleHazardRecognizer::NoHazard) {
837 FoundSUnit = CurSUnit;
838 break;
839 }
840
841 // Remember if this is a noop hazard.
842 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
843
844 NotReady.push_back(CurSUnit);
845 }
846
847 // Add the nodes that aren't ready back onto the available list.
848 if (!NotReady.empty()) {
849 AvailableQueue.push_all(NotReady);
850 NotReady.clear();
851 }
852
Dan Gohman343f0c02008-11-19 23:18:57 +0000853 // If we found a node to schedule, do it now.
854 if (FoundSUnit) {
855 ScheduleNodeTopDown(FoundSUnit, CurCycle);
Dan Gohman2836c282009-01-16 01:33:36 +0000856 HazardRec->EmitInstruction(FoundSUnit);
Dan Gohman343f0c02008-11-19 23:18:57 +0000857
David Goodwind94a4e52009-08-10 15:55:25 +0000858 // If we are using the target-specific hazards, then don't
859 // advance the cycle time just because we schedule a node. If
860 // the target allows it we can schedule multiple nodes in the
861 // same cycle.
862 if (!EnablePostRAHazardAvoidance) {
863 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
864 ++CurCycle;
865 }
Dan Gohman2836c282009-01-16 01:33:36 +0000866 } else if (!HasNoopHazards) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000867 // Otherwise, we have a pipeline stall, but no other problem, just advance
868 // the current cycle and try again.
869 DOUT << "*** Advancing cycle, no work to do\n";
Dan Gohman2836c282009-01-16 01:33:36 +0000870 HazardRec->AdvanceCycle();
Dan Gohman343f0c02008-11-19 23:18:57 +0000871 ++NumStalls;
872 ++CurCycle;
Dan Gohman2836c282009-01-16 01:33:36 +0000873 } else {
874 // Otherwise, we have no instructions to issue and we have instructions
875 // that will fault if we don't do this right. This is the case for
876 // processors without pipeline interlocks and other cases.
877 DOUT << "*** Emitting noop\n";
878 HazardRec->EmitNoop();
879 Sequence.push_back(0); // NULL here means noop
880 ++NumNoops;
881 ++CurCycle;
Dan Gohman343f0c02008-11-19 23:18:57 +0000882 }
883 }
884
885#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +0000886 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +0000887#endif
888}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000889
890//===----------------------------------------------------------------------===//
891// Public Constructor Functions
892//===----------------------------------------------------------------------===//
893
894FunctionPass *llvm::createPostRAScheduler() {
Dan Gohman343f0c02008-11-19 23:18:57 +0000895 return new PostRAScheduler();
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000896}