blob: 5042415c2cf37ced76d12ef9a9fd9cef25379f18 [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"
David Goodwin3a5f0d42009-08-11 01:44:26 +000040#include "llvm/Support/raw_ostream.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000041#include "llvm/ADT/Statistic.h"
Dan Gohman21d90032008-11-25 00:52:40 +000042#include <map>
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000043using namespace llvm;
44
Dan Gohman2836c282009-01-16 01:33:36 +000045STATISTIC(NumNoops, "Number of noops inserted");
Dan Gohman343f0c02008-11-19 23:18:57 +000046STATISTIC(NumStalls, "Number of pipeline stalls");
47
Dan Gohman21d90032008-11-25 00:52:40 +000048static cl::opt<bool>
49EnableAntiDepBreaking("break-anti-dependencies",
Dan Gohman00dc84a2008-12-16 19:27:52 +000050 cl::desc("Break post-RA scheduling anti-dependencies"),
51 cl::init(true), cl::Hidden);
Dan Gohman21d90032008-11-25 00:52:40 +000052
Dan Gohman2836c282009-01-16 01:33:36 +000053static cl::opt<bool>
54EnablePostRAHazardAvoidance("avoid-hazards",
David Goodwind94a4e52009-08-10 15:55:25 +000055 cl::desc("Enable exact hazard avoidance"),
56 cl::init(false), cl::Hidden);
Dan Gohman2836c282009-01-16 01:33:36 +000057
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000058namespace {
Dan Gohman343f0c02008-11-19 23:18:57 +000059 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000060 public:
61 static char ID;
Dan Gohman343f0c02008-11-19 23:18:57 +000062 PostRAScheduler() : MachineFunctionPass(&ID) {}
Dan Gohman21d90032008-11-25 00:52:40 +000063
Dan Gohman3f237442008-12-16 03:25:46 +000064 void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000065 AU.setPreservesCFG();
Dan Gohman3f237442008-12-16 03:25:46 +000066 AU.addRequired<MachineDominatorTree>();
67 AU.addPreserved<MachineDominatorTree>();
68 AU.addRequired<MachineLoopInfo>();
69 AU.addPreserved<MachineLoopInfo>();
70 MachineFunctionPass::getAnalysisUsage(AU);
71 }
72
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000073 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +000074 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000075 }
76
77 bool runOnMachineFunction(MachineFunction &Fn);
78 };
Dan Gohman343f0c02008-11-19 23:18:57 +000079 char PostRAScheduler::ID = 0;
80
81 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +000082 /// AvailableQueue - The priority queue to use for the available SUnits.
83 ///
84 LatencyPriorityQueue AvailableQueue;
85
86 /// PendingQueue - This contains all of the instructions whose operands have
87 /// been issued, but their results are not ready yet (due to the latency of
88 /// the operation). Once the operands becomes available, the instruction is
89 /// added to the AvailableQueue.
90 std::vector<SUnit*> PendingQueue;
91
Dan Gohman21d90032008-11-25 00:52:40 +000092 /// Topo - A topological ordering for SUnits.
93 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +000094
Dan Gohman79ce2762009-01-15 19:20:50 +000095 /// AllocatableSet - The set of allocatable registers.
96 /// We'll be ignoring anti-dependencies on non-allocatable registers,
97 /// because they may not be safe to break.
98 const BitVector AllocatableSet;
99
Dan Gohman2836c282009-01-16 01:33:36 +0000100 /// HazardRec - The hazard recognizer to use.
101 ScheduleHazardRecognizer *HazardRec;
102
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000103 /// Classes - For live regs that are only used in one register class in a
104 /// live range, the register class. If the register is not live, the
105 /// corresponding value is null. If the register is live but used in
106 /// multiple register classes, the corresponding value is -1 casted to a
107 /// pointer.
108 const TargetRegisterClass *
109 Classes[TargetRegisterInfo::FirstVirtualRegister];
110
111 /// RegRegs - Map registers to all their references within a live range.
112 std::multimap<unsigned, MachineOperand *> RegRefs;
113
114 /// The index of the most recent kill (proceding bottom-up), or ~0u if
115 /// the register is not live.
116 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
117
118 /// The index of the most recent complete def (proceding bottom up), or ~0u
119 /// if the register is live.
120 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
121
Dan Gohman21d90032008-11-25 00:52:40 +0000122 public:
Dan Gohman79ce2762009-01-15 19:20:50 +0000123 SchedulePostRATDList(MachineFunction &MF,
Dan Gohman3f237442008-12-16 03:25:46 +0000124 const MachineLoopInfo &MLI,
Dan Gohman2836c282009-01-16 01:33:36 +0000125 const MachineDominatorTree &MDT,
126 ScheduleHazardRecognizer *HR)
Dan Gohman79ce2762009-01-15 19:20:50 +0000127 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
Dan Gohman2836c282009-01-16 01:33:36 +0000128 AllocatableSet(TRI->getAllocatableSet(MF)),
129 HazardRec(HR) {}
130
131 ~SchedulePostRATDList() {
132 delete HazardRec;
133 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000134
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000135 /// StartBlock - Initialize register live-range state for scheduling in
136 /// this block.
137 ///
138 void StartBlock(MachineBasicBlock *BB);
139
140 /// Schedule - Schedule the instruction range using list scheduling.
141 ///
Dan Gohman343f0c02008-11-19 23:18:57 +0000142 void Schedule();
143
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000144 /// Observe - Update liveness information to account for the current
145 /// instruction, which will not be scheduled.
146 ///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000147 void Observe(MachineInstr *MI, unsigned Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000148
149 /// FinishBlock - Clean up register live-range state.
150 ///
151 void FinishBlock();
152
Dan Gohman343f0c02008-11-19 23:18:57 +0000153 private:
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000154 void PrescanInstruction(MachineInstr *MI);
155 void ScanInstruction(MachineInstr *MI, unsigned Count);
Dan Gohman54e4c362008-12-09 22:54:47 +0000156 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000157 void ReleaseSuccessors(SUnit *SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000158 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
159 void ListScheduleTopDown();
Dan Gohman21d90032008-11-25 00:52:40 +0000160 bool BreakAntiDependencies();
Dan Gohman26255ad2009-08-12 01:33:27 +0000161 unsigned findSuitableFreeRegister(unsigned AntiDepReg,
162 unsigned LastNewReg,
163 const TargetRegisterClass *);
Dan Gohman343f0c02008-11-19 23:18:57 +0000164 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000165}
166
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000167/// isSchedulingBoundary - Test if the given instruction should be
168/// considered a scheduling boundary. This primarily includes labels
169/// and terminators.
170///
171static bool isSchedulingBoundary(const MachineInstr *MI,
172 const MachineFunction &MF) {
173 // Terminators and labels can't be scheduled around.
174 if (MI->getDesc().isTerminator() || MI->isLabel())
175 return true;
176
Dan Gohmanbed353d2009-02-10 23:29:38 +0000177 // Don't attempt to schedule around any instruction that modifies
178 // a stack-oriented pointer, as it's unlikely to be profitable. This
179 // saves compile time, because it doesn't require every single
180 // stack slot reference to depend on the instruction that does the
181 // modification.
182 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
183 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
184 return true;
185
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000186 return false;
187}
188
Dan Gohman343f0c02008-11-19 23:18:57 +0000189bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000190 DEBUG(errs() << "PostRAScheduler\n");
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000191
Dan Gohman3f237442008-12-16 03:25:46 +0000192 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
193 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
David Goodwind94a4e52009-08-10 15:55:25 +0000194 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
Dan Gohman2836c282009-01-16 01:33:36 +0000195 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
David Goodwind94a4e52009-08-10 15:55:25 +0000196 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
197 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
Dan Gohman3f237442008-12-16 03:25:46 +0000198
Dan Gohman2836c282009-01-16 01:33:36 +0000199 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
Dan Gohman79ce2762009-01-15 19:20:50 +0000200
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000201 // Loop over all of the basic blocks
202 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000203 MBB != MBBe; ++MBB) {
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000204 // Initialize register live-range state for scheduling in this block.
205 Scheduler.StartBlock(MBB);
206
Dan Gohmanf7119392009-01-16 22:10:20 +0000207 // Schedule each sequence of instructions not interrupted by a label
208 // or anything else that effectively needs to shut down scheduling.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000209 MachineBasicBlock::iterator Current = MBB->end();
Dan Gohman47ac0f02009-02-11 04:27:20 +0000210 unsigned Count = MBB->size(), CurrentCount = Count;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000211 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
212 MachineInstr *MI = prior(I);
213 if (isSchedulingBoundary(MI, Fn)) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000214 Scheduler.Run(MBB, I, Current, CurrentCount);
215 Scheduler.EmitSchedule();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000216 Current = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000217 CurrentCount = Count - 1;
Dan Gohman1274ced2009-03-10 18:10:43 +0000218 Scheduler.Observe(MI, CurrentCount);
Dan Gohmanf7119392009-01-16 22:10:20 +0000219 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000220 I = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000221 --Count;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000222 }
Dan Gohman47ac0f02009-02-11 04:27:20 +0000223 assert(Count == 0 && "Instruction count mismatch!");
Duncan Sands9e8bd0b2009-03-11 09:04:34 +0000224 assert((MBB->begin() == Current || CurrentCount != 0) &&
Dan Gohman1274ced2009-03-10 18:10:43 +0000225 "Instruction count mismatch!");
226 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
Dan Gohman343f0c02008-11-19 23:18:57 +0000227 Scheduler.EmitSchedule();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000228
229 // Clean up register live-range state.
230 Scheduler.FinishBlock();
Dan Gohman343f0c02008-11-19 23:18:57 +0000231 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000232
233 return true;
234}
235
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000236/// StartBlock - Initialize register live-range state for scheduling in
237/// this block.
Dan Gohman21d90032008-11-25 00:52:40 +0000238///
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000239void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
240 // Call the superclass.
241 ScheduleDAGInstrs::StartBlock(BB);
Dan Gohman21d90032008-11-25 00:52:40 +0000242
David Goodwind94a4e52009-08-10 15:55:25 +0000243 // Reset the hazard recognizer.
244 HazardRec->Reset();
245
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000246 // Clear out the register class data.
247 std::fill(Classes, array_endof(Classes),
248 static_cast<const TargetRegisterClass *>(0));
Dan Gohman21d90032008-11-25 00:52:40 +0000249
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000250 // Initialize the indices to indicate that no registers are live.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000251 std::fill(KillIndices, array_endof(KillIndices), ~0u);
Dan Gohman21d90032008-11-25 00:52:40 +0000252 std::fill(DefIndices, array_endof(DefIndices), BB->size());
253
254 // Determine the live-out physregs for this block.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000255 if (!BB->empty() && BB->back().getDesc().isReturn())
Dan Gohman21d90032008-11-25 00:52:40 +0000256 // In a return block, examine the function live-out regs.
257 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
258 E = MRI.liveout_end(); I != E; ++I) {
259 unsigned Reg = *I;
260 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
261 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000262 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000263 // Repeat, for all aliases.
264 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
265 unsigned AliasReg = *Alias;
266 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
267 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000268 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000269 }
270 }
271 else
272 // In a non-return block, examine the live-in regs of all successors.
273 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
Dan Gohman47ac0f02009-02-11 04:27:20 +0000274 SE = BB->succ_end(); SI != SE; ++SI)
Dan Gohman21d90032008-11-25 00:52:40 +0000275 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
276 E = (*SI)->livein_end(); I != E; ++I) {
277 unsigned Reg = *I;
278 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
279 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000280 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000281 // Repeat, for all aliases.
282 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
283 unsigned AliasReg = *Alias;
284 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
285 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000286 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000287 }
288 }
289
290 // Consider callee-saved registers as live-out, since we're running after
291 // prologue/epilogue insertion so there's no way to add additional
292 // saved registers.
293 //
294 // TODO: If the callee saves and restores these, then we can potentially
295 // use them between the save and the restore. To do that, we could scan
296 // the exit blocks to see which of these registers are defined.
Dan Gohman00dc84a2008-12-16 19:27:52 +0000297 // Alternatively, callee-saved registers that aren't saved and restored
Dan Gohmanebb0a312008-12-03 19:30:13 +0000298 // could be marked live-in in every block.
Dan Gohman21d90032008-11-25 00:52:40 +0000299 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
300 unsigned Reg = *I;
301 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
302 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000303 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000304 // Repeat, for all aliases.
305 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
306 unsigned AliasReg = *Alias;
307 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
308 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000309 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000310 }
311 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000312}
313
314/// Schedule - Schedule the instruction range using list scheduling.
315///
316void SchedulePostRATDList::Schedule() {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000317 DEBUG(errs() << "********** List Scheduling **********\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000318
319 // Build the scheduling graph.
320 BuildSchedGraph();
321
322 if (EnableAntiDepBreaking) {
323 if (BreakAntiDependencies()) {
324 // We made changes. Update the dependency graph.
325 // Theoretically we could update the graph in place:
326 // When a live range is changed to use a different register, remove
327 // the def's anti-dependence *and* output-dependence edges due to
328 // that register, and add new anti-dependence and output-dependence
329 // edges based on the next live range of the register.
330 SUnits.clear();
331 EntrySU = SUnit();
332 ExitSU = SUnit();
333 BuildSchedGraph();
334 }
335 }
336
David Goodwind94a4e52009-08-10 15:55:25 +0000337 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
338 SUnits[su].dumpAll(this));
339
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000340 AvailableQueue.initNodes(SUnits);
341
342 ListScheduleTopDown();
343
344 AvailableQueue.releaseState();
345}
346
347/// Observe - Update liveness information to account for the current
348/// instruction, which will not be scheduled.
349///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000350void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000351 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
352
353 // Any register which was defined within the previous scheduling region
354 // may have been rescheduled and its lifetime may overlap with registers
355 // in ways not reflected in our current liveness state. For each such
356 // register, adjust the liveness state to be conservatively correct.
357 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
358 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
359 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
360 // Mark this register to be non-renamable.
361 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
362 // Move the def index to the end of the previous region, to reflect
363 // that the def could theoretically have been scheduled at the end.
364 DefIndices[Reg] = InsertPosIndex;
365 }
366
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000367 PrescanInstruction(MI);
Dan Gohman47ac0f02009-02-11 04:27:20 +0000368 ScanInstruction(MI, Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000369}
370
371/// FinishBlock - Clean up register live-range state.
372///
373void SchedulePostRATDList::FinishBlock() {
374 RegRefs.clear();
375
376 // Call the superclass.
377 ScheduleDAGInstrs::FinishBlock();
378}
379
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000380/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
381/// critical path.
382static SDep *CriticalPathStep(SUnit *SU) {
383 SDep *Next = 0;
384 unsigned NextDepth = 0;
385 // Find the predecessor edge with the greatest depth.
386 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
387 P != PE; ++P) {
388 SUnit *PredSU = P->getSUnit();
389 unsigned PredLatency = P->getLatency();
390 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
391 // In the case of a latency tie, prefer an anti-dependency edge over
392 // other types of edges.
393 if (NextDepth < PredTotalLatency ||
394 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
395 NextDepth = PredTotalLatency;
396 Next = &*P;
397 }
398 }
399 return Next;
400}
401
402void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
403 // Scan the register operands for this instruction and update
404 // Classes and RegRefs.
405 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
406 MachineOperand &MO = MI->getOperand(i);
407 if (!MO.isReg()) continue;
408 unsigned Reg = MO.getReg();
409 if (Reg == 0) continue;
Chris Lattner2a386882009-07-29 21:36:49 +0000410 const TargetRegisterClass *NewRC = 0;
411
412 if (i < MI->getDesc().getNumOperands())
413 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000414
415 // For now, only allow the register to be changed if its register
416 // class is consistent across all uses.
417 if (!Classes[Reg] && NewRC)
418 Classes[Reg] = NewRC;
419 else if (!NewRC || Classes[Reg] != NewRC)
420 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
421
422 // Now check for aliases.
423 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
424 // If an alias of the reg is used during the live range, give up.
425 // Note that this allows us to skip checking if AntiDepReg
426 // overlaps with any of the aliases, among other things.
427 unsigned AliasReg = *Alias;
428 if (Classes[AliasReg]) {
429 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
430 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
431 }
432 }
433
434 // If we're still willing to consider this register, note the reference.
435 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
436 RegRefs.insert(std::make_pair(Reg, &MO));
437 }
438}
439
440void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
441 unsigned Count) {
442 // Update liveness.
443 // Proceding upwards, registers that are defed but not used in this
444 // instruction are now dead.
445 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
446 MachineOperand &MO = MI->getOperand(i);
447 if (!MO.isReg()) continue;
448 unsigned Reg = MO.getReg();
449 if (Reg == 0) continue;
450 if (!MO.isDef()) continue;
451 // Ignore two-addr defs.
Bob Wilsond9df5012009-04-09 17:16:43 +0000452 if (MI->isRegTiedToUseOperand(i)) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000453
454 DefIndices[Reg] = Count;
455 KillIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000456 assert(((KillIndices[Reg] == ~0u) !=
457 (DefIndices[Reg] == ~0u)) &&
458 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000459 Classes[Reg] = 0;
460 RegRefs.erase(Reg);
461 // Repeat, for all subregs.
462 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
463 *Subreg; ++Subreg) {
464 unsigned SubregReg = *Subreg;
465 DefIndices[SubregReg] = Count;
466 KillIndices[SubregReg] = ~0u;
467 Classes[SubregReg] = 0;
468 RegRefs.erase(SubregReg);
469 }
470 // Conservatively mark super-registers as unusable.
471 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
472 *Super; ++Super) {
473 unsigned SuperReg = *Super;
474 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
475 }
476 }
477 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
478 MachineOperand &MO = MI->getOperand(i);
479 if (!MO.isReg()) continue;
480 unsigned Reg = MO.getReg();
481 if (Reg == 0) continue;
482 if (!MO.isUse()) continue;
483
Chris Lattner2a386882009-07-29 21:36:49 +0000484 const TargetRegisterClass *NewRC = 0;
485 if (i < MI->getDesc().getNumOperands())
486 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000487
488 // For now, only allow the register to be changed if its register
489 // class is consistent across all uses.
490 if (!Classes[Reg] && NewRC)
491 Classes[Reg] = NewRC;
492 else if (!NewRC || Classes[Reg] != NewRC)
493 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
494
495 RegRefs.insert(std::make_pair(Reg, &MO));
496
497 // It wasn't previously live but now it is, this is a kill.
498 if (KillIndices[Reg] == ~0u) {
499 KillIndices[Reg] = Count;
500 DefIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000501 assert(((KillIndices[Reg] == ~0u) !=
502 (DefIndices[Reg] == ~0u)) &&
503 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000504 }
505 // Repeat, for all aliases.
506 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
507 unsigned AliasReg = *Alias;
508 if (KillIndices[AliasReg] == ~0u) {
509 KillIndices[AliasReg] = Count;
510 DefIndices[AliasReg] = ~0u;
511 }
512 }
513 }
514}
515
Dan Gohman26255ad2009-08-12 01:33:27 +0000516unsigned
517SchedulePostRATDList::findSuitableFreeRegister(unsigned AntiDepReg,
518 unsigned LastNewReg,
519 const TargetRegisterClass *RC) {
520 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
521 RE = RC->allocation_order_end(MF); R != RE; ++R) {
522 unsigned NewReg = *R;
523 // Don't replace a register with itself.
524 if (NewReg == AntiDepReg) continue;
525 // Don't replace a register with one that was recently used to repair
526 // an anti-dependence with this AntiDepReg, because that would
527 // re-introduce that anti-dependence.
528 if (NewReg == LastNewReg) continue;
529 // If NewReg is dead and NewReg's most recent def is not before
530 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
531 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
532 "Kill and Def maps aren't consistent for AntiDepReg!");
533 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
534 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohmanda277572009-08-12 01:44:20 +0000535 if (KillIndices[NewReg] != ~0u ||
536 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
537 KillIndices[AntiDepReg] > DefIndices[NewReg])
Dan Gohman26255ad2009-08-12 01:33:27 +0000538 continue;
539 return NewReg;
540 }
541
542 // No registers are free and available!
543 return 0;
544}
545
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000546/// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
547/// of the ScheduleDAG and break them by renaming registers.
548///
549bool SchedulePostRATDList::BreakAntiDependencies() {
550 // The code below assumes that there is at least one instruction,
551 // so just duck out immediately if the block is empty.
552 if (SUnits.empty()) return false;
553
554 // Find the node at the bottom of the critical path.
555 SUnit *Max = 0;
556 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
557 SUnit *SU = &SUnits[i];
558 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
559 Max = SU;
560 }
561
David Goodwin3a5f0d42009-08-11 01:44:26 +0000562 DEBUG(errs() << "Critical path has total latency "
563 << (Max->getDepth() + Max->Latency) << "\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000564
565 // Track progress along the critical path through the SUnit graph as we walk
566 // the instructions.
567 SUnit *CriticalPathSU = Max;
568 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
Dan Gohman21d90032008-11-25 00:52:40 +0000569
570 // Consider this pattern:
571 // A = ...
572 // ... = A
573 // A = ...
574 // ... = A
575 // A = ...
576 // ... = A
577 // A = ...
578 // ... = A
579 // There are three anti-dependencies here, and without special care,
580 // we'd break all of them using the same register:
581 // A = ...
582 // ... = A
583 // B = ...
584 // ... = B
585 // B = ...
586 // ... = B
587 // B = ...
588 // ... = B
589 // because at each anti-dependence, B is the first register that
590 // isn't A which is free. This re-introduces anti-dependencies
591 // at all but one of the original anti-dependencies that we were
592 // trying to break. To avoid this, keep track of the most recent
David Goodwinc93d8372009-08-11 17:35:23 +0000593 // register that each register was replaced with, avoid
Dan Gohman21d90032008-11-25 00:52:40 +0000594 // using it to repair an anti-dependence on the same register.
595 // This lets us produce this:
596 // A = ...
597 // ... = A
598 // B = ...
599 // ... = B
600 // C = ...
601 // ... = C
602 // B = ...
603 // ... = B
604 // This still has an anti-dependence on B, but at least it isn't on the
605 // original critical path.
606 //
607 // TODO: If we tracked more than one register here, we could potentially
608 // fix that remaining critical edge too. This is a little more involved,
609 // because unlike the most recent register, less recent registers should
610 // still be considered, though only if no other registers are available.
611 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
612
Dan Gohman21d90032008-11-25 00:52:40 +0000613 // Attempt to break anti-dependence edges on the critical path. Walk the
614 // instructions from the bottom up, tracking information about liveness
615 // as we go to help determine which registers are available.
616 bool Changed = false;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000617 unsigned Count = InsertPosIndex - 1;
618 for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000619 I != E; --Count) {
620 MachineInstr *MI = --I;
Dan Gohman21d90032008-11-25 00:52:40 +0000621
Dan Gohman490b1832008-12-05 05:30:02 +0000622 // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
623 // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
624 // is left behind appearing to clobber the super-register, while the
625 // subregister needs to remain live. So we just ignore them.
626 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
627 continue;
628
Dan Gohman00dc84a2008-12-16 19:27:52 +0000629 // Check if this instruction has a dependence on the critical path that
630 // is an anti-dependence that we may be able to break. If it is, set
631 // AntiDepReg to the non-zero register associated with the anti-dependence.
632 //
633 // We limit our attention to the critical path as a heuristic to avoid
634 // breaking anti-dependence edges that aren't going to significantly
635 // impact the overall schedule. There are a limited number of registers
636 // and we want to save them for the important edges.
637 //
638 // TODO: Instructions with multiple defs could have multiple
639 // anti-dependencies. The current code here only knows how to break one
640 // edge per instruction. Note that we'd have to be able to break all of
641 // the anti-dependencies in an instruction in order to be effective.
642 unsigned AntiDepReg = 0;
643 if (MI == CriticalPathMI) {
644 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
645 SUnit *NextSU = Edge->getSUnit();
646
647 // Only consider anti-dependence edges.
648 if (Edge->getKind() == SDep::Anti) {
649 AntiDepReg = Edge->getReg();
650 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
651 // Don't break anti-dependencies on non-allocatable registers.
Dan Gohman49bb50e2009-01-16 21:57:43 +0000652 if (!AllocatableSet.test(AntiDepReg))
653 AntiDepReg = 0;
654 else {
Dan Gohman00dc84a2008-12-16 19:27:52 +0000655 // If the SUnit has other dependencies on the SUnit that it
656 // anti-depends on, don't bother breaking the anti-dependency
657 // since those edges would prevent such units from being
658 // scheduled past each other regardless.
659 //
660 // Also, if there are dependencies on other SUnits with the
661 // same register as the anti-dependency, don't attempt to
662 // break it.
663 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
664 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
665 if (P->getSUnit() == NextSU ?
666 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
667 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
668 AntiDepReg = 0;
669 break;
670 }
671 }
672 }
673 CriticalPathSU = NextSU;
674 CriticalPathMI = CriticalPathSU->getInstr();
675 } else {
676 // We've reached the end of the critical path.
677 CriticalPathSU = 0;
678 CriticalPathMI = 0;
679 }
680 }
Dan Gohman21d90032008-11-25 00:52:40 +0000681
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000682 PrescanInstruction(MI);
683
684 // If this instruction has a use of AntiDepReg, breaking it
685 // is invalid.
Dan Gohman21d90032008-11-25 00:52:40 +0000686 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
687 MachineOperand &MO = MI->getOperand(i);
688 if (!MO.isReg()) continue;
689 unsigned Reg = MO.getReg();
690 if (Reg == 0) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000691 if (MO.isUse() && AntiDepReg == Reg) {
Dan Gohman21d90032008-11-25 00:52:40 +0000692 AntiDepReg = 0;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000693 break;
Dan Gohman21d90032008-11-25 00:52:40 +0000694 }
Dan Gohman21d90032008-11-25 00:52:40 +0000695 }
696
697 // Determine AntiDepReg's register class, if it is live and is
698 // consistently used within a single class.
699 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
Nick Lewyckya89d1022008-11-27 17:29:52 +0000700 assert((AntiDepReg == 0 || RC != NULL) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000701 "Register should be live if it's causing an anti-dependence!");
702 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
703 AntiDepReg = 0;
704
705 // Look for a suitable register to use to break the anti-depenence.
706 //
707 // TODO: Instead of picking the first free register, consider which might
708 // be the best.
709 if (AntiDepReg != 0) {
Dan Gohman26255ad2009-08-12 01:33:27 +0000710 if (unsigned NewReg = findSuitableFreeRegister(AntiDepReg,
711 LastNewReg[AntiDepReg],
712 RC)) {
713 DEBUG(errs() << "Breaking anti-dependence edge on "
714 << TRI->getName(AntiDepReg)
715 << " with " << RegRefs.count(AntiDepReg) << " references"
716 << " using " << TRI->getName(NewReg) << "!\n");
Dan Gohman21d90032008-11-25 00:52:40 +0000717
Dan Gohman26255ad2009-08-12 01:33:27 +0000718 // Update the references to the old register to refer to the new
719 // register.
720 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
721 std::multimap<unsigned, MachineOperand *>::iterator>
722 Range = RegRefs.equal_range(AntiDepReg);
723 for (std::multimap<unsigned, MachineOperand *>::iterator
724 Q = Range.first, QE = Range.second; Q != QE; ++Q)
725 Q->second->setReg(NewReg);
Dan Gohman21d90032008-11-25 00:52:40 +0000726
Dan Gohman26255ad2009-08-12 01:33:27 +0000727 // We just went back in time and modified history; the
728 // liveness information for the anti-depenence reg is now
729 // inconsistent. Set the state as if it were dead.
730 Classes[NewReg] = Classes[AntiDepReg];
731 DefIndices[NewReg] = DefIndices[AntiDepReg];
732 KillIndices[NewReg] = KillIndices[AntiDepReg];
733 assert(((KillIndices[NewReg] == ~0u) !=
734 (DefIndices[NewReg] == ~0u)) &&
735 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000736
Dan Gohman26255ad2009-08-12 01:33:27 +0000737 Classes[AntiDepReg] = 0;
738 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
739 KillIndices[AntiDepReg] = ~0u;
740 assert(((KillIndices[AntiDepReg] == ~0u) !=
741 (DefIndices[AntiDepReg] == ~0u)) &&
742 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000743
Dan Gohman26255ad2009-08-12 01:33:27 +0000744 RegRefs.erase(AntiDepReg);
745 Changed = true;
746 LastNewReg[AntiDepReg] = NewReg;
Dan Gohman21d90032008-11-25 00:52:40 +0000747 }
748 }
749
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000750 ScanInstruction(MI, Count);
Dan Gohman21d90032008-11-25 00:52:40 +0000751 }
Dan Gohman21d90032008-11-25 00:52:40 +0000752
753 return Changed;
754}
755
Dan Gohman343f0c02008-11-19 23:18:57 +0000756//===----------------------------------------------------------------------===//
757// Top-Down Scheduling
758//===----------------------------------------------------------------------===//
759
760/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
761/// the PendingQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman54e4c362008-12-09 22:54:47 +0000762void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
763 SUnit *SuccSU = SuccEdge->getSUnit();
Dan Gohman343f0c02008-11-19 23:18:57 +0000764 --SuccSU->NumPredsLeft;
765
766#ifndef NDEBUG
767 if (SuccSU->NumPredsLeft < 0) {
Chris Lattner103289e2009-08-23 07:19:13 +0000768 errs() << "*** Scheduling failed! ***\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000769 SuccSU->dump(this);
Chris Lattner103289e2009-08-23 07:19:13 +0000770 errs() << " has been released too many times!\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000771 llvm_unreachable(0);
Dan Gohman343f0c02008-11-19 23:18:57 +0000772 }
773#endif
774
775 // Compute how many cycles it will be before this actually becomes
776 // available. This is the max of the start time of all predecessors plus
777 // their latencies.
Dan Gohman3f237442008-12-16 03:25:46 +0000778 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
Dan Gohman343f0c02008-11-19 23:18:57 +0000779
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000780 // If all the node's predecessors are scheduled, this node is ready
781 // to be scheduled. Ignore the special ExitSU node.
782 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Dan Gohman343f0c02008-11-19 23:18:57 +0000783 PendingQueue.push_back(SuccSU);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000784}
785
786/// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
787void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
788 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
789 I != E; ++I)
790 ReleaseSucc(SU, &*I);
Dan Gohman343f0c02008-11-19 23:18:57 +0000791}
792
793/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
794/// count of its successors. If a successor pending count is zero, add it to
795/// the Available queue.
796void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000797 DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman343f0c02008-11-19 23:18:57 +0000798 DEBUG(SU->dump(this));
799
800 Sequence.push_back(SU);
Dan Gohman3f237442008-12-16 03:25:46 +0000801 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
802 SU->setDepthToAtLeast(CurCycle);
Dan Gohman343f0c02008-11-19 23:18:57 +0000803
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000804 ReleaseSuccessors(SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000805 SU->isScheduled = true;
806 AvailableQueue.ScheduledNode(SU);
807}
808
809/// ListScheduleTopDown - The main loop of list scheduling for top-down
810/// schedulers.
811void SchedulePostRATDList::ListScheduleTopDown() {
812 unsigned CurCycle = 0;
813
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000814 // Release any successors of the special Entry node.
815 ReleaseSuccessors(&EntrySU);
816
Dan Gohman343f0c02008-11-19 23:18:57 +0000817 // All leaves to Available queue.
818 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
819 // It is available if it has no predecessors.
820 if (SUnits[i].Preds.empty()) {
821 AvailableQueue.push(&SUnits[i]);
822 SUnits[i].isAvailable = true;
823 }
824 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000825
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000826 // In any cycle where we can't schedule any instructions, we must
827 // stall or emit a noop, depending on the target.
828 bool CycleInstCnt = 0;
829
Dan Gohman343f0c02008-11-19 23:18:57 +0000830 // While Available queue is not empty, grab the node with the highest
831 // priority. If it is not ready put it back. Schedule the node.
Dan Gohman2836c282009-01-16 01:33:36 +0000832 std::vector<SUnit*> NotReady;
Dan Gohman343f0c02008-11-19 23:18:57 +0000833 Sequence.reserve(SUnits.size());
834 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
835 // Check to see if any of the pending instructions are ready to issue. If
836 // so, add them to the available queue.
Dan Gohman3f237442008-12-16 03:25:46 +0000837 unsigned MinDepth = ~0u;
Dan Gohman343f0c02008-11-19 23:18:57 +0000838 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman3f237442008-12-16 03:25:46 +0000839 if (PendingQueue[i]->getDepth() <= CurCycle) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000840 AvailableQueue.push(PendingQueue[i]);
841 PendingQueue[i]->isAvailable = true;
842 PendingQueue[i] = PendingQueue.back();
843 PendingQueue.pop_back();
844 --i; --e;
Dan Gohman3f237442008-12-16 03:25:46 +0000845 } else if (PendingQueue[i]->getDepth() < MinDepth)
846 MinDepth = PendingQueue[i]->getDepth();
Dan Gohman343f0c02008-11-19 23:18:57 +0000847 }
David Goodwinc93d8372009-08-11 17:35:23 +0000848
David Goodwin7cd01182009-08-11 17:56:42 +0000849 DEBUG(errs() << "\n*** Examining Available\n";
850 LatencyPriorityQueue q = AvailableQueue;
851 while (!q.empty()) {
852 SUnit *su = q.pop();
853 errs() << "Height " << su->getHeight() << ": ";
854 su->dump(this);
855 });
David Goodwinc93d8372009-08-11 17:35:23 +0000856
Dan Gohman2836c282009-01-16 01:33:36 +0000857 SUnit *FoundSUnit = 0;
858
859 bool HasNoopHazards = false;
860 while (!AvailableQueue.empty()) {
861 SUnit *CurSUnit = AvailableQueue.pop();
862
863 ScheduleHazardRecognizer::HazardType HT =
864 HazardRec->getHazardType(CurSUnit);
865 if (HT == ScheduleHazardRecognizer::NoHazard) {
866 FoundSUnit = CurSUnit;
867 break;
868 }
869
870 // Remember if this is a noop hazard.
871 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
872
873 NotReady.push_back(CurSUnit);
874 }
875
876 // Add the nodes that aren't ready back onto the available list.
877 if (!NotReady.empty()) {
878 AvailableQueue.push_all(NotReady);
879 NotReady.clear();
880 }
881
Dan Gohman343f0c02008-11-19 23:18:57 +0000882 // If we found a node to schedule, do it now.
883 if (FoundSUnit) {
884 ScheduleNodeTopDown(FoundSUnit, CurCycle);
Dan Gohman2836c282009-01-16 01:33:36 +0000885 HazardRec->EmitInstruction(FoundSUnit);
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000886 CycleInstCnt++;
Dan Gohman343f0c02008-11-19 23:18:57 +0000887
David Goodwind94a4e52009-08-10 15:55:25 +0000888 // If we are using the target-specific hazards, then don't
889 // advance the cycle time just because we schedule a node. If
890 // the target allows it we can schedule multiple nodes in the
891 // same cycle.
892 if (!EnablePostRAHazardAvoidance) {
893 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
894 ++CurCycle;
895 }
Dan Gohman2836c282009-01-16 01:33:36 +0000896 } else {
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000897 if (CycleInstCnt > 0) {
898 DEBUG(errs() << "*** Finished cycle " << CurCycle << '\n');
899 HazardRec->AdvanceCycle();
900 } else if (!HasNoopHazards) {
901 // Otherwise, we have a pipeline stall, but no other problem,
902 // just advance the current cycle and try again.
903 DEBUG(errs() << "*** Stall in cycle " << CurCycle << '\n');
904 HazardRec->AdvanceCycle();
905 ++NumStalls;
906 } else {
907 // Otherwise, we have no instructions to issue and we have instructions
908 // that will fault if we don't do this right. This is the case for
909 // processors without pipeline interlocks and other cases.
910 DEBUG(errs() << "*** Emitting noop in cycle " << CurCycle << '\n');
911 HazardRec->EmitNoop();
912 Sequence.push_back(0); // NULL here means noop
913 ++NumNoops;
914 }
915
Dan Gohman2836c282009-01-16 01:33:36 +0000916 ++CurCycle;
David Goodwin2ffb0ce2009-08-12 21:47:46 +0000917 CycleInstCnt = 0;
Dan Gohman343f0c02008-11-19 23:18:57 +0000918 }
919 }
920
921#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +0000922 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +0000923#endif
924}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000925
926//===----------------------------------------------------------------------===//
927// Public Constructor Functions
928//===----------------------------------------------------------------------===//
929
930FunctionPass *llvm::createPostRAScheduler() {
Dan Gohman343f0c02008-11-19 23:18:57 +0000931 return new PostRAScheduler();
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000932}