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/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineLoopInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
34 #include "llvm/Analysis/AliasAnalysis.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtarget.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/ADT/Statistic.h"
49 STATISTIC(NumNoops, "Number of noops inserted");
50 STATISTIC(NumStalls, "Number of pipeline stalls");
52 // Post-RA scheduling is enabled with
53 // TargetSubtarget.enablePostRAScheduler(). This flag can be used to
54 // override the target.
56 EnablePostRAScheduler("post-RA-scheduler",
57 cl::desc("Enable scheduling after register allocation"),
58 cl::init(false), cl::Hidden);
60 EnableAntiDepBreaking("break-anti-dependencies",
61 cl::desc("Break post-RA scheduling anti-dependencies"),
62 cl::init(true), cl::Hidden);
64 EnablePostRAHazardAvoidance("avoid-hazards",
65 cl::desc("Enable exact hazard avoidance"),
66 cl::init(true), cl::Hidden);
68 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
70 DebugDiv("postra-sched-debugdiv",
71 cl::desc("Debug control MBBs that are scheduled"),
72 cl::init(0), cl::Hidden);
74 DebugMod("postra-sched-debugmod",
75 cl::desc("Debug control MBBs that are scheduled"),
76 cl::init(0), cl::Hidden);
79 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
84 PostRAScheduler() : MachineFunctionPass(&ID) {}
86 void getAnalysisUsage(AnalysisUsage &AU) const {
88 AU.addRequired<AliasAnalysis>();
89 AU.addRequired<MachineDominatorTree>();
90 AU.addPreserved<MachineDominatorTree>();
91 AU.addRequired<MachineLoopInfo>();
92 AU.addPreserved<MachineLoopInfo>();
93 MachineFunctionPass::getAnalysisUsage(AU);
96 const char *getPassName() const {
97 return "Post RA top-down list latency scheduler";
100 bool runOnMachineFunction(MachineFunction &Fn);
102 char PostRAScheduler::ID = 0;
104 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
105 /// AvailableQueue - The priority queue to use for the available SUnits.
107 LatencyPriorityQueue AvailableQueue;
109 /// PendingQueue - This contains all of the instructions whose operands have
110 /// been issued, but their results are not ready yet (due to the latency of
111 /// the operation). Once the operands becomes available, the instruction is
112 /// added to the AvailableQueue.
113 std::vector<SUnit*> PendingQueue;
115 /// Topo - A topological ordering for SUnits.
116 ScheduleDAGTopologicalSort Topo;
118 /// AllocatableSet - The set of allocatable registers.
119 /// We'll be ignoring anti-dependencies on non-allocatable registers,
120 /// because they may not be safe to break.
121 const BitVector AllocatableSet;
123 /// HazardRec - The hazard recognizer to use.
124 ScheduleHazardRecognizer *HazardRec;
126 /// AA - AliasAnalysis for making memory reference queries.
129 /// Classes - For live regs that are only used in one register class in a
130 /// live range, the register class. If the register is not live, the
131 /// corresponding value is null. If the register is live but used in
132 /// multiple register classes, the corresponding value is -1 casted to a
134 const TargetRegisterClass *
135 Classes[TargetRegisterInfo::FirstVirtualRegister];
137 /// RegRegs - Map registers to all their references within a live range.
138 std::multimap<unsigned, MachineOperand *> RegRefs;
140 /// KillIndices - The index of the most recent kill (proceding bottom-up),
141 /// or ~0u if the register is not live.
142 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
144 /// DefIndices - The index of the most recent complete def (proceding bottom
145 /// up), or ~0u if the register is live.
146 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
148 /// KeepRegs - A set of registers which are live and cannot be changed to
149 /// break anti-dependencies.
150 SmallSet<unsigned, 4> KeepRegs;
153 SchedulePostRATDList(MachineFunction &MF,
154 const MachineLoopInfo &MLI,
155 const MachineDominatorTree &MDT,
156 ScheduleHazardRecognizer *HR,
158 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
159 AllocatableSet(TRI->getAllocatableSet(MF)),
160 HazardRec(HR), AA(aa) {}
162 ~SchedulePostRATDList() {
166 /// StartBlock - Initialize register live-range state for scheduling in
169 void StartBlock(MachineBasicBlock *BB);
171 /// Schedule - Schedule the instruction range using list scheduling.
175 /// FixupKills - Fix register kill flags that have been made
176 /// invalid due to scheduling
178 void FixupKills(MachineBasicBlock *MBB);
180 /// Observe - Update liveness information to account for the current
181 /// instruction, which will not be scheduled.
183 void Observe(MachineInstr *MI, unsigned Count);
185 /// FinishBlock - Clean up register live-range state.
190 void PrescanInstruction(MachineInstr *MI);
191 void ScanInstruction(MachineInstr *MI, unsigned Count);
192 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
193 void ReleaseSuccessors(SUnit *SU);
194 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
195 void ListScheduleTopDown();
196 bool BreakAntiDependencies();
197 unsigned findSuitableFreeRegister(unsigned AntiDepReg,
199 const TargetRegisterClass *);
200 void StartBlockForKills(MachineBasicBlock *BB);
202 // ToggleKillFlag - Toggle a register operand kill flag. Other
203 // adjustments may be made to the instruction if necessary. Return
204 // true if the operand has been deleted, false if not.
205 bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
209 /// isSchedulingBoundary - Test if the given instruction should be
210 /// considered a scheduling boundary. This primarily includes labels
213 static bool isSchedulingBoundary(const MachineInstr *MI,
214 const MachineFunction &MF) {
215 // Terminators and labels can't be scheduled around.
216 if (MI->getDesc().isTerminator() || MI->isLabel())
219 // Don't attempt to schedule around any instruction that modifies
220 // a stack-oriented pointer, as it's unlikely to be profitable. This
221 // saves compile time, because it doesn't require every single
222 // stack slot reference to depend on the instruction that does the
224 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
225 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
231 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
232 AA = &getAnalysis<AliasAnalysis>();
234 // Check for explicit enable/disable of post-ra scheduling.
235 if (EnablePostRAScheduler.getPosition() > 0) {
236 if (!EnablePostRAScheduler)
239 // Check that post-RA scheduling is enabled for this function
240 const TargetSubtarget &ST = Fn.getTarget().getSubtarget<TargetSubtarget>();
241 if (!ST.enablePostRAScheduler())
245 DEBUG(errs() << "PostRAScheduler\n");
247 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
248 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
249 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
250 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
251 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
252 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
254 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR, AA);
256 // Loop over all of the basic blocks
257 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
258 MBB != MBBe; ++MBB) {
260 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
262 static int bbcnt = 0;
263 if (bbcnt++ % DebugDiv != DebugMod)
265 errs() << "*** DEBUG scheduling " << Fn.getFunction()->getNameStr() <<
266 ":MBB ID#" << MBB->getNumber() << " ***\n";
270 // Initialize register live-range state for scheduling in this block.
271 Scheduler.StartBlock(MBB);
273 // Schedule each sequence of instructions not interrupted by a label
274 // or anything else that effectively needs to shut down scheduling.
275 MachineBasicBlock::iterator Current = MBB->end();
276 unsigned Count = MBB->size(), CurrentCount = Count;
277 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
278 MachineInstr *MI = prior(I);
279 if (isSchedulingBoundary(MI, Fn)) {
280 Scheduler.Run(MBB, I, Current, CurrentCount);
281 Scheduler.EmitSchedule(0);
283 CurrentCount = Count - 1;
284 Scheduler.Observe(MI, CurrentCount);
289 assert(Count == 0 && "Instruction count mismatch!");
290 assert((MBB->begin() == Current || CurrentCount != 0) &&
291 "Instruction count mismatch!");
292 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
293 Scheduler.EmitSchedule(0);
295 // Clean up register live-range state.
296 Scheduler.FinishBlock();
298 // Update register kills
299 Scheduler.FixupKills(MBB);
305 /// StartBlock - Initialize register live-range state for scheduling in
308 void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
309 // Call the superclass.
310 ScheduleDAGInstrs::StartBlock(BB);
312 // Reset the hazard recognizer.
315 // Clear out the register class data.
316 std::fill(Classes, array_endof(Classes),
317 static_cast<const TargetRegisterClass *>(0));
319 // Initialize the indices to indicate that no registers are live.
320 std::fill(KillIndices, array_endof(KillIndices), ~0u);
321 std::fill(DefIndices, array_endof(DefIndices), BB->size());
323 // Clear "do not change" set.
326 bool IsReturnBlock = (!BB->empty() && BB->back().getDesc().isReturn());
328 // Determine the live-out physregs for this block.
330 // In a return block, examine the function live-out regs.
331 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
332 E = MRI.liveout_end(); I != E; ++I) {
334 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
335 KillIndices[Reg] = BB->size();
336 DefIndices[Reg] = ~0u;
337 // Repeat, for all aliases.
338 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
339 unsigned AliasReg = *Alias;
340 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
341 KillIndices[AliasReg] = BB->size();
342 DefIndices[AliasReg] = ~0u;
346 // In a non-return block, examine the live-in regs of all successors.
347 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
348 SE = BB->succ_end(); SI != SE; ++SI)
349 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
350 E = (*SI)->livein_end(); I != E; ++I) {
352 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
353 KillIndices[Reg] = BB->size();
354 DefIndices[Reg] = ~0u;
355 // Repeat, for all aliases.
356 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
357 unsigned AliasReg = *Alias;
358 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
359 KillIndices[AliasReg] = BB->size();
360 DefIndices[AliasReg] = ~0u;
365 // Mark live-out callee-saved registers. In a return block this is
366 // all callee-saved registers. In non-return this is any
367 // callee-saved register that is not saved in the prolog.
368 const MachineFrameInfo *MFI = MF.getFrameInfo();
369 BitVector Pristine = MFI->getPristineRegs(BB);
370 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
372 if (!IsReturnBlock && !Pristine.test(Reg)) continue;
373 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
374 KillIndices[Reg] = BB->size();
375 DefIndices[Reg] = ~0u;
376 // Repeat, for all aliases.
377 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
378 unsigned AliasReg = *Alias;
379 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
380 KillIndices[AliasReg] = BB->size();
381 DefIndices[AliasReg] = ~0u;
386 /// Schedule - Schedule the instruction range using list scheduling.
388 void SchedulePostRATDList::Schedule() {
389 DEBUG(errs() << "********** List Scheduling **********\n");
391 // Build the scheduling graph.
394 if (EnableAntiDepBreaking) {
395 if (BreakAntiDependencies()) {
396 // We made changes. Update the dependency graph.
397 // Theoretically we could update the graph in place:
398 // When a live range is changed to use a different register, remove
399 // the def's anti-dependence *and* output-dependence edges due to
400 // that register, and add new anti-dependence and output-dependence
401 // edges based on the next live range of the register.
409 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
410 SUnits[su].dumpAll(this));
412 AvailableQueue.initNodes(SUnits);
414 ListScheduleTopDown();
416 AvailableQueue.releaseState();
419 /// Observe - Update liveness information to account for the current
420 /// instruction, which will not be scheduled.
422 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
423 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
425 // Any register which was defined within the previous scheduling region
426 // may have been rescheduled and its lifetime may overlap with registers
427 // in ways not reflected in our current liveness state. For each such
428 // register, adjust the liveness state to be conservatively correct.
429 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
430 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
431 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
432 // Mark this register to be non-renamable.
433 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
434 // Move the def index to the end of the previous region, to reflect
435 // that the def could theoretically have been scheduled at the end.
436 DefIndices[Reg] = InsertPosIndex;
439 PrescanInstruction(MI);
440 ScanInstruction(MI, Count);
443 /// FinishBlock - Clean up register live-range state.
445 void SchedulePostRATDList::FinishBlock() {
448 // Call the superclass.
449 ScheduleDAGInstrs::FinishBlock();
452 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
454 static SDep *CriticalPathStep(SUnit *SU) {
456 unsigned NextDepth = 0;
457 // Find the predecessor edge with the greatest depth.
458 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
460 SUnit *PredSU = P->getSUnit();
461 unsigned PredLatency = P->getLatency();
462 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
463 // In the case of a latency tie, prefer an anti-dependency edge over
464 // other types of edges.
465 if (NextDepth < PredTotalLatency ||
466 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
467 NextDepth = PredTotalLatency;
474 void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
475 // Scan the register operands for this instruction and update
476 // Classes and RegRefs.
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 const TargetRegisterClass *NewRC = 0;
484 if (i < MI->getDesc().getNumOperands())
485 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
487 // For now, only allow the register to be changed if its register
488 // class is consistent across all uses.
489 if (!Classes[Reg] && NewRC)
490 Classes[Reg] = NewRC;
491 else if (!NewRC || Classes[Reg] != NewRC)
492 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
494 // Now check for aliases.
495 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
496 // If an alias of the reg is used during the live range, give up.
497 // Note that this allows us to skip checking if AntiDepReg
498 // overlaps with any of the aliases, among other things.
499 unsigned AliasReg = *Alias;
500 if (Classes[AliasReg]) {
501 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
502 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
506 // If we're still willing to consider this register, note the reference.
507 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
508 RegRefs.insert(std::make_pair(Reg, &MO));
510 // It's not safe to change register allocation for source operands of
511 // that have special allocation requirements.
512 if (MO.isUse() && MI->getDesc().hasExtraSrcRegAllocReq()) {
513 if (KeepRegs.insert(Reg)) {
514 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
516 KeepRegs.insert(*Subreg);
522 void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
525 // Proceding upwards, registers that are defed but not used in this
526 // instruction are now dead.
527 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
528 MachineOperand &MO = MI->getOperand(i);
529 if (!MO.isReg()) continue;
530 unsigned Reg = MO.getReg();
531 if (Reg == 0) continue;
532 if (!MO.isDef()) continue;
533 // Ignore two-addr defs.
534 if (MI->isRegTiedToUseOperand(i)) continue;
536 DefIndices[Reg] = Count;
537 KillIndices[Reg] = ~0u;
538 assert(((KillIndices[Reg] == ~0u) !=
539 (DefIndices[Reg] == ~0u)) &&
540 "Kill and Def maps aren't consistent for Reg!");
544 // Repeat, for all subregs.
545 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
547 unsigned SubregReg = *Subreg;
548 DefIndices[SubregReg] = Count;
549 KillIndices[SubregReg] = ~0u;
550 KeepRegs.erase(SubregReg);
551 Classes[SubregReg] = 0;
552 RegRefs.erase(SubregReg);
554 // Conservatively mark super-registers as unusable.
555 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
557 unsigned SuperReg = *Super;
558 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
561 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
562 MachineOperand &MO = MI->getOperand(i);
563 if (!MO.isReg()) continue;
564 unsigned Reg = MO.getReg();
565 if (Reg == 0) continue;
566 if (!MO.isUse()) continue;
568 const TargetRegisterClass *NewRC = 0;
569 if (i < MI->getDesc().getNumOperands())
570 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
572 // For now, only allow the register to be changed if its register
573 // class is consistent across all uses.
574 if (!Classes[Reg] && NewRC)
575 Classes[Reg] = NewRC;
576 else if (!NewRC || Classes[Reg] != NewRC)
577 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
579 RegRefs.insert(std::make_pair(Reg, &MO));
581 // It wasn't previously live but now it is, this is a kill.
582 if (KillIndices[Reg] == ~0u) {
583 KillIndices[Reg] = Count;
584 DefIndices[Reg] = ~0u;
585 assert(((KillIndices[Reg] == ~0u) !=
586 (DefIndices[Reg] == ~0u)) &&
587 "Kill and Def maps aren't consistent for Reg!");
589 // Repeat, for all aliases.
590 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
591 unsigned AliasReg = *Alias;
592 if (KillIndices[AliasReg] == ~0u) {
593 KillIndices[AliasReg] = Count;
594 DefIndices[AliasReg] = ~0u;
601 SchedulePostRATDList::findSuitableFreeRegister(unsigned AntiDepReg,
603 const TargetRegisterClass *RC) {
604 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
605 RE = RC->allocation_order_end(MF); R != RE; ++R) {
606 unsigned NewReg = *R;
607 // Don't replace a register with itself.
608 if (NewReg == AntiDepReg) continue;
609 // Don't replace a register with one that was recently used to repair
610 // an anti-dependence with this AntiDepReg, because that would
611 // re-introduce that anti-dependence.
612 if (NewReg == LastNewReg) continue;
613 // If NewReg is dead and NewReg's most recent def is not before
614 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
615 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
616 "Kill and Def maps aren't consistent for AntiDepReg!");
617 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
618 "Kill and Def maps aren't consistent for NewReg!");
619 if (KillIndices[NewReg] != ~0u ||
620 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
621 KillIndices[AntiDepReg] > DefIndices[NewReg])
626 // No registers are free and available!
630 /// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
631 /// of the ScheduleDAG and break them by renaming registers.
633 bool SchedulePostRATDList::BreakAntiDependencies() {
634 // The code below assumes that there is at least one instruction,
635 // so just duck out immediately if the block is empty.
636 if (SUnits.empty()) return false;
638 // Find the node at the bottom of the critical path.
640 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
641 SUnit *SU = &SUnits[i];
642 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
646 DEBUG(errs() << "Critical path has total latency "
647 << (Max->getDepth() + Max->Latency) << "\n");
649 // Track progress along the critical path through the SUnit graph as we walk
651 SUnit *CriticalPathSU = Max;
652 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
654 // Consider this pattern:
663 // There are three anti-dependencies here, and without special care,
664 // we'd break all of them using the same register:
673 // because at each anti-dependence, B is the first register that
674 // isn't A which is free. This re-introduces anti-dependencies
675 // at all but one of the original anti-dependencies that we were
676 // trying to break. To avoid this, keep track of the most recent
677 // register that each register was replaced with, avoid
678 // using it to repair an anti-dependence on the same register.
679 // This lets us produce this:
688 // This still has an anti-dependence on B, but at least it isn't on the
689 // original critical path.
691 // TODO: If we tracked more than one register here, we could potentially
692 // fix that remaining critical edge too. This is a little more involved,
693 // because unlike the most recent register, less recent registers should
694 // still be considered, though only if no other registers are available.
695 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
697 // Attempt to break anti-dependence edges on the critical path. Walk the
698 // instructions from the bottom up, tracking information about liveness
699 // as we go to help determine which registers are available.
700 bool Changed = false;
701 unsigned Count = InsertPosIndex - 1;
702 for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
704 MachineInstr *MI = --I;
706 // Check if this instruction has a dependence on the critical path that
707 // is an anti-dependence that we may be able to break. If it is, set
708 // AntiDepReg to the non-zero register associated with the anti-dependence.
710 // We limit our attention to the critical path as a heuristic to avoid
711 // breaking anti-dependence edges that aren't going to significantly
712 // impact the overall schedule. There are a limited number of registers
713 // and we want to save them for the important edges.
715 // TODO: Instructions with multiple defs could have multiple
716 // anti-dependencies. The current code here only knows how to break one
717 // edge per instruction. Note that we'd have to be able to break all of
718 // the anti-dependencies in an instruction in order to be effective.
719 unsigned AntiDepReg = 0;
720 if (MI == CriticalPathMI) {
721 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
722 SUnit *NextSU = Edge->getSUnit();
724 // Only consider anti-dependence edges.
725 if (Edge->getKind() == SDep::Anti) {
726 AntiDepReg = Edge->getReg();
727 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
728 if (!AllocatableSet.test(AntiDepReg))
729 // Don't break anti-dependencies on non-allocatable registers.
731 else if (KeepRegs.count(AntiDepReg))
732 // Don't break anti-dependencies if an use down below requires
733 // this exact register.
736 // If the SUnit has other dependencies on the SUnit that it
737 // anti-depends on, don't bother breaking the anti-dependency
738 // since those edges would prevent such units from being
739 // scheduled past each other regardless.
741 // Also, if there are dependencies on other SUnits with the
742 // same register as the anti-dependency, don't attempt to
744 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
745 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
746 if (P->getSUnit() == NextSU ?
747 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
748 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
754 CriticalPathSU = NextSU;
755 CriticalPathMI = CriticalPathSU->getInstr();
757 // We've reached the end of the critical path.
763 PrescanInstruction(MI);
765 if (MI->getDesc().hasExtraDefRegAllocReq())
766 // If this instruction's defs have special allocation requirement, don't
767 // break this anti-dependency.
769 else if (AntiDepReg) {
770 // If this instruction has a use of AntiDepReg, breaking it
772 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
773 MachineOperand &MO = MI->getOperand(i);
774 if (!MO.isReg()) continue;
775 unsigned Reg = MO.getReg();
776 if (Reg == 0) continue;
777 if (MO.isUse() && AntiDepReg == Reg) {
784 // Determine AntiDepReg's register class, if it is live and is
785 // consistently used within a single class.
786 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
787 assert((AntiDepReg == 0 || RC != NULL) &&
788 "Register should be live if it's causing an anti-dependence!");
789 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
792 // Look for a suitable register to use to break the anti-depenence.
794 // TODO: Instead of picking the first free register, consider which might
796 if (AntiDepReg != 0) {
797 if (unsigned NewReg = findSuitableFreeRegister(AntiDepReg,
798 LastNewReg[AntiDepReg],
800 DEBUG(errs() << "Breaking anti-dependence edge on "
801 << TRI->getName(AntiDepReg)
802 << " with " << RegRefs.count(AntiDepReg) << " references"
803 << " using " << TRI->getName(NewReg) << "!\n");
805 // Update the references to the old register to refer to the new
807 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
808 std::multimap<unsigned, MachineOperand *>::iterator>
809 Range = RegRefs.equal_range(AntiDepReg);
810 for (std::multimap<unsigned, MachineOperand *>::iterator
811 Q = Range.first, QE = Range.second; Q != QE; ++Q)
812 Q->second->setReg(NewReg);
814 // We just went back in time and modified history; the
815 // liveness information for the anti-depenence reg is now
816 // inconsistent. Set the state as if it were dead.
817 Classes[NewReg] = Classes[AntiDepReg];
818 DefIndices[NewReg] = DefIndices[AntiDepReg];
819 KillIndices[NewReg] = KillIndices[AntiDepReg];
820 assert(((KillIndices[NewReg] == ~0u) !=
821 (DefIndices[NewReg] == ~0u)) &&
822 "Kill and Def maps aren't consistent for NewReg!");
824 Classes[AntiDepReg] = 0;
825 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
826 KillIndices[AntiDepReg] = ~0u;
827 assert(((KillIndices[AntiDepReg] == ~0u) !=
828 (DefIndices[AntiDepReg] == ~0u)) &&
829 "Kill and Def maps aren't consistent for AntiDepReg!");
831 RegRefs.erase(AntiDepReg);
833 LastNewReg[AntiDepReg] = NewReg;
837 ScanInstruction(MI, Count);
843 /// StartBlockForKills - Initialize register live-range state for updating kills
845 void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
846 // Initialize the indices to indicate that no registers are live.
847 std::fill(KillIndices, array_endof(KillIndices), ~0u);
849 // Determine the live-out physregs for this block.
850 if (!BB->empty() && BB->back().getDesc().isReturn()) {
851 // In a return block, examine the function live-out regs.
852 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
853 E = MRI.liveout_end(); I != E; ++I) {
855 KillIndices[Reg] = BB->size();
856 // Repeat, for all subregs.
857 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
859 KillIndices[*Subreg] = BB->size();
864 // In a non-return block, examine the live-in regs of all successors.
865 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
866 SE = BB->succ_end(); SI != SE; ++SI) {
867 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
868 E = (*SI)->livein_end(); I != E; ++I) {
870 KillIndices[Reg] = BB->size();
871 // Repeat, for all subregs.
872 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
874 KillIndices[*Subreg] = BB->size();
881 bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
882 MachineOperand &MO) {
883 // Setting kill flag...
889 // If MO itself is live, clear the kill flag...
890 if (KillIndices[MO.getReg()] != ~0u) {
895 // If any subreg of MO is live, then create an imp-def for that
896 // subreg and keep MO marked as killed.
899 const unsigned SuperReg = MO.getReg();
900 for (const unsigned *Subreg = TRI->getSubRegisters(SuperReg);
902 if (KillIndices[*Subreg] != ~0u) {
903 MI->addOperand(MachineOperand::CreateReg(*Subreg,
917 /// FixupKills - Fix the register kill flags, they may have been made
918 /// incorrect by instruction reordering.
920 void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
921 DEBUG(errs() << "Fixup kills for BB ID#" << MBB->getNumber() << '\n');
923 std::set<unsigned> killedRegs;
924 BitVector ReservedRegs = TRI->getReservedRegs(MF);
926 StartBlockForKills(MBB);
928 // Examine block from end to start...
929 unsigned Count = MBB->size();
930 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
932 MachineInstr *MI = --I;
934 // Update liveness. Registers that are defed but not used in this
935 // instruction are now dead. Mark register and all subregs as they
936 // are completely defined.
937 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
938 MachineOperand &MO = MI->getOperand(i);
939 if (!MO.isReg()) continue;
940 unsigned Reg = MO.getReg();
941 if (Reg == 0) continue;
942 if (!MO.isDef()) continue;
943 // Ignore two-addr defs.
944 if (MI->isRegTiedToUseOperand(i)) continue;
946 KillIndices[Reg] = ~0u;
948 // Repeat for all subregs.
949 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
951 KillIndices[*Subreg] = ~0u;
955 // Examine all used registers and set/clear kill flag. When a
956 // register is used multiple times we only set the kill flag on
959 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
960 MachineOperand &MO = MI->getOperand(i);
961 if (!MO.isReg() || !MO.isUse()) continue;
962 unsigned Reg = MO.getReg();
963 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
966 if (killedRegs.find(Reg) == killedRegs.end()) {
968 // A register is not killed if any subregs are live...
969 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
971 if (KillIndices[*Subreg] != ~0u) {
977 // If subreg is not live, then register is killed if it became
978 // live in this instruction
980 kill = (KillIndices[Reg] == ~0u);
983 if (MO.isKill() != kill) {
984 bool removed = ToggleKillFlag(MI, MO);
986 DEBUG(errs() << "Fixed <removed> in ");
988 DEBUG(errs() << "Fixed " << MO << " in ");
993 killedRegs.insert(Reg);
996 // Mark any used register (that is not using undef) and subregs as
998 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
999 MachineOperand &MO = MI->getOperand(i);
1000 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1001 unsigned Reg = MO.getReg();
1002 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
1004 KillIndices[Reg] = Count;
1006 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
1007 *Subreg; ++Subreg) {
1008 KillIndices[*Subreg] = Count;
1014 //===----------------------------------------------------------------------===//
1015 // Top-Down Scheduling
1016 //===----------------------------------------------------------------------===//
1018 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1019 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
1020 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
1021 SUnit *SuccSU = SuccEdge->getSUnit();
1024 if (SuccSU->NumPredsLeft == 0) {
1025 errs() << "*** Scheduling failed! ***\n";
1027 errs() << " has been released too many times!\n";
1028 llvm_unreachable(0);
1031 --SuccSU->NumPredsLeft;
1033 // Compute how many cycles it will be before this actually becomes
1034 // available. This is the max of the start time of all predecessors plus
1036 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
1038 // If all the node's predecessors are scheduled, this node is ready
1039 // to be scheduled. Ignore the special ExitSU node.
1040 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
1041 PendingQueue.push_back(SuccSU);
1044 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
1045 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
1046 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1048 ReleaseSucc(SU, &*I);
1051 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1052 /// count of its successors. If a successor pending count is zero, add it to
1053 /// the Available queue.
1054 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
1055 DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
1056 DEBUG(SU->dump(this));
1058 Sequence.push_back(SU);
1059 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1060 SU->setDepthToAtLeast(CurCycle);
1062 ReleaseSuccessors(SU);
1063 SU->isScheduled = true;
1064 AvailableQueue.ScheduledNode(SU);
1067 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1069 void SchedulePostRATDList::ListScheduleTopDown() {
1070 unsigned CurCycle = 0;
1072 // Release any successors of the special Entry node.
1073 ReleaseSuccessors(&EntrySU);
1075 // All leaves to Available queue.
1076 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1077 // It is available if it has no predecessors.
1078 if (SUnits[i].Preds.empty()) {
1079 AvailableQueue.push(&SUnits[i]);
1080 SUnits[i].isAvailable = true;
1084 // In any cycle where we can't schedule any instructions, we must
1085 // stall or emit a noop, depending on the target.
1086 bool CycleHasInsts = false;
1088 // While Available queue is not empty, grab the node with the highest
1089 // priority. If it is not ready put it back. Schedule the node.
1090 std::vector<SUnit*> NotReady;
1091 Sequence.reserve(SUnits.size());
1092 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
1093 // Check to see if any of the pending instructions are ready to issue. If
1094 // so, add them to the available queue.
1095 unsigned MinDepth = ~0u;
1096 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
1097 if (PendingQueue[i]->getDepth() <= CurCycle) {
1098 AvailableQueue.push(PendingQueue[i]);
1099 PendingQueue[i]->isAvailable = true;
1100 PendingQueue[i] = PendingQueue.back();
1101 PendingQueue.pop_back();
1103 } else if (PendingQueue[i]->getDepth() < MinDepth)
1104 MinDepth = PendingQueue[i]->getDepth();
1107 DEBUG(errs() << "\n*** Examining Available\n";
1108 LatencyPriorityQueue q = AvailableQueue;
1109 while (!q.empty()) {
1110 SUnit *su = q.pop();
1111 errs() << "Height " << su->getHeight() << ": ";
1115 SUnit *FoundSUnit = 0;
1117 bool HasNoopHazards = false;
1118 while (!AvailableQueue.empty()) {
1119 SUnit *CurSUnit = AvailableQueue.pop();
1121 ScheduleHazardRecognizer::HazardType HT =
1122 HazardRec->getHazardType(CurSUnit);
1123 if (HT == ScheduleHazardRecognizer::NoHazard) {
1124 FoundSUnit = CurSUnit;
1128 // Remember if this is a noop hazard.
1129 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
1131 NotReady.push_back(CurSUnit);
1134 // Add the nodes that aren't ready back onto the available list.
1135 if (!NotReady.empty()) {
1136 AvailableQueue.push_all(NotReady);
1140 // If we found a node to schedule, do it now.
1142 ScheduleNodeTopDown(FoundSUnit, CurCycle);
1143 HazardRec->EmitInstruction(FoundSUnit);
1144 CycleHasInsts = true;
1146 // If we are using the target-specific hazards, then don't
1147 // advance the cycle time just because we schedule a node. If
1148 // the target allows it we can schedule multiple nodes in the
1150 if (!EnablePostRAHazardAvoidance) {
1151 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
1155 if (CycleHasInsts) {
1156 DEBUG(errs() << "*** Finished cycle " << CurCycle << '\n');
1157 HazardRec->AdvanceCycle();
1158 } else if (!HasNoopHazards) {
1159 // Otherwise, we have a pipeline stall, but no other problem,
1160 // just advance the current cycle and try again.
1161 DEBUG(errs() << "*** Stall in cycle " << CurCycle << '\n');
1162 HazardRec->AdvanceCycle();
1165 // Otherwise, we have no instructions to issue and we have instructions
1166 // that will fault if we don't do this right. This is the case for
1167 // processors without pipeline interlocks and other cases.
1168 DEBUG(errs() << "*** Emitting noop in cycle " << CurCycle << '\n');
1169 HazardRec->EmitNoop();
1170 Sequence.push_back(0); // NULL here means noop
1175 CycleHasInsts = false;
1180 VerifySchedule(/*isBottomUp=*/false);
1184 //===----------------------------------------------------------------------===//
1185 // Public Constructor Functions
1186 //===----------------------------------------------------------------------===//
1188 FunctionPass *llvm::createPostRAScheduler() {
1189 return new PostRAScheduler();