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 "ScheduleDAGInstrs.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/LatencyPriorityQueue.h"
25 #include "llvm/CodeGen/SchedulerRegistry.h"
26 #include "llvm/CodeGen/MachineDominators.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
31 #include "llvm/Target/TargetLowering.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/ADT/Statistic.h"
42 STATISTIC(NumNoops, "Number of noops inserted");
43 STATISTIC(NumStalls, "Number of pipeline stalls");
46 EnableAntiDepBreaking("break-anti-dependencies",
47 cl::desc("Break post-RA scheduling anti-dependencies"),
48 cl::init(true), cl::Hidden);
51 EnablePostRAHazardAvoidance("avoid-hazards",
52 cl::desc("Enable simple hazard-avoidance"),
53 cl::init(true), cl::Hidden);
56 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
59 PostRAScheduler() : MachineFunctionPass(&ID) {}
61 void getAnalysisUsage(AnalysisUsage &AU) const {
63 AU.addRequired<MachineDominatorTree>();
64 AU.addPreserved<MachineDominatorTree>();
65 AU.addRequired<MachineLoopInfo>();
66 AU.addPreserved<MachineLoopInfo>();
67 MachineFunctionPass::getAnalysisUsage(AU);
70 const char *getPassName() const {
71 return "Post RA top-down list latency scheduler";
74 bool runOnMachineFunction(MachineFunction &Fn);
76 char PostRAScheduler::ID = 0;
78 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
79 /// AvailableQueue - The priority queue to use for the available SUnits.
81 LatencyPriorityQueue AvailableQueue;
83 /// PendingQueue - This contains all of the instructions whose operands have
84 /// been issued, but their results are not ready yet (due to the latency of
85 /// the operation). Once the operands becomes available, the instruction is
86 /// added to the AvailableQueue.
87 std::vector<SUnit*> PendingQueue;
89 /// Topo - A topological ordering for SUnits.
90 ScheduleDAGTopologicalSort Topo;
92 /// AllocatableSet - The set of allocatable registers.
93 /// We'll be ignoring anti-dependencies on non-allocatable registers,
94 /// because they may not be safe to break.
95 const BitVector AllocatableSet;
97 /// HazardRec - The hazard recognizer to use.
98 ScheduleHazardRecognizer *HazardRec;
100 /// Classes - For live regs that are only used in one register class in a
101 /// live range, the register class. If the register is not live, the
102 /// corresponding value is null. If the register is live but used in
103 /// multiple register classes, the corresponding value is -1 casted to a
105 const TargetRegisterClass *
106 Classes[TargetRegisterInfo::FirstVirtualRegister];
108 /// RegRegs - Map registers to all their references within a live range.
109 std::multimap<unsigned, MachineOperand *> RegRefs;
111 /// The index of the most recent kill (proceding bottom-up), or ~0u if
112 /// the register is not live.
113 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
115 /// The index of the most recent complete def (proceding bottom up), or ~0u
116 /// if the register is live.
117 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
120 SchedulePostRATDList(MachineFunction &MF,
121 const MachineLoopInfo &MLI,
122 const MachineDominatorTree &MDT,
123 ScheduleHazardRecognizer *HR)
124 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
125 AllocatableSet(TRI->getAllocatableSet(MF)),
128 ~SchedulePostRATDList() {
132 /// StartBlock - Initialize register live-range state for scheduling in
135 void StartBlock(MachineBasicBlock *BB);
137 /// Schedule - Schedule the instruction range using list scheduling.
141 /// Observe - Update liveness information to account for the current
142 /// instruction, which will not be scheduled.
144 void Observe(MachineInstr *MI, unsigned Count);
146 /// FinishBlock - Clean up register live-range state.
151 void PrescanInstruction(MachineInstr *MI);
152 void ScanInstruction(MachineInstr *MI, unsigned Count);
153 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
154 void ReleaseSuccessors(SUnit *SU);
155 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
156 void ListScheduleTopDown();
157 bool BreakAntiDependencies();
160 /// SimpleHazardRecognizer - A *very* simple hazard recognizer. It uses
161 /// a coarse classification and attempts to avoid that instructions of
162 /// a given class aren't grouped too densely together.
163 class SimpleHazardRecognizer : public ScheduleHazardRecognizer {
164 /// Class - A simple classification for SUnits.
169 /// Window - The Class values of the most recently issued
173 /// getClass - Classify the given SUnit.
174 Class getClass(const SUnit *SU) {
175 const MachineInstr *MI = SU->getInstr();
176 const TargetInstrDesc &TID = MI->getDesc();
184 /// Step - Rotate the existing entries in Window and insert the
185 /// given class value in position as the most recent.
187 std::copy(Window+1, array_endof(Window), Window);
188 Window[array_lengthof(Window)-1] = C;
192 SimpleHazardRecognizer() : Window() {}
194 virtual HazardType getHazardType(SUnit *SU) {
195 Class C = getClass(SU);
199 for (unsigned i = 0; i != array_lengthof(Window); ++i)
202 if (Score > array_lengthof(Window) * 2)
207 virtual void EmitInstruction(SUnit *SU) {
211 virtual void AdvanceCycle() {
217 /// isSchedulingBoundary - Test if the given instruction should be
218 /// considered a scheduling boundary. This primarily includes labels
221 static bool isSchedulingBoundary(const MachineInstr *MI,
222 const MachineFunction &MF) {
223 // Terminators and labels can't be scheduled around.
224 if (MI->getDesc().isTerminator() || MI->isLabel())
227 // Don't attempt to schedule around any instruction that modifies
228 // a stack-oriented pointer, as it's unlikely to be profitable. This
229 // saves compile time, because it doesn't require every single
230 // stack slot reference to depend on the instruction that does the
232 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
233 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
239 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
240 DOUT << "PostRAScheduler\n";
242 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
243 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
244 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
245 new SimpleHazardRecognizer :
246 new ScheduleHazardRecognizer();
248 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
250 // Loop over all of the basic blocks
251 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
252 MBB != MBBe; ++MBB) {
253 // Initialize register live-range state for scheduling in this block.
254 Scheduler.StartBlock(MBB);
256 // Schedule each sequence of instructions not interrupted by a label
257 // or anything else that effectively needs to shut down scheduling.
258 MachineBasicBlock::iterator Current = MBB->end();
259 unsigned Count = MBB->size(), CurrentCount = Count;
260 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
261 MachineInstr *MI = prior(I);
262 if (isSchedulingBoundary(MI, Fn)) {
263 Scheduler.Run(MBB, I, Current, CurrentCount);
264 Scheduler.EmitSchedule();
266 CurrentCount = Count - 1;
267 Scheduler.Observe(MI, CurrentCount);
272 assert(Count == 0 && "Instruction count mismatch!");
273 assert((MBB->begin() == Current || CurrentCount != 0) &&
274 "Instruction count mismatch!");
275 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
276 Scheduler.EmitSchedule();
278 // Clean up register live-range state.
279 Scheduler.FinishBlock();
285 /// StartBlock - Initialize register live-range state for scheduling in
288 void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
289 // Call the superclass.
290 ScheduleDAGInstrs::StartBlock(BB);
292 // Clear out the register class data.
293 std::fill(Classes, array_endof(Classes),
294 static_cast<const TargetRegisterClass *>(0));
296 // Initialize the indices to indicate that no registers are live.
297 std::fill(KillIndices, array_endof(KillIndices), ~0u);
298 std::fill(DefIndices, array_endof(DefIndices), BB->size());
300 // Determine the live-out physregs for this block.
301 if (!BB->empty() && BB->back().getDesc().isReturn())
302 // In a return block, examine the function live-out regs.
303 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
304 E = MRI.liveout_end(); I != E; ++I) {
306 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
307 KillIndices[Reg] = BB->size();
308 DefIndices[Reg] = ~0u;
309 // Repeat, for all aliases.
310 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
311 unsigned AliasReg = *Alias;
312 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
313 KillIndices[AliasReg] = BB->size();
314 DefIndices[AliasReg] = ~0u;
318 // In a non-return block, examine the live-in regs of all successors.
319 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
320 SE = BB->succ_end(); SI != SE; ++SI)
321 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
322 E = (*SI)->livein_end(); I != E; ++I) {
324 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
325 KillIndices[Reg] = BB->size();
326 DefIndices[Reg] = ~0u;
327 // Repeat, for all aliases.
328 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
329 unsigned AliasReg = *Alias;
330 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
331 KillIndices[AliasReg] = BB->size();
332 DefIndices[AliasReg] = ~0u;
336 // Consider callee-saved registers as live-out, since we're running after
337 // prologue/epilogue insertion so there's no way to add additional
340 // TODO: If the callee saves and restores these, then we can potentially
341 // use them between the save and the restore. To do that, we could scan
342 // the exit blocks to see which of these registers are defined.
343 // Alternatively, callee-saved registers that aren't saved and restored
344 // could be marked live-in in every block.
345 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
347 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
348 KillIndices[Reg] = BB->size();
349 DefIndices[Reg] = ~0u;
350 // Repeat, for all aliases.
351 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
352 unsigned AliasReg = *Alias;
353 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
354 KillIndices[AliasReg] = BB->size();
355 DefIndices[AliasReg] = ~0u;
360 /// Schedule - Schedule the instruction range using list scheduling.
362 void SchedulePostRATDList::Schedule() {
363 DOUT << "********** List Scheduling **********\n";
365 // Build the scheduling graph.
368 if (EnableAntiDepBreaking) {
369 if (BreakAntiDependencies()) {
370 // We made changes. Update the dependency graph.
371 // Theoretically we could update the graph in place:
372 // When a live range is changed to use a different register, remove
373 // the def's anti-dependence *and* output-dependence edges due to
374 // that register, and add new anti-dependence and output-dependence
375 // edges based on the next live range of the register.
383 AvailableQueue.initNodes(SUnits);
385 ListScheduleTopDown();
387 AvailableQueue.releaseState();
390 /// Observe - Update liveness information to account for the current
391 /// instruction, which will not be scheduled.
393 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
394 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
396 // Any register which was defined within the previous scheduling region
397 // may have been rescheduled and its lifetime may overlap with registers
398 // in ways not reflected in our current liveness state. For each such
399 // register, adjust the liveness state to be conservatively correct.
400 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
401 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
402 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
403 // Mark this register to be non-renamable.
404 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
405 // Move the def index to the end of the previous region, to reflect
406 // that the def could theoretically have been scheduled at the end.
407 DefIndices[Reg] = InsertPosIndex;
410 PrescanInstruction(MI);
411 ScanInstruction(MI, Count);
414 /// FinishBlock - Clean up register live-range state.
416 void SchedulePostRATDList::FinishBlock() {
419 // Call the superclass.
420 ScheduleDAGInstrs::FinishBlock();
423 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
425 static SDep *CriticalPathStep(SUnit *SU) {
427 unsigned NextDepth = 0;
428 // Find the predecessor edge with the greatest depth.
429 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
431 SUnit *PredSU = P->getSUnit();
432 unsigned PredLatency = P->getLatency();
433 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
434 // In the case of a latency tie, prefer an anti-dependency edge over
435 // other types of edges.
436 if (NextDepth < PredTotalLatency ||
437 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
438 NextDepth = PredTotalLatency;
445 void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
446 // Scan the register operands for this instruction and update
447 // Classes and RegRefs.
448 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
449 MachineOperand &MO = MI->getOperand(i);
450 if (!MO.isReg()) continue;
451 unsigned Reg = MO.getReg();
452 if (Reg == 0) continue;
453 const TargetRegisterClass *NewRC = 0;
455 if (i < MI->getDesc().getNumOperands())
456 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
458 // For now, only allow the register to be changed if its register
459 // class is consistent across all uses.
460 if (!Classes[Reg] && NewRC)
461 Classes[Reg] = NewRC;
462 else if (!NewRC || Classes[Reg] != NewRC)
463 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
465 // Now check for aliases.
466 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
467 // If an alias of the reg is used during the live range, give up.
468 // Note that this allows us to skip checking if AntiDepReg
469 // overlaps with any of the aliases, among other things.
470 unsigned AliasReg = *Alias;
471 if (Classes[AliasReg]) {
472 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
473 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
477 // If we're still willing to consider this register, note the reference.
478 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
479 RegRefs.insert(std::make_pair(Reg, &MO));
483 void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
486 // Proceding upwards, registers that are defed but not used in this
487 // instruction are now dead.
488 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
489 MachineOperand &MO = MI->getOperand(i);
490 if (!MO.isReg()) continue;
491 unsigned Reg = MO.getReg();
492 if (Reg == 0) continue;
493 if (!MO.isDef()) continue;
494 // Ignore two-addr defs.
495 if (MI->isRegTiedToUseOperand(i)) continue;
497 DefIndices[Reg] = Count;
498 KillIndices[Reg] = ~0u;
499 assert(((KillIndices[Reg] == ~0u) !=
500 (DefIndices[Reg] == ~0u)) &&
501 "Kill and Def maps aren't consistent for Reg!");
504 // Repeat, for all subregs.
505 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
507 unsigned SubregReg = *Subreg;
508 DefIndices[SubregReg] = Count;
509 KillIndices[SubregReg] = ~0u;
510 Classes[SubregReg] = 0;
511 RegRefs.erase(SubregReg);
513 // Conservatively mark super-registers as unusable.
514 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
516 unsigned SuperReg = *Super;
517 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
520 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
521 MachineOperand &MO = MI->getOperand(i);
522 if (!MO.isReg()) continue;
523 unsigned Reg = MO.getReg();
524 if (Reg == 0) continue;
525 if (!MO.isUse()) continue;
527 const TargetRegisterClass *NewRC = 0;
528 if (i < MI->getDesc().getNumOperands())
529 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
531 // For now, only allow the register to be changed if its register
532 // class is consistent across all uses.
533 if (!Classes[Reg] && NewRC)
534 Classes[Reg] = NewRC;
535 else if (!NewRC || Classes[Reg] != NewRC)
536 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
538 RegRefs.insert(std::make_pair(Reg, &MO));
540 // It wasn't previously live but now it is, this is a kill.
541 if (KillIndices[Reg] == ~0u) {
542 KillIndices[Reg] = Count;
543 DefIndices[Reg] = ~0u;
544 assert(((KillIndices[Reg] == ~0u) !=
545 (DefIndices[Reg] == ~0u)) &&
546 "Kill and Def maps aren't consistent for Reg!");
548 // Repeat, for all aliases.
549 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
550 unsigned AliasReg = *Alias;
551 if (KillIndices[AliasReg] == ~0u) {
552 KillIndices[AliasReg] = Count;
553 DefIndices[AliasReg] = ~0u;
559 /// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
560 /// of the ScheduleDAG and break them by renaming registers.
562 bool SchedulePostRATDList::BreakAntiDependencies() {
563 // The code below assumes that there is at least one instruction,
564 // so just duck out immediately if the block is empty.
565 if (SUnits.empty()) return false;
567 // Find the node at the bottom of the critical path.
569 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
570 SUnit *SU = &SUnits[i];
571 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
575 DOUT << "Critical path has total latency "
576 << (Max->getDepth() + Max->Latency) << "\n";
578 // Track progress along the critical path through the SUnit graph as we walk
580 SUnit *CriticalPathSU = Max;
581 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
583 // Consider this pattern:
592 // There are three anti-dependencies here, and without special care,
593 // we'd break all of them using the same register:
602 // because at each anti-dependence, B is the first register that
603 // isn't A which is free. This re-introduces anti-dependencies
604 // at all but one of the original anti-dependencies that we were
605 // trying to break. To avoid this, keep track of the most recent
606 // register that each register was replaced with, avoid avoid
607 // using it to repair an anti-dependence on the same register.
608 // This lets us produce this:
617 // This still has an anti-dependence on B, but at least it isn't on the
618 // original critical path.
620 // TODO: If we tracked more than one register here, we could potentially
621 // fix that remaining critical edge too. This is a little more involved,
622 // because unlike the most recent register, less recent registers should
623 // still be considered, though only if no other registers are available.
624 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
626 // Attempt to break anti-dependence edges on the critical path. Walk the
627 // instructions from the bottom up, tracking information about liveness
628 // as we go to help determine which registers are available.
629 bool Changed = false;
630 unsigned Count = InsertPosIndex - 1;
631 for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
633 MachineInstr *MI = --I;
635 // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
636 // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
637 // is left behind appearing to clobber the super-register, while the
638 // subregister needs to remain live. So we just ignore them.
639 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
642 // Check if this instruction has a dependence on the critical path that
643 // is an anti-dependence that we may be able to break. If it is, set
644 // AntiDepReg to the non-zero register associated with the anti-dependence.
646 // We limit our attention to the critical path as a heuristic to avoid
647 // breaking anti-dependence edges that aren't going to significantly
648 // impact the overall schedule. There are a limited number of registers
649 // and we want to save them for the important edges.
651 // TODO: Instructions with multiple defs could have multiple
652 // anti-dependencies. The current code here only knows how to break one
653 // edge per instruction. Note that we'd have to be able to break all of
654 // the anti-dependencies in an instruction in order to be effective.
655 unsigned AntiDepReg = 0;
656 if (MI == CriticalPathMI) {
657 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
658 SUnit *NextSU = Edge->getSUnit();
660 // Only consider anti-dependence edges.
661 if (Edge->getKind() == SDep::Anti) {
662 AntiDepReg = Edge->getReg();
663 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
664 // Don't break anti-dependencies on non-allocatable registers.
665 if (!AllocatableSet.test(AntiDepReg))
668 // If the SUnit has other dependencies on the SUnit that it
669 // anti-depends on, don't bother breaking the anti-dependency
670 // since those edges would prevent such units from being
671 // scheduled past each other regardless.
673 // Also, if there are dependencies on other SUnits with the
674 // same register as the anti-dependency, don't attempt to
676 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
677 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
678 if (P->getSUnit() == NextSU ?
679 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
680 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
686 CriticalPathSU = NextSU;
687 CriticalPathMI = CriticalPathSU->getInstr();
689 // We've reached the end of the critical path.
695 PrescanInstruction(MI);
697 // If this instruction has a use of AntiDepReg, breaking it
699 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
700 MachineOperand &MO = MI->getOperand(i);
701 if (!MO.isReg()) continue;
702 unsigned Reg = MO.getReg();
703 if (Reg == 0) continue;
704 if (MO.isUse() && AntiDepReg == Reg) {
710 // Determine AntiDepReg's register class, if it is live and is
711 // consistently used within a single class.
712 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
713 assert((AntiDepReg == 0 || RC != NULL) &&
714 "Register should be live if it's causing an anti-dependence!");
715 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
718 // Look for a suitable register to use to break the anti-depenence.
720 // TODO: Instead of picking the first free register, consider which might
722 if (AntiDepReg != 0) {
723 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
724 RE = RC->allocation_order_end(MF); R != RE; ++R) {
725 unsigned NewReg = *R;
726 // Don't replace a register with itself.
727 if (NewReg == AntiDepReg) continue;
728 // Don't replace a register with one that was recently used to repair
729 // an anti-dependence with this AntiDepReg, because that would
730 // re-introduce that anti-dependence.
731 if (NewReg == LastNewReg[AntiDepReg]) continue;
732 // If NewReg is dead and NewReg's most recent def is not before
733 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
734 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
735 "Kill and Def maps aren't consistent for AntiDepReg!");
736 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
737 "Kill and Def maps aren't consistent for NewReg!");
738 if (KillIndices[NewReg] == ~0u &&
739 Classes[NewReg] != reinterpret_cast<TargetRegisterClass *>(-1) &&
740 KillIndices[AntiDepReg] <= DefIndices[NewReg]) {
741 DOUT << "Breaking anti-dependence edge on "
742 << TRI->getName(AntiDepReg)
743 << " with " << RegRefs.count(AntiDepReg) << " references"
744 << " using " << TRI->getName(NewReg) << "!\n";
746 // Update the references to the old register to refer to the new
748 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
749 std::multimap<unsigned, MachineOperand *>::iterator>
750 Range = RegRefs.equal_range(AntiDepReg);
751 for (std::multimap<unsigned, MachineOperand *>::iterator
752 Q = Range.first, QE = Range.second; Q != QE; ++Q)
753 Q->second->setReg(NewReg);
755 // We just went back in time and modified history; the
756 // liveness information for the anti-depenence reg is now
757 // inconsistent. Set the state as if it were dead.
758 Classes[NewReg] = Classes[AntiDepReg];
759 DefIndices[NewReg] = DefIndices[AntiDepReg];
760 KillIndices[NewReg] = KillIndices[AntiDepReg];
761 assert(((KillIndices[NewReg] == ~0u) !=
762 (DefIndices[NewReg] == ~0u)) &&
763 "Kill and Def maps aren't consistent for NewReg!");
765 Classes[AntiDepReg] = 0;
766 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
767 KillIndices[AntiDepReg] = ~0u;
768 assert(((KillIndices[AntiDepReg] == ~0u) !=
769 (DefIndices[AntiDepReg] == ~0u)) &&
770 "Kill and Def maps aren't consistent for AntiDepReg!");
772 RegRefs.erase(AntiDepReg);
774 LastNewReg[AntiDepReg] = NewReg;
780 ScanInstruction(MI, Count);
786 //===----------------------------------------------------------------------===//
787 // Top-Down Scheduling
788 //===----------------------------------------------------------------------===//
790 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
791 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
792 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
793 SUnit *SuccSU = SuccEdge->getSUnit();
794 --SuccSU->NumPredsLeft;
797 if (SuccSU->NumPredsLeft < 0) {
798 cerr << "*** Scheduling failed! ***\n";
800 cerr << " has been released too many times!\n";
805 // Compute how many cycles it will be before this actually becomes
806 // available. This is the max of the start time of all predecessors plus
808 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
810 // If all the node's predecessors are scheduled, this node is ready
811 // to be scheduled. Ignore the special ExitSU node.
812 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
813 PendingQueue.push_back(SuccSU);
816 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
817 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
818 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
820 ReleaseSucc(SU, &*I);
823 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
824 /// count of its successors. If a successor pending count is zero, add it to
825 /// the Available queue.
826 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
827 DOUT << "*** Scheduling [" << CurCycle << "]: ";
828 DEBUG(SU->dump(this));
830 Sequence.push_back(SU);
831 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
832 SU->setDepthToAtLeast(CurCycle);
834 ReleaseSuccessors(SU);
835 SU->isScheduled = true;
836 AvailableQueue.ScheduledNode(SU);
839 /// ListScheduleTopDown - The main loop of list scheduling for top-down
841 void SchedulePostRATDList::ListScheduleTopDown() {
842 unsigned CurCycle = 0;
844 // Release any successors of the special Entry node.
845 ReleaseSuccessors(&EntrySU);
847 // All leaves to Available queue.
848 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
849 // It is available if it has no predecessors.
850 if (SUnits[i].Preds.empty()) {
851 AvailableQueue.push(&SUnits[i]);
852 SUnits[i].isAvailable = true;
856 // While Available queue is not empty, grab the node with the highest
857 // priority. If it is not ready put it back. Schedule the node.
858 std::vector<SUnit*> NotReady;
859 Sequence.reserve(SUnits.size());
860 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
861 // Check to see if any of the pending instructions are ready to issue. If
862 // so, add them to the available queue.
863 unsigned MinDepth = ~0u;
864 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
865 if (PendingQueue[i]->getDepth() <= CurCycle) {
866 AvailableQueue.push(PendingQueue[i]);
867 PendingQueue[i]->isAvailable = true;
868 PendingQueue[i] = PendingQueue.back();
869 PendingQueue.pop_back();
871 } else if (PendingQueue[i]->getDepth() < MinDepth)
872 MinDepth = PendingQueue[i]->getDepth();
875 // If there are no instructions available, don't try to issue anything, and
876 // don't advance the hazard recognizer.
877 if (AvailableQueue.empty()) {
878 CurCycle = MinDepth != ~0u ? MinDepth : CurCycle + 1;
882 SUnit *FoundSUnit = 0;
884 bool HasNoopHazards = false;
885 while (!AvailableQueue.empty()) {
886 SUnit *CurSUnit = AvailableQueue.pop();
888 ScheduleHazardRecognizer::HazardType HT =
889 HazardRec->getHazardType(CurSUnit);
890 if (HT == ScheduleHazardRecognizer::NoHazard) {
891 FoundSUnit = CurSUnit;
895 // Remember if this is a noop hazard.
896 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
898 NotReady.push_back(CurSUnit);
901 // Add the nodes that aren't ready back onto the available list.
902 if (!NotReady.empty()) {
903 AvailableQueue.push_all(NotReady);
907 // If we found a node to schedule, do it now.
909 ScheduleNodeTopDown(FoundSUnit, CurCycle);
910 HazardRec->EmitInstruction(FoundSUnit);
912 // If this is a pseudo-op node, we don't want to increment the current
914 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
916 } else if (!HasNoopHazards) {
917 // Otherwise, we have a pipeline stall, but no other problem, just advance
918 // the current cycle and try again.
919 DOUT << "*** Advancing cycle, no work to do\n";
920 HazardRec->AdvanceCycle();
924 // Otherwise, we have no instructions to issue and we have instructions
925 // that will fault if we don't do this right. This is the case for
926 // processors without pipeline interlocks and other cases.
927 DOUT << "*** Emitting noop\n";
928 HazardRec->EmitNoop();
929 Sequence.push_back(0); // NULL here means noop
936 VerifySchedule(/*isBottomUp=*/false);
940 //===----------------------------------------------------------------------===//
941 // Public Constructor Functions
942 //===----------------------------------------------------------------------===//
944 FunctionPass *llvm::createPostRAScheduler() {
945 return new PostRAScheduler();