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