1a744be1bf01079cd58c3b21d48cf5fe22fa6db4
[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 "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/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtarget.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/ADT/Statistic.h"
44 #include <map>
45 #include <set>
46 using namespace llvm;
47
48 STATISTIC(NumNoops, "Number of noops inserted");
49 STATISTIC(NumStalls, "Number of pipeline stalls");
50
51 static cl::opt<bool>
52 EnableAntiDepBreaking("break-anti-dependencies",
53                       cl::desc("Break post-RA scheduling anti-dependencies"),
54                       cl::init(true), cl::Hidden);
55
56 static cl::opt<bool>
57 EnablePostRAHazardAvoidance("avoid-hazards",
58                       cl::desc("Enable exact hazard avoidance"),
59                       cl::init(true), cl::Hidden);
60
61 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
62 static cl::opt<int>
63 DebugDiv("postra-sched-debugdiv",
64                       cl::desc("Debug control MBBs that are scheduled"),
65                       cl::init(0), cl::Hidden);
66 static cl::opt<int>
67 DebugMod("postra-sched-debugmod",
68                       cl::desc("Debug control MBBs that are scheduled"),
69                       cl::init(0), cl::Hidden);
70
71 namespace {
72   class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
73   public:
74     static char ID;
75     PostRAScheduler() : MachineFunctionPass(&ID) {}
76
77     void getAnalysisUsage(AnalysisUsage &AU) const {
78       AU.setPreservesCFG();
79       AU.addRequired<MachineDominatorTree>();
80       AU.addPreserved<MachineDominatorTree>();
81       AU.addRequired<MachineLoopInfo>();
82       AU.addPreserved<MachineLoopInfo>();
83       MachineFunctionPass::getAnalysisUsage(AU);
84     }
85
86     const char *getPassName() const {
87       return "Post RA top-down list latency scheduler";
88     }
89
90     bool runOnMachineFunction(MachineFunction &Fn);
91   };
92   char PostRAScheduler::ID = 0;
93
94   class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
95     /// AvailableQueue - The priority queue to use for the available SUnits.
96     ///
97     LatencyPriorityQueue AvailableQueue;
98   
99     /// PendingQueue - This contains all of the instructions whose operands have
100     /// been issued, but their results are not ready yet (due to the latency of
101     /// the operation).  Once the operands becomes available, the instruction is
102     /// added to the AvailableQueue.
103     std::vector<SUnit*> PendingQueue;
104
105     /// Topo - A topological ordering for SUnits.
106     ScheduleDAGTopologicalSort Topo;
107
108     /// AllocatableSet - The set of allocatable registers.
109     /// We'll be ignoring anti-dependencies on non-allocatable registers,
110     /// because they may not be safe to break.
111     const BitVector AllocatableSet;
112
113     /// HazardRec - The hazard recognizer to use.
114     ScheduleHazardRecognizer *HazardRec;
115
116     /// Classes - For live regs that are only used in one register class in a
117     /// live range, the register class. If the register is not live, the
118     /// corresponding value is null. If the register is live but used in
119     /// multiple register classes, the corresponding value is -1 casted to a
120     /// pointer.
121     const TargetRegisterClass *
122       Classes[TargetRegisterInfo::FirstVirtualRegister];
123
124     /// RegRegs - Map registers to all their references within a live range.
125     std::multimap<unsigned, MachineOperand *> RegRefs;
126
127     /// KillIndices - The index of the most recent kill (proceding bottom-up),
128     /// or ~0u if the register is not live.
129     unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
130
131     /// DefIndices - The index of the most recent complete def (proceding bottom
132     /// up), or ~0u if the register is live.
133     unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
134
135     /// KeepRegs - A set of registers which are live and cannot be changed to
136     /// break anti-dependencies.
137     SmallSet<unsigned, 4> KeepRegs;
138
139   public:
140     SchedulePostRATDList(MachineFunction &MF,
141                          const MachineLoopInfo &MLI,
142                          const MachineDominatorTree &MDT,
143                          ScheduleHazardRecognizer *HR)
144       : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
145         AllocatableSet(TRI->getAllocatableSet(MF)),
146         HazardRec(HR) {}
147
148     ~SchedulePostRATDList() {
149       delete HazardRec;
150     }
151
152     /// StartBlock - Initialize register live-range state for scheduling in
153     /// this block.
154     ///
155     void StartBlock(MachineBasicBlock *BB);
156
157     /// Schedule - Schedule the instruction range using list scheduling.
158     ///
159     void Schedule();
160     
161     /// FixupKills - Fix register kill flags that have been made
162     /// invalid due to scheduling
163     ///
164     void FixupKills(MachineBasicBlock *MBB);
165
166     /// Observe - Update liveness information to account for the current
167     /// instruction, which will not be scheduled.
168     ///
169     void Observe(MachineInstr *MI, unsigned Count);
170
171     /// FinishBlock - Clean up register live-range state.
172     ///
173     void FinishBlock();
174
175   private:
176     void PrescanInstruction(MachineInstr *MI);
177     void ScanInstruction(MachineInstr *MI, unsigned Count);
178     void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
179     void ReleaseSuccessors(SUnit *SU);
180     void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
181     void ListScheduleTopDown();
182     bool BreakAntiDependencies();
183     unsigned findSuitableFreeRegister(unsigned AntiDepReg,
184                                       unsigned LastNewReg,
185                                       const TargetRegisterClass *);
186     void StartBlockForKills(MachineBasicBlock *BB);
187     
188     // ToggleKillFlag - Toggle a register operand kill flag. Other
189     // adjustments may be made to the instruction if necessary. Return
190     // true if the operand has been deleted, false if not.
191     bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
192   };
193 }
194
195 /// isSchedulingBoundary - Test if the given instruction should be
196 /// considered a scheduling boundary. This primarily includes labels
197 /// and terminators.
198 ///
199 static bool isSchedulingBoundary(const MachineInstr *MI,
200                                  const MachineFunction &MF) {
201   // Terminators and labels can't be scheduled around.
202   if (MI->getDesc().isTerminator() || MI->isLabel())
203     return true;
204
205   // Don't attempt to schedule around any instruction that modifies
206   // a stack-oriented pointer, as it's unlikely to be profitable. This
207   // saves compile time, because it doesn't require every single
208   // stack slot reference to depend on the instruction that does the
209   // modification.
210   const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
211   if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
212     return true;
213
214   return false;
215 }
216
217 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
218   // Check that post-RA scheduling is enabled for this function
219   const TargetSubtarget &ST = Fn.getTarget().getSubtarget<TargetSubtarget>();
220   if (!ST.enablePostRAScheduler())
221     return true;
222
223   DEBUG(errs() << "PostRAScheduler\n");
224
225   const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
226   const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
227   const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
228   ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
229     (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
230     (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
231
232   SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
233
234   // Loop over all of the basic blocks
235   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
236        MBB != MBBe; ++MBB) {
237 #ifndef NDEBUG
238     // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
239     if (DebugDiv > 0) {
240       static int bbcnt = 0;
241       if (bbcnt++ % DebugDiv != DebugMod)
242         continue;
243       errs() << "*** DEBUG scheduling " << Fn.getFunction()->getNameStr() <<
244         ":MBB ID#" << MBB->getNumber() << " ***\n";
245     }
246 #endif
247
248     // Initialize register live-range state for scheduling in this block.
249     Scheduler.StartBlock(MBB);
250
251     // Schedule each sequence of instructions not interrupted by a label
252     // or anything else that effectively needs to shut down scheduling.
253     MachineBasicBlock::iterator Current = MBB->end();
254     unsigned Count = MBB->size(), CurrentCount = Count;
255     for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
256       MachineInstr *MI = prior(I);
257       if (isSchedulingBoundary(MI, Fn)) {
258         Scheduler.Run(MBB, I, Current, CurrentCount);
259         Scheduler.EmitSchedule(0);
260         Current = MI;
261         CurrentCount = Count - 1;
262         Scheduler.Observe(MI, CurrentCount);
263       }
264       I = MI;
265       --Count;
266     }
267     assert(Count == 0 && "Instruction count mismatch!");
268     assert((MBB->begin() == Current || CurrentCount != 0) &&
269            "Instruction count mismatch!");
270     Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
271     Scheduler.EmitSchedule(0);
272
273     // Clean up register live-range state.
274     Scheduler.FinishBlock();
275
276     // Update register kills
277     Scheduler.FixupKills(MBB);
278   }
279
280   return true;
281 }
282   
283 /// StartBlock - Initialize register live-range state for scheduling in
284 /// this block.
285 ///
286 void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
287   // Call the superclass.
288   ScheduleDAGInstrs::StartBlock(BB);
289
290   // Reset the hazard recognizer.
291   HazardRec->Reset();
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   // Clear "do not change" set.
302   KeepRegs.clear();
303
304   // Determine the live-out physregs for this block.
305   if (!BB->empty() && BB->back().getDesc().isReturn()) {
306     // In a return block, examine the function live-out regs.
307     for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
308          E = MRI.liveout_end(); I != E; ++I) {
309       unsigned Reg = *I;
310       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
311       KillIndices[Reg] = BB->size();
312       DefIndices[Reg] = ~0u;
313       // Repeat, for all aliases.
314       for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
315         unsigned AliasReg = *Alias;
316         Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
317         KillIndices[AliasReg] = BB->size();
318         DefIndices[AliasReg] = ~0u;
319       }
320     }
321   } else {
322     // In a non-return block, examine the live-in regs of all successors.
323     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
324          SE = BB->succ_end(); SI != SE; ++SI)
325       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
326            E = (*SI)->livein_end(); I != E; ++I) {
327         unsigned Reg = *I;
328         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
329         KillIndices[Reg] = BB->size();
330         DefIndices[Reg] = ~0u;
331         // Repeat, for all aliases.
332         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
333           unsigned AliasReg = *Alias;
334           Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
335           KillIndices[AliasReg] = BB->size();
336           DefIndices[AliasReg] = ~0u;
337         }
338       }
339
340     // Also mark as live-out any callee-saved registers that were not
341     // saved in the prolog.
342     const MachineFrameInfo *MFI = MF.getFrameInfo();
343     BitVector Pristine = MFI->getPristineRegs(BB);
344     for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
345       unsigned Reg = *I;
346       if (!Pristine.test(Reg)) continue;
347       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
348       KillIndices[Reg] = BB->size();
349       DefIndices[Reg] = ~0u;
350       // Repeat, for all aliases.
351       for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
352         unsigned AliasReg = *Alias;
353         Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
354         KillIndices[AliasReg] = BB->size();
355         DefIndices[AliasReg] = ~0u;
356       }
357     }
358   }
359 }
360
361 /// Schedule - Schedule the instruction range using list scheduling.
362 ///
363 void SchedulePostRATDList::Schedule() {
364   DEBUG(errs() << "********** 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   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
385           SUnits[su].dumpAll(this));
386
387   AvailableQueue.initNodes(SUnits);
388
389   ListScheduleTopDown();
390   
391   AvailableQueue.releaseState();
392 }
393
394 /// Observe - Update liveness information to account for the current
395 /// instruction, which will not be scheduled.
396 ///
397 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
398   assert(Count < InsertPosIndex && "Instruction index out of expected range!");
399
400   // Any register which was defined within the previous scheduling region
401   // may have been rescheduled and its lifetime may overlap with registers
402   // in ways not reflected in our current liveness state. For each such
403   // register, adjust the liveness state to be conservatively correct.
404   for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
405     if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
406       assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
407       // Mark this register to be non-renamable.
408       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
409       // Move the def index to the end of the previous region, to reflect
410       // that the def could theoretically have been scheduled at the end.
411       DefIndices[Reg] = InsertPosIndex;
412     }
413
414   PrescanInstruction(MI);
415   ScanInstruction(MI, Count);
416 }
417
418 /// FinishBlock - Clean up register live-range state.
419 ///
420 void SchedulePostRATDList::FinishBlock() {
421   RegRefs.clear();
422
423   // Call the superclass.
424   ScheduleDAGInstrs::FinishBlock();
425 }
426
427 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
428 /// critical path.
429 static SDep *CriticalPathStep(SUnit *SU) {
430   SDep *Next = 0;
431   unsigned NextDepth = 0;
432   // Find the predecessor edge with the greatest depth.
433   for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
434        P != PE; ++P) {
435     SUnit *PredSU = P->getSUnit();
436     unsigned PredLatency = P->getLatency();
437     unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
438     // In the case of a latency tie, prefer an anti-dependency edge over
439     // other types of edges.
440     if (NextDepth < PredTotalLatency ||
441         (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
442       NextDepth = PredTotalLatency;
443       Next = &*P;
444     }
445   }
446   return Next;
447 }
448
449 void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
450   // Scan the register operands for this instruction and update
451   // Classes and RegRefs.
452   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
453     MachineOperand &MO = MI->getOperand(i);
454     if (!MO.isReg()) continue;
455     unsigned Reg = MO.getReg();
456     if (Reg == 0) continue;
457     const TargetRegisterClass *NewRC = 0;
458     
459     if (i < MI->getDesc().getNumOperands())
460       NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
461
462     // For now, only allow the register to be changed if its register
463     // class is consistent across all uses.
464     if (!Classes[Reg] && NewRC)
465       Classes[Reg] = NewRC;
466     else if (!NewRC || Classes[Reg] != NewRC)
467       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
468
469     // Now check for aliases.
470     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
471       // If an alias of the reg is used during the live range, give up.
472       // Note that this allows us to skip checking if AntiDepReg
473       // overlaps with any of the aliases, among other things.
474       unsigned AliasReg = *Alias;
475       if (Classes[AliasReg]) {
476         Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
477         Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
478       }
479     }
480
481     // If we're still willing to consider this register, note the reference.
482     if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
483       RegRefs.insert(std::make_pair(Reg, &MO));
484
485     // It's not safe to change register allocation for source operands of
486     // that have special allocation requirements.
487     if (MO.isUse() && MI->getDesc().hasExtraSrcRegAllocReq()) {
488       if (KeepRegs.insert(Reg)) {
489         for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
490              *Subreg; ++Subreg)
491           KeepRegs.insert(*Subreg);
492       }
493     }
494   }
495 }
496
497 void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
498                                            unsigned Count) {
499   // Update liveness.
500   // Proceding upwards, registers that are defed but not used in this
501   // instruction are now dead.
502   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
503     MachineOperand &MO = MI->getOperand(i);
504     if (!MO.isReg()) continue;
505     unsigned Reg = MO.getReg();
506     if (Reg == 0) continue;
507     if (!MO.isDef()) continue;
508     // Ignore two-addr defs.
509     if (MI->isRegTiedToUseOperand(i)) continue;
510
511     DefIndices[Reg] = Count;
512     KillIndices[Reg] = ~0u;
513     assert(((KillIndices[Reg] == ~0u) !=
514             (DefIndices[Reg] == ~0u)) &&
515            "Kill and Def maps aren't consistent for Reg!");
516     KeepRegs.erase(Reg);
517     Classes[Reg] = 0;
518     RegRefs.erase(Reg);
519     // Repeat, for all subregs.
520     for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
521          *Subreg; ++Subreg) {
522       unsigned SubregReg = *Subreg;
523       DefIndices[SubregReg] = Count;
524       KillIndices[SubregReg] = ~0u;
525       KeepRegs.erase(SubregReg);
526       Classes[SubregReg] = 0;
527       RegRefs.erase(SubregReg);
528     }
529     // Conservatively mark super-registers as unusable.
530     for (const unsigned *Super = TRI->getSuperRegisters(Reg);
531          *Super; ++Super) {
532       unsigned SuperReg = *Super;
533       Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
534     }
535   }
536   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
537     MachineOperand &MO = MI->getOperand(i);
538     if (!MO.isReg()) continue;
539     unsigned Reg = MO.getReg();
540     if (Reg == 0) continue;
541     if (!MO.isUse()) continue;
542
543     const TargetRegisterClass *NewRC = 0;
544     if (i < MI->getDesc().getNumOperands())
545       NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
546
547     // For now, only allow the register to be changed if its register
548     // class is consistent across all uses.
549     if (!Classes[Reg] && NewRC)
550       Classes[Reg] = NewRC;
551     else if (!NewRC || Classes[Reg] != NewRC)
552       Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
553
554     RegRefs.insert(std::make_pair(Reg, &MO));
555
556     // It wasn't previously live but now it is, this is a kill.
557     if (KillIndices[Reg] == ~0u) {
558       KillIndices[Reg] = Count;
559       DefIndices[Reg] = ~0u;
560           assert(((KillIndices[Reg] == ~0u) !=
561                   (DefIndices[Reg] == ~0u)) &&
562                "Kill and Def maps aren't consistent for Reg!");
563     }
564     // Repeat, for all aliases.
565     for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
566       unsigned AliasReg = *Alias;
567       if (KillIndices[AliasReg] == ~0u) {
568         KillIndices[AliasReg] = Count;
569         DefIndices[AliasReg] = ~0u;
570       }
571     }
572   }
573 }
574
575 unsigned
576 SchedulePostRATDList::findSuitableFreeRegister(unsigned AntiDepReg,
577                                                unsigned LastNewReg,
578                                                const TargetRegisterClass *RC) {
579   for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
580        RE = RC->allocation_order_end(MF); R != RE; ++R) {
581     unsigned NewReg = *R;
582     // Don't replace a register with itself.
583     if (NewReg == AntiDepReg) continue;
584     // Don't replace a register with one that was recently used to repair
585     // an anti-dependence with this AntiDepReg, because that would
586     // re-introduce that anti-dependence.
587     if (NewReg == LastNewReg) continue;
588     // If NewReg is dead and NewReg's most recent def is not before
589     // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
590     assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
591            "Kill and Def maps aren't consistent for AntiDepReg!");
592     assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
593            "Kill and Def maps aren't consistent for NewReg!");
594     if (KillIndices[NewReg] != ~0u ||
595         Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
596         KillIndices[AntiDepReg] > DefIndices[NewReg])
597       continue;
598     return NewReg;
599   }
600
601   // No registers are free and available!
602   return 0;
603 }
604
605 /// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
606 /// of the ScheduleDAG and break them by renaming registers.
607 ///
608 bool SchedulePostRATDList::BreakAntiDependencies() {
609   // The code below assumes that there is at least one instruction,
610   // so just duck out immediately if the block is empty.
611   if (SUnits.empty()) return false;
612
613   // Find the node at the bottom of the critical path.
614   SUnit *Max = 0;
615   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
616     SUnit *SU = &SUnits[i];
617     if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
618       Max = SU;
619   }
620
621   DEBUG(errs() << "Critical path has total latency "
622         << (Max->getDepth() + Max->Latency) << "\n");
623
624   // Track progress along the critical path through the SUnit graph as we walk
625   // the instructions.
626   SUnit *CriticalPathSU = Max;
627   MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
628
629   // Consider this pattern:
630   //   A = ...
631   //   ... = A
632   //   A = ...
633   //   ... = A
634   //   A = ...
635   //   ... = A
636   //   A = ...
637   //   ... = A
638   // There are three anti-dependencies here, and without special care,
639   // we'd break all of them using the same register:
640   //   A = ...
641   //   ... = A
642   //   B = ...
643   //   ... = B
644   //   B = ...
645   //   ... = B
646   //   B = ...
647   //   ... = B
648   // because at each anti-dependence, B is the first register that
649   // isn't A which is free.  This re-introduces anti-dependencies
650   // at all but one of the original anti-dependencies that we were
651   // trying to break.  To avoid this, keep track of the most recent
652   // register that each register was replaced with, avoid
653   // using it to repair an anti-dependence on the same register.
654   // This lets us produce this:
655   //   A = ...
656   //   ... = A
657   //   B = ...
658   //   ... = B
659   //   C = ...
660   //   ... = C
661   //   B = ...
662   //   ... = B
663   // This still has an anti-dependence on B, but at least it isn't on the
664   // original critical path.
665   //
666   // TODO: If we tracked more than one register here, we could potentially
667   // fix that remaining critical edge too. This is a little more involved,
668   // because unlike the most recent register, less recent registers should
669   // still be considered, though only if no other registers are available.
670   unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
671
672   // Attempt to break anti-dependence edges on the critical path. Walk the
673   // instructions from the bottom up, tracking information about liveness
674   // as we go to help determine which registers are available.
675   bool Changed = false;
676   unsigned Count = InsertPosIndex - 1;
677   for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
678        I != E; --Count) {
679     MachineInstr *MI = --I;
680
681     // Check if this instruction has a dependence on the critical path that
682     // is an anti-dependence that we may be able to break. If it is, set
683     // AntiDepReg to the non-zero register associated with the anti-dependence.
684     //
685     // We limit our attention to the critical path as a heuristic to avoid
686     // breaking anti-dependence edges that aren't going to significantly
687     // impact the overall schedule. There are a limited number of registers
688     // and we want to save them for the important edges.
689     // 
690     // TODO: Instructions with multiple defs could have multiple
691     // anti-dependencies. The current code here only knows how to break one
692     // edge per instruction. Note that we'd have to be able to break all of
693     // the anti-dependencies in an instruction in order to be effective.
694     unsigned AntiDepReg = 0;
695     if (MI == CriticalPathMI) {
696       if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
697         SUnit *NextSU = Edge->getSUnit();
698
699         // Only consider anti-dependence edges.
700         if (Edge->getKind() == SDep::Anti) {
701           AntiDepReg = Edge->getReg();
702           assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
703           if (!AllocatableSet.test(AntiDepReg))
704             // Don't break anti-dependencies on non-allocatable registers.
705             AntiDepReg = 0;
706           else if (KeepRegs.count(AntiDepReg))
707             // Don't break anti-dependencies if an use down below requires
708             // this exact register.
709             AntiDepReg = 0;
710           else {
711             // If the SUnit has other dependencies on the SUnit that it
712             // anti-depends on, don't bother breaking the anti-dependency
713             // since those edges would prevent such units from being
714             // scheduled past each other regardless.
715             //
716             // Also, if there are dependencies on other SUnits with the
717             // same register as the anti-dependency, don't attempt to
718             // break it.
719             for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
720                  PE = CriticalPathSU->Preds.end(); P != PE; ++P)
721               if (P->getSUnit() == NextSU ?
722                     (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
723                     (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
724                 AntiDepReg = 0;
725                 break;
726               }
727           }
728         }
729         CriticalPathSU = NextSU;
730         CriticalPathMI = CriticalPathSU->getInstr();
731       } else {
732         // We've reached the end of the critical path.
733         CriticalPathSU = 0;
734         CriticalPathMI = 0;
735       }
736     }
737
738     PrescanInstruction(MI);
739
740     if (MI->getDesc().hasExtraDefRegAllocReq())
741       // If this instruction's defs have special allocation requirement, don't
742       // break this anti-dependency.
743       AntiDepReg = 0;
744     else if (AntiDepReg) {
745       // If this instruction has a use of AntiDepReg, breaking it
746       // is invalid.
747       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
748         MachineOperand &MO = MI->getOperand(i);
749         if (!MO.isReg()) continue;
750         unsigned Reg = MO.getReg();
751         if (Reg == 0) continue;
752         if (MO.isUse() && AntiDepReg == Reg) {
753           AntiDepReg = 0;
754           break;
755         }
756       }
757     }
758
759     // Determine AntiDepReg's register class, if it is live and is
760     // consistently used within a single class.
761     const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
762     assert((AntiDepReg == 0 || RC != NULL) &&
763            "Register should be live if it's causing an anti-dependence!");
764     if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
765       AntiDepReg = 0;
766
767     // Look for a suitable register to use to break the anti-depenence.
768     //
769     // TODO: Instead of picking the first free register, consider which might
770     // be the best.
771     if (AntiDepReg != 0) {
772       if (unsigned NewReg = findSuitableFreeRegister(AntiDepReg,
773                                                      LastNewReg[AntiDepReg],
774                                                      RC)) {
775         DEBUG(errs() << "Breaking anti-dependence edge on "
776               << TRI->getName(AntiDepReg)
777               << " with " << RegRefs.count(AntiDepReg) << " references"
778               << " using " << TRI->getName(NewReg) << "!\n");
779
780         // Update the references to the old register to refer to the new
781         // register.
782         std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
783                   std::multimap<unsigned, MachineOperand *>::iterator>
784            Range = RegRefs.equal_range(AntiDepReg);
785         for (std::multimap<unsigned, MachineOperand *>::iterator
786              Q = Range.first, QE = Range.second; Q != QE; ++Q)
787           Q->second->setReg(NewReg);
788
789         // We just went back in time and modified history; the
790         // liveness information for the anti-depenence reg is now
791         // inconsistent. Set the state as if it were dead.
792         Classes[NewReg] = Classes[AntiDepReg];
793         DefIndices[NewReg] = DefIndices[AntiDepReg];
794         KillIndices[NewReg] = KillIndices[AntiDepReg];
795         assert(((KillIndices[NewReg] == ~0u) !=
796                 (DefIndices[NewReg] == ~0u)) &&
797              "Kill and Def maps aren't consistent for NewReg!");
798
799         Classes[AntiDepReg] = 0;
800         DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
801         KillIndices[AntiDepReg] = ~0u;
802         assert(((KillIndices[AntiDepReg] == ~0u) !=
803                 (DefIndices[AntiDepReg] == ~0u)) &&
804              "Kill and Def maps aren't consistent for AntiDepReg!");
805
806         RegRefs.erase(AntiDepReg);
807         Changed = true;
808         LastNewReg[AntiDepReg] = NewReg;
809       }
810     }
811
812     ScanInstruction(MI, Count);
813   }
814
815   return Changed;
816 }
817
818 /// StartBlockForKills - Initialize register live-range state for updating kills
819 ///
820 void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
821   // Initialize the indices to indicate that no registers are live.
822   std::fill(KillIndices, array_endof(KillIndices), ~0u);
823
824   // Determine the live-out physregs for this block.
825   if (!BB->empty() && BB->back().getDesc().isReturn()) {
826     // In a return block, examine the function live-out regs.
827     for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
828            E = MRI.liveout_end(); I != E; ++I) {
829       unsigned Reg = *I;
830       KillIndices[Reg] = BB->size();
831       // Repeat, for all subregs.
832       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
833            *Subreg; ++Subreg) {
834         KillIndices[*Subreg] = BB->size();
835       }
836     }
837   }
838   else {
839     // In a non-return block, examine the live-in regs of all successors.
840     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
841            SE = BB->succ_end(); SI != SE; ++SI) {
842       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
843              E = (*SI)->livein_end(); I != E; ++I) {
844         unsigned Reg = *I;
845         KillIndices[Reg] = BB->size();
846         // Repeat, for all subregs.
847         for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
848              *Subreg; ++Subreg) {
849           KillIndices[*Subreg] = BB->size();
850         }
851       }
852     }
853   }
854 }
855
856 bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
857                                           MachineOperand &MO) {
858   // Setting kill flag...
859   if (!MO.isKill()) {
860     MO.setIsKill(true);
861     return false;
862   }
863   
864   // If MO itself is live, clear the kill flag...
865   if (KillIndices[MO.getReg()] != ~0u) {
866     MO.setIsKill(false);
867     return false;
868   }
869
870   // If any subreg of MO is live, then create an imp-def for that
871   // subreg and keep MO marked as killed.
872   bool AllDead = true;
873   const unsigned SuperReg = MO.getReg();
874   for (const unsigned *Subreg = TRI->getSubRegisters(SuperReg);
875        *Subreg; ++Subreg) {
876     if (KillIndices[*Subreg] != ~0u) {
877       MI->addOperand(MachineOperand::CreateReg(*Subreg,
878                                                true  /*IsDef*/,
879                                                true  /*IsImp*/,
880                                                false /*IsKill*/,
881                                                false /*IsDead*/));
882       AllDead = false;
883     }
884   }
885
886   MO.setIsKill(AllDead);
887   return false;
888 }
889
890 /// FixupKills - Fix the register kill flags, they may have been made
891 /// incorrect by instruction reordering.
892 ///
893 void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
894   DEBUG(errs() << "Fixup kills for BB ID#" << MBB->getNumber() << '\n');
895
896   std::set<unsigned> killedRegs;
897   BitVector ReservedRegs = TRI->getReservedRegs(MF);
898
899   StartBlockForKills(MBB);
900   
901   // Examine block from end to start...
902   unsigned Count = MBB->size();
903   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
904        I != E; --Count) {
905     MachineInstr *MI = --I;
906
907     // Update liveness.  Registers that are defed but not used in this
908     // instruction are now dead. Mark register and all subregs as they
909     // are completely defined.
910     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
911       MachineOperand &MO = MI->getOperand(i);
912       if (!MO.isReg()) continue;
913       unsigned Reg = MO.getReg();
914       if (Reg == 0) continue;
915       if (!MO.isDef()) continue;
916       // Ignore two-addr defs.
917       if (MI->isRegTiedToUseOperand(i)) continue;
918       
919       KillIndices[Reg] = ~0u;
920       
921       // Repeat for all subregs.
922       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
923            *Subreg; ++Subreg) {
924         KillIndices[*Subreg] = ~0u;
925       }
926     }
927
928     // Examine all used registers and set/clear kill flag. When a
929     // register is used multiple times we only set the kill flag on
930     // the first use.
931     killedRegs.clear();
932     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
933       MachineOperand &MO = MI->getOperand(i);
934       if (!MO.isReg() || !MO.isUse()) continue;
935       unsigned Reg = MO.getReg();
936       if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
937
938       bool kill = false;
939       if (killedRegs.find(Reg) == killedRegs.end()) {
940         kill = true;
941         // A register is not killed if any subregs are live...
942         for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
943              *Subreg; ++Subreg) {
944           if (KillIndices[*Subreg] != ~0u) {
945             kill = false;
946             break;
947           }
948         }
949
950         // If subreg is not live, then register is killed if it became
951         // live in this instruction
952         if (kill)
953           kill = (KillIndices[Reg] == ~0u);
954       }
955       
956       if (MO.isKill() != kill) {
957         bool removed = ToggleKillFlag(MI, MO);
958         if (removed) {
959           DEBUG(errs() << "Fixed <removed> in ");
960         } else {
961           DEBUG(errs() << "Fixed " << MO << " in ");
962         }
963         DEBUG(MI->dump());
964       }
965       
966       killedRegs.insert(Reg);
967     }
968     
969     // Mark any used register (that is not using undef) and subregs as
970     // now live...
971     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
972       MachineOperand &MO = MI->getOperand(i);
973       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
974       unsigned Reg = MO.getReg();
975       if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
976
977       KillIndices[Reg] = Count;
978       
979       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
980            *Subreg; ++Subreg) {
981         KillIndices[*Subreg] = Count;
982       }
983     }
984   }
985 }
986
987 //===----------------------------------------------------------------------===//
988 //  Top-Down Scheduling
989 //===----------------------------------------------------------------------===//
990
991 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
992 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
993 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
994   SUnit *SuccSU = SuccEdge->getSUnit();
995
996 #ifndef NDEBUG
997   if (SuccSU->NumPredsLeft == 0) {
998     errs() << "*** Scheduling failed! ***\n";
999     SuccSU->dump(this);
1000     errs() << " has been released too many times!\n";
1001     llvm_unreachable(0);
1002   }
1003 #endif
1004   --SuccSU->NumPredsLeft;
1005
1006   // Compute how many cycles it will be before this actually becomes
1007   // available.  This is the max of the start time of all predecessors plus
1008   // their latencies.
1009   SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
1010   
1011   // If all the node's predecessors are scheduled, this node is ready
1012   // to be scheduled. Ignore the special ExitSU node.
1013   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
1014     PendingQueue.push_back(SuccSU);
1015 }
1016
1017 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
1018 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
1019   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1020        I != E; ++I)
1021     ReleaseSucc(SU, &*I);
1022 }
1023
1024 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1025 /// count of its successors. If a successor pending count is zero, add it to
1026 /// the Available queue.
1027 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
1028   DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
1029   DEBUG(SU->dump(this));
1030   
1031   Sequence.push_back(SU);
1032   assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1033   SU->setDepthToAtLeast(CurCycle);
1034
1035   ReleaseSuccessors(SU);
1036   SU->isScheduled = true;
1037   AvailableQueue.ScheduledNode(SU);
1038 }
1039
1040 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1041 /// schedulers.
1042 void SchedulePostRATDList::ListScheduleTopDown() {
1043   unsigned CurCycle = 0;
1044
1045   // Release any successors of the special Entry node.
1046   ReleaseSuccessors(&EntrySU);
1047
1048   // All leaves to Available queue.
1049   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1050     // It is available if it has no predecessors.
1051     if (SUnits[i].Preds.empty()) {
1052       AvailableQueue.push(&SUnits[i]);
1053       SUnits[i].isAvailable = true;
1054     }
1055   }
1056
1057   // In any cycle where we can't schedule any instructions, we must
1058   // stall or emit a noop, depending on the target.
1059   bool CycleHasInsts = false;
1060
1061   // While Available queue is not empty, grab the node with the highest
1062   // priority. If it is not ready put it back.  Schedule the node.
1063   std::vector<SUnit*> NotReady;
1064   Sequence.reserve(SUnits.size());
1065   while (!AvailableQueue.empty() || !PendingQueue.empty()) {
1066     // Check to see if any of the pending instructions are ready to issue.  If
1067     // so, add them to the available queue.
1068     unsigned MinDepth = ~0u;
1069     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
1070       if (PendingQueue[i]->getDepth() <= CurCycle) {
1071         AvailableQueue.push(PendingQueue[i]);
1072         PendingQueue[i]->isAvailable = true;
1073         PendingQueue[i] = PendingQueue.back();
1074         PendingQueue.pop_back();
1075         --i; --e;
1076       } else if (PendingQueue[i]->getDepth() < MinDepth)
1077         MinDepth = PendingQueue[i]->getDepth();
1078     }
1079
1080     DEBUG(errs() << "\n*** Examining Available\n";
1081           LatencyPriorityQueue q = AvailableQueue;
1082           while (!q.empty()) {
1083             SUnit *su = q.pop();
1084             errs() << "Height " << su->getHeight() << ": ";
1085             su->dump(this);
1086           });
1087
1088     SUnit *FoundSUnit = 0;
1089
1090     bool HasNoopHazards = false;
1091     while (!AvailableQueue.empty()) {
1092       SUnit *CurSUnit = AvailableQueue.pop();
1093
1094       ScheduleHazardRecognizer::HazardType HT =
1095         HazardRec->getHazardType(CurSUnit);
1096       if (HT == ScheduleHazardRecognizer::NoHazard) {
1097         FoundSUnit = CurSUnit;
1098         break;
1099       }
1100
1101       // Remember if this is a noop hazard.
1102       HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
1103
1104       NotReady.push_back(CurSUnit);
1105     }
1106
1107     // Add the nodes that aren't ready back onto the available list.
1108     if (!NotReady.empty()) {
1109       AvailableQueue.push_all(NotReady);
1110       NotReady.clear();
1111     }
1112
1113     // If we found a node to schedule, do it now.
1114     if (FoundSUnit) {
1115       ScheduleNodeTopDown(FoundSUnit, CurCycle);
1116       HazardRec->EmitInstruction(FoundSUnit);
1117       CycleHasInsts = true;
1118
1119       // If we are using the target-specific hazards, then don't
1120       // advance the cycle time just because we schedule a node. If
1121       // the target allows it we can schedule multiple nodes in the
1122       // same cycle.
1123       if (!EnablePostRAHazardAvoidance) {
1124         if (FoundSUnit->Latency)  // Don't increment CurCycle for pseudo-ops!
1125           ++CurCycle;
1126       }
1127     } else {
1128       if (CycleHasInsts) {
1129         DEBUG(errs() << "*** Finished cycle " << CurCycle << '\n');
1130         HazardRec->AdvanceCycle();
1131       } else if (!HasNoopHazards) {
1132         // Otherwise, we have a pipeline stall, but no other problem,
1133         // just advance the current cycle and try again.
1134         DEBUG(errs() << "*** Stall in cycle " << CurCycle << '\n');
1135         HazardRec->AdvanceCycle();
1136         ++NumStalls;
1137       } else {
1138         // Otherwise, we have no instructions to issue and we have instructions
1139         // that will fault if we don't do this right.  This is the case for
1140         // processors without pipeline interlocks and other cases.
1141         DEBUG(errs() << "*** Emitting noop in cycle " << CurCycle << '\n');
1142         HazardRec->EmitNoop();
1143         Sequence.push_back(0);   // NULL here means noop
1144         ++NumNoops;
1145       }
1146
1147       ++CurCycle;
1148       CycleHasInsts = false;
1149     }
1150   }
1151
1152 #ifndef NDEBUG
1153   VerifySchedule(/*isBottomUp=*/false);
1154 #endif
1155 }
1156
1157 //===----------------------------------------------------------------------===//
1158 //                         Public Constructor Functions
1159 //===----------------------------------------------------------------------===//
1160
1161 FunctionPass *llvm::createPostRAScheduler() {
1162   return new PostRAScheduler();
1163 }