blob: 1e72b1201b0d7178d29f83c828049b4d07369835 [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"
Dan Gohman3f237442008-12-16 03:25:46 +000026#include "llvm/CodeGen/MachineDominators.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000027#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohman3f237442008-12-16 03:25:46 +000028#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman21d90032008-11-25 00:52:40 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/Target/TargetInstrInfo.h"
31#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner459525d2008-01-14 19:00:06 +000032#include "llvm/Support/Compiler.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000033#include "llvm/Support/Debug.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000034#include "llvm/ADT/Statistic.h"
Dan Gohman21d90032008-11-25 00:52:40 +000035#include <map>
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",
Dan Gohman00dc84a2008-12-16 19:27:52 +000042 cl::desc("Break post-RA scheduling anti-dependencies"),
43 cl::init(true), cl::Hidden);
Dan Gohman21d90032008-11-25 00:52:40 +000044
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
Dan Gohman3f237442008-12-16 03:25:46 +000051 void getAnalysisUsage(AnalysisUsage &AU) const {
52 AU.addRequired<MachineDominatorTree>();
53 AU.addPreserved<MachineDominatorTree>();
54 AU.addRequired<MachineLoopInfo>();
55 AU.addPreserved<MachineLoopInfo>();
56 MachineFunctionPass::getAnalysisUsage(AU);
57 }
58
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000059 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +000060 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000061 }
62
63 bool runOnMachineFunction(MachineFunction &Fn);
64 };
Dan Gohman343f0c02008-11-19 23:18:57 +000065 char PostRAScheduler::ID = 0;
66
67 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +000068 /// AvailableQueue - The priority queue to use for the available SUnits.
69 ///
70 LatencyPriorityQueue AvailableQueue;
71
72 /// PendingQueue - This contains all of the instructions whose operands have
73 /// been issued, but their results are not ready yet (due to the latency of
74 /// the operation). Once the operands becomes available, the instruction is
75 /// added to the AvailableQueue.
76 std::vector<SUnit*> PendingQueue;
77
Dan Gohman21d90032008-11-25 00:52:40 +000078 /// Topo - A topological ordering for SUnits.
79 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +000080
Dan Gohman21d90032008-11-25 00:52:40 +000081 public:
Dan Gohman3f237442008-12-16 03:25:46 +000082 SchedulePostRATDList(MachineBasicBlock *mbb, const TargetMachine &tm,
83 const MachineLoopInfo &MLI,
84 const MachineDominatorTree &MDT)
85 : ScheduleDAGInstrs(mbb, tm, MLI, MDT), Topo(SUnits) {}
Dan Gohman343f0c02008-11-19 23:18:57 +000086
87 void Schedule();
88
89 private:
Dan Gohman54e4c362008-12-09 22:54:47 +000090 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohman343f0c02008-11-19 23:18:57 +000091 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
92 void ListScheduleTopDown();
Dan Gohman21d90032008-11-25 00:52:40 +000093 bool BreakAntiDependencies();
Dan Gohman343f0c02008-11-19 23:18:57 +000094 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000095}
96
Dan Gohman343f0c02008-11-19 23:18:57 +000097bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
98 DOUT << "PostRAScheduler\n";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000099
Dan Gohman3f237442008-12-16 03:25:46 +0000100 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
101 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
102
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000103 // Loop over all of the basic blocks
104 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000105 MBB != MBBe; ++MBB) {
106
Dan Gohman3f237442008-12-16 03:25:46 +0000107 SchedulePostRATDList Scheduler(MBB, Fn.getTarget(), MLI, MDT);
Dan Gohman343f0c02008-11-19 23:18:57 +0000108
109 Scheduler.Run();
110
111 Scheduler.EmitSchedule();
112 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000113
114 return true;
115}
116
Dan Gohman343f0c02008-11-19 23:18:57 +0000117/// Schedule - Schedule the DAG using list scheduling.
118void SchedulePostRATDList::Schedule() {
119 DOUT << "********** List Scheduling **********\n";
120
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000121 // Build the scheduling graph.
122 BuildSchedGraph();
Dan Gohman343f0c02008-11-19 23:18:57 +0000123
Dan Gohman21d90032008-11-25 00:52:40 +0000124 if (EnableAntiDepBreaking) {
125 if (BreakAntiDependencies()) {
126 // We made changes. Update the dependency graph.
127 // Theoretically we could update the graph in place:
128 // When a live range is changed to use a different register, remove
129 // the def's anti-dependence *and* output-dependence edges due to
130 // that register, and add new anti-dependence and output-dependence
131 // edges based on the next live range of the register.
132 SUnits.clear();
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000133 BuildSchedGraph();
Dan Gohman21d90032008-11-25 00:52:40 +0000134 }
135 }
136
Dan Gohman343f0c02008-11-19 23:18:57 +0000137 AvailableQueue.initNodes(SUnits);
Dan Gohman21d90032008-11-25 00:52:40 +0000138
Dan Gohman343f0c02008-11-19 23:18:57 +0000139 ListScheduleTopDown();
140
141 AvailableQueue.releaseState();
142}
143
Dan Gohman21d90032008-11-25 00:52:40 +0000144/// getInstrOperandRegClass - Return register class of the operand of an
145/// instruction of the specified TargetInstrDesc.
146static const TargetRegisterClass*
147getInstrOperandRegClass(const TargetRegisterInfo *TRI,
148 const TargetInstrInfo *TII, const TargetInstrDesc &II,
149 unsigned Op) {
150 if (Op >= II.getNumOperands())
151 return NULL;
152 if (II.OpInfo[Op].isLookupPtrRegClass())
153 return TII->getPointerRegClass();
154 return TRI->getRegClass(II.OpInfo[Op].RegClass);
155}
156
Dan Gohman3f237442008-12-16 03:25:46 +0000157/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
158/// critical path.
159static SDep *CriticalPathStep(SUnit *SU) {
160 SDep *Next = 0;
161 unsigned NextDepth = 0;
162 // Find the predecessor edge with the greatest depth.
163 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
164 P != PE; ++P) {
165 SUnit *PredSU = P->getSUnit();
166 unsigned PredLatency = P->getLatency();
167 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
168 // In the case of a latency tie, prefer an anti-dependency edge over
169 // other types of edges.
170 if (NextDepth < PredTotalLatency ||
171 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
172 NextDepth = PredTotalLatency;
173 Next = &*P;
174 }
175 }
176 return Next;
177}
178
Dan Gohman21d90032008-11-25 00:52:40 +0000179/// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
180/// of the ScheduleDAG and break them by renaming registers.
181///
182bool SchedulePostRATDList::BreakAntiDependencies() {
183 // The code below assumes that there is at least one instruction,
184 // so just duck out immediately if the block is empty.
185 if (BB->empty()) return false;
186
Dan Gohman3f237442008-12-16 03:25:46 +0000187 // Find the node at the bottom of the critical path.
Dan Gohman21d90032008-11-25 00:52:40 +0000188 SUnit *Max = 0;
Dan Gohman3f237442008-12-16 03:25:46 +0000189 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
190 SUnit *SU = &SUnits[i];
191 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
Dan Gohman21d90032008-11-25 00:52:40 +0000192 Max = SU;
193 }
194
195 DOUT << "Critical path has total latency "
Dan Gohman3f237442008-12-16 03:25:46 +0000196 << (Max ? Max->getDepth() + Max->Latency : 0) << "\n";
Dan Gohman21d90032008-11-25 00:52:40 +0000197
Dan Gohman00dc84a2008-12-16 19:27:52 +0000198 // We'll be ignoring anti-dependencies on non-allocatable registers, because
199 // they may not be safe to break.
200 const BitVector AllocatableSet = TRI->getAllocatableSet(*MF);
201
202 // Track progress along the critical path through the SUnit graph as we walk
203 // the instructions.
204 SUnit *CriticalPathSU = Max;
205 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
Dan Gohman21d90032008-11-25 00:52:40 +0000206
207 // For live regs that are only used in one register class in a live range,
Dan Gohmane96cc772008-12-03 19:38:38 +0000208 // the register class. If the register is not live, the corresponding value
209 // is null. If the register is live but used in multiple register classes,
210 // the corresponding value is -1 casted to a pointer.
Dan Gohman21d90032008-11-25 00:52:40 +0000211 const TargetRegisterClass *
212 Classes[TargetRegisterInfo::FirstVirtualRegister] = {};
213
214 // Map registers to all their references within a live range.
215 std::multimap<unsigned, MachineOperand *> RegRefs;
216
Dan Gohman6c3643c2008-12-19 22:23:43 +0000217 // The index of the most recent kill (proceding bottom-up), or ~0u if
Dan Gohman21d90032008-11-25 00:52:40 +0000218 // the register is not live.
219 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
Dan Gohman6c3643c2008-12-19 22:23:43 +0000220 std::fill(KillIndices, array_endof(KillIndices), ~0u);
221 // The index of the most recent complete def (proceding bottom up), or ~0u if
Dan Gohman21d90032008-11-25 00:52:40 +0000222 // the register is live.
223 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
224 std::fill(DefIndices, array_endof(DefIndices), BB->size());
225
226 // Determine the live-out physregs for this block.
Dan Gohman00dc84a2008-12-16 19:27:52 +0000227 if (BB->back().getDesc().isReturn())
Dan Gohman21d90032008-11-25 00:52:40 +0000228 // In a return block, examine the function live-out regs.
229 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
230 E = MRI.liveout_end(); I != E; ++I) {
231 unsigned Reg = *I;
232 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
233 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000234 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000235 // Repeat, for all aliases.
236 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
237 unsigned AliasReg = *Alias;
238 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
239 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000240 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000241 }
242 }
243 else
244 // In a non-return block, examine the live-in regs of all successors.
245 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
246 SE = BB->succ_end(); SI != SE; ++SI)
247 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
248 E = (*SI)->livein_end(); I != E; ++I) {
249 unsigned Reg = *I;
250 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
251 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000252 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000253 // Repeat, for all aliases.
254 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
255 unsigned AliasReg = *Alias;
256 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
257 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000258 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000259 }
260 }
261
262 // Consider callee-saved registers as live-out, since we're running after
263 // prologue/epilogue insertion so there's no way to add additional
264 // saved registers.
265 //
266 // TODO: If the callee saves and restores these, then we can potentially
267 // use them between the save and the restore. To do that, we could scan
268 // the exit blocks to see which of these registers are defined.
Dan Gohman00dc84a2008-12-16 19:27:52 +0000269 // Alternatively, callee-saved registers that aren't saved and restored
Dan Gohmanebb0a312008-12-03 19:30:13 +0000270 // could be marked live-in in every block.
Dan Gohman21d90032008-11-25 00:52:40 +0000271 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
272 unsigned Reg = *I;
273 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
274 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000275 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000276 // Repeat, for all aliases.
277 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
278 unsigned AliasReg = *Alias;
279 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
280 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000281 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000282 }
283 }
284
285 // Consider this pattern:
286 // A = ...
287 // ... = A
288 // A = ...
289 // ... = A
290 // A = ...
291 // ... = A
292 // A = ...
293 // ... = A
294 // There are three anti-dependencies here, and without special care,
295 // we'd break all of them using the same register:
296 // A = ...
297 // ... = A
298 // B = ...
299 // ... = B
300 // B = ...
301 // ... = B
302 // B = ...
303 // ... = B
304 // because at each anti-dependence, B is the first register that
305 // isn't A which is free. This re-introduces anti-dependencies
306 // at all but one of the original anti-dependencies that we were
307 // trying to break. To avoid this, keep track of the most recent
308 // register that each register was replaced with, avoid avoid
309 // using it to repair an anti-dependence on the same register.
310 // This lets us produce this:
311 // A = ...
312 // ... = A
313 // B = ...
314 // ... = B
315 // C = ...
316 // ... = C
317 // B = ...
318 // ... = B
319 // This still has an anti-dependence on B, but at least it isn't on the
320 // original critical path.
321 //
322 // TODO: If we tracked more than one register here, we could potentially
323 // fix that remaining critical edge too. This is a little more involved,
324 // because unlike the most recent register, less recent registers should
325 // still be considered, though only if no other registers are available.
326 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
327
Dan Gohman21d90032008-11-25 00:52:40 +0000328 // Attempt to break anti-dependence edges on the critical path. Walk the
329 // instructions from the bottom up, tracking information about liveness
330 // as we go to help determine which registers are available.
331 bool Changed = false;
332 unsigned Count = BB->size() - 1;
333 for (MachineBasicBlock::reverse_iterator I = BB->rbegin(), E = BB->rend();
334 I != E; ++I, --Count) {
335 MachineInstr *MI = &*I;
336
Dan Gohman490b1832008-12-05 05:30:02 +0000337 // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
338 // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
339 // is left behind appearing to clobber the super-register, while the
340 // subregister needs to remain live. So we just ignore them.
341 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
342 continue;
343
Dan Gohman00dc84a2008-12-16 19:27:52 +0000344 // Check if this instruction has a dependence on the critical path that
345 // is an anti-dependence that we may be able to break. If it is, set
346 // AntiDepReg to the non-zero register associated with the anti-dependence.
347 //
348 // We limit our attention to the critical path as a heuristic to avoid
349 // breaking anti-dependence edges that aren't going to significantly
350 // impact the overall schedule. There are a limited number of registers
351 // and we want to save them for the important edges.
352 //
353 // TODO: Instructions with multiple defs could have multiple
354 // anti-dependencies. The current code here only knows how to break one
355 // edge per instruction. Note that we'd have to be able to break all of
356 // the anti-dependencies in an instruction in order to be effective.
357 unsigned AntiDepReg = 0;
358 if (MI == CriticalPathMI) {
359 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
360 SUnit *NextSU = Edge->getSUnit();
361
362 // Only consider anti-dependence edges.
363 if (Edge->getKind() == SDep::Anti) {
364 AntiDepReg = Edge->getReg();
365 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
366 // Don't break anti-dependencies on non-allocatable registers.
367 if (AllocatableSet.test(AntiDepReg)) {
368 // If the SUnit has other dependencies on the SUnit that it
369 // anti-depends on, don't bother breaking the anti-dependency
370 // since those edges would prevent such units from being
371 // scheduled past each other regardless.
372 //
373 // Also, if there are dependencies on other SUnits with the
374 // same register as the anti-dependency, don't attempt to
375 // break it.
376 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
377 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
378 if (P->getSUnit() == NextSU ?
379 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
380 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
381 AntiDepReg = 0;
382 break;
383 }
384 }
385 }
386 CriticalPathSU = NextSU;
387 CriticalPathMI = CriticalPathSU->getInstr();
388 } else {
389 // We've reached the end of the critical path.
390 CriticalPathSU = 0;
391 CriticalPathMI = 0;
392 }
393 }
Dan Gohman21d90032008-11-25 00:52:40 +0000394
395 // Scan the register operands for this instruction and update
396 // Classes and RegRefs.
397 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
398 MachineOperand &MO = MI->getOperand(i);
399 if (!MO.isReg()) continue;
400 unsigned Reg = MO.getReg();
401 if (Reg == 0) continue;
402 const TargetRegisterClass *NewRC =
403 getInstrOperandRegClass(TRI, TII, MI->getDesc(), i);
404
405 // If this instruction has a use of AntiDepReg, breaking it
406 // is invalid.
407 if (MO.isUse() && AntiDepReg == Reg)
408 AntiDepReg = 0;
409
410 // For now, only allow the register to be changed if its register
411 // class is consistent across all uses.
412 if (!Classes[Reg] && NewRC)
413 Classes[Reg] = NewRC;
414 else if (!NewRC || Classes[Reg] != NewRC)
415 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
416
417 // Now check for aliases.
418 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
419 // If an alias of the reg is used during the live range, give up.
420 // Note that this allows us to skip checking if AntiDepReg
421 // overlaps with any of the aliases, among other things.
422 unsigned AliasReg = *Alias;
423 if (Classes[AliasReg]) {
424 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
425 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
426 }
427 }
428
429 // If we're still willing to consider this register, note the reference.
430 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
431 RegRefs.insert(std::make_pair(Reg, &MO));
432 }
433
434 // Determine AntiDepReg's register class, if it is live and is
435 // consistently used within a single class.
436 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
Nick Lewyckya89d1022008-11-27 17:29:52 +0000437 assert((AntiDepReg == 0 || RC != NULL) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000438 "Register should be live if it's causing an anti-dependence!");
439 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
440 AntiDepReg = 0;
441
442 // Look for a suitable register to use to break the anti-depenence.
443 //
444 // TODO: Instead of picking the first free register, consider which might
445 // be the best.
446 if (AntiDepReg != 0) {
447 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(*MF),
448 RE = RC->allocation_order_end(*MF); R != RE; ++R) {
449 unsigned NewReg = *R;
450 // Don't replace a register with itself.
451 if (NewReg == AntiDepReg) continue;
452 // Don't replace a register with one that was recently used to repair
453 // an anti-dependence with this AntiDepReg, because that would
454 // re-introduce that anti-dependence.
455 if (NewReg == LastNewReg[AntiDepReg]) continue;
456 // If NewReg is dead and NewReg's most recent def is not before
457 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000458 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000459 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman6c3643c2008-12-19 22:23:43 +0000460 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000461 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman6c3643c2008-12-19 22:23:43 +0000462 if (KillIndices[NewReg] == ~0u &&
Dan Gohmanfde221f2008-12-16 06:20:58 +0000463 Classes[NewReg] != reinterpret_cast<TargetRegisterClass *>(-1) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000464 KillIndices[AntiDepReg] <= DefIndices[NewReg]) {
Dan Gohman80e201b2008-12-04 02:15:26 +0000465 DOUT << "Breaking anti-dependence edge on "
466 << TRI->getName(AntiDepReg)
Dan Gohmancef874a2008-12-03 23:07:27 +0000467 << " with " << RegRefs.count(AntiDepReg) << " references"
Dan Gohman80e201b2008-12-04 02:15:26 +0000468 << " using " << TRI->getName(NewReg) << "!\n";
Dan Gohman21d90032008-11-25 00:52:40 +0000469
470 // Update the references to the old register to refer to the new
471 // register.
472 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
473 std::multimap<unsigned, MachineOperand *>::iterator>
474 Range = RegRefs.equal_range(AntiDepReg);
475 for (std::multimap<unsigned, MachineOperand *>::iterator
476 Q = Range.first, QE = Range.second; Q != QE; ++Q)
477 Q->second->setReg(NewReg);
478
479 // We just went back in time and modified history; the
480 // liveness information for the anti-depenence reg is now
481 // inconsistent. Set the state as if it were dead.
482 Classes[NewReg] = Classes[AntiDepReg];
483 DefIndices[NewReg] = DefIndices[AntiDepReg];
484 KillIndices[NewReg] = KillIndices[AntiDepReg];
485
486 Classes[AntiDepReg] = 0;
487 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
Dan Gohman6c3643c2008-12-19 22:23:43 +0000488 KillIndices[AntiDepReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000489
490 RegRefs.erase(AntiDepReg);
491 Changed = true;
492 LastNewReg[AntiDepReg] = NewReg;
493 break;
494 }
495 }
496 }
497
498 // Update liveness.
Dan Gohmancef874a2008-12-03 23:07:27 +0000499 // Proceding upwards, registers that are defed but not used in this
500 // instruction are now dead.
Dan Gohman21d90032008-11-25 00:52:40 +0000501 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
502 MachineOperand &MO = MI->getOperand(i);
503 if (!MO.isReg()) continue;
504 unsigned Reg = MO.getReg();
505 if (Reg == 0) continue;
Dan Gohmancef874a2008-12-03 23:07:27 +0000506 if (!MO.isDef()) continue;
507 // Ignore two-addr defs.
Dan Gohman2ce7f202008-12-05 05:45:42 +0000508 if (MI->isRegReDefinedByTwoAddr(i)) continue;
Dan Gohmancef874a2008-12-03 23:07:27 +0000509
Dan Gohman21d90032008-11-25 00:52:40 +0000510 DefIndices[Reg] = Count;
Dan Gohman6c3643c2008-12-19 22:23:43 +0000511 KillIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000512 Classes[Reg] = 0;
513 RegRefs.erase(Reg);
514 // Repeat, for all subregs.
515 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
516 *Subreg; ++Subreg) {
517 unsigned SubregReg = *Subreg;
518 DefIndices[SubregReg] = Count;
Dan Gohman6c3643c2008-12-19 22:23:43 +0000519 KillIndices[SubregReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000520 Classes[SubregReg] = 0;
521 RegRefs.erase(SubregReg);
522 }
Dan Gohman00dc84a2008-12-16 19:27:52 +0000523 // Conservatively mark super-registers as unusable.
Dan Gohman3f237442008-12-16 03:25:46 +0000524 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
525 *Super; ++Super) {
526 unsigned SuperReg = *Super;
527 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
528 }
Dan Gohman21d90032008-11-25 00:52:40 +0000529 }
Dan Gohmancef874a2008-12-03 23:07:27 +0000530 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
531 MachineOperand &MO = MI->getOperand(i);
532 if (!MO.isReg()) continue;
533 unsigned Reg = MO.getReg();
534 if (Reg == 0) continue;
535 if (!MO.isUse()) continue;
536
537 const TargetRegisterClass *NewRC =
538 getInstrOperandRegClass(TRI, TII, MI->getDesc(), i);
539
540 // For now, only allow the register to be changed if its register
541 // class is consistent across all uses.
542 if (!Classes[Reg] && NewRC)
543 Classes[Reg] = NewRC;
544 else if (!NewRC || Classes[Reg] != NewRC)
545 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
546
547 RegRefs.insert(std::make_pair(Reg, &MO));
548
549 // It wasn't previously live but now it is, this is a kill.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000550 if (KillIndices[Reg] == ~0u) {
Dan Gohmancef874a2008-12-03 23:07:27 +0000551 KillIndices[Reg] = Count;
Dan Gohman6c3643c2008-12-19 22:23:43 +0000552 DefIndices[Reg] = ~0u;
Dan Gohmancef874a2008-12-03 23:07:27 +0000553 }
554 // Repeat, for all aliases.
555 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
556 unsigned AliasReg = *Alias;
Dan Gohman6c3643c2008-12-19 22:23:43 +0000557 if (KillIndices[AliasReg] == ~0u) {
Dan Gohmancef874a2008-12-03 23:07:27 +0000558 KillIndices[AliasReg] = Count;
Dan Gohman6c3643c2008-12-19 22:23:43 +0000559 DefIndices[AliasReg] = ~0u;
Dan Gohmancef874a2008-12-03 23:07:27 +0000560 }
561 }
562 }
Dan Gohman21d90032008-11-25 00:52:40 +0000563 }
Dan Gohman6c3643c2008-12-19 22:23:43 +0000564 assert(Count == ~0u && "Count mismatch!");
Dan Gohman21d90032008-11-25 00:52:40 +0000565
566 return Changed;
567}
568
Dan Gohman343f0c02008-11-19 23:18:57 +0000569//===----------------------------------------------------------------------===//
570// Top-Down Scheduling
571//===----------------------------------------------------------------------===//
572
573/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
574/// the PendingQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman54e4c362008-12-09 22:54:47 +0000575void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
576 SUnit *SuccSU = SuccEdge->getSUnit();
Dan Gohman343f0c02008-11-19 23:18:57 +0000577 --SuccSU->NumPredsLeft;
578
579#ifndef NDEBUG
580 if (SuccSU->NumPredsLeft < 0) {
581 cerr << "*** Scheduling failed! ***\n";
582 SuccSU->dump(this);
583 cerr << " has been released too many times!\n";
584 assert(0);
585 }
586#endif
587
588 // Compute how many cycles it will be before this actually becomes
589 // available. This is the max of the start time of all predecessors plus
590 // their latencies.
Dan Gohman3f237442008-12-16 03:25:46 +0000591 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
Dan Gohman343f0c02008-11-19 23:18:57 +0000592
593 if (SuccSU->NumPredsLeft == 0) {
594 PendingQueue.push_back(SuccSU);
595 }
596}
597
598/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
599/// count of its successors. If a successor pending count is zero, add it to
600/// the Available queue.
601void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
602 DOUT << "*** Scheduling [" << CurCycle << "]: ";
603 DEBUG(SU->dump(this));
604
605 Sequence.push_back(SU);
Dan Gohman3f237442008-12-16 03:25:46 +0000606 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
607 SU->setDepthToAtLeast(CurCycle);
Dan Gohman343f0c02008-11-19 23:18:57 +0000608
609 // Top down: release successors.
610 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
611 I != E; ++I)
Dan Gohman54e4c362008-12-09 22:54:47 +0000612 ReleaseSucc(SU, &*I);
Dan Gohman343f0c02008-11-19 23:18:57 +0000613
614 SU->isScheduled = true;
615 AvailableQueue.ScheduledNode(SU);
616}
617
618/// ListScheduleTopDown - The main loop of list scheduling for top-down
619/// schedulers.
620void SchedulePostRATDList::ListScheduleTopDown() {
621 unsigned CurCycle = 0;
622
623 // All leaves to Available queue.
624 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
625 // It is available if it has no predecessors.
626 if (SUnits[i].Preds.empty()) {
627 AvailableQueue.push(&SUnits[i]);
628 SUnits[i].isAvailable = true;
629 }
630 }
631
632 // While Available queue is not empty, grab the node with the highest
633 // priority. If it is not ready put it back. Schedule the node.
634 Sequence.reserve(SUnits.size());
635 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
636 // Check to see if any of the pending instructions are ready to issue. If
637 // so, add them to the available queue.
Dan Gohman3f237442008-12-16 03:25:46 +0000638 unsigned MinDepth = ~0u;
Dan Gohman343f0c02008-11-19 23:18:57 +0000639 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman3f237442008-12-16 03:25:46 +0000640 if (PendingQueue[i]->getDepth() <= CurCycle) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000641 AvailableQueue.push(PendingQueue[i]);
642 PendingQueue[i]->isAvailable = true;
643 PendingQueue[i] = PendingQueue.back();
644 PendingQueue.pop_back();
645 --i; --e;
Dan Gohman3f237442008-12-16 03:25:46 +0000646 } else if (PendingQueue[i]->getDepth() < MinDepth)
647 MinDepth = PendingQueue[i]->getDepth();
Dan Gohman343f0c02008-11-19 23:18:57 +0000648 }
649
Dan Gohman21d90032008-11-25 00:52:40 +0000650 // If there are no instructions available, don't try to issue anything.
Dan Gohman343f0c02008-11-19 23:18:57 +0000651 if (AvailableQueue.empty()) {
Dan Gohman3f237442008-12-16 03:25:46 +0000652 CurCycle = MinDepth != ~0u ? MinDepth : CurCycle + 1;
Dan Gohman343f0c02008-11-19 23:18:57 +0000653 continue;
654 }
655
656 SUnit *FoundSUnit = AvailableQueue.pop();
657
658 // If we found a node to schedule, do it now.
659 if (FoundSUnit) {
660 ScheduleNodeTopDown(FoundSUnit, CurCycle);
661
662 // If this is a pseudo-op node, we don't want to increment the current
663 // cycle.
664 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
665 ++CurCycle;
666 } else {
667 // Otherwise, we have a pipeline stall, but no other problem, just advance
668 // the current cycle and try again.
669 DOUT << "*** Advancing cycle, no work to do\n";
670 ++NumStalls;
671 ++CurCycle;
672 }
673 }
674
675#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +0000676 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +0000677#endif
678}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000679
680//===----------------------------------------------------------------------===//
681// Public Constructor Functions
682//===----------------------------------------------------------------------===//
683
684FunctionPass *llvm::createPostRAScheduler() {
Dan Gohman343f0c02008-11-19 23:18:57 +0000685 return new PostRAScheduler();
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000686}