blob: 2f7c0118a05d92771e9e94b04a6e4b7884f9fbd7 [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"
Dan Gohmancef874a2008-12-03 23:07:27 +000034#include "llvm/ADT/SmallVector.h"
Dan Gohman21d90032008-11-25 00:52:40 +000035#include <map>
36#include <climits>
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000037using namespace llvm;
38
Dan Gohman343f0c02008-11-19 23:18:57 +000039STATISTIC(NumStalls, "Number of pipeline stalls");
40
Dan Gohman21d90032008-11-25 00:52:40 +000041static cl::opt<bool>
42EnableAntiDepBreaking("break-anti-dependencies",
43 cl::desc("Break scheduling anti-dependencies"),
44 cl::init(false));
45
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000046namespace {
Dan Gohman343f0c02008-11-19 23:18:57 +000047 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000048 public:
49 static char ID;
Dan Gohman343f0c02008-11-19 23:18:57 +000050 PostRAScheduler() : MachineFunctionPass(&ID) {}
Dan Gohman21d90032008-11-25 00:52:40 +000051
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000052 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +000053 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000054 }
55
56 bool runOnMachineFunction(MachineFunction &Fn);
57 };
Dan Gohman343f0c02008-11-19 23:18:57 +000058 char PostRAScheduler::ID = 0;
59
60 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +000061 /// AvailableQueue - The priority queue to use for the available SUnits.
62 ///
63 LatencyPriorityQueue AvailableQueue;
64
65 /// PendingQueue - This contains all of the instructions whose operands have
66 /// been issued, but their results are not ready yet (due to the latency of
67 /// the operation). Once the operands becomes available, the instruction is
68 /// added to the AvailableQueue.
69 std::vector<SUnit*> PendingQueue;
70
Dan Gohman21d90032008-11-25 00:52:40 +000071 /// Topo - A topological ordering for SUnits.
72 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +000073
Dan Gohman21d90032008-11-25 00:52:40 +000074 public:
75 SchedulePostRATDList(MachineBasicBlock *mbb, const TargetMachine &tm)
76 : ScheduleDAGInstrs(mbb, tm), Topo(SUnits) {}
Dan Gohman343f0c02008-11-19 23:18:57 +000077
78 void Schedule();
79
80 private:
Dan Gohman54e4c362008-12-09 22:54:47 +000081 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohman343f0c02008-11-19 23:18:57 +000082 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
83 void ListScheduleTopDown();
Dan Gohman21d90032008-11-25 00:52:40 +000084 bool BreakAntiDependencies();
Dan Gohman343f0c02008-11-19 23:18:57 +000085 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000086}
87
Dan Gohman343f0c02008-11-19 23:18:57 +000088bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
89 DOUT << "PostRAScheduler\n";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000090
91 // Loop over all of the basic blocks
92 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +000093 MBB != MBBe; ++MBB) {
94
Dan Gohman21d90032008-11-25 00:52:40 +000095 SchedulePostRATDList Scheduler(MBB, Fn.getTarget());
Dan Gohman343f0c02008-11-19 23:18:57 +000096
97 Scheduler.Run();
98
99 Scheduler.EmitSchedule();
100 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000101
102 return true;
103}
104
Dan Gohman343f0c02008-11-19 23:18:57 +0000105/// Schedule - Schedule the DAG using list scheduling.
106void SchedulePostRATDList::Schedule() {
107 DOUT << "********** List Scheduling **********\n";
108
109 // Build scheduling units.
110 BuildSchedUnits();
111
Dan Gohman21d90032008-11-25 00:52:40 +0000112 if (EnableAntiDepBreaking) {
113 if (BreakAntiDependencies()) {
114 // We made changes. Update the dependency graph.
115 // Theoretically we could update the graph in place:
116 // When a live range is changed to use a different register, remove
117 // the def's anti-dependence *and* output-dependence edges due to
118 // that register, and add new anti-dependence and output-dependence
119 // edges based on the next live range of the register.
120 SUnits.clear();
121 BuildSchedUnits();
122 }
123 }
124
Dan Gohman343f0c02008-11-19 23:18:57 +0000125 AvailableQueue.initNodes(SUnits);
Dan Gohman21d90032008-11-25 00:52:40 +0000126
Dan Gohman343f0c02008-11-19 23:18:57 +0000127 ListScheduleTopDown();
128
129 AvailableQueue.releaseState();
130}
131
Dan Gohman21d90032008-11-25 00:52:40 +0000132/// getInstrOperandRegClass - Return register class of the operand of an
133/// instruction of the specified TargetInstrDesc.
134static const TargetRegisterClass*
135getInstrOperandRegClass(const TargetRegisterInfo *TRI,
136 const TargetInstrInfo *TII, const TargetInstrDesc &II,
137 unsigned Op) {
138 if (Op >= II.getNumOperands())
139 return NULL;
140 if (II.OpInfo[Op].isLookupPtrRegClass())
141 return TII->getPointerRegClass();
142 return TRI->getRegClass(II.OpInfo[Op].RegClass);
143}
144
145/// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
146/// of the ScheduleDAG and break them by renaming registers.
147///
148bool SchedulePostRATDList::BreakAntiDependencies() {
149 // The code below assumes that there is at least one instruction,
150 // so just duck out immediately if the block is empty.
151 if (BB->empty()) return false;
152
153 Topo.InitDAGTopologicalSorting();
154
155 // Compute a critical path for the DAG.
156 SUnit *Max = 0;
157 std::vector<SDep *> CriticalPath(SUnits.size());
158 for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
159 E = Topo.end(); I != E; ++I) {
160 SUnit *SU = &SUnits[*I];
161 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
162 P != PE; ++P) {
Dan Gohman54e4c362008-12-09 22:54:47 +0000163 SUnit *PredSU = P->getSUnit();
Dan Gohmane5617512008-12-03 19:37:34 +0000164 // This assumes that there's no delay for reusing registers.
Dan Gohman54e4c362008-12-09 22:54:47 +0000165 unsigned PredLatency = P->getLatency();
Dan Gohmane5617512008-12-03 19:37:34 +0000166 unsigned PredTotalLatency = PredSU->CycleBound + PredLatency;
167 if (SU->CycleBound < PredTotalLatency ||
Dan Gohman54e4c362008-12-09 22:54:47 +0000168 (SU->CycleBound == PredTotalLatency &&
169 P->getKind() == SDep::Anti)) {
Dan Gohmane5617512008-12-03 19:37:34 +0000170 SU->CycleBound = PredTotalLatency;
Dan Gohman21d90032008-11-25 00:52:40 +0000171 CriticalPath[*I] = &*P;
172 }
173 }
174 // Keep track of the node at the end of the critical path.
175 if (!Max || SU->CycleBound + SU->Latency > Max->CycleBound + Max->Latency)
176 Max = SU;
177 }
178
179 DOUT << "Critical path has total latency "
180 << (Max ? Max->CycleBound + Max->Latency : 0) << "\n";
181
182 // Walk the critical path from the bottom up. Collect all anti-dependence
183 // edges on the critical path. Skip anti-dependencies between SUnits that
184 // are connected with other edges, since such units won't be able to be
185 // scheduled past each other anyway.
186 //
187 // The heuristic is that edges on the critical path are more important to
188 // break than other edges. And since there are a limited number of
189 // registers, we don't want to waste them breaking edges that aren't
190 // important.
191 //
192 // TODO: Instructions with multiple defs could have multiple
193 // anti-dependencies. The current code here only knows how to break one
194 // edge per instruction. Note that we'd have to be able to break all of
195 // the anti-dependencies in an instruction in order to be effective.
196 BitVector AllocatableSet = TRI->getAllocatableSet(*MF);
197 DenseMap<MachineInstr *, unsigned> CriticalAntiDeps;
198 for (SUnit *SU = Max; CriticalPath[SU->NodeNum];
Dan Gohman54e4c362008-12-09 22:54:47 +0000199 SU = CriticalPath[SU->NodeNum]->getSUnit()) {
Dan Gohman21d90032008-11-25 00:52:40 +0000200 SDep *Edge = CriticalPath[SU->NodeNum];
Dan Gohman54e4c362008-12-09 22:54:47 +0000201 SUnit *NextSU = Edge->getSUnit();
Dan Gohman0dba0e52008-12-03 19:32:26 +0000202 // Only consider anti-dependence edges.
Dan Gohman54e4c362008-12-09 22:54:47 +0000203 if (Edge->getKind() != SDep::Anti)
Dan Gohman0dba0e52008-12-03 19:32:26 +0000204 continue;
Dan Gohman54e4c362008-12-09 22:54:47 +0000205 unsigned AntiDepReg = Edge->getReg();
Dan Gohman0dba0e52008-12-03 19:32:26 +0000206 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
Dan Gohman21d90032008-11-25 00:52:40 +0000207 // Don't break anti-dependencies on non-allocatable registers.
208 if (!AllocatableSet.test(AntiDepReg))
209 continue;
210 // If the SUnit has other dependencies on the SUnit that it
211 // anti-depends on, don't bother breaking the anti-dependency.
212 // Also, if there are dependencies on other SUnits with the
213 // same register as the anti-dependency, don't attempt to
214 // break it.
215 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
216 P != PE; ++P)
Dan Gohman54e4c362008-12-09 22:54:47 +0000217 if (P->getSUnit() == NextSU ?
218 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
219 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
Dan Gohman21d90032008-11-25 00:52:40 +0000220 AntiDepReg = 0;
221 break;
222 }
223 if (AntiDepReg != 0)
224 CriticalAntiDeps[SU->getInstr()] = AntiDepReg;
225 }
226
227 // For live regs that are only used in one register class in a live range,
Dan Gohmane96cc772008-12-03 19:38:38 +0000228 // the register class. If the register is not live, the corresponding value
229 // is null. If the register is live but used in multiple register classes,
230 // the corresponding value is -1 casted to a pointer.
Dan Gohman21d90032008-11-25 00:52:40 +0000231 const TargetRegisterClass *
232 Classes[TargetRegisterInfo::FirstVirtualRegister] = {};
233
234 // Map registers to all their references within a live range.
235 std::multimap<unsigned, MachineOperand *> RegRefs;
236
237 // The index of the most recent kill (proceding bottom-up), or -1 if
238 // the register is not live.
239 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
240 std::fill(KillIndices, array_endof(KillIndices), -1);
241 // The index of the most recent def (proceding bottom up), or -1 if
242 // the register is live.
243 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
244 std::fill(DefIndices, array_endof(DefIndices), BB->size());
245
246 // Determine the live-out physregs for this block.
247 if (!BB->empty() && BB->back().getDesc().isReturn())
248 // In a return block, examine the function live-out regs.
249 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
250 E = MRI.liveout_end(); I != E; ++I) {
251 unsigned Reg = *I;
252 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
253 KillIndices[Reg] = BB->size();
254 DefIndices[Reg] = -1;
255 // Repeat, for all aliases.
256 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
257 unsigned AliasReg = *Alias;
258 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
259 KillIndices[AliasReg] = BB->size();
260 DefIndices[AliasReg] = -1;
261 }
262 }
263 else
264 // In a non-return block, examine the live-in regs of all successors.
265 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
266 SE = BB->succ_end(); SI != SE; ++SI)
267 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
268 E = (*SI)->livein_end(); I != E; ++I) {
269 unsigned Reg = *I;
270 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
271 KillIndices[Reg] = BB->size();
272 DefIndices[Reg] = -1;
273 // Repeat, for all aliases.
274 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
275 unsigned AliasReg = *Alias;
276 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
277 KillIndices[AliasReg] = BB->size();
278 DefIndices[AliasReg] = -1;
279 }
280 }
281
282 // Consider callee-saved registers as live-out, since we're running after
283 // prologue/epilogue insertion so there's no way to add additional
284 // saved registers.
285 //
286 // TODO: If the callee saves and restores these, then we can potentially
287 // use them between the save and the restore. To do that, we could scan
288 // the exit blocks to see which of these registers are defined.
Dan Gohmanebb0a312008-12-03 19:30:13 +0000289 // Alternatively, calle-saved registers that aren't saved and restored
290 // could be marked live-in in every block.
Dan Gohman21d90032008-11-25 00:52:40 +0000291 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
292 unsigned Reg = *I;
293 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
294 KillIndices[Reg] = BB->size();
295 DefIndices[Reg] = -1;
296 // Repeat, for all aliases.
297 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
298 unsigned AliasReg = *Alias;
299 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
300 KillIndices[AliasReg] = BB->size();
301 DefIndices[AliasReg] = -1;
302 }
303 }
304
305 // Consider this pattern:
306 // A = ...
307 // ... = A
308 // A = ...
309 // ... = A
310 // A = ...
311 // ... = A
312 // A = ...
313 // ... = A
314 // There are three anti-dependencies here, and without special care,
315 // we'd break all of them using the same register:
316 // A = ...
317 // ... = A
318 // B = ...
319 // ... = B
320 // B = ...
321 // ... = B
322 // B = ...
323 // ... = B
324 // because at each anti-dependence, B is the first register that
325 // isn't A which is free. This re-introduces anti-dependencies
326 // at all but one of the original anti-dependencies that we were
327 // trying to break. To avoid this, keep track of the most recent
328 // register that each register was replaced with, avoid avoid
329 // using it to repair an anti-dependence on the same register.
330 // This lets us produce this:
331 // A = ...
332 // ... = A
333 // B = ...
334 // ... = B
335 // C = ...
336 // ... = C
337 // B = ...
338 // ... = B
339 // This still has an anti-dependence on B, but at least it isn't on the
340 // original critical path.
341 //
342 // TODO: If we tracked more than one register here, we could potentially
343 // fix that remaining critical edge too. This is a little more involved,
344 // because unlike the most recent register, less recent registers should
345 // still be considered, though only if no other registers are available.
346 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
347
Dan Gohman21d90032008-11-25 00:52:40 +0000348 // Attempt to break anti-dependence edges on the critical path. Walk the
349 // instructions from the bottom up, tracking information about liveness
350 // as we go to help determine which registers are available.
351 bool Changed = false;
352 unsigned Count = BB->size() - 1;
353 for (MachineBasicBlock::reverse_iterator I = BB->rbegin(), E = BB->rend();
354 I != E; ++I, --Count) {
355 MachineInstr *MI = &*I;
356
Dan Gohman490b1832008-12-05 05:30:02 +0000357 // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
358 // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
359 // is left behind appearing to clobber the super-register, while the
360 // subregister needs to remain live. So we just ignore them.
361 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
362 continue;
363
Dan Gohman21d90032008-11-25 00:52:40 +0000364 // Check if this instruction has an anti-dependence that we're
365 // interested in.
366 DenseMap<MachineInstr *, unsigned>::iterator C = CriticalAntiDeps.find(MI);
367 unsigned AntiDepReg = C != CriticalAntiDeps.end() ?
368 C->second : 0;
369
370 // Scan the register operands for this instruction and update
371 // Classes and RegRefs.
372 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
373 MachineOperand &MO = MI->getOperand(i);
374 if (!MO.isReg()) continue;
375 unsigned Reg = MO.getReg();
376 if (Reg == 0) continue;
377 const TargetRegisterClass *NewRC =
378 getInstrOperandRegClass(TRI, TII, MI->getDesc(), i);
379
380 // If this instruction has a use of AntiDepReg, breaking it
381 // is invalid.
382 if (MO.isUse() && AntiDepReg == Reg)
383 AntiDepReg = 0;
384
385 // For now, only allow the register to be changed if its register
386 // class is consistent across all uses.
387 if (!Classes[Reg] && NewRC)
388 Classes[Reg] = NewRC;
389 else if (!NewRC || Classes[Reg] != NewRC)
390 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
391
392 // Now check for aliases.
393 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
394 // If an alias of the reg is used during the live range, give up.
395 // Note that this allows us to skip checking if AntiDepReg
396 // overlaps with any of the aliases, among other things.
397 unsigned AliasReg = *Alias;
398 if (Classes[AliasReg]) {
399 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
400 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
401 }
402 }
403
404 // If we're still willing to consider this register, note the reference.
405 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
406 RegRefs.insert(std::make_pair(Reg, &MO));
407 }
408
409 // Determine AntiDepReg's register class, if it is live and is
410 // consistently used within a single class.
411 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
Nick Lewyckya89d1022008-11-27 17:29:52 +0000412 assert((AntiDepReg == 0 || RC != NULL) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000413 "Register should be live if it's causing an anti-dependence!");
414 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
415 AntiDepReg = 0;
416
417 // Look for a suitable register to use to break the anti-depenence.
418 //
419 // TODO: Instead of picking the first free register, consider which might
420 // be the best.
421 if (AntiDepReg != 0) {
422 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(*MF),
423 RE = RC->allocation_order_end(*MF); R != RE; ++R) {
424 unsigned NewReg = *R;
425 // Don't replace a register with itself.
426 if (NewReg == AntiDepReg) continue;
427 // Don't replace a register with one that was recently used to repair
428 // an anti-dependence with this AntiDepReg, because that would
429 // re-introduce that anti-dependence.
430 if (NewReg == LastNewReg[AntiDepReg]) continue;
431 // If NewReg is dead and NewReg's most recent def is not before
432 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
Dan Gohman878ef1d2008-11-25 18:53:54 +0000433 assert(((KillIndices[AntiDepReg] == -1u) != (DefIndices[AntiDepReg] == -1u)) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000434 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman878ef1d2008-11-25 18:53:54 +0000435 assert(((KillIndices[NewReg] == -1u) != (DefIndices[NewReg] == -1u)) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000436 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman878ef1d2008-11-25 18:53:54 +0000437 if (KillIndices[NewReg] == -1u &&
Dan Gohman21d90032008-11-25 00:52:40 +0000438 KillIndices[AntiDepReg] <= DefIndices[NewReg]) {
Dan Gohman80e201b2008-12-04 02:15:26 +0000439 DOUT << "Breaking anti-dependence edge on "
440 << TRI->getName(AntiDepReg)
Dan Gohmancef874a2008-12-03 23:07:27 +0000441 << " with " << RegRefs.count(AntiDepReg) << " references"
Dan Gohman80e201b2008-12-04 02:15:26 +0000442 << " using " << TRI->getName(NewReg) << "!\n";
Dan Gohman21d90032008-11-25 00:52:40 +0000443
444 // Update the references to the old register to refer to the new
445 // register.
446 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
447 std::multimap<unsigned, MachineOperand *>::iterator>
448 Range = RegRefs.equal_range(AntiDepReg);
449 for (std::multimap<unsigned, MachineOperand *>::iterator
450 Q = Range.first, QE = Range.second; Q != QE; ++Q)
451 Q->second->setReg(NewReg);
452
453 // We just went back in time and modified history; the
454 // liveness information for the anti-depenence reg is now
455 // inconsistent. Set the state as if it were dead.
456 Classes[NewReg] = Classes[AntiDepReg];
457 DefIndices[NewReg] = DefIndices[AntiDepReg];
458 KillIndices[NewReg] = KillIndices[AntiDepReg];
459
460 Classes[AntiDepReg] = 0;
461 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
462 KillIndices[AntiDepReg] = -1;
463
464 RegRefs.erase(AntiDepReg);
465 Changed = true;
466 LastNewReg[AntiDepReg] = NewReg;
467 break;
468 }
469 }
470 }
471
472 // Update liveness.
Dan Gohmancef874a2008-12-03 23:07:27 +0000473 // Proceding upwards, registers that are defed but not used in this
474 // instruction are now dead.
Dan Gohman21d90032008-11-25 00:52:40 +0000475 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
476 MachineOperand &MO = MI->getOperand(i);
477 if (!MO.isReg()) continue;
478 unsigned Reg = MO.getReg();
479 if (Reg == 0) continue;
Dan Gohmancef874a2008-12-03 23:07:27 +0000480 if (!MO.isDef()) continue;
481 // Ignore two-addr defs.
Dan Gohman2ce7f202008-12-05 05:45:42 +0000482 if (MI->isRegReDefinedByTwoAddr(i)) continue;
Dan Gohmancef874a2008-12-03 23:07:27 +0000483
Dan Gohman21d90032008-11-25 00:52:40 +0000484 DefIndices[Reg] = Count;
485 KillIndices[Reg] = -1;
486 Classes[Reg] = 0;
487 RegRefs.erase(Reg);
488 // Repeat, for all subregs.
489 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
490 *Subreg; ++Subreg) {
491 unsigned SubregReg = *Subreg;
492 DefIndices[SubregReg] = Count;
493 KillIndices[SubregReg] = -1;
494 Classes[SubregReg] = 0;
495 RegRefs.erase(SubregReg);
496 }
497 }
Dan Gohmancef874a2008-12-03 23:07:27 +0000498 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
499 MachineOperand &MO = MI->getOperand(i);
500 if (!MO.isReg()) continue;
501 unsigned Reg = MO.getReg();
502 if (Reg == 0) continue;
503 if (!MO.isUse()) continue;
504
505 const TargetRegisterClass *NewRC =
506 getInstrOperandRegClass(TRI, TII, MI->getDesc(), i);
507
508 // For now, only allow the register to be changed if its register
509 // class is consistent across all uses.
510 if (!Classes[Reg] && NewRC)
511 Classes[Reg] = NewRC;
512 else if (!NewRC || Classes[Reg] != NewRC)
513 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
514
515 RegRefs.insert(std::make_pair(Reg, &MO));
516
517 // It wasn't previously live but now it is, this is a kill.
518 if (KillIndices[Reg] == -1u) {
519 KillIndices[Reg] = Count;
520 DefIndices[Reg] = -1u;
521 }
522 // Repeat, for all aliases.
523 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
524 unsigned AliasReg = *Alias;
525 if (KillIndices[AliasReg] == -1u) {
526 KillIndices[AliasReg] = Count;
527 DefIndices[AliasReg] = -1u;
528 }
529 }
530 }
Dan Gohman21d90032008-11-25 00:52:40 +0000531 }
532 assert(Count == -1u && "Count mismatch!");
533
534 return Changed;
535}
536
Dan Gohman343f0c02008-11-19 23:18:57 +0000537//===----------------------------------------------------------------------===//
538// Top-Down Scheduling
539//===----------------------------------------------------------------------===//
540
541/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
542/// the PendingQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman54e4c362008-12-09 22:54:47 +0000543void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
544 SUnit *SuccSU = SuccEdge->getSUnit();
Dan Gohman343f0c02008-11-19 23:18:57 +0000545 --SuccSU->NumPredsLeft;
546
547#ifndef NDEBUG
548 if (SuccSU->NumPredsLeft < 0) {
549 cerr << "*** Scheduling failed! ***\n";
550 SuccSU->dump(this);
551 cerr << " has been released too many times!\n";
552 assert(0);
553 }
554#endif
555
556 // Compute how many cycles it will be before this actually becomes
557 // available. This is the max of the start time of all predecessors plus
558 // their latencies.
Dan Gohman54e4c362008-12-09 22:54:47 +0000559 unsigned PredDoneCycle = SU->Cycle + SuccEdge->getLatency();
Dan Gohman343f0c02008-11-19 23:18:57 +0000560 SuccSU->CycleBound = std::max(SuccSU->CycleBound, PredDoneCycle);
561
562 if (SuccSU->NumPredsLeft == 0) {
563 PendingQueue.push_back(SuccSU);
564 }
565}
566
567/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
568/// count of its successors. If a successor pending count is zero, add it to
569/// the Available queue.
570void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
571 DOUT << "*** Scheduling [" << CurCycle << "]: ";
572 DEBUG(SU->dump(this));
573
574 Sequence.push_back(SU);
575 SU->Cycle = CurCycle;
576
577 // Top down: release successors.
578 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
579 I != E; ++I)
Dan Gohman54e4c362008-12-09 22:54:47 +0000580 ReleaseSucc(SU, &*I);
Dan Gohman343f0c02008-11-19 23:18:57 +0000581
582 SU->isScheduled = true;
583 AvailableQueue.ScheduledNode(SU);
584}
585
586/// ListScheduleTopDown - The main loop of list scheduling for top-down
587/// schedulers.
588void SchedulePostRATDList::ListScheduleTopDown() {
589 unsigned CurCycle = 0;
590
591 // All leaves to Available queue.
592 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
593 // It is available if it has no predecessors.
594 if (SUnits[i].Preds.empty()) {
595 AvailableQueue.push(&SUnits[i]);
596 SUnits[i].isAvailable = true;
597 }
598 }
599
600 // While Available queue is not empty, grab the node with the highest
601 // priority. If it is not ready put it back. Schedule the node.
602 Sequence.reserve(SUnits.size());
603 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
604 // Check to see if any of the pending instructions are ready to issue. If
605 // so, add them to the available queue.
606 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
607 if (PendingQueue[i]->CycleBound == CurCycle) {
608 AvailableQueue.push(PendingQueue[i]);
609 PendingQueue[i]->isAvailable = true;
610 PendingQueue[i] = PendingQueue.back();
611 PendingQueue.pop_back();
612 --i; --e;
613 } else {
Dan Gohman54e4c362008-12-09 22:54:47 +0000614 assert(PendingQueue[i]->CycleBound > CurCycle && "Non-positive latency?");
Dan Gohman343f0c02008-11-19 23:18:57 +0000615 }
616 }
617
Dan Gohman21d90032008-11-25 00:52:40 +0000618 // If there are no instructions available, don't try to issue anything.
Dan Gohman343f0c02008-11-19 23:18:57 +0000619 if (AvailableQueue.empty()) {
620 ++CurCycle;
621 continue;
622 }
623
624 SUnit *FoundSUnit = AvailableQueue.pop();
625
626 // If we found a node to schedule, do it now.
627 if (FoundSUnit) {
628 ScheduleNodeTopDown(FoundSUnit, CurCycle);
629
630 // If this is a pseudo-op node, we don't want to increment the current
631 // cycle.
632 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
633 ++CurCycle;
634 } else {
635 // Otherwise, we have a pipeline stall, but no other problem, just advance
636 // the current cycle and try again.
637 DOUT << "*** Advancing cycle, no work to do\n";
638 ++NumStalls;
639 ++CurCycle;
640 }
641 }
642
643#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +0000644 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +0000645#endif
646}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000647
648//===----------------------------------------------------------------------===//
649// Public Constructor Functions
650//===----------------------------------------------------------------------===//
651
652FunctionPass *llvm::createPostRAScheduler() {
Dan Gohman343f0c02008-11-19 23:18:57 +0000653 return new PostRAScheduler();
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000654}