blob: f3aef575f0757fd446c9e4315b89209a9e5baaee [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"
22#include "llvm/CodeGen/Passes.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000023#include "llvm/CodeGen/ScheduleDAGInstrs.h"
24#include "llvm/CodeGen/LatencyPriorityQueue.h"
25#include "llvm/CodeGen/SchedulerRegistry.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000026#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohman21d90032008-11-25 00:52:40 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner459525d2008-01-14 19:00:06 +000030#include "llvm/Support/Compiler.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000031#include "llvm/Support/Debug.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000032#include "llvm/ADT/Statistic.h"
Dan Gohman21d90032008-11-25 00:52:40 +000033#include "llvm/ADT/DenseSet.h"
34#include <map>
35#include <climits>
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000036using namespace llvm;
37
Dan Gohman343f0c02008-11-19 23:18:57 +000038STATISTIC(NumStalls, "Number of pipeline stalls");
39
Dan Gohman21d90032008-11-25 00:52:40 +000040static cl::opt<bool>
41EnableAntiDepBreaking("break-anti-dependencies",
42 cl::desc("Break scheduling anti-dependencies"),
43 cl::init(false));
44
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000045namespace {
Dan Gohman343f0c02008-11-19 23:18:57 +000046 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000047 public:
48 static char ID;
Dan Gohman343f0c02008-11-19 23:18:57 +000049 PostRAScheduler() : MachineFunctionPass(&ID) {}
Dan Gohman21d90032008-11-25 00:52:40 +000050
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000051 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +000052 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000053 }
54
55 bool runOnMachineFunction(MachineFunction &Fn);
56 };
Dan Gohman343f0c02008-11-19 23:18:57 +000057 char PostRAScheduler::ID = 0;
58
59 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +000060 /// AvailableQueue - The priority queue to use for the available SUnits.
61 ///
62 LatencyPriorityQueue AvailableQueue;
63
64 /// PendingQueue - This contains all of the instructions whose operands have
65 /// been issued, but their results are not ready yet (due to the latency of
66 /// the operation). Once the operands becomes available, the instruction is
67 /// added to the AvailableQueue.
68 std::vector<SUnit*> PendingQueue;
69
Dan Gohman21d90032008-11-25 00:52:40 +000070 /// Topo - A topological ordering for SUnits.
71 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +000072
Dan Gohman21d90032008-11-25 00:52:40 +000073 public:
74 SchedulePostRATDList(MachineBasicBlock *mbb, const TargetMachine &tm)
75 : ScheduleDAGInstrs(mbb, tm), Topo(SUnits) {}
Dan Gohman343f0c02008-11-19 23:18:57 +000076
77 void Schedule();
78
79 private:
80 void ReleaseSucc(SUnit *SU, SUnit *SuccSU, bool isChain);
81 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
82 void ListScheduleTopDown();
Dan Gohman21d90032008-11-25 00:52:40 +000083 bool BreakAntiDependencies();
Dan Gohman343f0c02008-11-19 23:18:57 +000084 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000085}
86
Dan Gohman343f0c02008-11-19 23:18:57 +000087bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
88 DOUT << "PostRAScheduler\n";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000089
90 // Loop over all of the basic blocks
91 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +000092 MBB != MBBe; ++MBB) {
93
Dan Gohman21d90032008-11-25 00:52:40 +000094 SchedulePostRATDList Scheduler(MBB, Fn.getTarget());
Dan Gohman343f0c02008-11-19 23:18:57 +000095
96 Scheduler.Run();
97
98 Scheduler.EmitSchedule();
99 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000100
101 return true;
102}
103
Dan Gohman343f0c02008-11-19 23:18:57 +0000104/// Schedule - Schedule the DAG using list scheduling.
105void SchedulePostRATDList::Schedule() {
106 DOUT << "********** List Scheduling **********\n";
107
108 // Build scheduling units.
109 BuildSchedUnits();
110
Dan Gohman21d90032008-11-25 00:52:40 +0000111 if (EnableAntiDepBreaking) {
112 if (BreakAntiDependencies()) {
113 // We made changes. Update the dependency graph.
114 // Theoretically we could update the graph in place:
115 // When a live range is changed to use a different register, remove
116 // the def's anti-dependence *and* output-dependence edges due to
117 // that register, and add new anti-dependence and output-dependence
118 // edges based on the next live range of the register.
119 SUnits.clear();
120 BuildSchedUnits();
121 }
122 }
123
Dan Gohman343f0c02008-11-19 23:18:57 +0000124 AvailableQueue.initNodes(SUnits);
Dan Gohman21d90032008-11-25 00:52:40 +0000125
Dan Gohman343f0c02008-11-19 23:18:57 +0000126 ListScheduleTopDown();
127
128 AvailableQueue.releaseState();
129}
130
Dan Gohman21d90032008-11-25 00:52:40 +0000131/// getInstrOperandRegClass - Return register class of the operand of an
132/// instruction of the specified TargetInstrDesc.
133static const TargetRegisterClass*
134getInstrOperandRegClass(const TargetRegisterInfo *TRI,
135 const TargetInstrInfo *TII, const TargetInstrDesc &II,
136 unsigned Op) {
137 if (Op >= II.getNumOperands())
138 return NULL;
139 if (II.OpInfo[Op].isLookupPtrRegClass())
140 return TII->getPointerRegClass();
141 return TRI->getRegClass(II.OpInfo[Op].RegClass);
142}
143
144/// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
145/// of the ScheduleDAG and break them by renaming registers.
146///
147bool SchedulePostRATDList::BreakAntiDependencies() {
148 // The code below assumes that there is at least one instruction,
149 // so just duck out immediately if the block is empty.
150 if (BB->empty()) return false;
151
152 Topo.InitDAGTopologicalSorting();
153
154 // Compute a critical path for the DAG.
155 SUnit *Max = 0;
156 std::vector<SDep *> CriticalPath(SUnits.size());
157 for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
158 E = Topo.end(); I != E; ++I) {
159 SUnit *SU = &SUnits[*I];
160 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
161 P != PE; ++P) {
162 SUnit *PredSU = P->Dep;
Dan Gohmane5617512008-12-03 19:37:34 +0000163 // This assumes that there's no delay for reusing registers.
164 unsigned PredLatency = (P->isCtrl && P->Reg != 0) ? 1 : PredSU->Latency;
165 unsigned PredTotalLatency = PredSU->CycleBound + PredLatency;
166 if (SU->CycleBound < PredTotalLatency ||
167 (SU->CycleBound == PredTotalLatency && !P->isAntiDep)) {
168 SU->CycleBound = PredTotalLatency;
Dan Gohman21d90032008-11-25 00:52:40 +0000169 CriticalPath[*I] = &*P;
170 }
171 }
172 // Keep track of the node at the end of the critical path.
173 if (!Max || SU->CycleBound + SU->Latency > Max->CycleBound + Max->Latency)
174 Max = SU;
175 }
176
177 DOUT << "Critical path has total latency "
178 << (Max ? Max->CycleBound + Max->Latency : 0) << "\n";
179
180 // Walk the critical path from the bottom up. Collect all anti-dependence
181 // edges on the critical path. Skip anti-dependencies between SUnits that
182 // are connected with other edges, since such units won't be able to be
183 // scheduled past each other anyway.
184 //
185 // The heuristic is that edges on the critical path are more important to
186 // break than other edges. And since there are a limited number of
187 // registers, we don't want to waste them breaking edges that aren't
188 // important.
189 //
190 // TODO: Instructions with multiple defs could have multiple
191 // anti-dependencies. The current code here only knows how to break one
192 // edge per instruction. Note that we'd have to be able to break all of
193 // the anti-dependencies in an instruction in order to be effective.
194 BitVector AllocatableSet = TRI->getAllocatableSet(*MF);
195 DenseMap<MachineInstr *, unsigned> CriticalAntiDeps;
196 for (SUnit *SU = Max; CriticalPath[SU->NodeNum];
197 SU = CriticalPath[SU->NodeNum]->Dep) {
198 SDep *Edge = CriticalPath[SU->NodeNum];
199 SUnit *NextSU = Edge->Dep;
200 unsigned AntiDepReg = Edge->Reg;
Dan Gohman0dba0e52008-12-03 19:32:26 +0000201 // Only consider anti-dependence edges.
202 if (!Edge->isAntiDep)
203 continue;
204 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
Dan Gohman21d90032008-11-25 00:52:40 +0000205 // Don't break anti-dependencies on non-allocatable registers.
206 if (!AllocatableSet.test(AntiDepReg))
207 continue;
208 // If the SUnit has other dependencies on the SUnit that it
209 // anti-depends on, don't bother breaking the anti-dependency.
210 // Also, if there are dependencies on other SUnits with the
211 // same register as the anti-dependency, don't attempt to
212 // break it.
213 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
214 P != PE; ++P)
215 if (P->Dep == NextSU ?
216 (!P->isAntiDep || P->Reg != AntiDepReg) :
217 (!P->isCtrl && !P->isAntiDep && P->Reg == AntiDepReg)) {
218 AntiDepReg = 0;
219 break;
220 }
221 if (AntiDepReg != 0)
222 CriticalAntiDeps[SU->getInstr()] = AntiDepReg;
223 }
224
225 // For live regs that are only used in one register class in a live range,
226 // the register class. If the register is not live or is referenced in
227 // multiple register classes, the corresponding value is null. If the
228 // register is used in multiple register classes, the corresponding value
229 // is -1 casted to a pointer.
230 const TargetRegisterClass *
231 Classes[TargetRegisterInfo::FirstVirtualRegister] = {};
232
233 // Map registers to all their references within a live range.
234 std::multimap<unsigned, MachineOperand *> RegRefs;
235
236 // The index of the most recent kill (proceding bottom-up), or -1 if
237 // the register is not live.
238 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
239 std::fill(KillIndices, array_endof(KillIndices), -1);
240 // The index of the most recent def (proceding bottom up), or -1 if
241 // the register is live.
242 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
243 std::fill(DefIndices, array_endof(DefIndices), BB->size());
244
245 // Determine the live-out physregs for this block.
246 if (!BB->empty() && BB->back().getDesc().isReturn())
247 // In a return block, examine the function live-out regs.
248 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
249 E = MRI.liveout_end(); I != E; ++I) {
250 unsigned Reg = *I;
251 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
252 KillIndices[Reg] = BB->size();
253 DefIndices[Reg] = -1;
254 // Repeat, for all aliases.
255 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
256 unsigned AliasReg = *Alias;
257 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
258 KillIndices[AliasReg] = BB->size();
259 DefIndices[AliasReg] = -1;
260 }
261 }
262 else
263 // In a non-return block, examine the live-in regs of all successors.
264 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
265 SE = BB->succ_end(); SI != SE; ++SI)
266 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
267 E = (*SI)->livein_end(); I != E; ++I) {
268 unsigned Reg = *I;
269 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
270 KillIndices[Reg] = BB->size();
271 DefIndices[Reg] = -1;
272 // Repeat, for all aliases.
273 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
274 unsigned AliasReg = *Alias;
275 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
276 KillIndices[AliasReg] = BB->size();
277 DefIndices[AliasReg] = -1;
278 }
279 }
280
281 // Consider callee-saved registers as live-out, since we're running after
282 // prologue/epilogue insertion so there's no way to add additional
283 // saved registers.
284 //
285 // TODO: If the callee saves and restores these, then we can potentially
286 // use them between the save and the restore. To do that, we could scan
287 // the exit blocks to see which of these registers are defined.
Dan Gohmanebb0a312008-12-03 19:30:13 +0000288 // Alternatively, calle-saved registers that aren't saved and restored
289 // could be marked live-in in every block.
Dan Gohman21d90032008-11-25 00:52:40 +0000290 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
291 unsigned Reg = *I;
292 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
293 KillIndices[Reg] = BB->size();
294 DefIndices[Reg] = -1;
295 // Repeat, for all aliases.
296 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
297 unsigned AliasReg = *Alias;
298 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
299 KillIndices[AliasReg] = BB->size();
300 DefIndices[AliasReg] = -1;
301 }
302 }
303
304 // Consider this pattern:
305 // A = ...
306 // ... = A
307 // A = ...
308 // ... = A
309 // A = ...
310 // ... = A
311 // A = ...
312 // ... = A
313 // There are three anti-dependencies here, and without special care,
314 // we'd break all of them using the same register:
315 // A = ...
316 // ... = A
317 // B = ...
318 // ... = B
319 // B = ...
320 // ... = B
321 // B = ...
322 // ... = B
323 // because at each anti-dependence, B is the first register that
324 // isn't A which is free. This re-introduces anti-dependencies
325 // at all but one of the original anti-dependencies that we were
326 // trying to break. To avoid this, keep track of the most recent
327 // register that each register was replaced with, avoid avoid
328 // using it to repair an anti-dependence on the same register.
329 // This lets us produce this:
330 // A = ...
331 // ... = A
332 // B = ...
333 // ... = B
334 // C = ...
335 // ... = C
336 // B = ...
337 // ... = B
338 // This still has an anti-dependence on B, but at least it isn't on the
339 // original critical path.
340 //
341 // TODO: If we tracked more than one register here, we could potentially
342 // fix that remaining critical edge too. This is a little more involved,
343 // because unlike the most recent register, less recent registers should
344 // still be considered, though only if no other registers are available.
345 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
346
347 // A registers defined and not used in an instruction. This is used for
348 // liveness tracking and is declared outside the loop only to avoid
349 // having it be re-allocated on each iteration.
350 DenseSet<unsigned> Defs;
351
352 // Attempt to break anti-dependence edges on the critical path. Walk the
353 // instructions from the bottom up, tracking information about liveness
354 // as we go to help determine which registers are available.
355 bool Changed = false;
356 unsigned Count = BB->size() - 1;
357 for (MachineBasicBlock::reverse_iterator I = BB->rbegin(), E = BB->rend();
358 I != E; ++I, --Count) {
359 MachineInstr *MI = &*I;
360
361 // Check if this instruction has an anti-dependence that we're
362 // interested in.
363 DenseMap<MachineInstr *, unsigned>::iterator C = CriticalAntiDeps.find(MI);
364 unsigned AntiDepReg = C != CriticalAntiDeps.end() ?
365 C->second : 0;
366
367 // Scan the register operands for this instruction and update
368 // Classes and RegRefs.
369 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
370 MachineOperand &MO = MI->getOperand(i);
371 if (!MO.isReg()) continue;
372 unsigned Reg = MO.getReg();
373 if (Reg == 0) continue;
374 const TargetRegisterClass *NewRC =
375 getInstrOperandRegClass(TRI, TII, MI->getDesc(), i);
376
377 // If this instruction has a use of AntiDepReg, breaking it
378 // is invalid.
379 if (MO.isUse() && AntiDepReg == Reg)
380 AntiDepReg = 0;
381
382 // For now, only allow the register to be changed if its register
383 // class is consistent across all uses.
384 if (!Classes[Reg] && NewRC)
385 Classes[Reg] = NewRC;
386 else if (!NewRC || Classes[Reg] != NewRC)
387 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
388
389 // Now check for aliases.
390 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
391 // If an alias of the reg is used during the live range, give up.
392 // Note that this allows us to skip checking if AntiDepReg
393 // overlaps with any of the aliases, among other things.
394 unsigned AliasReg = *Alias;
395 if (Classes[AliasReg]) {
396 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
397 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
398 }
399 }
400
401 // If we're still willing to consider this register, note the reference.
402 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
403 RegRefs.insert(std::make_pair(Reg, &MO));
404 }
405
406 // Determine AntiDepReg's register class, if it is live and is
407 // consistently used within a single class.
408 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
Nick Lewyckya89d1022008-11-27 17:29:52 +0000409 assert((AntiDepReg == 0 || RC != NULL) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000410 "Register should be live if it's causing an anti-dependence!");
411 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
412 AntiDepReg = 0;
413
414 // Look for a suitable register to use to break the anti-depenence.
415 //
416 // TODO: Instead of picking the first free register, consider which might
417 // be the best.
418 if (AntiDepReg != 0) {
419 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(*MF),
420 RE = RC->allocation_order_end(*MF); R != RE; ++R) {
421 unsigned NewReg = *R;
422 // Don't replace a register with itself.
423 if (NewReg == AntiDepReg) continue;
424 // Don't replace a register with one that was recently used to repair
425 // an anti-dependence with this AntiDepReg, because that would
426 // re-introduce that anti-dependence.
427 if (NewReg == LastNewReg[AntiDepReg]) continue;
428 // If NewReg is dead and NewReg's most recent def is not before
429 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
Dan Gohman878ef1d2008-11-25 18:53:54 +0000430 assert(((KillIndices[AntiDepReg] == -1u) != (DefIndices[AntiDepReg] == -1u)) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000431 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman878ef1d2008-11-25 18:53:54 +0000432 assert(((KillIndices[NewReg] == -1u) != (DefIndices[NewReg] == -1u)) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000433 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman878ef1d2008-11-25 18:53:54 +0000434 if (KillIndices[NewReg] == -1u &&
Dan Gohman21d90032008-11-25 00:52:40 +0000435 KillIndices[AntiDepReg] <= DefIndices[NewReg]) {
436 DOUT << "Breaking anti-dependence edge on reg " << AntiDepReg
437 << " with reg " << NewReg << "!\n";
438
439 // Update the references to the old register to refer to the new
440 // register.
441 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
442 std::multimap<unsigned, MachineOperand *>::iterator>
443 Range = RegRefs.equal_range(AntiDepReg);
444 for (std::multimap<unsigned, MachineOperand *>::iterator
445 Q = Range.first, QE = Range.second; Q != QE; ++Q)
446 Q->second->setReg(NewReg);
447
448 // We just went back in time and modified history; the
449 // liveness information for the anti-depenence reg is now
450 // inconsistent. Set the state as if it were dead.
451 Classes[NewReg] = Classes[AntiDepReg];
452 DefIndices[NewReg] = DefIndices[AntiDepReg];
453 KillIndices[NewReg] = KillIndices[AntiDepReg];
454
455 Classes[AntiDepReg] = 0;
456 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
457 KillIndices[AntiDepReg] = -1;
458
459 RegRefs.erase(AntiDepReg);
460 Changed = true;
461 LastNewReg[AntiDepReg] = NewReg;
462 break;
463 }
464 }
465 }
466
467 // Update liveness.
468 Defs.clear();
469 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
470 MachineOperand &MO = MI->getOperand(i);
471 if (!MO.isReg()) continue;
472 unsigned Reg = MO.getReg();
473 if (Reg == 0) continue;
474 if (MO.isDef())
475 Defs.insert(Reg);
476 else {
477 // Treat a use in the same instruction as a def as an extension of
478 // a live range.
479 Defs.erase(Reg);
480 // It wasn't previously live but now it is, this is a kill.
Dan Gohman878ef1d2008-11-25 18:53:54 +0000481 if (KillIndices[Reg] == -1u) {
Dan Gohman21d90032008-11-25 00:52:40 +0000482 KillIndices[Reg] = Count;
Dan Gohman878ef1d2008-11-25 18:53:54 +0000483 DefIndices[Reg] = -1u;
Dan Gohman21d90032008-11-25 00:52:40 +0000484 }
485 // Repeat, for all aliases.
486 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
487 unsigned AliasReg = *Alias;
488 Defs.erase(AliasReg);
Dan Gohman878ef1d2008-11-25 18:53:54 +0000489 if (KillIndices[AliasReg] == -1u) {
Dan Gohman21d90032008-11-25 00:52:40 +0000490 KillIndices[AliasReg] = Count;
Dan Gohman878ef1d2008-11-25 18:53:54 +0000491 DefIndices[AliasReg] = -1u;
Dan Gohman21d90032008-11-25 00:52:40 +0000492 }
493 }
494 }
495 }
496 // Proceding upwards, registers that are defed but not used in this
497 // instruction are now dead.
498 for (DenseSet<unsigned>::iterator D = Defs.begin(), DE = Defs.end();
499 D != DE; ++D) {
500 unsigned Reg = *D;
501 DefIndices[Reg] = Count;
502 KillIndices[Reg] = -1;
503 Classes[Reg] = 0;
504 RegRefs.erase(Reg);
505 // Repeat, for all subregs.
506 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
507 *Subreg; ++Subreg) {
508 unsigned SubregReg = *Subreg;
509 DefIndices[SubregReg] = Count;
510 KillIndices[SubregReg] = -1;
511 Classes[SubregReg] = 0;
512 RegRefs.erase(SubregReg);
513 }
514 }
515 }
516 assert(Count == -1u && "Count mismatch!");
517
518 return Changed;
519}
520
Dan Gohman343f0c02008-11-19 23:18:57 +0000521//===----------------------------------------------------------------------===//
522// Top-Down Scheduling
523//===----------------------------------------------------------------------===//
524
525/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
526/// the PendingQueue if the count reaches zero. Also update its cycle bound.
527void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SUnit *SuccSU, bool isChain) {
528 --SuccSU->NumPredsLeft;
529
530#ifndef NDEBUG
531 if (SuccSU->NumPredsLeft < 0) {
532 cerr << "*** Scheduling failed! ***\n";
533 SuccSU->dump(this);
534 cerr << " has been released too many times!\n";
535 assert(0);
536 }
537#endif
538
539 // Compute how many cycles it will be before this actually becomes
540 // available. This is the max of the start time of all predecessors plus
541 // their latencies.
542 // If this is a token edge, we don't need to wait for the latency of the
543 // preceeding instruction (e.g. a long-latency load) unless there is also
544 // some other data dependence.
545 unsigned PredDoneCycle = SU->Cycle;
546 if (!isChain)
547 PredDoneCycle += SU->Latency;
548 else if (SU->Latency)
549 PredDoneCycle += 1;
550 SuccSU->CycleBound = std::max(SuccSU->CycleBound, PredDoneCycle);
551
552 if (SuccSU->NumPredsLeft == 0) {
553 PendingQueue.push_back(SuccSU);
554 }
555}
556
557/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
558/// count of its successors. If a successor pending count is zero, add it to
559/// the Available queue.
560void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
561 DOUT << "*** Scheduling [" << CurCycle << "]: ";
562 DEBUG(SU->dump(this));
563
564 Sequence.push_back(SU);
565 SU->Cycle = CurCycle;
566
567 // Top down: release successors.
568 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
569 I != E; ++I)
570 ReleaseSucc(SU, I->Dep, I->isCtrl);
571
572 SU->isScheduled = true;
573 AvailableQueue.ScheduledNode(SU);
574}
575
576/// ListScheduleTopDown - The main loop of list scheduling for top-down
577/// schedulers.
578void SchedulePostRATDList::ListScheduleTopDown() {
579 unsigned CurCycle = 0;
580
581 // All leaves to Available queue.
582 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
583 // It is available if it has no predecessors.
584 if (SUnits[i].Preds.empty()) {
585 AvailableQueue.push(&SUnits[i]);
586 SUnits[i].isAvailable = true;
587 }
588 }
589
590 // While Available queue is not empty, grab the node with the highest
591 // priority. If it is not ready put it back. Schedule the node.
592 Sequence.reserve(SUnits.size());
593 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
594 // Check to see if any of the pending instructions are ready to issue. If
595 // so, add them to the available queue.
596 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
597 if (PendingQueue[i]->CycleBound == CurCycle) {
598 AvailableQueue.push(PendingQueue[i]);
599 PendingQueue[i]->isAvailable = true;
600 PendingQueue[i] = PendingQueue.back();
601 PendingQueue.pop_back();
602 --i; --e;
603 } else {
604 assert(PendingQueue[i]->CycleBound > CurCycle && "Negative latency?");
605 }
606 }
607
Dan Gohman21d90032008-11-25 00:52:40 +0000608 // If there are no instructions available, don't try to issue anything.
Dan Gohman343f0c02008-11-19 23:18:57 +0000609 if (AvailableQueue.empty()) {
610 ++CurCycle;
611 continue;
612 }
613
614 SUnit *FoundSUnit = AvailableQueue.pop();
615
616 // If we found a node to schedule, do it now.
617 if (FoundSUnit) {
618 ScheduleNodeTopDown(FoundSUnit, CurCycle);
619
620 // If this is a pseudo-op node, we don't want to increment the current
621 // cycle.
622 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
623 ++CurCycle;
624 } else {
625 // Otherwise, we have a pipeline stall, but no other problem, just advance
626 // the current cycle and try again.
627 DOUT << "*** Advancing cycle, no work to do\n";
628 ++NumStalls;
629 ++CurCycle;
630 }
631 }
632
633#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +0000634 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +0000635#endif
636}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000637
638//===----------------------------------------------------------------------===//
639// Public Constructor Functions
640//===----------------------------------------------------------------------===//
641
642FunctionPass *llvm::createPostRAScheduler() {
Dan Gohman343f0c02008-11-19 23:18:57 +0000643 return new PostRAScheduler();
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000644}