1 //===----- SchedulePostRAList.cpp - list scheduler ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
19 //===----------------------------------------------------------------------===//
21 #define DEBUG_TYPE "post-RA-sched"
22 #include "ExactHazardRecognizer.h"
23 #include "SimpleHazardRecognizer.h"
24 #include "ScheduleDAGInstrs.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/LatencyPriorityQueue.h"
27 #include "llvm/CodeGen/SchedulerRegistry.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
33 #include "llvm/Target/TargetLowering.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/ADT/Statistic.h"
45 STATISTIC(NumNoops, "Number of noops inserted");
46 STATISTIC(NumStalls, "Number of pipeline stalls");
49 EnableAntiDepBreaking("break-anti-dependencies",
50 cl::desc("Break post-RA scheduling anti-dependencies"),
51 cl::init(true), cl::Hidden);
54 EnablePostRAHazardAvoidance("avoid-hazards",
55 cl::desc("Enable exact hazard avoidance"),
56 cl::init(false), cl::Hidden);
59 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
62 PostRAScheduler() : MachineFunctionPass(&ID) {}
64 void getAnalysisUsage(AnalysisUsage &AU) const {
66 AU.addRequired<MachineDominatorTree>();
67 AU.addPreserved<MachineDominatorTree>();
68 AU.addRequired<MachineLoopInfo>();
69 AU.addPreserved<MachineLoopInfo>();
70 MachineFunctionPass::getAnalysisUsage(AU);
73 const char *getPassName() const {
74 return "Post RA top-down list latency scheduler";
77 bool runOnMachineFunction(MachineFunction &Fn);
79 char PostRAScheduler::ID = 0;
81 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
82 /// AvailableQueue - The priority queue to use for the available SUnits.
84 LatencyPriorityQueue AvailableQueue;
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;
92 /// Topo - A topological ordering for SUnits.
93 ScheduleDAGTopologicalSort Topo;
95 /// 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;
100 /// HazardRec - The hazard recognizer to use.
101 ScheduleHazardRecognizer *HazardRec;
103 /// 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
108 const TargetRegisterClass *
109 Classes[TargetRegisterInfo::FirstVirtualRegister];
111 /// RegRegs - Map registers to all their references within a live range.
112 std::multimap<unsigned, MachineOperand *> RegRefs;
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];
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];
123 SchedulePostRATDList(MachineFunction &MF,
124 const MachineLoopInfo &MLI,
125 const MachineDominatorTree &MDT,
126 ScheduleHazardRecognizer *HR)
127 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
128 AllocatableSet(TRI->getAllocatableSet(MF)),
131 ~SchedulePostRATDList() {
135 /// StartBlock - Initialize register live-range state for scheduling in
138 void StartBlock(MachineBasicBlock *BB);
140 /// Schedule - Schedule the instruction range using list scheduling.
144 /// Observe - Update liveness information to account for the current
145 /// instruction, which will not be scheduled.
147 void Observe(MachineInstr *MI, unsigned Count);
149 /// FinishBlock - Clean up register live-range state.
154 void PrescanInstruction(MachineInstr *MI);
155 void ScanInstruction(MachineInstr *MI, unsigned Count);
156 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
157 void ReleaseSuccessors(SUnit *SU);
158 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
159 void ListScheduleTopDown();
160 bool BreakAntiDependencies();
161 unsigned findSuitableFreeRegister(unsigned AntiDepReg,
163 const TargetRegisterClass *);
167 /// isSchedulingBoundary - Test if the given instruction should be
168 /// considered a scheduling boundary. This primarily includes labels
171 static 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())
177 // 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
182 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
183 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
189 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
190 DEBUG(errs() << "PostRAScheduler\n");
192 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
193 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
194 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
195 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
196 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
197 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
199 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
201 // Loop over all of the basic blocks
202 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
203 MBB != MBBe; ++MBB) {
204 // Initialize register live-range state for scheduling in this block.
205 Scheduler.StartBlock(MBB);
207 // Schedule each sequence of instructions not interrupted by a label
208 // or anything else that effectively needs to shut down scheduling.
209 MachineBasicBlock::iterator Current = MBB->end();
210 unsigned Count = MBB->size(), CurrentCount = Count;
211 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
212 MachineInstr *MI = prior(I);
213 if (isSchedulingBoundary(MI, Fn)) {
214 Scheduler.Run(MBB, I, Current, CurrentCount);
215 Scheduler.EmitSchedule();
217 CurrentCount = Count - 1;
218 Scheduler.Observe(MI, CurrentCount);
223 assert(Count == 0 && "Instruction count mismatch!");
224 assert((MBB->begin() == Current || CurrentCount != 0) &&
225 "Instruction count mismatch!");
226 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
227 Scheduler.EmitSchedule();
229 // Clean up register live-range state.
230 Scheduler.FinishBlock();
236 /// StartBlock - Initialize register live-range state for scheduling in
239 void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
240 // Call the superclass.
241 ScheduleDAGInstrs::StartBlock(BB);
243 // Reset the hazard recognizer.
246 // Clear out the register class data.
247 std::fill(Classes, array_endof(Classes),
248 static_cast<const TargetRegisterClass *>(0));
250 // Initialize the indices to indicate that no registers are live.
251 std::fill(KillIndices, array_endof(KillIndices), ~0u);
252 std::fill(DefIndices, array_endof(DefIndices), BB->size());
254 // Determine the live-out physregs for this block.
255 if (!BB->empty() && BB->back().getDesc().isReturn())
256 // 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) {
260 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
261 KillIndices[Reg] = BB->size();
262 DefIndices[Reg] = ~0u;
263 // 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();
268 DefIndices[AliasReg] = ~0u;
272 // In a non-return block, examine the live-in regs of all successors.
273 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
274 SE = BB->succ_end(); SI != SE; ++SI)
275 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
276 E = (*SI)->livein_end(); I != E; ++I) {
278 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
279 KillIndices[Reg] = BB->size();
280 DefIndices[Reg] = ~0u;
281 // 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();
286 DefIndices[AliasReg] = ~0u;
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
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.
297 // Alternatively, callee-saved registers that aren't saved and restored
298 // could be marked live-in in every block.
299 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
301 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
302 KillIndices[Reg] = BB->size();
303 DefIndices[Reg] = ~0u;
304 // 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();
309 DefIndices[AliasReg] = ~0u;
314 /// Schedule - Schedule the instruction range using list scheduling.
316 void SchedulePostRATDList::Schedule() {
317 DEBUG(errs() << "********** List Scheduling **********\n");
319 // Build the scheduling graph.
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.
337 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
338 SUnits[su].dumpAll(this));
340 AvailableQueue.initNodes(SUnits);
342 ListScheduleTopDown();
344 AvailableQueue.releaseState();
347 /// Observe - Update liveness information to account for the current
348 /// instruction, which will not be scheduled.
350 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
351 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
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;
367 PrescanInstruction(MI);
368 ScanInstruction(MI, Count);
371 /// FinishBlock - Clean up register live-range state.
373 void SchedulePostRATDList::FinishBlock() {
376 // Call the superclass.
377 ScheduleDAGInstrs::FinishBlock();
380 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
382 static SDep *CriticalPathStep(SUnit *SU) {
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();
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;
402 void 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;
410 const TargetRegisterClass *NewRC = 0;
412 if (i < MI->getDesc().getNumOperands())
413 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
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);
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);
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));
440 void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
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.
452 if (MI->isRegTiedToUseOperand(i)) continue;
454 DefIndices[Reg] = Count;
455 KillIndices[Reg] = ~0u;
456 assert(((KillIndices[Reg] == ~0u) !=
457 (DefIndices[Reg] == ~0u)) &&
458 "Kill and Def maps aren't consistent for Reg!");
461 // Repeat, for all subregs.
462 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
464 unsigned SubregReg = *Subreg;
465 DefIndices[SubregReg] = Count;
466 KillIndices[SubregReg] = ~0u;
467 Classes[SubregReg] = 0;
468 RegRefs.erase(SubregReg);
470 // Conservatively mark super-registers as unusable.
471 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
473 unsigned SuperReg = *Super;
474 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
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;
484 const TargetRegisterClass *NewRC = 0;
485 if (i < MI->getDesc().getNumOperands())
486 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
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);
495 RegRefs.insert(std::make_pair(Reg, &MO));
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;
501 assert(((KillIndices[Reg] == ~0u) !=
502 (DefIndices[Reg] == ~0u)) &&
503 "Kill and Def maps aren't consistent for Reg!");
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;
517 SchedulePostRATDList::findSuitableFreeRegister(unsigned AntiDepReg,
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!");
535 if (KillIndices[NewReg] != ~0u ||
536 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
537 KillIndices[AntiDepReg] > DefIndices[NewReg])
542 // No registers are free and available!
546 /// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
547 /// of the ScheduleDAG and break them by renaming registers.
549 bool 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;
554 // Find the node at the bottom of the critical path.
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)
562 DEBUG(errs() << "Critical path has total latency "
563 << (Max->getDepth() + Max->Latency) << "\n");
565 // Track progress along the critical path through the SUnit graph as we walk
567 SUnit *CriticalPathSU = Max;
568 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
570 // Consider this pattern:
579 // There are three anti-dependencies here, and without special care,
580 // we'd break all of them using the same register:
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
593 // register that each register was replaced with, avoid
594 // using it to repair an anti-dependence on the same register.
595 // This lets us produce this:
604 // This still has an anti-dependence on B, but at least it isn't on the
605 // original critical path.
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] = {};
613 // 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;
617 unsigned Count = InsertPosIndex - 1;
618 for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
620 MachineInstr *MI = --I;
622 // 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)
629 // 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.
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.
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();
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.
652 if (!AllocatableSet.test(AntiDepReg))
655 // 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.
660 // Also, if there are dependencies on other SUnits with the
661 // same register as the anti-dependency, don't attempt to
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)) {
673 CriticalPathSU = NextSU;
674 CriticalPathMI = CriticalPathSU->getInstr();
676 // We've reached the end of the critical path.
682 PrescanInstruction(MI);
684 // If this instruction has a use of AntiDepReg, breaking it
686 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;
691 if (MO.isUse() && AntiDepReg == Reg) {
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;
700 assert((AntiDepReg == 0 || RC != NULL) &&
701 "Register should be live if it's causing an anti-dependence!");
702 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
705 // Look for a suitable register to use to break the anti-depenence.
707 // TODO: Instead of picking the first free register, consider which might
709 if (AntiDepReg != 0) {
710 if (unsigned NewReg = findSuitableFreeRegister(AntiDepReg,
711 LastNewReg[AntiDepReg],
713 DEBUG(errs() << "Breaking anti-dependence edge on "
714 << TRI->getName(AntiDepReg)
715 << " with " << RegRefs.count(AntiDepReg) << " references"
716 << " using " << TRI->getName(NewReg) << "!\n");
718 // Update the references to the old register to refer to the new
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);
727 // 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!");
737 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!");
744 RegRefs.erase(AntiDepReg);
746 LastNewReg[AntiDepReg] = NewReg;
750 ScanInstruction(MI, Count);
756 //===----------------------------------------------------------------------===//
757 // Top-Down Scheduling
758 //===----------------------------------------------------------------------===//
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.
762 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
763 SUnit *SuccSU = SuccEdge->getSUnit();
764 --SuccSU->NumPredsLeft;
767 if (SuccSU->NumPredsLeft < 0) {
768 cerr << "*** Scheduling failed! ***\n";
770 cerr << " has been released too many times!\n";
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
778 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
780 // 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)
783 PendingQueue.push_back(SuccSU);
786 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
787 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
788 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
790 ReleaseSucc(SU, &*I);
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.
796 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
797 DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
798 DEBUG(SU->dump(this));
800 Sequence.push_back(SU);
801 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
802 SU->setDepthToAtLeast(CurCycle);
804 ReleaseSuccessors(SU);
805 SU->isScheduled = true;
806 AvailableQueue.ScheduledNode(SU);
809 /// ListScheduleTopDown - The main loop of list scheduling for top-down
811 void SchedulePostRATDList::ListScheduleTopDown() {
812 unsigned CurCycle = 0;
814 // Release any successors of the special Entry node.
815 ReleaseSuccessors(&EntrySU);
817 // 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;
826 // 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;
830 // 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.
832 std::vector<SUnit*> NotReady;
833 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.
837 unsigned MinDepth = ~0u;
838 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
839 if (PendingQueue[i]->getDepth() <= CurCycle) {
840 AvailableQueue.push(PendingQueue[i]);
841 PendingQueue[i]->isAvailable = true;
842 PendingQueue[i] = PendingQueue.back();
843 PendingQueue.pop_back();
845 } else if (PendingQueue[i]->getDepth() < MinDepth)
846 MinDepth = PendingQueue[i]->getDepth();
849 DEBUG(errs() << "\n*** Examining Available\n";
850 LatencyPriorityQueue q = AvailableQueue;
853 errs() << "Height " << su->getHeight() << ": ";
857 SUnit *FoundSUnit = 0;
859 bool HasNoopHazards = false;
860 while (!AvailableQueue.empty()) {
861 SUnit *CurSUnit = AvailableQueue.pop();
863 ScheduleHazardRecognizer::HazardType HT =
864 HazardRec->getHazardType(CurSUnit);
865 if (HT == ScheduleHazardRecognizer::NoHazard) {
866 FoundSUnit = CurSUnit;
870 // Remember if this is a noop hazard.
871 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
873 NotReady.push_back(CurSUnit);
876 // Add the nodes that aren't ready back onto the available list.
877 if (!NotReady.empty()) {
878 AvailableQueue.push_all(NotReady);
882 // If we found a node to schedule, do it now.
884 ScheduleNodeTopDown(FoundSUnit, CurCycle);
885 HazardRec->EmitInstruction(FoundSUnit);
888 // 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
892 if (!EnablePostRAHazardAvoidance) {
893 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
897 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();
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
922 VerifySchedule(/*isBottomUp=*/false);
926 //===----------------------------------------------------------------------===//
927 // Public Constructor Functions
928 //===----------------------------------------------------------------------===//
930 FunctionPass *llvm::createPostRAScheduler() {
931 return new PostRAScheduler();