Fix PR3667
[oota-llvm.git] / lib / CodeGen / PostRASchedulerList.cpp
1 //===----- SchedulePostRAList.cpp - list scheduler ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements a top-down list scheduler, using standard algorithms.
11 // The basic approach uses a priority queue of available nodes to schedule.
12 // One at a time, nodes are taken from the priority queue (thus in priority
13 // order), checked for legality to schedule, and emitted if legal.
14 //
15 // Nodes may not be legal to schedule either due to structural hazards (e.g.
16 // pipeline or resource constraints) or because an input to the instruction has
17 // not completed execution.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #define DEBUG_TYPE "post-RA-sched"
22 #include "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/ADT/Statistic.h"
38 #include <map>
39 using namespace llvm;
40
41 STATISTIC(NumNoops, "Number of noops inserted");
42 STATISTIC(NumStalls, "Number of pipeline stalls");
43
44 static cl::opt<bool>
45 EnableAntiDepBreaking("break-anti-dependencies",
46                       cl::desc("Break post-RA scheduling anti-dependencies"),
47                       cl::init(true), cl::Hidden);
48
49 static cl::opt<bool>
50 EnablePostRAHazardAvoidance("avoid-hazards",
51                       cl::desc("Enable simple hazard-avoidance"),
52                       cl::init(true), cl::Hidden);
53
54 namespace {
55   class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
56   public:
57     static char ID;
58     PostRAScheduler() : MachineFunctionPass(&ID) {}
59
60     void getAnalysisUsage(AnalysisUsage &AU) const {
61       AU.addRequired<MachineDominatorTree>();
62       AU.addPreserved<MachineDominatorTree>();
63       AU.addRequired<MachineLoopInfo>();
64       AU.addPreserved<MachineLoopInfo>();
65       MachineFunctionPass::getAnalysisUsage(AU);
66     }
67
68     const char *getPassName() const {
69       return "Post RA top-down list latency scheduler";
70     }
71
72     bool runOnMachineFunction(MachineFunction &Fn);
73   };
74   char PostRAScheduler::ID = 0;
75
76   class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
77     /// AvailableQueue - The priority queue to use for the available SUnits.
78     ///
79     LatencyPriorityQueue AvailableQueue;
80   
81     /// PendingQueue - This contains all of the instructions whose operands have
82     /// been issued, but their results are not ready yet (due to the latency of
83     /// the operation).  Once the operands becomes available, the instruction is
84     /// added to the AvailableQueue.
85     std::vector<SUnit*> PendingQueue;
86
87     /// Topo - A topological ordering for SUnits.
88     ScheduleDAGTopologicalSort Topo;
89
90     /// AllocatableSet - The set of allocatable registers.
91     /// We'll be ignoring anti-dependencies on non-allocatable registers,
92     /// because they may not be safe to break.
93     const BitVector AllocatableSet;
94
95     /// HazardRec - The hazard recognizer to use.
96     ScheduleHazardRecognizer *HazardRec;
97
98     /// Classes - For live regs that are only used in one register class in a
99     /// live range, the register class. If the register is not live, the
100     /// corresponding value is null. If the register is live but used in
101     /// multiple register classes, the corresponding value is -1 casted to a
102     /// pointer.
103     const TargetRegisterClass *
104       Classes[TargetRegisterInfo::FirstVirtualRegister];
105
106     /// RegRegs - Map registers to all their references within a live range.
107     std::multimap<unsigned, MachineOperand *> RegRefs;
108
109     /// The index of the most recent kill (proceding bottom-up), or ~0u if
110     /// the register is not live.
111     unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
112
113     /// The index of the most recent complete def (proceding bottom up), or ~0u
114     /// if the register is live.
115     unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
116
117   public:
118     SchedulePostRATDList(MachineFunction &MF,
119                          const MachineLoopInfo &MLI,
120                          const MachineDominatorTree &MDT,
121                          ScheduleHazardRecognizer *HR)
122       : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
123         AllocatableSet(TRI->getAllocatableSet(MF)),
124         HazardRec(HR) {}
125
126     ~SchedulePostRATDList() {
127       delete HazardRec;
128     }
129
130     /// StartBlock - Initialize register live-range state for scheduling in
131     /// this block.
132     ///
133     void StartBlock(MachineBasicBlock *BB);
134
135     /// Schedule - Schedule the instruction range using list scheduling.
136     ///
137     void Schedule();
138
139     /// Observe - Update liveness information to account for the current
140     /// instruction, which will not be scheduled.
141     ///
142     void Observe(MachineInstr *MI, unsigned Count);
143
144     /// FinishBlock - Clean up register live-range state.
145     ///
146     void FinishBlock();
147
148   private:
149     void PrescanInstruction(MachineInstr *MI);
150     void ScanInstruction(MachineInstr *MI, unsigned Count);
151     void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
152     void ReleaseSuccessors(SUnit *SU);
153     void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
154     void ListScheduleTopDown();
155     bool BreakAntiDependencies();
156   };
157
158   /// SimpleHazardRecognizer - A *very* simple hazard recognizer. It uses
159   /// a coarse classification and attempts to avoid that instructions of
160   /// a given class aren't grouped too densely together.
161   class SimpleHazardRecognizer : public ScheduleHazardRecognizer {
162     /// Class - A simple classification for SUnits.
163     enum Class {
164       Other, Load, Store
165     };
166
167     /// Window - The Class values of the most recently issued
168     /// instructions.
169     Class Window[8];
170
171     /// getClass - Classify the given SUnit.
172     Class getClass(const SUnit *SU) {
173       const MachineInstr *MI = SU->getInstr();
174       const TargetInstrDesc &TID = MI->getDesc();
175       if (TID.mayLoad())
176         return Load;
177       if (TID.mayStore())
178         return Store;
179       return Other;
180     }
181
182     /// Step - Rotate the existing entries in Window and insert the
183     /// given class value in position as the most recent.
184     void Step(Class C) {
185       std::copy(Window+1, array_endof(Window), Window);
186       Window[array_lengthof(Window)-1] = C;
187     }
188
189   public:
190     SimpleHazardRecognizer() : Window() {}
191
192     virtual HazardType getHazardType(SUnit *SU) {
193       Class C = getClass(SU);
194       if (C == Other)
195         return NoHazard;
196       unsigned Score = 0;
197       for (unsigned i = 0; i != array_lengthof(Window); ++i)
198         if (Window[i] == C)
199           Score += i + 1;
200       if (Score > array_lengthof(Window) * 2)
201         return Hazard;
202       return NoHazard;
203     }
204
205     virtual void EmitInstruction(SUnit *SU) {
206       Step(getClass(SU));
207     }
208
209     virtual void AdvanceCycle() {
210       Step(Other);
211     }
212   };
213 }
214
215 /// isSchedulingBoundary - Test if the given instruction should be
216 /// considered a scheduling boundary. This primarily includes labels
217 /// and terminators.
218 ///
219 static bool isSchedulingBoundary(const MachineInstr *MI,
220                                  const MachineFunction &MF) {
221   // Terminators and labels can't be scheduled around.
222   if (MI->getDesc().isTerminator() || MI->isLabel())
223     return true;
224
225   // Don't attempt to schedule around any instruction that modifies
226   // a stack-oriented pointer, as it's unlikely to be profitable. This
227   // saves compile time, because it doesn't require every single
228   // stack slot reference to depend on the instruction that does the
229   // modification.
230   const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
231   if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
232     return true;
233
234   return false;
235 }
236
237 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
238   DOUT << "PostRAScheduler\n";
239
240   const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
241   const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
242   ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
243                                  new SimpleHazardRecognizer :
244                                  new ScheduleHazardRecognizer();
245
246   SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
247
248   // Loop over all of the basic blocks
249   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
250        MBB != MBBe; ++MBB) {
251     // Initialize register live-range state for scheduling in this block.
252     Scheduler.StartBlock(MBB);
253
254     // Schedule each sequence of instructions not interrupted by a label
255     // or anything else that effectively needs to shut down scheduling.
256     MachineBasicBlock::iterator Current = MBB->end();
257     unsigned Count = MBB->size(), CurrentCount = Count;
258     for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
259       MachineInstr *MI = prior(I);
260       if (isSchedulingBoundary(MI, Fn)) {
261         if (I != Current) {
262           Scheduler.Run(MBB, I, Current, CurrentCount);
263           Scheduler.EmitSchedule();
264         }
265         Scheduler.Observe(MI, Count);
266         Current = MI;
267         CurrentCount = Count - 1;
268       }
269       I = MI;
270       --Count;
271     }
272     assert(Count == 0 && "Instruction count mismatch!");
273     if (MBB->begin() != Current) {
274       assert(CurrentCount != 0 && "Instruction count mismatch!");
275       Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
276     }
277     Scheduler.EmitSchedule();
278
279     // Clean up register live-range state.
280     Scheduler.FinishBlock();
281   }
282
283   return true;
284 }
285   
286 /// StartBlock - Initialize register live-range state for scheduling in
287 /// this block.
288 ///
289 void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
290   // Call the superclass.
291   ScheduleDAGInstrs::StartBlock(BB);
292
293   // Clear out the register class data.
294   std::fill(Classes, array_endof(Classes),
295             static_cast<const TargetRegisterClass *>(0));
296
297   // Initialize the indices to indicate that no registers are live.
298   std::fill(KillIndices, array_endof(KillIndices), ~0u);
299   std::fill(DefIndices, array_endof(DefIndices), BB->size());
300
301   // Determine the live-out physregs for this block.
302   if (!BB->empty() && BB->back().getDesc().isReturn())
303     // In a return block, examine the function live-out regs.
304     for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
305          E = MRI.liveout_end(); I != E; ++I) {
306       unsigned Reg = *I;
307       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
308       KillIndices[Reg] = BB->size();
309       DefIndices[Reg] = ~0u;
310       // Repeat, for all aliases.
311       for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
312         unsigned AliasReg = *Alias;
313         Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
314         KillIndices[AliasReg] = BB->size();
315         DefIndices[AliasReg] = ~0u;
316       }
317     }
318   else
319     // In a non-return block, examine the live-in regs of all successors.
320     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
321          SE = BB->succ_end(); SI != SE; ++SI)
322       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
323            E = (*SI)->livein_end(); I != E; ++I) {
324         unsigned Reg = *I;
325         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
326         KillIndices[Reg] = BB->size();
327         DefIndices[Reg] = ~0u;
328         // Repeat, for all aliases.
329         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
330           unsigned AliasReg = *Alias;
331           Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
332           KillIndices[AliasReg] = BB->size();
333           DefIndices[AliasReg] = ~0u;
334         }
335       }
336
337   // Consider callee-saved registers as live-out, since we're running after
338   // prologue/epilogue insertion so there's no way to add additional
339   // saved registers.
340   //
341   // TODO: If the callee saves and restores these, then we can potentially
342   // use them between the save and the restore. To do that, we could scan
343   // the exit blocks to see which of these registers are defined.
344   // Alternatively, callee-saved registers that aren't saved and restored
345   // could be marked live-in in every block.
346   for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
347     unsigned Reg = *I;
348     Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
349     KillIndices[Reg] = BB->size();
350     DefIndices[Reg] = ~0u;
351     // Repeat, for all aliases.
352     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
353       unsigned AliasReg = *Alias;
354       Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
355       KillIndices[AliasReg] = BB->size();
356       DefIndices[AliasReg] = ~0u;
357     }
358   }
359 }
360
361 /// Schedule - Schedule the instruction range using list scheduling.
362 ///
363 void SchedulePostRATDList::Schedule() {
364   DOUT << "********** List Scheduling **********\n";
365   
366   // Build the scheduling graph.
367   BuildSchedGraph();
368
369   if (EnableAntiDepBreaking) {
370     if (BreakAntiDependencies()) {
371       // We made changes. Update the dependency graph.
372       // Theoretically we could update the graph in place:
373       // When a live range is changed to use a different register, remove
374       // the def's anti-dependence *and* output-dependence edges due to
375       // that register, and add new anti-dependence and output-dependence
376       // edges based on the next live range of the register.
377       SUnits.clear();
378       EntrySU = SUnit();
379       ExitSU = SUnit();
380       BuildSchedGraph();
381     }
382   }
383
384   AvailableQueue.initNodes(SUnits);
385
386   ListScheduleTopDown();
387   
388   AvailableQueue.releaseState();
389 }
390
391 /// Observe - Update liveness information to account for the current
392 /// instruction, which will not be scheduled.
393 ///
394 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
395   PrescanInstruction(MI);
396   ScanInstruction(MI, Count);
397 }
398
399 /// FinishBlock - Clean up register live-range state.
400 ///
401 void SchedulePostRATDList::FinishBlock() {
402   RegRefs.clear();
403
404   // Call the superclass.
405   ScheduleDAGInstrs::FinishBlock();
406 }
407
408 /// getInstrOperandRegClass - Return register class of the operand of an
409 /// instruction of the specified TargetInstrDesc.
410 static const TargetRegisterClass*
411 getInstrOperandRegClass(const TargetRegisterInfo *TRI,
412                          const TargetInstrDesc &II, unsigned Op) {
413   if (Op >= II.getNumOperands())
414     return NULL;
415   if (II.OpInfo[Op].isLookupPtrRegClass())
416     return TRI->getPointerRegClass();
417   return TRI->getRegClass(II.OpInfo[Op].RegClass);
418 }
419
420 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
421 /// critical path.
422 static SDep *CriticalPathStep(SUnit *SU) {
423   SDep *Next = 0;
424   unsigned NextDepth = 0;
425   // Find the predecessor edge with the greatest depth.
426   for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
427        P != PE; ++P) {
428     SUnit *PredSU = P->getSUnit();
429     unsigned PredLatency = P->getLatency();
430     unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
431     // In the case of a latency tie, prefer an anti-dependency edge over
432     // other types of edges.
433     if (NextDepth < PredTotalLatency ||
434         (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
435       NextDepth = PredTotalLatency;
436       Next = &*P;
437     }
438   }
439   return Next;
440 }
441
442 void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
443   // Scan the register operands for this instruction and update
444   // Classes and RegRefs.
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     const TargetRegisterClass *NewRC =
451       getInstrOperandRegClass(TRI, MI->getDesc(), i);
452
453     // For now, only allow the register to be changed if its register
454     // class is consistent across all uses.
455     if (!Classes[Reg] && NewRC)
456       Classes[Reg] = NewRC;
457     else if (!NewRC || Classes[Reg] != NewRC)
458       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
459
460     // Now check for aliases.
461     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
462       // If an alias of the reg is used during the live range, give up.
463       // Note that this allows us to skip checking if AntiDepReg
464       // overlaps with any of the aliases, among other things.
465       unsigned AliasReg = *Alias;
466       if (Classes[AliasReg]) {
467         Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
468         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
469       }
470     }
471
472     // If we're still willing to consider this register, note the reference.
473     if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
474       RegRefs.insert(std::make_pair(Reg, &MO));
475   }
476 }
477
478 void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
479                                            unsigned Count) {
480   // Update liveness.
481   // Proceding upwards, registers that are defed but not used in this
482   // instruction are now dead.
483   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
484     MachineOperand &MO = MI->getOperand(i);
485     if (!MO.isReg()) continue;
486     unsigned Reg = MO.getReg();
487     if (Reg == 0) continue;
488     if (!MO.isDef()) continue;
489     // Ignore two-addr defs.
490     if (MI->isRegReDefinedByTwoAddr(i)) continue;
491
492     DefIndices[Reg] = Count;
493     KillIndices[Reg] = ~0u;
494           assert(((KillIndices[Reg] == ~0u) !=
495                   (DefIndices[Reg] == ~0u)) &&
496                "Kill and Def maps aren't consistent for Reg!");
497     Classes[Reg] = 0;
498     RegRefs.erase(Reg);
499     // Repeat, for all subregs.
500     for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
501          *Subreg; ++Subreg) {
502       unsigned SubregReg = *Subreg;
503       DefIndices[SubregReg] = Count;
504       KillIndices[SubregReg] = ~0u;
505       Classes[SubregReg] = 0;
506       RegRefs.erase(SubregReg);
507     }
508     // Conservatively mark super-registers as unusable.
509     for (const unsigned *Super = TRI->getSuperRegisters(Reg);
510          *Super; ++Super) {
511       unsigned SuperReg = *Super;
512       Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
513     }
514   }
515   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
516     MachineOperand &MO = MI->getOperand(i);
517     if (!MO.isReg()) continue;
518     unsigned Reg = MO.getReg();
519     if (Reg == 0) continue;
520     if (!MO.isUse()) continue;
521
522     const TargetRegisterClass *NewRC =
523       getInstrOperandRegClass(TRI, MI->getDesc(), i);
524
525     // For now, only allow the register to be changed if its register
526     // class is consistent across all uses.
527     if (!Classes[Reg] && NewRC)
528       Classes[Reg] = NewRC;
529     else if (!NewRC || Classes[Reg] != NewRC)
530       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
531
532     RegRefs.insert(std::make_pair(Reg, &MO));
533
534     // It wasn't previously live but now it is, this is a kill.
535     if (KillIndices[Reg] == ~0u) {
536       KillIndices[Reg] = Count;
537       DefIndices[Reg] = ~0u;
538           assert(((KillIndices[Reg] == ~0u) !=
539                   (DefIndices[Reg] == ~0u)) &&
540                "Kill and Def maps aren't consistent for Reg!");
541     }
542     // Repeat, for all aliases.
543     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
544       unsigned AliasReg = *Alias;
545       if (KillIndices[AliasReg] == ~0u) {
546         KillIndices[AliasReg] = Count;
547         DefIndices[AliasReg] = ~0u;
548       }
549     }
550   }
551 }
552
553 /// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
554 /// of the ScheduleDAG and break them by renaming registers.
555 ///
556 bool SchedulePostRATDList::BreakAntiDependencies() {
557   // The code below assumes that there is at least one instruction,
558   // so just duck out immediately if the block is empty.
559   if (SUnits.empty()) return false;
560
561   // Find the node at the bottom of the critical path.
562   SUnit *Max = 0;
563   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
564     SUnit *SU = &SUnits[i];
565     if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
566       Max = SU;
567   }
568
569   DOUT << "Critical path has total latency "
570        << (Max->getDepth() + Max->Latency) << "\n";
571
572   // Track progress along the critical path through the SUnit graph as we walk
573   // the instructions.
574   SUnit *CriticalPathSU = Max;
575   MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
576
577   // Consider this pattern:
578   //   A = ...
579   //   ... = A
580   //   A = ...
581   //   ... = A
582   //   A = ...
583   //   ... = A
584   //   A = ...
585   //   ... = A
586   // There are three anti-dependencies here, and without special care,
587   // we'd break all of them using the same register:
588   //   A = ...
589   //   ... = A
590   //   B = ...
591   //   ... = B
592   //   B = ...
593   //   ... = B
594   //   B = ...
595   //   ... = B
596   // because at each anti-dependence, B is the first register that
597   // isn't A which is free.  This re-introduces anti-dependencies
598   // at all but one of the original anti-dependencies that we were
599   // trying to break.  To avoid this, keep track of the most recent
600   // register that each register was replaced with, avoid avoid
601   // using it to repair an anti-dependence on the same register.
602   // This lets us produce this:
603   //   A = ...
604   //   ... = A
605   //   B = ...
606   //   ... = B
607   //   C = ...
608   //   ... = C
609   //   B = ...
610   //   ... = B
611   // This still has an anti-dependence on B, but at least it isn't on the
612   // original critical path.
613   //
614   // TODO: If we tracked more than one register here, we could potentially
615   // fix that remaining critical edge too. This is a little more involved,
616   // because unlike the most recent register, less recent registers should
617   // still be considered, though only if no other registers are available.
618   unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
619
620   // Attempt to break anti-dependence edges on the critical path. Walk the
621   // instructions from the bottom up, tracking information about liveness
622   // as we go to help determine which registers are available.
623   bool Changed = false;
624   unsigned Count = InsertPosIndex - 1;
625   for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
626        I != E; --Count) {
627     MachineInstr *MI = --I;
628
629     // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
630     // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
631     // is left behind appearing to clobber the super-register, while the
632     // subregister needs to remain live. So we just ignore them.
633     if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
634       continue;
635
636     // Check if this instruction has a dependence on the critical path that
637     // is an anti-dependence that we may be able to break. If it is, set
638     // AntiDepReg to the non-zero register associated with the anti-dependence.
639     //
640     // We limit our attention to the critical path as a heuristic to avoid
641     // breaking anti-dependence edges that aren't going to significantly
642     // impact the overall schedule. There are a limited number of registers
643     // and we want to save them for the important edges.
644     // 
645     // TODO: Instructions with multiple defs could have multiple
646     // anti-dependencies. The current code here only knows how to break one
647     // edge per instruction. Note that we'd have to be able to break all of
648     // the anti-dependencies in an instruction in order to be effective.
649     unsigned AntiDepReg = 0;
650     if (MI == CriticalPathMI) {
651       if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
652         SUnit *NextSU = Edge->getSUnit();
653
654         // Only consider anti-dependence edges.
655         if (Edge->getKind() == SDep::Anti) {
656           AntiDepReg = Edge->getReg();
657           assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
658           // Don't break anti-dependencies on non-allocatable registers.
659           if (!AllocatableSet.test(AntiDepReg))
660             AntiDepReg = 0;
661           else {
662             // If the SUnit has other dependencies on the SUnit that it
663             // anti-depends on, don't bother breaking the anti-dependency
664             // since those edges would prevent such units from being
665             // scheduled past each other regardless.
666             //
667             // Also, if there are dependencies on other SUnits with the
668             // same register as the anti-dependency, don't attempt to
669             // break it.
670             for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
671                  PE = CriticalPathSU->Preds.end(); P != PE; ++P)
672               if (P->getSUnit() == NextSU ?
673                     (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
674                     (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
675                 AntiDepReg = 0;
676                 break;
677               }
678           }
679         }
680         CriticalPathSU = NextSU;
681         CriticalPathMI = CriticalPathSU->getInstr();
682       } else {
683         // We've reached the end of the critical path.
684         CriticalPathSU = 0;
685         CriticalPathMI = 0;
686       }
687     }
688
689     PrescanInstruction(MI);
690
691     // If this instruction has a use of AntiDepReg, breaking it
692     // is invalid.
693     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
694       MachineOperand &MO = MI->getOperand(i);
695       if (!MO.isReg()) continue;
696       unsigned Reg = MO.getReg();
697       if (Reg == 0) continue;
698       if (MO.isUse() && AntiDepReg == Reg) {
699         AntiDepReg = 0;
700         break;
701       }
702     }
703
704     // Determine AntiDepReg's register class, if it is live and is
705     // consistently used within a single class.
706     const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
707     assert((AntiDepReg == 0 || RC != NULL) &&
708            "Register should be live if it's causing an anti-dependence!");
709     if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
710       AntiDepReg = 0;
711
712     // Look for a suitable register to use to break the anti-depenence.
713     //
714     // TODO: Instead of picking the first free register, consider which might
715     // be the best.
716     if (AntiDepReg != 0) {
717       for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
718            RE = RC->allocation_order_end(MF); R != RE; ++R) {
719         unsigned NewReg = *R;
720         // Don't replace a register with itself.
721         if (NewReg == AntiDepReg) continue;
722         // Don't replace a register with one that was recently used to repair
723         // an anti-dependence with this AntiDepReg, because that would
724         // re-introduce that anti-dependence.
725         if (NewReg == LastNewReg[AntiDepReg]) continue;
726         // If NewReg is dead and NewReg's most recent def is not before
727         // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
728         assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
729                "Kill and Def maps aren't consistent for AntiDepReg!");
730         assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
731                "Kill and Def maps aren't consistent for NewReg!");
732         if (KillIndices[NewReg] == ~0u &&
733             Classes[NewReg] != reinterpret_cast<TargetRegisterClass *>(-1) &&
734             KillIndices[AntiDepReg] <= DefIndices[NewReg]) {
735           DOUT << "Breaking anti-dependence edge on "
736                << TRI->getName(AntiDepReg)
737                << " with " << RegRefs.count(AntiDepReg) << " references"
738                << " using " << TRI->getName(NewReg) << "!\n";
739
740           // Update the references to the old register to refer to the new
741           // register.
742           std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
743                     std::multimap<unsigned, MachineOperand *>::iterator>
744              Range = RegRefs.equal_range(AntiDepReg);
745           for (std::multimap<unsigned, MachineOperand *>::iterator
746                Q = Range.first, QE = Range.second; Q != QE; ++Q)
747             Q->second->setReg(NewReg);
748
749           // We just went back in time and modified history; the
750           // liveness information for the anti-depenence reg is now
751           // inconsistent. Set the state as if it were dead.
752           Classes[NewReg] = Classes[AntiDepReg];
753           DefIndices[NewReg] = DefIndices[AntiDepReg];
754           KillIndices[NewReg] = KillIndices[AntiDepReg];
755           assert(((KillIndices[NewReg] == ~0u) !=
756                   (DefIndices[NewReg] == ~0u)) &&
757                "Kill and Def maps aren't consistent for NewReg!");
758
759           Classes[AntiDepReg] = 0;
760           DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
761           KillIndices[AntiDepReg] = ~0u;
762           assert(((KillIndices[AntiDepReg] == ~0u) !=
763                   (DefIndices[AntiDepReg] == ~0u)) &&
764                "Kill and Def maps aren't consistent for AntiDepReg!");
765
766           RegRefs.erase(AntiDepReg);
767           Changed = true;
768           LastNewReg[AntiDepReg] = NewReg;
769           break;
770         }
771       }
772     }
773
774     ScanInstruction(MI, Count);
775   }
776
777   return Changed;
778 }
779
780 //===----------------------------------------------------------------------===//
781 //  Top-Down Scheduling
782 //===----------------------------------------------------------------------===//
783
784 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
785 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
786 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
787   SUnit *SuccSU = SuccEdge->getSUnit();
788   --SuccSU->NumPredsLeft;
789   
790 #ifndef NDEBUG
791   if (SuccSU->NumPredsLeft < 0) {
792     cerr << "*** Scheduling failed! ***\n";
793     SuccSU->dump(this);
794     cerr << " has been released too many times!\n";
795     assert(0);
796   }
797 #endif
798   
799   // Compute how many cycles it will be before this actually becomes
800   // available.  This is the max of the start time of all predecessors plus
801   // their latencies.
802   SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
803   
804   // If all the node's predecessors are scheduled, this node is ready
805   // to be scheduled. Ignore the special ExitSU node.
806   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
807     PendingQueue.push_back(SuccSU);
808 }
809
810 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
811 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
812   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
813        I != E; ++I)
814     ReleaseSucc(SU, &*I);
815 }
816
817 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
818 /// count of its successors. If a successor pending count is zero, add it to
819 /// the Available queue.
820 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
821   DOUT << "*** Scheduling [" << CurCycle << "]: ";
822   DEBUG(SU->dump(this));
823   
824   Sequence.push_back(SU);
825   assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
826   SU->setDepthToAtLeast(CurCycle);
827
828   ReleaseSuccessors(SU);
829   SU->isScheduled = true;
830   AvailableQueue.ScheduledNode(SU);
831 }
832
833 /// ListScheduleTopDown - The main loop of list scheduling for top-down
834 /// schedulers.
835 void SchedulePostRATDList::ListScheduleTopDown() {
836   unsigned CurCycle = 0;
837
838   // Release any successors of the special Entry node.
839   ReleaseSuccessors(&EntrySU);
840
841   // All leaves to Available queue.
842   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
843     // It is available if it has no predecessors.
844     if (SUnits[i].Preds.empty()) {
845       AvailableQueue.push(&SUnits[i]);
846       SUnits[i].isAvailable = true;
847     }
848   }
849
850   // While Available queue is not empty, grab the node with the highest
851   // priority. If it is not ready put it back.  Schedule the node.
852   std::vector<SUnit*> NotReady;
853   Sequence.reserve(SUnits.size());
854   while (!AvailableQueue.empty() || !PendingQueue.empty()) {
855     // Check to see if any of the pending instructions are ready to issue.  If
856     // so, add them to the available queue.
857     unsigned MinDepth = ~0u;
858     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
859       if (PendingQueue[i]->getDepth() <= CurCycle) {
860         AvailableQueue.push(PendingQueue[i]);
861         PendingQueue[i]->isAvailable = true;
862         PendingQueue[i] = PendingQueue.back();
863         PendingQueue.pop_back();
864         --i; --e;
865       } else if (PendingQueue[i]->getDepth() < MinDepth)
866         MinDepth = PendingQueue[i]->getDepth();
867     }
868     
869     // If there are no instructions available, don't try to issue anything, and
870     // don't advance the hazard recognizer.
871     if (AvailableQueue.empty()) {
872       CurCycle = MinDepth != ~0u ? MinDepth : CurCycle + 1;
873       continue;
874     }
875
876     SUnit *FoundSUnit = 0;
877
878     bool HasNoopHazards = false;
879     while (!AvailableQueue.empty()) {
880       SUnit *CurSUnit = AvailableQueue.pop();
881
882       ScheduleHazardRecognizer::HazardType HT =
883         HazardRec->getHazardType(CurSUnit);
884       if (HT == ScheduleHazardRecognizer::NoHazard) {
885         FoundSUnit = CurSUnit;
886         break;
887       }
888
889       // Remember if this is a noop hazard.
890       HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
891
892       NotReady.push_back(CurSUnit);
893     }
894
895     // Add the nodes that aren't ready back onto the available list.
896     if (!NotReady.empty()) {
897       AvailableQueue.push_all(NotReady);
898       NotReady.clear();
899     }
900
901     // If we found a node to schedule, do it now.
902     if (FoundSUnit) {
903       ScheduleNodeTopDown(FoundSUnit, CurCycle);
904       HazardRec->EmitInstruction(FoundSUnit);
905
906       // If this is a pseudo-op node, we don't want to increment the current
907       // cycle.
908       if (FoundSUnit->Latency)  // Don't increment CurCycle for pseudo-ops!
909         ++CurCycle;
910     } else if (!HasNoopHazards) {
911       // Otherwise, we have a pipeline stall, but no other problem, just advance
912       // the current cycle and try again.
913       DOUT << "*** Advancing cycle, no work to do\n";
914       HazardRec->AdvanceCycle();
915       ++NumStalls;
916       ++CurCycle;
917     } else {
918       // Otherwise, we have no instructions to issue and we have instructions
919       // that will fault if we don't do this right.  This is the case for
920       // processors without pipeline interlocks and other cases.
921       DOUT << "*** Emitting noop\n";
922       HazardRec->EmitNoop();
923       Sequence.push_back(0);   // NULL here means noop
924       ++NumNoops;
925       ++CurCycle;
926     }
927   }
928
929 #ifndef NDEBUG
930   VerifySchedule(/*isBottomUp=*/false);
931 #endif
932 }
933
934 //===----------------------------------------------------------------------===//
935 //                         Public Constructor Functions
936 //===----------------------------------------------------------------------===//
937
938 FunctionPass *llvm::createPostRAScheduler() {
939   return new PostRAScheduler();
940 }