blob: 902f50517c5f70fdc92ed416792d8394be931dda [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
David Goodwin471850a2009-10-01 21:46:35 +000051// Post-RA scheduling is enabled with
52// TargetSubtarget.enablePostRAScheduler(). This flag can be used to
53// override the target.
54static cl::opt<bool>
55EnablePostRAScheduler("post-RA-scheduler",
56 cl::desc("Enable scheduling after register allocation"),
David Goodwin9843a932009-10-01 22:19:57 +000057 cl::init(false), cl::Hidden);
Dan Gohman21d90032008-11-25 00:52:40 +000058static cl::opt<bool>
59EnableAntiDepBreaking("break-anti-dependencies",
Dan Gohman00dc84a2008-12-16 19:27:52 +000060 cl::desc("Break post-RA scheduling anti-dependencies"),
61 cl::init(true), cl::Hidden);
Dan Gohman2836c282009-01-16 01:33:36 +000062static cl::opt<bool>
63EnablePostRAHazardAvoidance("avoid-hazards",
David Goodwind94a4e52009-08-10 15:55:25 +000064 cl::desc("Enable exact hazard avoidance"),
David Goodwin5e411782009-09-03 22:15:25 +000065 cl::init(true), cl::Hidden);
Dan Gohman2836c282009-01-16 01:33:36 +000066
David Goodwin1f152282009-09-01 18:34:03 +000067// If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
68static cl::opt<int>
69DebugDiv("postra-sched-debugdiv",
70 cl::desc("Debug control MBBs that are scheduled"),
71 cl::init(0), cl::Hidden);
72static cl::opt<int>
73DebugMod("postra-sched-debugmod",
74 cl::desc("Debug control MBBs that are scheduled"),
75 cl::init(0), cl::Hidden);
76
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000077namespace {
Dan Gohman343f0c02008-11-19 23:18:57 +000078 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000079 public:
80 static char ID;
Dan Gohman343f0c02008-11-19 23:18:57 +000081 PostRAScheduler() : MachineFunctionPass(&ID) {}
Dan Gohman21d90032008-11-25 00:52:40 +000082
Dan Gohman3f237442008-12-16 03:25:46 +000083 void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000084 AU.setPreservesCFG();
Dan Gohman3f237442008-12-16 03:25:46 +000085 AU.addRequired<MachineDominatorTree>();
86 AU.addPreserved<MachineDominatorTree>();
87 AU.addRequired<MachineLoopInfo>();
88 AU.addPreserved<MachineLoopInfo>();
89 MachineFunctionPass::getAnalysisUsage(AU);
90 }
91
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000092 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +000093 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000094 }
95
96 bool runOnMachineFunction(MachineFunction &Fn);
97 };
Dan Gohman343f0c02008-11-19 23:18:57 +000098 char PostRAScheduler::ID = 0;
99
100 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +0000101 /// AvailableQueue - The priority queue to use for the available SUnits.
102 ///
103 LatencyPriorityQueue AvailableQueue;
104
105 /// PendingQueue - This contains all of the instructions whose operands have
106 /// been issued, but their results are not ready yet (due to the latency of
107 /// the operation). Once the operands becomes available, the instruction is
108 /// added to the AvailableQueue.
109 std::vector<SUnit*> PendingQueue;
110
Dan Gohman21d90032008-11-25 00:52:40 +0000111 /// Topo - A topological ordering for SUnits.
112 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +0000113
Dan Gohman79ce2762009-01-15 19:20:50 +0000114 /// AllocatableSet - The set of allocatable registers.
115 /// We'll be ignoring anti-dependencies on non-allocatable registers,
116 /// because they may not be safe to break.
117 const BitVector AllocatableSet;
118
Dan Gohman2836c282009-01-16 01:33:36 +0000119 /// HazardRec - The hazard recognizer to use.
120 ScheduleHazardRecognizer *HazardRec;
121
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000122 /// Classes - For live regs that are only used in one register class in a
123 /// live range, the register class. If the register is not live, the
124 /// corresponding value is null. If the register is live but used in
125 /// multiple register classes, the corresponding value is -1 casted to a
126 /// pointer.
127 const TargetRegisterClass *
128 Classes[TargetRegisterInfo::FirstVirtualRegister];
129
130 /// RegRegs - Map registers to all their references within a live range.
131 std::multimap<unsigned, MachineOperand *> RegRefs;
132
Evan Cheng714e8bc2009-10-01 08:26:23 +0000133 /// KillIndices - The index of the most recent kill (proceding bottom-up),
134 /// or ~0u if the register is not live.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000135 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
136
Evan Cheng714e8bc2009-10-01 08:26:23 +0000137 /// DefIndices - The index of the most recent complete def (proceding bottom
138 /// up), or ~0u if the register is live.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000139 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
140
Evan Cheng714e8bc2009-10-01 08:26:23 +0000141 /// KeepRegs - A set of registers which are live and cannot be changed to
142 /// break anti-dependencies.
143 SmallSet<unsigned, 4> KeepRegs;
144
Dan Gohman21d90032008-11-25 00:52:40 +0000145 public:
Dan Gohman79ce2762009-01-15 19:20:50 +0000146 SchedulePostRATDList(MachineFunction &MF,
Dan Gohman3f237442008-12-16 03:25:46 +0000147 const MachineLoopInfo &MLI,
Dan Gohman2836c282009-01-16 01:33:36 +0000148 const MachineDominatorTree &MDT,
149 ScheduleHazardRecognizer *HR)
Dan Gohman79ce2762009-01-15 19:20:50 +0000150 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
Dan Gohman2836c282009-01-16 01:33:36 +0000151 AllocatableSet(TRI->getAllocatableSet(MF)),
152 HazardRec(HR) {}
153
154 ~SchedulePostRATDList() {
155 delete HazardRec;
156 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000157
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000158 /// StartBlock - Initialize register live-range state for scheduling in
159 /// this block.
160 ///
161 void StartBlock(MachineBasicBlock *BB);
162
163 /// Schedule - Schedule the instruction range using list scheduling.
164 ///
Dan Gohman343f0c02008-11-19 23:18:57 +0000165 void Schedule();
David Goodwin88a589c2009-08-25 17:03:05 +0000166
167 /// FixupKills - Fix register kill flags that have been made
168 /// invalid due to scheduling
169 ///
170 void FixupKills(MachineBasicBlock *MBB);
Dan Gohman343f0c02008-11-19 23:18:57 +0000171
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000172 /// Observe - Update liveness information to account for the current
173 /// instruction, which will not be scheduled.
174 ///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000175 void Observe(MachineInstr *MI, unsigned Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000176
177 /// FinishBlock - Clean up register live-range state.
178 ///
179 void FinishBlock();
180
Dan Gohman343f0c02008-11-19 23:18:57 +0000181 private:
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000182 void PrescanInstruction(MachineInstr *MI);
183 void ScanInstruction(MachineInstr *MI, unsigned Count);
Dan Gohman54e4c362008-12-09 22:54:47 +0000184 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000185 void ReleaseSuccessors(SUnit *SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000186 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
187 void ListScheduleTopDown();
Dan Gohman21d90032008-11-25 00:52:40 +0000188 bool BreakAntiDependencies();
Dan Gohman26255ad2009-08-12 01:33:27 +0000189 unsigned findSuitableFreeRegister(unsigned AntiDepReg,
190 unsigned LastNewReg,
191 const TargetRegisterClass *);
David Goodwin5e411782009-09-03 22:15:25 +0000192 void StartBlockForKills(MachineBasicBlock *BB);
David Goodwin8f909342009-09-23 16:35:25 +0000193
194 // ToggleKillFlag - Toggle a register operand kill flag. Other
195 // adjustments may be made to the instruction if necessary. Return
196 // true if the operand has been deleted, false if not.
197 bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
Dan Gohman343f0c02008-11-19 23:18:57 +0000198 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000199}
200
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000201/// isSchedulingBoundary - Test if the given instruction should be
202/// considered a scheduling boundary. This primarily includes labels
203/// and terminators.
204///
205static bool isSchedulingBoundary(const MachineInstr *MI,
206 const MachineFunction &MF) {
207 // Terminators and labels can't be scheduled around.
208 if (MI->getDesc().isTerminator() || MI->isLabel())
209 return true;
210
Dan Gohmanbed353d2009-02-10 23:29:38 +0000211 // Don't attempt to schedule around any instruction that modifies
212 // a stack-oriented pointer, as it's unlikely to be profitable. This
213 // saves compile time, because it doesn't require every single
214 // stack slot reference to depend on the instruction that does the
215 // modification.
216 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
217 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
218 return true;
219
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000220 return false;
221}
222
Dan Gohman343f0c02008-11-19 23:18:57 +0000223bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
David Goodwin471850a2009-10-01 21:46:35 +0000224 // Check for explicit enable/disable of post-ra scheduling.
225 if (EnablePostRAScheduler.getPosition() > 0) {
226 if (!EnablePostRAScheduler)
227 return true;
228 } else {
229 // Check that post-RA scheduling is enabled for this function
230 const TargetSubtarget &ST = Fn.getTarget().getSubtarget<TargetSubtarget>();
231 if (!ST.enablePostRAScheduler())
232 return true;
233 }
David Goodwin0dad89f2009-09-30 00:10:16 +0000234
David Goodwin3a5f0d42009-08-11 01:44:26 +0000235 DEBUG(errs() << "PostRAScheduler\n");
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000236
Dan Gohman3f237442008-12-16 03:25:46 +0000237 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
238 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
David Goodwind94a4e52009-08-10 15:55:25 +0000239 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
Dan Gohman2836c282009-01-16 01:33:36 +0000240 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
David Goodwind94a4e52009-08-10 15:55:25 +0000241 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
242 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
Dan Gohman3f237442008-12-16 03:25:46 +0000243
Dan Gohman2836c282009-01-16 01:33:36 +0000244 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
Dan Gohman79ce2762009-01-15 19:20:50 +0000245
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000246 // Loop over all of the basic blocks
247 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000248 MBB != MBBe; ++MBB) {
David Goodwin1f152282009-09-01 18:34:03 +0000249#ifndef NDEBUG
250 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
251 if (DebugDiv > 0) {
252 static int bbcnt = 0;
253 if (bbcnt++ % DebugDiv != DebugMod)
254 continue;
255 errs() << "*** DEBUG scheduling " << Fn.getFunction()->getNameStr() <<
256 ":MBB ID#" << MBB->getNumber() << " ***\n";
257 }
258#endif
259
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000260 // Initialize register live-range state for scheduling in this block.
261 Scheduler.StartBlock(MBB);
262
Dan Gohmanf7119392009-01-16 22:10:20 +0000263 // Schedule each sequence of instructions not interrupted by a label
264 // or anything else that effectively needs to shut down scheduling.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000265 MachineBasicBlock::iterator Current = MBB->end();
Dan Gohman47ac0f02009-02-11 04:27:20 +0000266 unsigned Count = MBB->size(), CurrentCount = Count;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000267 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
268 MachineInstr *MI = prior(I);
269 if (isSchedulingBoundary(MI, Fn)) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000270 Scheduler.Run(MBB, I, Current, CurrentCount);
Evan Chengfb2e7522009-09-18 21:02:19 +0000271 Scheduler.EmitSchedule(0);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000272 Current = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000273 CurrentCount = Count - 1;
Dan Gohman1274ced2009-03-10 18:10:43 +0000274 Scheduler.Observe(MI, CurrentCount);
Dan Gohmanf7119392009-01-16 22:10:20 +0000275 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000276 I = MI;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000277 --Count;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000278 }
Dan Gohman47ac0f02009-02-11 04:27:20 +0000279 assert(Count == 0 && "Instruction count mismatch!");
Duncan Sands9e8bd0b2009-03-11 09:04:34 +0000280 assert((MBB->begin() == Current || CurrentCount != 0) &&
Dan Gohman1274ced2009-03-10 18:10:43 +0000281 "Instruction count mismatch!");
282 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
Evan Chengfb2e7522009-09-18 21:02:19 +0000283 Scheduler.EmitSchedule(0);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000284
285 // Clean up register live-range state.
286 Scheduler.FinishBlock();
David Goodwin88a589c2009-08-25 17:03:05 +0000287
David Goodwin5e411782009-09-03 22:15:25 +0000288 // Update register kills
David Goodwin88a589c2009-08-25 17:03:05 +0000289 Scheduler.FixupKills(MBB);
Dan Gohman343f0c02008-11-19 23:18:57 +0000290 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000291
292 return true;
293}
294
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000295/// StartBlock - Initialize register live-range state for scheduling in
296/// this block.
Dan Gohman21d90032008-11-25 00:52:40 +0000297///
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000298void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
299 // Call the superclass.
300 ScheduleDAGInstrs::StartBlock(BB);
Dan Gohman21d90032008-11-25 00:52:40 +0000301
David Goodwind94a4e52009-08-10 15:55:25 +0000302 // Reset the hazard recognizer.
303 HazardRec->Reset();
304
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000305 // Clear out the register class data.
306 std::fill(Classes, array_endof(Classes),
307 static_cast<const TargetRegisterClass *>(0));
Dan Gohman21d90032008-11-25 00:52:40 +0000308
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000309 // Initialize the indices to indicate that no registers are live.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000310 std::fill(KillIndices, array_endof(KillIndices), ~0u);
Dan Gohman21d90032008-11-25 00:52:40 +0000311 std::fill(DefIndices, array_endof(DefIndices), BB->size());
312
Evan Cheng714e8bc2009-10-01 08:26:23 +0000313 // Clear "do not change" set.
314 KeepRegs.clear();
315
David Goodwin63bcbb72009-10-01 23:28:47 +0000316 bool IsReturnBlock = (!BB->empty() && BB->back().getDesc().isReturn());
317
Dan Gohman21d90032008-11-25 00:52:40 +0000318 // Determine the live-out physregs for this block.
David Goodwin63bcbb72009-10-01 23:28:47 +0000319 if (IsReturnBlock) {
Dan Gohman21d90032008-11-25 00:52:40 +0000320 // In a return block, examine the function live-out regs.
321 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
322 E = MRI.liveout_end(); I != E; ++I) {
323 unsigned Reg = *I;
324 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
325 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000326 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000327 // Repeat, for all aliases.
328 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
329 unsigned AliasReg = *Alias;
330 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
331 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000332 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000333 }
334 }
David Goodwinc7951f82009-10-01 19:45:32 +0000335 } else {
Dan Gohman21d90032008-11-25 00:52:40 +0000336 // In a non-return block, examine the live-in regs of all successors.
337 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
Dan Gohman47ac0f02009-02-11 04:27:20 +0000338 SE = BB->succ_end(); SI != SE; ++SI)
Dan Gohman21d90032008-11-25 00:52:40 +0000339 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
340 E = (*SI)->livein_end(); I != E; ++I) {
341 unsigned Reg = *I;
342 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
343 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000344 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000345 // Repeat, for all aliases.
346 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
347 unsigned AliasReg = *Alias;
348 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
349 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000350 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000351 }
352 }
David Goodwin63bcbb72009-10-01 23:28:47 +0000353 }
Dan Gohman21d90032008-11-25 00:52:40 +0000354
David Goodwin63bcbb72009-10-01 23:28:47 +0000355 // Mark live-out callee-saved registers. In a return block this is
356 // all callee-saved registers. In non-return this is any
357 // callee-saved register that is not saved in the prolog.
358 const MachineFrameInfo *MFI = MF.getFrameInfo();
359 BitVector Pristine = MFI->getPristineRegs(BB);
360 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
361 unsigned Reg = *I;
362 if (!IsReturnBlock && !Pristine.test(Reg)) continue;
363 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
364 KillIndices[Reg] = BB->size();
365 DefIndices[Reg] = ~0u;
366 // Repeat, for all aliases.
367 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
368 unsigned AliasReg = *Alias;
369 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
370 KillIndices[AliasReg] = BB->size();
371 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000372 }
373 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000374}
375
376/// Schedule - Schedule the instruction range using list scheduling.
377///
378void SchedulePostRATDList::Schedule() {
David Goodwin3a5f0d42009-08-11 01:44:26 +0000379 DEBUG(errs() << "********** List Scheduling **********\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000380
381 // Build the scheduling graph.
382 BuildSchedGraph();
383
384 if (EnableAntiDepBreaking) {
385 if (BreakAntiDependencies()) {
386 // We made changes. Update the dependency graph.
387 // Theoretically we could update the graph in place:
388 // When a live range is changed to use a different register, remove
389 // the def's anti-dependence *and* output-dependence edges due to
390 // that register, and add new anti-dependence and output-dependence
391 // edges based on the next live range of the register.
392 SUnits.clear();
393 EntrySU = SUnit();
394 ExitSU = SUnit();
395 BuildSchedGraph();
396 }
397 }
398
David Goodwind94a4e52009-08-10 15:55:25 +0000399 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
400 SUnits[su].dumpAll(this));
401
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000402 AvailableQueue.initNodes(SUnits);
403
404 ListScheduleTopDown();
405
406 AvailableQueue.releaseState();
407}
408
409/// Observe - Update liveness information to account for the current
410/// instruction, which will not be scheduled.
411///
Dan Gohman47ac0f02009-02-11 04:27:20 +0000412void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
Dan Gohman1274ced2009-03-10 18:10:43 +0000413 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
414
415 // Any register which was defined within the previous scheduling region
416 // may have been rescheduled and its lifetime may overlap with registers
417 // in ways not reflected in our current liveness state. For each such
418 // register, adjust the liveness state to be conservatively correct.
419 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
420 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
421 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
422 // Mark this register to be non-renamable.
423 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
424 // Move the def index to the end of the previous region, to reflect
425 // that the def could theoretically have been scheduled at the end.
426 DefIndices[Reg] = InsertPosIndex;
427 }
428
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000429 PrescanInstruction(MI);
Dan Gohman47ac0f02009-02-11 04:27:20 +0000430 ScanInstruction(MI, Count);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000431}
432
433/// FinishBlock - Clean up register live-range state.
434///
435void SchedulePostRATDList::FinishBlock() {
436 RegRefs.clear();
437
438 // Call the superclass.
439 ScheduleDAGInstrs::FinishBlock();
440}
441
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000442/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
443/// critical path.
444static SDep *CriticalPathStep(SUnit *SU) {
445 SDep *Next = 0;
446 unsigned NextDepth = 0;
447 // Find the predecessor edge with the greatest depth.
448 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
449 P != PE; ++P) {
450 SUnit *PredSU = P->getSUnit();
451 unsigned PredLatency = P->getLatency();
452 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
453 // In the case of a latency tie, prefer an anti-dependency edge over
454 // other types of edges.
455 if (NextDepth < PredTotalLatency ||
456 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
457 NextDepth = PredTotalLatency;
458 Next = &*P;
459 }
460 }
461 return Next;
462}
463
464void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
465 // Scan the register operands for this instruction and update
466 // Classes and RegRefs.
467 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
468 MachineOperand &MO = MI->getOperand(i);
469 if (!MO.isReg()) continue;
470 unsigned Reg = MO.getReg();
471 if (Reg == 0) continue;
Chris Lattner2a386882009-07-29 21:36:49 +0000472 const TargetRegisterClass *NewRC = 0;
473
474 if (i < MI->getDesc().getNumOperands())
475 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000476
477 // For now, only allow the register to be changed if its register
478 // class is consistent across all uses.
479 if (!Classes[Reg] && NewRC)
480 Classes[Reg] = NewRC;
481 else if (!NewRC || Classes[Reg] != NewRC)
482 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
483
484 // Now check for aliases.
485 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
486 // If an alias of the reg is used during the live range, give up.
487 // Note that this allows us to skip checking if AntiDepReg
488 // overlaps with any of the aliases, among other things.
489 unsigned AliasReg = *Alias;
490 if (Classes[AliasReg]) {
491 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
492 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
493 }
494 }
495
496 // If we're still willing to consider this register, note the reference.
497 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
498 RegRefs.insert(std::make_pair(Reg, &MO));
David Goodwinc7951f82009-10-01 19:45:32 +0000499
500 // It's not safe to change register allocation for source operands of
501 // that have special allocation requirements.
502 if (MO.isUse() && MI->getDesc().hasExtraSrcRegAllocReq()) {
503 if (KeepRegs.insert(Reg)) {
504 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
505 *Subreg; ++Subreg)
506 KeepRegs.insert(*Subreg);
507 }
508 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000509 }
510}
511
512void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
513 unsigned Count) {
514 // Update liveness.
515 // Proceding upwards, registers that are defed but not used in this
516 // instruction are now dead.
517 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
518 MachineOperand &MO = MI->getOperand(i);
519 if (!MO.isReg()) continue;
520 unsigned Reg = MO.getReg();
521 if (Reg == 0) continue;
522 if (!MO.isDef()) continue;
523 // Ignore two-addr defs.
Bob Wilsond9df5012009-04-09 17:16:43 +0000524 if (MI->isRegTiedToUseOperand(i)) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000525
526 DefIndices[Reg] = Count;
527 KillIndices[Reg] = ~0u;
Evan Cheng714e8bc2009-10-01 08:26:23 +0000528 assert(((KillIndices[Reg] == ~0u) !=
529 (DefIndices[Reg] == ~0u)) &&
530 "Kill and Def maps aren't consistent for Reg!");
531 KeepRegs.erase(Reg);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000532 Classes[Reg] = 0;
533 RegRefs.erase(Reg);
534 // Repeat, for all subregs.
535 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
536 *Subreg; ++Subreg) {
537 unsigned SubregReg = *Subreg;
538 DefIndices[SubregReg] = Count;
539 KillIndices[SubregReg] = ~0u;
Evan Cheng714e8bc2009-10-01 08:26:23 +0000540 KeepRegs.erase(SubregReg);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000541 Classes[SubregReg] = 0;
542 RegRefs.erase(SubregReg);
543 }
David Goodwin7886cd82009-08-29 00:11:13 +0000544 // Conservatively mark super-registers as unusable.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000545 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
546 *Super; ++Super) {
547 unsigned SuperReg = *Super;
548 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
549 }
550 }
551 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
552 MachineOperand &MO = MI->getOperand(i);
553 if (!MO.isReg()) continue;
554 unsigned Reg = MO.getReg();
555 if (Reg == 0) continue;
556 if (!MO.isUse()) continue;
557
Chris Lattner2a386882009-07-29 21:36:49 +0000558 const TargetRegisterClass *NewRC = 0;
559 if (i < MI->getDesc().getNumOperands())
560 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000561
562 // For now, only allow the register to be changed if its register
563 // class is consistent across all uses.
564 if (!Classes[Reg] && NewRC)
565 Classes[Reg] = NewRC;
566 else if (!NewRC || Classes[Reg] != NewRC)
567 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
568
569 RegRefs.insert(std::make_pair(Reg, &MO));
570
571 // It wasn't previously live but now it is, this is a kill.
572 if (KillIndices[Reg] == ~0u) {
573 KillIndices[Reg] = Count;
574 DefIndices[Reg] = ~0u;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000575 assert(((KillIndices[Reg] == ~0u) !=
576 (DefIndices[Reg] == ~0u)) &&
577 "Kill and Def maps aren't consistent for Reg!");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000578 }
579 // Repeat, for all aliases.
580 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
581 unsigned AliasReg = *Alias;
582 if (KillIndices[AliasReg] == ~0u) {
583 KillIndices[AliasReg] = Count;
584 DefIndices[AliasReg] = ~0u;
585 }
586 }
587 }
588}
589
Dan Gohman26255ad2009-08-12 01:33:27 +0000590unsigned
591SchedulePostRATDList::findSuitableFreeRegister(unsigned AntiDepReg,
592 unsigned LastNewReg,
593 const TargetRegisterClass *RC) {
594 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
595 RE = RC->allocation_order_end(MF); R != RE; ++R) {
596 unsigned NewReg = *R;
597 // Don't replace a register with itself.
598 if (NewReg == AntiDepReg) continue;
599 // Don't replace a register with one that was recently used to repair
600 // an anti-dependence with this AntiDepReg, because that would
601 // re-introduce that anti-dependence.
602 if (NewReg == LastNewReg) continue;
603 // If NewReg is dead and NewReg's most recent def is not before
604 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
605 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
606 "Kill and Def maps aren't consistent for AntiDepReg!");
607 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
608 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohmanda277572009-08-12 01:44:20 +0000609 if (KillIndices[NewReg] != ~0u ||
610 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
611 KillIndices[AntiDepReg] > DefIndices[NewReg])
Dan Gohman26255ad2009-08-12 01:33:27 +0000612 continue;
613 return NewReg;
614 }
615
616 // No registers are free and available!
617 return 0;
618}
619
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000620/// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
621/// of the ScheduleDAG and break them by renaming registers.
622///
623bool SchedulePostRATDList::BreakAntiDependencies() {
624 // The code below assumes that there is at least one instruction,
625 // so just duck out immediately if the block is empty.
626 if (SUnits.empty()) return false;
627
628 // Find the node at the bottom of the critical path.
629 SUnit *Max = 0;
630 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
631 SUnit *SU = &SUnits[i];
632 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
633 Max = SU;
634 }
635
David Goodwin3a5f0d42009-08-11 01:44:26 +0000636 DEBUG(errs() << "Critical path has total latency "
637 << (Max->getDepth() + Max->Latency) << "\n");
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000638
639 // Track progress along the critical path through the SUnit graph as we walk
640 // the instructions.
641 SUnit *CriticalPathSU = Max;
642 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
Dan Gohman21d90032008-11-25 00:52:40 +0000643
644 // Consider this pattern:
645 // A = ...
646 // ... = A
647 // A = ...
648 // ... = A
649 // A = ...
650 // ... = A
651 // A = ...
652 // ... = A
653 // There are three anti-dependencies here, and without special care,
654 // we'd break all of them using the same register:
655 // A = ...
656 // ... = A
657 // B = ...
658 // ... = B
659 // B = ...
660 // ... = B
661 // B = ...
662 // ... = B
663 // because at each anti-dependence, B is the first register that
664 // isn't A which is free. This re-introduces anti-dependencies
665 // at all but one of the original anti-dependencies that we were
666 // trying to break. To avoid this, keep track of the most recent
David Goodwinc93d8372009-08-11 17:35:23 +0000667 // register that each register was replaced with, avoid
Dan Gohman21d90032008-11-25 00:52:40 +0000668 // using it to repair an anti-dependence on the same register.
669 // This lets us produce this:
670 // A = ...
671 // ... = A
672 // B = ...
673 // ... = B
674 // C = ...
675 // ... = C
676 // B = ...
677 // ... = B
678 // This still has an anti-dependence on B, but at least it isn't on the
679 // original critical path.
680 //
681 // TODO: If we tracked more than one register here, we could potentially
682 // fix that remaining critical edge too. This is a little more involved,
683 // because unlike the most recent register, less recent registers should
684 // still be considered, though only if no other registers are available.
685 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
686
Dan Gohman21d90032008-11-25 00:52:40 +0000687 // Attempt to break anti-dependence edges on the critical path. Walk the
688 // instructions from the bottom up, tracking information about liveness
689 // as we go to help determine which registers are available.
690 bool Changed = false;
Dan Gohman47ac0f02009-02-11 04:27:20 +0000691 unsigned Count = InsertPosIndex - 1;
692 for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000693 I != E; --Count) {
694 MachineInstr *MI = --I;
Dan Gohman21d90032008-11-25 00:52:40 +0000695
Dan Gohman00dc84a2008-12-16 19:27:52 +0000696 // Check if this instruction has a dependence on the critical path that
697 // is an anti-dependence that we may be able to break. If it is, set
698 // AntiDepReg to the non-zero register associated with the anti-dependence.
699 //
700 // We limit our attention to the critical path as a heuristic to avoid
701 // breaking anti-dependence edges that aren't going to significantly
702 // impact the overall schedule. There are a limited number of registers
703 // and we want to save them for the important edges.
704 //
705 // TODO: Instructions with multiple defs could have multiple
706 // anti-dependencies. The current code here only knows how to break one
707 // edge per instruction. Note that we'd have to be able to break all of
708 // the anti-dependencies in an instruction in order to be effective.
709 unsigned AntiDepReg = 0;
710 if (MI == CriticalPathMI) {
711 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
712 SUnit *NextSU = Edge->getSUnit();
713
714 // Only consider anti-dependence edges.
715 if (Edge->getKind() == SDep::Anti) {
716 AntiDepReg = Edge->getReg();
717 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
Dan Gohman49bb50e2009-01-16 21:57:43 +0000718 if (!AllocatableSet.test(AntiDepReg))
Evan Cheng714e8bc2009-10-01 08:26:23 +0000719 // Don't break anti-dependencies on non-allocatable registers.
720 AntiDepReg = 0;
721 else if (KeepRegs.count(AntiDepReg))
722 // Don't break anti-dependencies if an use down below requires
723 // this exact register.
Dan Gohman49bb50e2009-01-16 21:57:43 +0000724 AntiDepReg = 0;
725 else {
Dan Gohman00dc84a2008-12-16 19:27:52 +0000726 // If the SUnit has other dependencies on the SUnit that it
727 // anti-depends on, don't bother breaking the anti-dependency
728 // since those edges would prevent such units from being
729 // scheduled past each other regardless.
730 //
731 // Also, if there are dependencies on other SUnits with the
732 // same register as the anti-dependency, don't attempt to
733 // break it.
734 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
735 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
736 if (P->getSUnit() == NextSU ?
737 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
738 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
739 AntiDepReg = 0;
740 break;
741 }
742 }
743 }
744 CriticalPathSU = NextSU;
745 CriticalPathMI = CriticalPathSU->getInstr();
746 } else {
747 // We've reached the end of the critical path.
748 CriticalPathSU = 0;
749 CriticalPathMI = 0;
750 }
751 }
Dan Gohman21d90032008-11-25 00:52:40 +0000752
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000753 PrescanInstruction(MI);
754
Evan Cheng714e8bc2009-10-01 08:26:23 +0000755 if (MI->getDesc().hasExtraDefRegAllocReq())
756 // If this instruction's defs have special allocation requirement, don't
757 // break this anti-dependency.
758 AntiDepReg = 0;
759 else if (AntiDepReg) {
760 // If this instruction has a use of AntiDepReg, breaking it
761 // is invalid.
762 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
763 MachineOperand &MO = MI->getOperand(i);
764 if (!MO.isReg()) continue;
765 unsigned Reg = MO.getReg();
766 if (Reg == 0) continue;
767 if (MO.isUse() && AntiDepReg == Reg) {
768 AntiDepReg = 0;
769 break;
770 }
Dan Gohman21d90032008-11-25 00:52:40 +0000771 }
Dan Gohman21d90032008-11-25 00:52:40 +0000772 }
773
774 // Determine AntiDepReg's register class, if it is live and is
775 // consistently used within a single class.
776 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
Nick Lewyckya89d1022008-11-27 17:29:52 +0000777 assert((AntiDepReg == 0 || RC != NULL) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000778 "Register should be live if it's causing an anti-dependence!");
779 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
780 AntiDepReg = 0;
781
782 // Look for a suitable register to use to break the anti-depenence.
783 //
784 // TODO: Instead of picking the first free register, consider which might
785 // be the best.
786 if (AntiDepReg != 0) {
Dan Gohman26255ad2009-08-12 01:33:27 +0000787 if (unsigned NewReg = findSuitableFreeRegister(AntiDepReg,
788 LastNewReg[AntiDepReg],
789 RC)) {
790 DEBUG(errs() << "Breaking anti-dependence edge on "
791 << TRI->getName(AntiDepReg)
792 << " with " << RegRefs.count(AntiDepReg) << " references"
793 << " using " << TRI->getName(NewReg) << "!\n");
Dan Gohman21d90032008-11-25 00:52:40 +0000794
Dan Gohman26255ad2009-08-12 01:33:27 +0000795 // Update the references to the old register to refer to the new
796 // register.
797 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
798 std::multimap<unsigned, MachineOperand *>::iterator>
799 Range = RegRefs.equal_range(AntiDepReg);
800 for (std::multimap<unsigned, MachineOperand *>::iterator
801 Q = Range.first, QE = Range.second; Q != QE; ++Q)
802 Q->second->setReg(NewReg);
Dan Gohman21d90032008-11-25 00:52:40 +0000803
Dan Gohman26255ad2009-08-12 01:33:27 +0000804 // We just went back in time and modified history; the
805 // liveness information for the anti-depenence reg is now
806 // inconsistent. Set the state as if it were dead.
807 Classes[NewReg] = Classes[AntiDepReg];
808 DefIndices[NewReg] = DefIndices[AntiDepReg];
809 KillIndices[NewReg] = KillIndices[AntiDepReg];
810 assert(((KillIndices[NewReg] == ~0u) !=
811 (DefIndices[NewReg] == ~0u)) &&
812 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000813
Dan Gohman26255ad2009-08-12 01:33:27 +0000814 Classes[AntiDepReg] = 0;
815 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
816 KillIndices[AntiDepReg] = ~0u;
817 assert(((KillIndices[AntiDepReg] == ~0u) !=
818 (DefIndices[AntiDepReg] == ~0u)) &&
819 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman21d90032008-11-25 00:52:40 +0000820
Dan Gohman26255ad2009-08-12 01:33:27 +0000821 RegRefs.erase(AntiDepReg);
822 Changed = true;
823 LastNewReg[AntiDepReg] = NewReg;
Dan Gohman21d90032008-11-25 00:52:40 +0000824 }
825 }
826
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000827 ScanInstruction(MI, Count);
Dan Gohman21d90032008-11-25 00:52:40 +0000828 }
Dan Gohman21d90032008-11-25 00:52:40 +0000829
830 return Changed;
831}
832
David Goodwin5e411782009-09-03 22:15:25 +0000833/// StartBlockForKills - Initialize register live-range state for updating kills
834///
835void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
836 // Initialize the indices to indicate that no registers are live.
837 std::fill(KillIndices, array_endof(KillIndices), ~0u);
838
839 // Determine the live-out physregs for this block.
840 if (!BB->empty() && BB->back().getDesc().isReturn()) {
841 // In a return block, examine the function live-out regs.
842 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
843 E = MRI.liveout_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 else {
854 // In a non-return block, examine the live-in regs of all successors.
855 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
856 SE = BB->succ_end(); SI != SE; ++SI) {
857 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
858 E = (*SI)->livein_end(); I != E; ++I) {
859 unsigned Reg = *I;
860 KillIndices[Reg] = BB->size();
861 // Repeat, for all subregs.
862 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
863 *Subreg; ++Subreg) {
864 KillIndices[*Subreg] = BB->size();
865 }
866 }
867 }
868 }
869}
870
David Goodwin8f909342009-09-23 16:35:25 +0000871bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
872 MachineOperand &MO) {
873 // Setting kill flag...
874 if (!MO.isKill()) {
875 MO.setIsKill(true);
876 return false;
877 }
878
879 // If MO itself is live, clear the kill flag...
880 if (KillIndices[MO.getReg()] != ~0u) {
881 MO.setIsKill(false);
882 return false;
883 }
884
885 // If any subreg of MO is live, then create an imp-def for that
886 // subreg and keep MO marked as killed.
887 bool AllDead = true;
888 const unsigned SuperReg = MO.getReg();
889 for (const unsigned *Subreg = TRI->getSubRegisters(SuperReg);
890 *Subreg; ++Subreg) {
891 if (KillIndices[*Subreg] != ~0u) {
892 MI->addOperand(MachineOperand::CreateReg(*Subreg,
893 true /*IsDef*/,
894 true /*IsImp*/,
895 false /*IsKill*/,
896 false /*IsDead*/));
897 AllDead = false;
898 }
899 }
900
901 MO.setIsKill(AllDead);
902 return false;
903}
904
David Goodwin88a589c2009-08-25 17:03:05 +0000905/// FixupKills - Fix the register kill flags, they may have been made
906/// incorrect by instruction reordering.
907///
908void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
909 DEBUG(errs() << "Fixup kills for BB ID#" << MBB->getNumber() << '\n');
910
911 std::set<unsigned> killedRegs;
912 BitVector ReservedRegs = TRI->getReservedRegs(MF);
David Goodwin5e411782009-09-03 22:15:25 +0000913
914 StartBlockForKills(MBB);
David Goodwin7886cd82009-08-29 00:11:13 +0000915
916 // Examine block from end to start...
David Goodwin88a589c2009-08-25 17:03:05 +0000917 unsigned Count = MBB->size();
918 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
919 I != E; --Count) {
920 MachineInstr *MI = --I;
921
David Goodwin7886cd82009-08-29 00:11:13 +0000922 // Update liveness. Registers that are defed but not used in this
923 // instruction are now dead. Mark register and all subregs as they
924 // are completely defined.
925 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
926 MachineOperand &MO = MI->getOperand(i);
927 if (!MO.isReg()) continue;
928 unsigned Reg = MO.getReg();
929 if (Reg == 0) continue;
930 if (!MO.isDef()) continue;
931 // Ignore two-addr defs.
932 if (MI->isRegTiedToUseOperand(i)) continue;
933
David Goodwin7886cd82009-08-29 00:11:13 +0000934 KillIndices[Reg] = ~0u;
935
936 // Repeat for all subregs.
937 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
938 *Subreg; ++Subreg) {
939 KillIndices[*Subreg] = ~0u;
940 }
941 }
David Goodwin88a589c2009-08-25 17:03:05 +0000942
David Goodwin8f909342009-09-23 16:35:25 +0000943 // Examine all used registers and set/clear kill flag. When a
944 // register is used multiple times we only set the kill flag on
945 // the first use.
David Goodwin88a589c2009-08-25 17:03:05 +0000946 killedRegs.clear();
947 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
948 MachineOperand &MO = MI->getOperand(i);
949 if (!MO.isReg() || !MO.isUse()) continue;
950 unsigned Reg = MO.getReg();
951 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
952
David Goodwin7886cd82009-08-29 00:11:13 +0000953 bool kill = false;
954 if (killedRegs.find(Reg) == killedRegs.end()) {
955 kill = true;
956 // A register is not killed if any subregs are live...
957 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
958 *Subreg; ++Subreg) {
959 if (KillIndices[*Subreg] != ~0u) {
960 kill = false;
961 break;
962 }
963 }
964
965 // If subreg is not live, then register is killed if it became
966 // live in this instruction
967 if (kill)
968 kill = (KillIndices[Reg] == ~0u);
969 }
970
David Goodwin88a589c2009-08-25 17:03:05 +0000971 if (MO.isKill() != kill) {
David Goodwin8f909342009-09-23 16:35:25 +0000972 bool removed = ToggleKillFlag(MI, MO);
973 if (removed) {
974 DEBUG(errs() << "Fixed <removed> in ");
975 } else {
976 DEBUG(errs() << "Fixed " << MO << " in ");
977 }
David Goodwin88a589c2009-08-25 17:03:05 +0000978 DEBUG(MI->dump());
979 }
David Goodwin7886cd82009-08-29 00:11:13 +0000980
David Goodwin88a589c2009-08-25 17:03:05 +0000981 killedRegs.insert(Reg);
982 }
David Goodwin7886cd82009-08-29 00:11:13 +0000983
David Goodwina3251db2009-08-31 20:47:02 +0000984 // Mark any used register (that is not using undef) and subregs as
985 // now live...
David Goodwin7886cd82009-08-29 00:11:13 +0000986 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
987 MachineOperand &MO = MI->getOperand(i);
David Goodwina3251db2009-08-31 20:47:02 +0000988 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
David Goodwin7886cd82009-08-29 00:11:13 +0000989 unsigned Reg = MO.getReg();
990 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
991
David Goodwin7886cd82009-08-29 00:11:13 +0000992 KillIndices[Reg] = Count;
993
994 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
995 *Subreg; ++Subreg) {
996 KillIndices[*Subreg] = Count;
997 }
998 }
David Goodwin88a589c2009-08-25 17:03:05 +0000999 }
1000}
1001
Dan Gohman343f0c02008-11-19 23:18:57 +00001002//===----------------------------------------------------------------------===//
1003// Top-Down Scheduling
1004//===----------------------------------------------------------------------===//
1005
1006/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1007/// the PendingQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman54e4c362008-12-09 22:54:47 +00001008void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
1009 SUnit *SuccSU = SuccEdge->getSUnit();
Reid Klecknerc277ab02009-09-30 20:15:38 +00001010
Dan Gohman343f0c02008-11-19 23:18:57 +00001011#ifndef NDEBUG
Reid Klecknerc277ab02009-09-30 20:15:38 +00001012 if (SuccSU->NumPredsLeft == 0) {
Chris Lattner103289e2009-08-23 07:19:13 +00001013 errs() << "*** Scheduling failed! ***\n";
Dan Gohman343f0c02008-11-19 23:18:57 +00001014 SuccSU->dump(this);
Chris Lattner103289e2009-08-23 07:19:13 +00001015 errs() << " has been released too many times!\n";
Torok Edwinc23197a2009-07-14 16:55:14 +00001016 llvm_unreachable(0);
Dan Gohman343f0c02008-11-19 23:18:57 +00001017 }
1018#endif
Reid Klecknerc277ab02009-09-30 20:15:38 +00001019 --SuccSU->NumPredsLeft;
1020
Dan Gohman343f0c02008-11-19 23:18:57 +00001021 // Compute how many cycles it will be before this actually becomes
1022 // available. This is the max of the start time of all predecessors plus
1023 // their latencies.
Dan Gohman3f237442008-12-16 03:25:46 +00001024 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
Dan Gohman343f0c02008-11-19 23:18:57 +00001025
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001026 // If all the node's predecessors are scheduled, this node is ready
1027 // to be scheduled. Ignore the special ExitSU node.
1028 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Dan Gohman343f0c02008-11-19 23:18:57 +00001029 PendingQueue.push_back(SuccSU);
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001030}
1031
1032/// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
1033void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
1034 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1035 I != E; ++I)
1036 ReleaseSucc(SU, &*I);
Dan Gohman343f0c02008-11-19 23:18:57 +00001037}
1038
1039/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1040/// count of its successors. If a successor pending count is zero, add it to
1041/// the Available queue.
1042void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
David Goodwin3a5f0d42009-08-11 01:44:26 +00001043 DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
Dan Gohman343f0c02008-11-19 23:18:57 +00001044 DEBUG(SU->dump(this));
1045
1046 Sequence.push_back(SU);
Dan Gohman3f237442008-12-16 03:25:46 +00001047 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1048 SU->setDepthToAtLeast(CurCycle);
Dan Gohman343f0c02008-11-19 23:18:57 +00001049
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001050 ReleaseSuccessors(SU);
Dan Gohman343f0c02008-11-19 23:18:57 +00001051 SU->isScheduled = true;
1052 AvailableQueue.ScheduledNode(SU);
1053}
1054
1055/// ListScheduleTopDown - The main loop of list scheduling for top-down
1056/// schedulers.
1057void SchedulePostRATDList::ListScheduleTopDown() {
1058 unsigned CurCycle = 0;
1059
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001060 // Release any successors of the special Entry node.
1061 ReleaseSuccessors(&EntrySU);
1062
Dan Gohman343f0c02008-11-19 23:18:57 +00001063 // All leaves to Available queue.
1064 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1065 // It is available if it has no predecessors.
1066 if (SUnits[i].Preds.empty()) {
1067 AvailableQueue.push(&SUnits[i]);
1068 SUnits[i].isAvailable = true;
1069 }
1070 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +00001071
David Goodwin2ffb0ce2009-08-12 21:47:46 +00001072 // In any cycle where we can't schedule any instructions, we must
1073 // stall or emit a noop, depending on the target.
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001074 bool CycleHasInsts = false;
David Goodwin2ffb0ce2009-08-12 21:47:46 +00001075
Dan Gohman343f0c02008-11-19 23:18:57 +00001076 // While Available queue is not empty, grab the node with the highest
1077 // priority. If it is not ready put it back. Schedule the node.
Dan Gohman2836c282009-01-16 01:33:36 +00001078 std::vector<SUnit*> NotReady;
Dan Gohman343f0c02008-11-19 23:18:57 +00001079 Sequence.reserve(SUnits.size());
1080 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
1081 // Check to see if any of the pending instructions are ready to issue. If
1082 // so, add them to the available queue.
Dan Gohman3f237442008-12-16 03:25:46 +00001083 unsigned MinDepth = ~0u;
Dan Gohman343f0c02008-11-19 23:18:57 +00001084 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman3f237442008-12-16 03:25:46 +00001085 if (PendingQueue[i]->getDepth() <= CurCycle) {
Dan Gohman343f0c02008-11-19 23:18:57 +00001086 AvailableQueue.push(PendingQueue[i]);
1087 PendingQueue[i]->isAvailable = true;
1088 PendingQueue[i] = PendingQueue.back();
1089 PendingQueue.pop_back();
1090 --i; --e;
Dan Gohman3f237442008-12-16 03:25:46 +00001091 } else if (PendingQueue[i]->getDepth() < MinDepth)
1092 MinDepth = PendingQueue[i]->getDepth();
Dan Gohman343f0c02008-11-19 23:18:57 +00001093 }
David Goodwinc93d8372009-08-11 17:35:23 +00001094
David Goodwin7cd01182009-08-11 17:56:42 +00001095 DEBUG(errs() << "\n*** Examining Available\n";
1096 LatencyPriorityQueue q = AvailableQueue;
1097 while (!q.empty()) {
1098 SUnit *su = q.pop();
1099 errs() << "Height " << su->getHeight() << ": ";
1100 su->dump(this);
1101 });
David Goodwinc93d8372009-08-11 17:35:23 +00001102
Dan Gohman2836c282009-01-16 01:33:36 +00001103 SUnit *FoundSUnit = 0;
1104
1105 bool HasNoopHazards = false;
1106 while (!AvailableQueue.empty()) {
1107 SUnit *CurSUnit = AvailableQueue.pop();
1108
1109 ScheduleHazardRecognizer::HazardType HT =
1110 HazardRec->getHazardType(CurSUnit);
1111 if (HT == ScheduleHazardRecognizer::NoHazard) {
1112 FoundSUnit = CurSUnit;
1113 break;
1114 }
1115
1116 // Remember if this is a noop hazard.
1117 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
1118
1119 NotReady.push_back(CurSUnit);
1120 }
1121
1122 // Add the nodes that aren't ready back onto the available list.
1123 if (!NotReady.empty()) {
1124 AvailableQueue.push_all(NotReady);
1125 NotReady.clear();
1126 }
1127
Dan Gohman343f0c02008-11-19 23:18:57 +00001128 // If we found a node to schedule, do it now.
1129 if (FoundSUnit) {
1130 ScheduleNodeTopDown(FoundSUnit, CurCycle);
Dan Gohman2836c282009-01-16 01:33:36 +00001131 HazardRec->EmitInstruction(FoundSUnit);
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001132 CycleHasInsts = true;
Dan Gohman343f0c02008-11-19 23:18:57 +00001133
David Goodwind94a4e52009-08-10 15:55:25 +00001134 // If we are using the target-specific hazards, then don't
1135 // advance the cycle time just because we schedule a node. If
1136 // the target allows it we can schedule multiple nodes in the
1137 // same cycle.
1138 if (!EnablePostRAHazardAvoidance) {
1139 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
1140 ++CurCycle;
1141 }
Dan Gohman2836c282009-01-16 01:33:36 +00001142 } else {
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001143 if (CycleHasInsts) {
David Goodwin2ffb0ce2009-08-12 21:47:46 +00001144 DEBUG(errs() << "*** Finished cycle " << CurCycle << '\n');
1145 HazardRec->AdvanceCycle();
1146 } else if (!HasNoopHazards) {
1147 // Otherwise, we have a pipeline stall, but no other problem,
1148 // just advance the current cycle and try again.
1149 DEBUG(errs() << "*** Stall in cycle " << CurCycle << '\n');
1150 HazardRec->AdvanceCycle();
1151 ++NumStalls;
1152 } else {
1153 // Otherwise, we have no instructions to issue and we have instructions
1154 // that will fault if we don't do this right. This is the case for
1155 // processors without pipeline interlocks and other cases.
1156 DEBUG(errs() << "*** Emitting noop in cycle " << CurCycle << '\n');
1157 HazardRec->EmitNoop();
1158 Sequence.push_back(0); // NULL here means noop
1159 ++NumNoops;
1160 }
1161
Dan Gohman2836c282009-01-16 01:33:36 +00001162 ++CurCycle;
Benjamin Kramerbe441c02009-09-06 12:10:17 +00001163 CycleHasInsts = false;
Dan Gohman343f0c02008-11-19 23:18:57 +00001164 }
1165 }
1166
1167#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +00001168 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +00001169#endif
1170}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00001171
1172//===----------------------------------------------------------------------===//
1173// Public Constructor Functions
1174//===----------------------------------------------------------------------===//
1175
1176FunctionPass *llvm::createPostRAScheduler() {
Dan Gohman343f0c02008-11-19 23:18:57 +00001177 return new PostRAScheduler();
Dale Johannesene7e7d0d2007-07-13 17:13:54 +00001178}