blob: 1a744be1bf01079cd58c3b21d48cf5fe22fa6db4 [file] [log] [blame]
Dale Johannesen72f15962007-07-13 17:31:29 +00001//===----- SchedulePostRAList.cpp - list scheduler ------------------------===//
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00007//
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"
David Goodwind94a4e52009-08-10 15:55:25 +000022#include "ExactHazardRecognizer.h"
23#include "SimpleHazardRecognizer.h"
Dan Gohman6dc75fe2009-02-06 17:12:10 +000024#include "ScheduleDAGInstrs.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000025#include "llvm/CodeGen/Passes.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000026#include "llvm/CodeGen/LatencyPriorityQueue.h"
27#include "llvm/CodeGen/SchedulerRegistry.h"
Dan Gohman3f237442008-12-16 03:25:46 +000028#include "llvm/CodeGen/MachineDominators.h"
David Goodwinc7951f82009-10-01 19:45:32 +000029#include "llvm/CodeGen/MachineFrameInfo.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000030#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohman3f237442008-12-16 03:25:46 +000031#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman21d90032008-11-25 00:52:40 +000032#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman2836c282009-01-16 01:33:36 +000033#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Dan Gohmanbed353d2009-02-10 23:29:38 +000034#include "llvm/Target/TargetLowering.h"
Dan Gohman79ce2762009-01-15 19:20:50 +000035#include "llvm/Target/TargetMachine.h"
Dan Gohman21d90032008-11-25 00:52:40 +000036#include "llvm/Target/TargetInstrInfo.h"
37#include "llvm/Target/TargetRegisterInfo.h"
David Goodwin0dad89f2009-09-30 00:10:16 +000038#include "llvm/Target/TargetSubtarget.h"
Chris Lattner459525d2008-01-14 19:00:06 +000039#include "llvm/Support/Compiler.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000040#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000041#include "llvm/Support/ErrorHandling.h"
David Goodwin3a5f0d42009-08-11 01:44:26 +000042#include "llvm/Support/raw_ostream.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000043#include "llvm/ADT/Statistic.h"
Dan Gohman21d90032008-11-25 00:52:40 +000044#include <map>
David Goodwin88a589c2009-08-25 17:03:05 +000045#include <set>
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000046using namespace llvm;
47
Dan Gohman2836c282009-01-16 01:33:36 +000048STATISTIC(NumNoops, "Number of noops inserted");
Dan Gohman343f0c02008-11-19 23:18:57 +000049STATISTIC(NumStalls, "Number of pipeline stalls");
50
Dan Gohman21d90032008-11-25 00:52:40 +000051static cl::opt<bool>
52EnableAntiDepBreaking("break-anti-dependencies",
Dan Gohman00dc84a2008-12-16 19:27:52 +000053 cl::desc("Break post-RA scheduling anti-dependencies"),
54 cl::init(true), cl::Hidden);
Dan Gohman21d90032008-11-25 00:52:40 +000055
Dan Gohman2836c282009-01-16 01:33:36 +000056static cl::opt<bool>
57EnablePostRAHazardAvoidance("avoid-hazards",
David Goodwind94a4e52009-08-10 15:55:25 +000058 cl::desc("Enable exact hazard avoidance"),
David Goodwin5e411782009-09-03 22:15:25 +000059 cl::init(true), cl::Hidden);
Dan Gohman2836c282009-01-16 01:33:36 +000060
David Goodwin1f152282009-09-01 18:34:03 +000061// If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
62static cl::opt<int>
63DebugDiv("postra-sched-debugdiv",
64 cl::desc("Debug control MBBs that are scheduled"),
65 cl::init(0), cl::Hidden);
66static cl::opt<int>
67DebugMod("postra-sched-debugmod",
68 cl::desc("Debug control MBBs that are scheduled"),
69 cl::init(0), cl::Hidden);
70
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000071namespace {
Dan Gohman343f0c02008-11-19 23:18:57 +000072 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000073 public:
74 static char ID;
Dan Gohman343f0c02008-11-19 23:18:57 +000075 PostRAScheduler() : MachineFunctionPass(&ID) {}
Dan Gohman21d90032008-11-25 00:52:40 +000076
Dan Gohman3f237442008-12-16 03:25:46 +000077 void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000078 AU.setPreservesCFG();
Dan Gohman3f237442008-12-16 03:25:46 +000079 AU.addRequired<MachineDominatorTree>();
80 AU.addPreserved<MachineDominatorTree>();
81 AU.addRequired<MachineLoopInfo>();
82 AU.addPreserved<MachineLoopInfo>();
83 MachineFunctionPass::getAnalysisUsage(AU);
84 }
85
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000086 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +000087 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000088 }
89
90 bool runOnMachineFunction(MachineFunction &Fn);
91 };
Dan Gohman343f0c02008-11-19 23:18:57 +000092 char PostRAScheduler::ID = 0;
93
94 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +000095 /// 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
Dan Gohman21d90032008-11-25 00:52:40 +0000105 /// Topo - A topological ordering for SUnits.
106 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +0000107
Dan Gohman79ce2762009-01-15 19:20:50 +0000108 /// 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
Dan Gohman2836c282009-01-16 01:33:36 +0000113 /// HazardRec - The hazard recognizer to use.
114 ScheduleHazardRecognizer *HazardRec;
115
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000116 /// 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
Evan Cheng714e8bc2009-10-01 08:26:23 +0000127 /// KillIndices - The index of the most recent kill (proceding bottom-up),
128 /// or ~0u if the register is not live.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000129 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
130
Evan Cheng714e8bc2009-10-01 08:26:23 +0000131 /// DefIndices - The index of the most recent complete def (proceding bottom
132 /// up), or ~0u if the register is live.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000133 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
134
Evan Cheng714e8bc2009-10-01 08:26:23 +0000135 /// KeepRegs - A set of registers which are live and cannot be changed to
136 /// break anti-dependencies.
137 SmallSet<unsigned, 4> KeepRegs;
138
Dan Gohman21d90032008-11-25 00:52:40 +0000139 public:
Dan Gohman79ce2762009-01-15 19:20:50 +0000140 SchedulePostRATDList(MachineFunction &MF,
Dan Gohman3f237442008-12-16 03:25:46 +0000141 const MachineLoopInfo &MLI,
Dan Gohman2836c282009-01-16 01:33:36 +0000142 const MachineDominatorTree &MDT,
143 ScheduleHazardRecognizer *HR)
Dan Gohman79ce2762009-01-15 19:20:50 +0000144 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
Dan Gohman2836c282009-01-16 01:33:36 +0000145 AllocatableSet(TRI->getAllocatableSet(MF)),
146 HazardRec(HR) {}
147
148 ~SchedulePostRATDList() {
149 delete HazardRec;
150 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000151
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000152 /// 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 ///
Dan Gohman343f0c02008-11-19 23:18:57 +0000159 void Schedule();
David Goodwin88a589c2009-08-25 17:03:05 +0000160
161 /// FixupKills - Fix register kill flags that have been made
162 /// invalid due to scheduling
163 ///
164 void FixupKills(MachineBasicBlock *MBB);
Dan Gohman343f0c02008-11-19 23:18:57 +0000165
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000166 /// Observe - Update liveness information to account for the current
167 /// instruction, which will not be scheduled.
168 ///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000169 void Observe(MachineInstr *MI, unsigned Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000170
171 /// FinishBlock - Clean up register live-range state.
172 ///
173 void FinishBlock();
174
Dan Gohman343f0c02008-11-19 23:18:57 +0000175 private:
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000176 void PrescanInstruction(MachineInstr *MI);
177 void ScanInstruction(MachineInstr *MI, unsigned Count);
Dan Gohman54e4c362008-12-09 22:54:47 +0000178 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000179 void ReleaseSuccessors(SUnit *SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000180 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
181 void ListScheduleTopDown();
Dan Gohman21d90032008-11-25 00:52:40 +0000182 bool BreakAntiDependencies();
Dan Gohman26255ad2009-08-12 01:33:27 +0000183 unsigned findSuitableFreeRegister(unsigned AntiDepReg,
184 unsigned LastNewReg,
185 const TargetRegisterClass *);
David Goodwin5e411782009-09-03 22:15:25 +0000186 void StartBlockForKills(MachineBasicBlock *BB);
David Goodwin8f909342009-09-23 16:35:25 +0000187
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);
Dan Gohman343f0c02008-11-19 23:18:57 +0000192 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000193}
194
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000195/// isSchedulingBoundary - Test if the given instruction should be
196/// considered a scheduling boundary. This primarily includes labels
197/// and terminators.
198///
199static 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
Dan Gohmanbed353d2009-02-10 23:29:38 +0000205 // 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
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000214 return false;
215}
216
Dan Gohman343f0c02008-11-19 23:18:57 +0000217bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
David Goodwin0dad89f2009-09-30 00:10:16 +0000218 // 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
David Goodwin3a5f0d42009-08-11 01:44:26 +0000223 DEBUG(errs() << "PostRAScheduler\n");
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000224
Dan Gohman3f237442008-12-16 03:25:46 +0000225 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
226 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
David Goodwind94a4e52009-08-10 15:55:25 +0000227 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
Dan Gohman2836c282009-01-16 01:33:36 +0000228 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
David Goodwind94a4e52009-08-10 15:55:25 +0000229 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
230 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
Dan Gohman3f237442008-12-16 03:25:46 +0000231
Dan Gohman2836c282009-01-16 01:33:36 +0000232 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
Dan Gohman79ce2762009-01-15 19:20:50 +0000233
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000234 // Loop over all of the basic blocks
235 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000236 MBB != MBBe; ++MBB) {
David Goodwin1f152282009-09-01 18:34:03 +0000237#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
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000248 // Initialize register live-range state for scheduling in this block.
249 Scheduler.StartBlock(MBB);
250
Dan Gohmanf7119392009-01-16 22:10:20 +0000251 // Schedule each sequence of instructions not interrupted by a label
252 // or anything else that effectively needs to shut down scheduling.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000253 MachineBasicBlock::iterator Current = MBB->end();
Dan Gohman47ac0f02009-02-11 04:27:20 +0000254 unsigned Count = MBB->size(), CurrentCount = Count;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000255 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
256 MachineInstr *MI = prior(I);
257 if (isSchedulingBoundary(MI, Fn)) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000258 Scheduler.Run(MBB, I, Current, CurrentCount);
Evan Chengfb2e7522009-09-18 21:02:19 +0000259 Scheduler.EmitSchedule(0);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000260 Current = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000261 CurrentCount = Count - 1;
Dan Gohman1274ced2009-03-10 18:10:43 +0000262 Scheduler.Observe(MI, CurrentCount);
Dan Gohmanf7119392009-01-16 22:10:20 +0000263 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000264 I = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000265 --Count;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000266 }
Dan Gohman47ac0f02009-02-11 04:27:20 +0000267 assert(Count == 0 && "Instruction count mismatch!");
Duncan Sands9e8bd0b2009-03-11 09:04:34 +0000268 assert((MBB->begin() == Current || CurrentCount != 0) &&
Dan Gohman1274ced2009-03-10 18:10:43 +0000269 "Instruction count mismatch!");
270 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
Evan Chengfb2e7522009-09-18 21:02:19 +0000271 Scheduler.EmitSchedule(0);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000272
273 // Clean up register live-range state.
274 Scheduler.FinishBlock();
David Goodwin88a589c2009-08-25 17:03:05 +0000275
David Goodwin5e411782009-09-03 22:15:25 +0000276 // Update register kills
David Goodwin88a589c2009-08-25 17:03:05 +0000277 Scheduler.FixupKills(MBB);
Dan Gohman343f0c02008-11-19 23:18:57 +0000278 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000279
280 return true;
281}
282
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000283/// StartBlock - Initialize register live-range state for scheduling in
284/// this block.
Dan Gohman21d90032008-11-25 00:52:40 +0000285///
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000286void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
287 // Call the superclass.
288 ScheduleDAGInstrs::StartBlock(BB);
Dan Gohman21d90032008-11-25 00:52:40 +0000289
David Goodwind94a4e52009-08-10 15:55:25 +0000290 // Reset the hazard recognizer.
291 HazardRec->Reset();
292
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000293 // Clear out the register class data.
294 std::fill(Classes, array_endof(Classes),
295 static_cast<const TargetRegisterClass *>(0));
Dan Gohman21d90032008-11-25 00:52:40 +0000296
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000297 // Initialize the indices to indicate that no registers are live.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000298 std::fill(KillIndices, array_endof(KillIndices), ~0u);
Dan Gohman21d90032008-11-25 00:52:40 +0000299 std::fill(DefIndices, array_endof(DefIndices), BB->size());
300
Evan Cheng714e8bc2009-10-01 08:26:23 +0000301 // Clear "do not change" set.
302 KeepRegs.clear();
303
Dan Gohman21d90032008-11-25 00:52:40 +0000304 // Determine the live-out physregs for this block.
David Goodwinc7951f82009-10-01 19:45:32 +0000305 if (!BB->empty() && BB->back().getDesc().isReturn()) {
Dan Gohman21d90032008-11-25 00:52:40 +0000306 // 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();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000312 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000313 // 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();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000318 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000319 }
320 }
David Goodwinc7951f82009-10-01 19:45:32 +0000321 } else {
Dan Gohman21d90032008-11-25 00:52:40 +0000322 // In a non-return block, examine the live-in regs of all successors.
323 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
Dan Gohman47ac0f02009-02-11 04:27:20 +0000324 SE = BB->succ_end(); SI != SE; ++SI)
Dan Gohman21d90032008-11-25 00:52:40 +0000325 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();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000330 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000331 // 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();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000336 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000337 }
338 }
339
David Goodwinc7951f82009-10-01 19:45:32 +0000340 // 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 }
Dan Gohman21d90032008-11-25 00:52:40 +0000357 }
358 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000359}
360
361/// Schedule - Schedule the instruction range using list scheduling.
362///
363void SchedulePostRATDList::Schedule() {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000364 DEBUG(errs() << "********** List Scheduling **********\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000365
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
David Goodwind94a4e52009-08-10 15:55:25 +0000384 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
385 SUnits[su].dumpAll(this));
386
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000387 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///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000397void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000398 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
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000414 PrescanInstruction(MI);
Dan Gohman47ac0f02009-02-11 04:27:20 +0000415 ScanInstruction(MI, Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000416}
417
418/// FinishBlock - Clean up register live-range state.
419///
420void SchedulePostRATDList::FinishBlock() {
421 RegRefs.clear();
422
423 // Call the superclass.
424 ScheduleDAGInstrs::FinishBlock();
425}
426
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000427/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
428/// critical path.
429static 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
449void 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;
Chris Lattner2a386882009-07-29 21:36:49 +0000457 const TargetRegisterClass *NewRC = 0;
458
459 if (i < MI->getDesc().getNumOperands())
460 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000461
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));
David Goodwinc7951f82009-10-01 19:45:32 +0000484
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 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000494 }
495}
496
497void 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.
Bob Wilsond9df5012009-04-09 17:16:43 +0000509 if (MI->isRegTiedToUseOperand(i)) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000510
511 DefIndices[Reg] = Count;
512 KillIndices[Reg] = ~0u;
Evan Cheng714e8bc2009-10-01 08:26:23 +0000513 assert(((KillIndices[Reg] == ~0u) !=
514 (DefIndices[Reg] == ~0u)) &&
515 "Kill and Def maps aren't consistent for Reg!");
516 KeepRegs.erase(Reg);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000517 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;
Evan Cheng714e8bc2009-10-01 08:26:23 +0000525 KeepRegs.erase(SubregReg);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000526 Classes[SubregReg] = 0;
527 RegRefs.erase(SubregReg);
528 }
David Goodwin7886cd82009-08-29 00:11:13 +0000529 // Conservatively mark super-registers as unusable.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000530 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
Chris Lattner2a386882009-07-29 21:36:49 +0000543 const TargetRegisterClass *NewRC = 0;
544 if (i < MI->getDesc().getNumOperands())
545 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000546
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;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000560 assert(((KillIndices[Reg] == ~0u) !=
561 (DefIndices[Reg] == ~0u)) &&
562 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000563 }
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
Dan Gohman26255ad2009-08-12 01:33:27 +0000575unsigned
576SchedulePostRATDList::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!");
Dan Gohmanda277572009-08-12 01:44:20 +0000594 if (KillIndices[NewReg] != ~0u ||
595 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
596 KillIndices[AntiDepReg] > DefIndices[NewReg])
Dan Gohman26255ad2009-08-12 01:33:27 +0000597 continue;
598 return NewReg;
599 }
600
601 // No registers are free and available!
602 return 0;
603}
604
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000605/// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
606/// of the ScheduleDAG and break them by renaming registers.
607///
608bool 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
David Goodwin3a5f0d42009-08-11 01:44:26 +0000621 DEBUG(errs() << "Critical path has total latency "
622 << (Max->getDepth() + Max->Latency) << "\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000623
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();
Dan Gohman21d90032008-11-25 00:52:40 +0000628
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
David Goodwinc93d8372009-08-11 17:35:23 +0000652 // register that each register was replaced with, avoid
Dan Gohman21d90032008-11-25 00:52:40 +0000653 // 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
Dan Gohman21d90032008-11-25 00:52:40 +0000672 // 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;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000676 unsigned Count = InsertPosIndex - 1;
677 for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000678 I != E; --Count) {
679 MachineInstr *MI = --I;
Dan Gohman21d90032008-11-25 00:52:40 +0000680
Dan Gohman00dc84a2008-12-16 19:27:52 +0000681 // 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?");
Dan Gohman49bb50e2009-01-16 21:57:43 +0000703 if (!AllocatableSet.test(AntiDepReg))
Evan Cheng714e8bc2009-10-01 08:26:23 +0000704 // 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.
Dan Gohman49bb50e2009-01-16 21:57:43 +0000709 AntiDepReg = 0;
710 else {
Dan Gohman00dc84a2008-12-16 19:27:52 +0000711 // 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 }
Dan Gohman21d90032008-11-25 00:52:40 +0000737
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000738 PrescanInstruction(MI);
739
Evan Cheng714e8bc2009-10-01 08:26:23 +0000740 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 }
Dan Gohman21d90032008-11-25 00:52:40 +0000756 }
Dan Gohman21d90032008-11-25 00:52:40 +0000757 }
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;
Nick Lewyckya89d1022008-11-27 17:29:52 +0000762 assert((AntiDepReg == 0 || RC != NULL) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000763 "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) {
Dan Gohman26255ad2009-08-12 01:33:27 +0000772 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");
Dan Gohman21d90032008-11-25 00:52:40 +0000779
Dan Gohman26255ad2009-08-12 01:33:27 +0000780 // 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);
Dan Gohman21d90032008-11-25 00:52:40 +0000788
Dan Gohman26255ad2009-08-12 01:33:27 +0000789 // 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!");
Dan Gohman21d90032008-11-25 00:52:40 +0000798
Dan Gohman26255ad2009-08-12 01:33:27 +0000799 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!");
Dan Gohman21d90032008-11-25 00:52:40 +0000805
Dan Gohman26255ad2009-08-12 01:33:27 +0000806 RegRefs.erase(AntiDepReg);
807 Changed = true;
808 LastNewReg[AntiDepReg] = NewReg;
Dan Gohman21d90032008-11-25 00:52:40 +0000809 }
810 }
811
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000812 ScanInstruction(MI, Count);
Dan Gohman21d90032008-11-25 00:52:40 +0000813 }
Dan Gohman21d90032008-11-25 00:52:40 +0000814
815 return Changed;
816}
817
David Goodwin5e411782009-09-03 22:15:25 +0000818/// StartBlockForKills - Initialize register live-range state for updating kills
819///
820void 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
David Goodwin8f909342009-09-23 16:35:25 +0000856bool 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
David Goodwin88a589c2009-08-25 17:03:05 +0000890/// FixupKills - Fix the register kill flags, they may have been made
891/// incorrect by instruction reordering.
892///
893void 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);
David Goodwin5e411782009-09-03 22:15:25 +0000898
899 StartBlockForKills(MBB);
David Goodwin7886cd82009-08-29 00:11:13 +0000900
901 // Examine block from end to start...
David Goodwin88a589c2009-08-25 17:03:05 +0000902 unsigned Count = MBB->size();
903 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
904 I != E; --Count) {
905 MachineInstr *MI = --I;
906
David Goodwin7886cd82009-08-29 00:11:13 +0000907 // 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
David Goodwin7886cd82009-08-29 00:11:13 +0000919 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 }
David Goodwin88a589c2009-08-25 17:03:05 +0000927
David Goodwin8f909342009-09-23 16:35:25 +0000928 // 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.
David Goodwin88a589c2009-08-25 17:03:05 +0000931 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
David Goodwin7886cd82009-08-29 00:11:13 +0000938 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
David Goodwin88a589c2009-08-25 17:03:05 +0000956 if (MO.isKill() != kill) {
David Goodwin8f909342009-09-23 16:35:25 +0000957 bool removed = ToggleKillFlag(MI, MO);
958 if (removed) {
959 DEBUG(errs() << "Fixed <removed> in ");
960 } else {
961 DEBUG(errs() << "Fixed " << MO << " in ");
962 }
David Goodwin88a589c2009-08-25 17:03:05 +0000963 DEBUG(MI->dump());
964 }
David Goodwin7886cd82009-08-29 00:11:13 +0000965
David Goodwin88a589c2009-08-25 17:03:05 +0000966 killedRegs.insert(Reg);
967 }
David Goodwin7886cd82009-08-29 00:11:13 +0000968
David Goodwina3251db2009-08-31 20:47:02 +0000969 // Mark any used register (that is not using undef) and subregs as
970 // now live...
David Goodwin7886cd82009-08-29 00:11:13 +0000971 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
972 MachineOperand &MO = MI->getOperand(i);
David Goodwina3251db2009-08-31 20:47:02 +0000973 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
David Goodwin7886cd82009-08-29 00:11:13 +0000974 unsigned Reg = MO.getReg();
975 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
976
David Goodwin7886cd82009-08-29 00:11:13 +0000977 KillIndices[Reg] = Count;
978
979 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
980 *Subreg; ++Subreg) {
981 KillIndices[*Subreg] = Count;
982 }
983 }
David Goodwin88a589c2009-08-25 17:03:05 +0000984 }
985}
986
Dan Gohman343f0c02008-11-19 23:18:57 +0000987//===----------------------------------------------------------------------===//
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.
Dan Gohman54e4c362008-12-09 22:54:47 +0000993void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
994 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Klecknerc277ab02009-09-30 20:15:38 +0000995
Dan Gohman343f0c02008-11-19 23:18:57 +0000996#ifndef NDEBUG
Reid Klecknerc277ab02009-09-30 20:15:38 +0000997 if (SuccSU->NumPredsLeft == 0) {
Chris Lattner103289e2009-08-23 07:19:13 +0000998 errs() << "*** Scheduling failed! ***\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000999 SuccSU->dump(this);
Chris Lattner103289e2009-08-23 07:19:13 +00001000 errs() << " has been released too many times!\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001001 llvm_unreachable(0);
Dan Gohman343f0c02008-11-19 23:18:57 +00001002 }
1003#endif
Reid Klecknerc277ab02009-09-30 20:15:38 +00001004 --SuccSU->NumPredsLeft;
1005
Dan Gohman343f0c02008-11-19 23:18:57 +00001006 // 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.
Dan Gohman3f237442008-12-16 03:25:46 +00001009 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
Dan Gohman343f0c02008-11-19 23:18:57 +00001010
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001011 // 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)
Dan Gohman343f0c02008-11-19 23:18:57 +00001014 PendingQueue.push_back(SuccSU);
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001015}
1016
1017/// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
1018void 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);
Dan Gohman343f0c02008-11-19 23:18:57 +00001022}
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.
1027void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
David Goodwin3a5f0d42009-08-11 01:44:26 +00001028 DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman343f0c02008-11-19 23:18:57 +00001029 DEBUG(SU->dump(this));
1030
1031 Sequence.push_back(SU);
Dan Gohman3f237442008-12-16 03:25:46 +00001032 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1033 SU->setDepthToAtLeast(CurCycle);
Dan Gohman343f0c02008-11-19 23:18:57 +00001034
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001035 ReleaseSuccessors(SU);
Dan Gohman343f0c02008-11-19 23:18:57 +00001036 SU->isScheduled = true;
1037 AvailableQueue.ScheduledNode(SU);
1038}
1039
1040/// ListScheduleTopDown - The main loop of list scheduling for top-down
1041/// schedulers.
1042void SchedulePostRATDList::ListScheduleTopDown() {
1043 unsigned CurCycle = 0;
1044
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001045 // Release any successors of the special Entry node.
1046 ReleaseSuccessors(&EntrySU);
1047
Dan Gohman343f0c02008-11-19 23:18:57 +00001048 // 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 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001056
David Goodwin2ffb0ce2009-08-12 21:47:46 +00001057 // In any cycle where we can't schedule any instructions, we must
1058 // stall or emit a noop, depending on the target.
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001059 bool CycleHasInsts = false;
David Goodwin2ffb0ce2009-08-12 21:47:46 +00001060
Dan Gohman343f0c02008-11-19 23:18:57 +00001061 // 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.
Dan Gohman2836c282009-01-16 01:33:36 +00001063 std::vector<SUnit*> NotReady;
Dan Gohman343f0c02008-11-19 23:18:57 +00001064 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.
Dan Gohman3f237442008-12-16 03:25:46 +00001068 unsigned MinDepth = ~0u;
Dan Gohman343f0c02008-11-19 23:18:57 +00001069 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman3f237442008-12-16 03:25:46 +00001070 if (PendingQueue[i]->getDepth() <= CurCycle) {
Dan Gohman343f0c02008-11-19 23:18:57 +00001071 AvailableQueue.push(PendingQueue[i]);
1072 PendingQueue[i]->isAvailable = true;
1073 PendingQueue[i] = PendingQueue.back();
1074 PendingQueue.pop_back();
1075 --i; --e;
Dan Gohman3f237442008-12-16 03:25:46 +00001076 } else if (PendingQueue[i]->getDepth() < MinDepth)
1077 MinDepth = PendingQueue[i]->getDepth();
Dan Gohman343f0c02008-11-19 23:18:57 +00001078 }
David Goodwinc93d8372009-08-11 17:35:23 +00001079
David Goodwin7cd01182009-08-11 17:56:42 +00001080 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 });
David Goodwinc93d8372009-08-11 17:35:23 +00001087
Dan Gohman2836c282009-01-16 01:33:36 +00001088 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
Dan Gohman343f0c02008-11-19 23:18:57 +00001113 // If we found a node to schedule, do it now.
1114 if (FoundSUnit) {
1115 ScheduleNodeTopDown(FoundSUnit, CurCycle);
Dan Gohman2836c282009-01-16 01:33:36 +00001116 HazardRec->EmitInstruction(FoundSUnit);
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001117 CycleHasInsts = true;
Dan Gohman343f0c02008-11-19 23:18:57 +00001118
David Goodwind94a4e52009-08-10 15:55:25 +00001119 // 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 }
Dan Gohman2836c282009-01-16 01:33:36 +00001127 } else {
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001128 if (CycleHasInsts) {
David Goodwin2ffb0ce2009-08-12 21:47:46 +00001129 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
Dan Gohman2836c282009-01-16 01:33:36 +00001147 ++CurCycle;
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001148 CycleHasInsts = false;
Dan Gohman343f0c02008-11-19 23:18:57 +00001149 }
1150 }
1151
1152#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +00001153 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +00001154#endif
1155}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00001156
1157//===----------------------------------------------------------------------===//
1158// Public Constructor Functions
1159//===----------------------------------------------------------------------===//
1160
1161FunctionPass *llvm::createPostRAScheduler() {
Dan Gohman343f0c02008-11-19 23:18:57 +00001162 return new PostRAScheduler();
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00001163}