blob: 617b4ac1ec22d3361d54d1e6de7e4ac45ac2009f [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"
Dan Gohman6dc75fe2009-02-06 17:12:10 +000022#include "ScheduleDAGInstrs.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000023#include "llvm/CodeGen/Passes.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000024#include "llvm/CodeGen/LatencyPriorityQueue.h"
25#include "llvm/CodeGen/SchedulerRegistry.h"
Dan Gohman3f237442008-12-16 03:25:46 +000026#include "llvm/CodeGen/MachineDominators.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000027#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohman3f237442008-12-16 03:25:46 +000028#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman21d90032008-11-25 00:52:40 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman2836c282009-01-16 01:33:36 +000030#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
Dan Gohman79ce2762009-01-15 19:20:50 +000031#include "llvm/Target/TargetMachine.h"
Dan Gohman21d90032008-11-25 00:52:40 +000032#include "llvm/Target/TargetInstrInfo.h"
33#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner459525d2008-01-14 19:00:06 +000034#include "llvm/Support/Compiler.h"
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000035#include "llvm/Support/Debug.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000036#include "llvm/ADT/Statistic.h"
Dan Gohman21d90032008-11-25 00:52:40 +000037#include <map>
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000038using namespace llvm;
39
Dan Gohman2836c282009-01-16 01:33:36 +000040STATISTIC(NumNoops, "Number of noops inserted");
Dan Gohman343f0c02008-11-19 23:18:57 +000041STATISTIC(NumStalls, "Number of pipeline stalls");
42
Dan Gohman21d90032008-11-25 00:52:40 +000043static cl::opt<bool>
44EnableAntiDepBreaking("break-anti-dependencies",
Dan Gohman00dc84a2008-12-16 19:27:52 +000045 cl::desc("Break post-RA scheduling anti-dependencies"),
46 cl::init(true), cl::Hidden);
Dan Gohman21d90032008-11-25 00:52:40 +000047
Dan Gohman2836c282009-01-16 01:33:36 +000048static cl::opt<bool>
49EnablePostRAHazardAvoidance("avoid-hazards",
50 cl::desc("Enable simple hazard-avoidance"),
51 cl::init(true), cl::Hidden);
52
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000053namespace {
Dan Gohman343f0c02008-11-19 23:18:57 +000054 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000055 public:
56 static char ID;
Dan Gohman343f0c02008-11-19 23:18:57 +000057 PostRAScheduler() : MachineFunctionPass(&ID) {}
Dan Gohman21d90032008-11-25 00:52:40 +000058
Dan Gohman3f237442008-12-16 03:25:46 +000059 void getAnalysisUsage(AnalysisUsage &AU) const {
60 AU.addRequired<MachineDominatorTree>();
61 AU.addPreserved<MachineDominatorTree>();
62 AU.addRequired<MachineLoopInfo>();
63 AU.addPreserved<MachineLoopInfo>();
64 MachineFunctionPass::getAnalysisUsage(AU);
65 }
66
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000067 const char *getPassName() const {
Dan Gohman21d90032008-11-25 00:52:40 +000068 return "Post RA top-down list latency scheduler";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000069 }
70
71 bool runOnMachineFunction(MachineFunction &Fn);
72 };
Dan Gohman343f0c02008-11-19 23:18:57 +000073 char PostRAScheduler::ID = 0;
74
75 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
Dan Gohman343f0c02008-11-19 23:18:57 +000076 /// AvailableQueue - The priority queue to use for the available SUnits.
77 ///
78 LatencyPriorityQueue AvailableQueue;
79
80 /// PendingQueue - This contains all of the instructions whose operands have
81 /// been issued, but their results are not ready yet (due to the latency of
82 /// the operation). Once the operands becomes available, the instruction is
83 /// added to the AvailableQueue.
84 std::vector<SUnit*> PendingQueue;
85
Dan Gohman21d90032008-11-25 00:52:40 +000086 /// Topo - A topological ordering for SUnits.
87 ScheduleDAGTopologicalSort Topo;
Dan Gohman343f0c02008-11-19 23:18:57 +000088
Dan Gohman79ce2762009-01-15 19:20:50 +000089 /// AllocatableSet - The set of allocatable registers.
90 /// We'll be ignoring anti-dependencies on non-allocatable registers,
91 /// because they may not be safe to break.
92 const BitVector AllocatableSet;
93
Dan Gohman2836c282009-01-16 01:33:36 +000094 /// HazardRec - The hazard recognizer to use.
95 ScheduleHazardRecognizer *HazardRec;
96
Dan Gohman9e64bbb2009-02-10 23:27:53 +000097 /// Classes - For live regs that are only used in one register class in a
98 /// live range, the register class. If the register is not live, the
99 /// corresponding value is null. If the register is live but used in
100 /// multiple register classes, the corresponding value is -1 casted to a
101 /// pointer.
102 const TargetRegisterClass *
103 Classes[TargetRegisterInfo::FirstVirtualRegister];
104
105 /// RegRegs - Map registers to all their references within a live range.
106 std::multimap<unsigned, MachineOperand *> RegRefs;
107
108 /// The index of the most recent kill (proceding bottom-up), or ~0u if
109 /// the register is not live.
110 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
111
112 /// The index of the most recent complete def (proceding bottom up), or ~0u
113 /// if the register is live.
114 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
115
Dan Gohman21d90032008-11-25 00:52:40 +0000116 public:
Dan Gohman79ce2762009-01-15 19:20:50 +0000117 SchedulePostRATDList(MachineFunction &MF,
Dan Gohman3f237442008-12-16 03:25:46 +0000118 const MachineLoopInfo &MLI,
Dan Gohman2836c282009-01-16 01:33:36 +0000119 const MachineDominatorTree &MDT,
120 ScheduleHazardRecognizer *HR)
Dan Gohman79ce2762009-01-15 19:20:50 +0000121 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
Dan Gohman2836c282009-01-16 01:33:36 +0000122 AllocatableSet(TRI->getAllocatableSet(MF)),
123 HazardRec(HR) {}
124
125 ~SchedulePostRATDList() {
126 delete HazardRec;
127 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000128
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000129 /// StartBlock - Initialize register live-range state for scheduling in
130 /// this block.
131 ///
132 void StartBlock(MachineBasicBlock *BB);
133
134 /// Schedule - Schedule the instruction range using list scheduling.
135 ///
Dan Gohman343f0c02008-11-19 23:18:57 +0000136 void Schedule();
137
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000138 /// Observe - Update liveness information to account for the current
139 /// instruction, which will not be scheduled.
140 ///
141 void Observe(MachineInstr *MI);
142
143 /// FinishBlock - Clean up register live-range state.
144 ///
145 void FinishBlock();
146
Dan Gohman343f0c02008-11-19 23:18:57 +0000147 private:
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000148 void PrescanInstruction(MachineInstr *MI);
149 void ScanInstruction(MachineInstr *MI, unsigned Count);
Dan Gohman54e4c362008-12-09 22:54:47 +0000150 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000151 void ReleaseSuccessors(SUnit *SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000152 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
153 void ListScheduleTopDown();
Dan Gohman21d90032008-11-25 00:52:40 +0000154 bool BreakAntiDependencies();
Dan Gohman343f0c02008-11-19 23:18:57 +0000155 };
Dan Gohman2836c282009-01-16 01:33:36 +0000156
157 /// SimpleHazardRecognizer - A *very* simple hazard recognizer. It uses
158 /// a coarse classification and attempts to avoid that instructions of
159 /// a given class aren't grouped too densely together.
160 class SimpleHazardRecognizer : public ScheduleHazardRecognizer {
161 /// Class - A simple classification for SUnits.
162 enum Class {
163 Other, Load, Store
164 };
165
166 /// Window - The Class values of the most recently issued
167 /// instructions.
168 Class Window[8];
169
170 /// getClass - Classify the given SUnit.
171 Class getClass(const SUnit *SU) {
172 const MachineInstr *MI = SU->getInstr();
173 const TargetInstrDesc &TID = MI->getDesc();
174 if (TID.mayLoad())
175 return Load;
176 if (TID.mayStore())
177 return Store;
178 return Other;
179 }
180
181 /// Step - Rotate the existing entries in Window and insert the
182 /// given class value in position as the most recent.
183 void Step(Class C) {
184 std::copy(Window+1, array_endof(Window), Window);
185 Window[array_lengthof(Window)-1] = C;
186 }
187
188 public:
189 SimpleHazardRecognizer() : Window() {}
190
191 virtual HazardType getHazardType(SUnit *SU) {
192 Class C = getClass(SU);
193 if (C == Other)
194 return NoHazard;
195 unsigned Score = 0;
Dan Gohman79ce4ce2009-01-16 17:55:08 +0000196 for (unsigned i = 0; i != array_lengthof(Window); ++i)
Dan Gohman2836c282009-01-16 01:33:36 +0000197 if (Window[i] == C)
198 Score += i + 1;
199 if (Score > array_lengthof(Window) * 2)
200 return Hazard;
201 return NoHazard;
202 }
203
204 virtual void EmitInstruction(SUnit *SU) {
205 Step(getClass(SU));
206 }
207
208 virtual void AdvanceCycle() {
209 Step(Other);
210 }
211 };
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000212}
213
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000214/// isSchedulingBoundary - Test if the given instruction should be
215/// considered a scheduling boundary. This primarily includes labels
216/// and terminators.
217///
218static bool isSchedulingBoundary(const MachineInstr *MI,
219 const MachineFunction &MF) {
220 // Terminators and labels can't be scheduled around.
221 if (MI->getDesc().isTerminator() || MI->isLabel())
222 return true;
223
224 return false;
225}
226
Dan Gohman343f0c02008-11-19 23:18:57 +0000227bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
228 DOUT << "PostRAScheduler\n";
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000229
Dan Gohman3f237442008-12-16 03:25:46 +0000230 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
231 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
Dan Gohman2836c282009-01-16 01:33:36 +0000232 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
233 new SimpleHazardRecognizer :
234 new ScheduleHazardRecognizer();
Dan Gohman3f237442008-12-16 03:25:46 +0000235
Dan Gohman2836c282009-01-16 01:33:36 +0000236 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
Dan Gohman79ce2762009-01-15 19:20:50 +0000237
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000238 // Loop over all of the basic blocks
239 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000240 MBB != MBBe; ++MBB) {
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000241 // Initialize register live-range state for scheduling in this block.
242 Scheduler.StartBlock(MBB);
243
Dan Gohmanf7119392009-01-16 22:10:20 +0000244 // Schedule each sequence of instructions not interrupted by a label
245 // or anything else that effectively needs to shut down scheduling.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000246 MachineBasicBlock::iterator Current = MBB->end();
247 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
248 MachineInstr *MI = prior(I);
249 if (isSchedulingBoundary(MI, Fn)) {
250 if (I != Current) {
251 Scheduler.Run(0, MBB, I, Current);
252 Scheduler.EmitSchedule();
253 }
254 Scheduler.Observe(MI);
255 Current = MI;
Dan Gohmanf7119392009-01-16 22:10:20 +0000256 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000257 I = MI;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000258 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000259 Scheduler.Run(0, MBB, MBB->begin(), Current);
Dan Gohman343f0c02008-11-19 23:18:57 +0000260 Scheduler.EmitSchedule();
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000261
262 // Clean up register live-range state.
263 Scheduler.FinishBlock();
Dan Gohman343f0c02008-11-19 23:18:57 +0000264 }
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000265
266 return true;
267}
268
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000269/// StartBlock - Initialize register live-range state for scheduling in
270/// this block.
Dan Gohman21d90032008-11-25 00:52:40 +0000271///
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000272void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
273 // Call the superclass.
274 ScheduleDAGInstrs::StartBlock(BB);
Dan Gohman21d90032008-11-25 00:52:40 +0000275
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000276 // Clear out the register class data.
277 std::fill(Classes, array_endof(Classes),
278 static_cast<const TargetRegisterClass *>(0));
Dan Gohman21d90032008-11-25 00:52:40 +0000279
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000280 // Initialize the indices to indicate that no registers are live.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000281 std::fill(KillIndices, array_endof(KillIndices), ~0u);
Dan Gohman21d90032008-11-25 00:52:40 +0000282 std::fill(DefIndices, array_endof(DefIndices), BB->size());
283
284 // Determine the live-out physregs for this block.
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000285 if (!BB->empty() && BB->back().getDesc().isReturn())
Dan Gohman21d90032008-11-25 00:52:40 +0000286 // In a return block, examine the function live-out regs.
287 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
288 E = MRI.liveout_end(); I != E; ++I) {
289 unsigned Reg = *I;
290 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
291 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000292 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000293 // Repeat, for all aliases.
294 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
295 unsigned AliasReg = *Alias;
296 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
297 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000298 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000299 }
300 }
301 else
302 // In a non-return block, examine the live-in regs of all successors.
303 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
304 SE = BB->succ_end(); SI != SE; ++SI)
305 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
306 E = (*SI)->livein_end(); I != E; ++I) {
307 unsigned Reg = *I;
308 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
309 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000310 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000311 // Repeat, for all aliases.
312 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
313 unsigned AliasReg = *Alias;
314 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
315 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000316 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000317 }
318 }
319
320 // Consider callee-saved registers as live-out, since we're running after
321 // prologue/epilogue insertion so there's no way to add additional
322 // saved registers.
323 //
324 // TODO: If the callee saves and restores these, then we can potentially
325 // use them between the save and the restore. To do that, we could scan
326 // the exit blocks to see which of these registers are defined.
Dan Gohman00dc84a2008-12-16 19:27:52 +0000327 // Alternatively, callee-saved registers that aren't saved and restored
Dan Gohmanebb0a312008-12-03 19:30:13 +0000328 // could be marked live-in in every block.
Dan Gohman21d90032008-11-25 00:52:40 +0000329 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
330 unsigned Reg = *I;
331 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
332 KillIndices[Reg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000333 DefIndices[Reg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000334 // Repeat, for all aliases.
335 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
336 unsigned AliasReg = *Alias;
337 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
338 KillIndices[AliasReg] = BB->size();
Dan Gohman6c3643c2008-12-19 22:23:43 +0000339 DefIndices[AliasReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000340 }
341 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000342}
343
344/// Schedule - Schedule the instruction range using list scheduling.
345///
346void SchedulePostRATDList::Schedule() {
347 DOUT << "********** List Scheduling **********\n";
348
349 // Build the scheduling graph.
350 BuildSchedGraph();
351
352 if (EnableAntiDepBreaking) {
353 if (BreakAntiDependencies()) {
354 // We made changes. Update the dependency graph.
355 // Theoretically we could update the graph in place:
356 // When a live range is changed to use a different register, remove
357 // the def's anti-dependence *and* output-dependence edges due to
358 // that register, and add new anti-dependence and output-dependence
359 // edges based on the next live range of the register.
360 SUnits.clear();
361 EntrySU = SUnit();
362 ExitSU = SUnit();
363 BuildSchedGraph();
364 }
365 }
366
367 AvailableQueue.initNodes(SUnits);
368
369 ListScheduleTopDown();
370
371 AvailableQueue.releaseState();
372}
373
374/// Observe - Update liveness information to account for the current
375/// instruction, which will not be scheduled.
376///
377void SchedulePostRATDList::Observe(MachineInstr *MI) {
378 PrescanInstruction(MI);
379 ScanInstruction(MI, 0);
380}
381
382/// FinishBlock - Clean up register live-range state.
383///
384void SchedulePostRATDList::FinishBlock() {
385 RegRefs.clear();
386
387 // Call the superclass.
388 ScheduleDAGInstrs::FinishBlock();
389}
390
391/// getInstrOperandRegClass - Return register class of the operand of an
392/// instruction of the specified TargetInstrDesc.
393static const TargetRegisterClass*
394getInstrOperandRegClass(const TargetRegisterInfo *TRI,
395 const TargetInstrDesc &II, unsigned Op) {
396 if (Op >= II.getNumOperands())
397 return NULL;
398 if (II.OpInfo[Op].isLookupPtrRegClass())
399 return TRI->getPointerRegClass();
400 return TRI->getRegClass(II.OpInfo[Op].RegClass);
401}
402
403/// CriticalPathStep - Return the next SUnit after SU on the bottom-up
404/// critical path.
405static SDep *CriticalPathStep(SUnit *SU) {
406 SDep *Next = 0;
407 unsigned NextDepth = 0;
408 // Find the predecessor edge with the greatest depth.
409 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
410 P != PE; ++P) {
411 SUnit *PredSU = P->getSUnit();
412 unsigned PredLatency = P->getLatency();
413 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
414 // In the case of a latency tie, prefer an anti-dependency edge over
415 // other types of edges.
416 if (NextDepth < PredTotalLatency ||
417 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
418 NextDepth = PredTotalLatency;
419 Next = &*P;
420 }
421 }
422 return Next;
423}
424
425void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
426 // Scan the register operands for this instruction and update
427 // Classes and RegRefs.
428 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
429 MachineOperand &MO = MI->getOperand(i);
430 if (!MO.isReg()) continue;
431 unsigned Reg = MO.getReg();
432 if (Reg == 0) continue;
433 const TargetRegisterClass *NewRC =
434 getInstrOperandRegClass(TRI, MI->getDesc(), i);
435
436 // For now, only allow the register to be changed if its register
437 // class is consistent across all uses.
438 if (!Classes[Reg] && NewRC)
439 Classes[Reg] = NewRC;
440 else if (!NewRC || Classes[Reg] != NewRC)
441 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
442
443 // Now check for aliases.
444 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
445 // If an alias of the reg is used during the live range, give up.
446 // Note that this allows us to skip checking if AntiDepReg
447 // overlaps with any of the aliases, among other things.
448 unsigned AliasReg = *Alias;
449 if (Classes[AliasReg]) {
450 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
451 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
452 }
453 }
454
455 // If we're still willing to consider this register, note the reference.
456 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
457 RegRefs.insert(std::make_pair(Reg, &MO));
458 }
459}
460
461void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
462 unsigned Count) {
463 // Update liveness.
464 // Proceding upwards, registers that are defed but not used in this
465 // instruction are now dead.
466 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
467 MachineOperand &MO = MI->getOperand(i);
468 if (!MO.isReg()) continue;
469 unsigned Reg = MO.getReg();
470 if (Reg == 0) continue;
471 if (!MO.isDef()) continue;
472 // Ignore two-addr defs.
473 if (MI->isRegReDefinedByTwoAddr(i)) continue;
474
475 DefIndices[Reg] = Count;
476 KillIndices[Reg] = ~0u;
477 Classes[Reg] = 0;
478 RegRefs.erase(Reg);
479 // Repeat, for all subregs.
480 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
481 *Subreg; ++Subreg) {
482 unsigned SubregReg = *Subreg;
483 DefIndices[SubregReg] = Count;
484 KillIndices[SubregReg] = ~0u;
485 Classes[SubregReg] = 0;
486 RegRefs.erase(SubregReg);
487 }
488 // Conservatively mark super-registers as unusable.
489 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
490 *Super; ++Super) {
491 unsigned SuperReg = *Super;
492 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
493 }
494 }
495 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
496 MachineOperand &MO = MI->getOperand(i);
497 if (!MO.isReg()) continue;
498 unsigned Reg = MO.getReg();
499 if (Reg == 0) continue;
500 if (!MO.isUse()) continue;
501
502 const TargetRegisterClass *NewRC =
503 getInstrOperandRegClass(TRI, MI->getDesc(), i);
504
505 // For now, only allow the register to be changed if its register
506 // class is consistent across all uses.
507 if (!Classes[Reg] && NewRC)
508 Classes[Reg] = NewRC;
509 else if (!NewRC || Classes[Reg] != NewRC)
510 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
511
512 RegRefs.insert(std::make_pair(Reg, &MO));
513
514 // It wasn't previously live but now it is, this is a kill.
515 if (KillIndices[Reg] == ~0u) {
516 KillIndices[Reg] = Count;
517 DefIndices[Reg] = ~0u;
518 }
519 // Repeat, for all aliases.
520 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
521 unsigned AliasReg = *Alias;
522 if (KillIndices[AliasReg] == ~0u) {
523 KillIndices[AliasReg] = Count;
524 DefIndices[AliasReg] = ~0u;
525 }
526 }
527 }
528}
529
530/// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
531/// of the ScheduleDAG and break them by renaming registers.
532///
533bool SchedulePostRATDList::BreakAntiDependencies() {
534 // The code below assumes that there is at least one instruction,
535 // so just duck out immediately if the block is empty.
536 if (SUnits.empty()) return false;
537
538 // Find the node at the bottom of the critical path.
539 SUnit *Max = 0;
540 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
541 SUnit *SU = &SUnits[i];
542 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
543 Max = SU;
544 }
545
546 DOUT << "Critical path has total latency "
547 << (Max->getDepth() + Max->Latency) << "\n";
548
549 // Track progress along the critical path through the SUnit graph as we walk
550 // the instructions.
551 SUnit *CriticalPathSU = Max;
552 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
Dan Gohman21d90032008-11-25 00:52:40 +0000553
554 // Consider this pattern:
555 // A = ...
556 // ... = A
557 // A = ...
558 // ... = A
559 // A = ...
560 // ... = A
561 // A = ...
562 // ... = A
563 // There are three anti-dependencies here, and without special care,
564 // we'd break all of them using the same register:
565 // A = ...
566 // ... = A
567 // B = ...
568 // ... = B
569 // B = ...
570 // ... = B
571 // B = ...
572 // ... = B
573 // because at each anti-dependence, B is the first register that
574 // isn't A which is free. This re-introduces anti-dependencies
575 // at all but one of the original anti-dependencies that we were
576 // trying to break. To avoid this, keep track of the most recent
577 // register that each register was replaced with, avoid avoid
578 // using it to repair an anti-dependence on the same register.
579 // This lets us produce this:
580 // A = ...
581 // ... = A
582 // B = ...
583 // ... = B
584 // C = ...
585 // ... = C
586 // B = ...
587 // ... = B
588 // This still has an anti-dependence on B, but at least it isn't on the
589 // original critical path.
590 //
591 // TODO: If we tracked more than one register here, we could potentially
592 // fix that remaining critical edge too. This is a little more involved,
593 // because unlike the most recent register, less recent registers should
594 // still be considered, though only if no other registers are available.
595 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
596
Dan Gohman21d90032008-11-25 00:52:40 +0000597 // Attempt to break anti-dependence edges on the critical path. Walk the
598 // instructions from the bottom up, tracking information about liveness
599 // as we go to help determine which registers are available.
600 bool Changed = false;
Dan Gohman43f07fb2009-02-03 18:57:45 +0000601 unsigned Count = SUnits.size() - 1;
602 for (MachineBasicBlock::iterator I = End, E = Begin;
603 I != E; --Count) {
604 MachineInstr *MI = --I;
Dan Gohman21d90032008-11-25 00:52:40 +0000605
Dan Gohman490b1832008-12-05 05:30:02 +0000606 // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
607 // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
608 // is left behind appearing to clobber the super-register, while the
609 // subregister needs to remain live. So we just ignore them.
610 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
611 continue;
612
Dan Gohman00dc84a2008-12-16 19:27:52 +0000613 // Check if this instruction has a dependence on the critical path that
614 // is an anti-dependence that we may be able to break. If it is, set
615 // AntiDepReg to the non-zero register associated with the anti-dependence.
616 //
617 // We limit our attention to the critical path as a heuristic to avoid
618 // breaking anti-dependence edges that aren't going to significantly
619 // impact the overall schedule. There are a limited number of registers
620 // and we want to save them for the important edges.
621 //
622 // TODO: Instructions with multiple defs could have multiple
623 // anti-dependencies. The current code here only knows how to break one
624 // edge per instruction. Note that we'd have to be able to break all of
625 // the anti-dependencies in an instruction in order to be effective.
626 unsigned AntiDepReg = 0;
627 if (MI == CriticalPathMI) {
628 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
629 SUnit *NextSU = Edge->getSUnit();
630
631 // Only consider anti-dependence edges.
632 if (Edge->getKind() == SDep::Anti) {
633 AntiDepReg = Edge->getReg();
634 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
635 // Don't break anti-dependencies on non-allocatable registers.
Dan Gohman49bb50e2009-01-16 21:57:43 +0000636 if (!AllocatableSet.test(AntiDepReg))
637 AntiDepReg = 0;
638 else {
Dan Gohman00dc84a2008-12-16 19:27:52 +0000639 // If the SUnit has other dependencies on the SUnit that it
640 // anti-depends on, don't bother breaking the anti-dependency
641 // since those edges would prevent such units from being
642 // scheduled past each other regardless.
643 //
644 // Also, if there are dependencies on other SUnits with the
645 // same register as the anti-dependency, don't attempt to
646 // break it.
647 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
648 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
649 if (P->getSUnit() == NextSU ?
650 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
651 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
652 AntiDepReg = 0;
653 break;
654 }
655 }
656 }
657 CriticalPathSU = NextSU;
658 CriticalPathMI = CriticalPathSU->getInstr();
659 } else {
660 // We've reached the end of the critical path.
661 CriticalPathSU = 0;
662 CriticalPathMI = 0;
663 }
664 }
Dan Gohman21d90032008-11-25 00:52:40 +0000665
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000666 PrescanInstruction(MI);
667
668 // If this instruction has a use of AntiDepReg, breaking it
669 // is invalid.
Dan Gohman21d90032008-11-25 00:52:40 +0000670 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
671 MachineOperand &MO = MI->getOperand(i);
672 if (!MO.isReg()) continue;
673 unsigned Reg = MO.getReg();
674 if (Reg == 0) continue;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000675 if (MO.isUse() && AntiDepReg == Reg) {
Dan Gohman21d90032008-11-25 00:52:40 +0000676 AntiDepReg = 0;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000677 break;
Dan Gohman21d90032008-11-25 00:52:40 +0000678 }
Dan Gohman21d90032008-11-25 00:52:40 +0000679 }
680
681 // Determine AntiDepReg's register class, if it is live and is
682 // consistently used within a single class.
683 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
Nick Lewyckya89d1022008-11-27 17:29:52 +0000684 assert((AntiDepReg == 0 || RC != NULL) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000685 "Register should be live if it's causing an anti-dependence!");
686 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
687 AntiDepReg = 0;
688
689 // Look for a suitable register to use to break the anti-depenence.
690 //
691 // TODO: Instead of picking the first free register, consider which might
692 // be the best.
693 if (AntiDepReg != 0) {
Dan Gohman79ce2762009-01-15 19:20:50 +0000694 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
695 RE = RC->allocation_order_end(MF); R != RE; ++R) {
Dan Gohman21d90032008-11-25 00:52:40 +0000696 unsigned NewReg = *R;
697 // Don't replace a register with itself.
698 if (NewReg == AntiDepReg) continue;
699 // Don't replace a register with one that was recently used to repair
700 // an anti-dependence with this AntiDepReg, because that would
701 // re-introduce that anti-dependence.
702 if (NewReg == LastNewReg[AntiDepReg]) continue;
703 // If NewReg is dead and NewReg's most recent def is not before
704 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
Dan Gohman6c3643c2008-12-19 22:23:43 +0000705 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000706 "Kill and Def maps aren't consistent for AntiDepReg!");
Dan Gohman6c3643c2008-12-19 22:23:43 +0000707 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000708 "Kill and Def maps aren't consistent for NewReg!");
Dan Gohman6c3643c2008-12-19 22:23:43 +0000709 if (KillIndices[NewReg] == ~0u &&
Dan Gohmanfde221f2008-12-16 06:20:58 +0000710 Classes[NewReg] != reinterpret_cast<TargetRegisterClass *>(-1) &&
Dan Gohman21d90032008-11-25 00:52:40 +0000711 KillIndices[AntiDepReg] <= DefIndices[NewReg]) {
Dan Gohman80e201b2008-12-04 02:15:26 +0000712 DOUT << "Breaking anti-dependence edge on "
713 << TRI->getName(AntiDepReg)
Dan Gohmancef874a2008-12-03 23:07:27 +0000714 << " with " << RegRefs.count(AntiDepReg) << " references"
Dan Gohman80e201b2008-12-04 02:15:26 +0000715 << " using " << TRI->getName(NewReg) << "!\n";
Dan Gohman21d90032008-11-25 00:52:40 +0000716
717 // Update the references to the old register to refer to the new
718 // register.
719 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
720 std::multimap<unsigned, MachineOperand *>::iterator>
721 Range = RegRefs.equal_range(AntiDepReg);
722 for (std::multimap<unsigned, MachineOperand *>::iterator
723 Q = Range.first, QE = Range.second; Q != QE; ++Q)
724 Q->second->setReg(NewReg);
725
726 // We just went back in time and modified history; the
727 // liveness information for the anti-depenence reg is now
728 // inconsistent. Set the state as if it were dead.
729 Classes[NewReg] = Classes[AntiDepReg];
730 DefIndices[NewReg] = DefIndices[AntiDepReg];
731 KillIndices[NewReg] = KillIndices[AntiDepReg];
732
733 Classes[AntiDepReg] = 0;
734 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
Dan Gohman6c3643c2008-12-19 22:23:43 +0000735 KillIndices[AntiDepReg] = ~0u;
Dan Gohman21d90032008-11-25 00:52:40 +0000736
737 RegRefs.erase(AntiDepReg);
738 Changed = true;
739 LastNewReg[AntiDepReg] = NewReg;
740 break;
741 }
742 }
743 }
744
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000745 ScanInstruction(MI, Count);
Dan Gohman21d90032008-11-25 00:52:40 +0000746 }
Dan Gohman6c3643c2008-12-19 22:23:43 +0000747 assert(Count == ~0u && "Count mismatch!");
Dan Gohman21d90032008-11-25 00:52:40 +0000748
749 return Changed;
750}
751
Dan Gohman343f0c02008-11-19 23:18:57 +0000752//===----------------------------------------------------------------------===//
753// Top-Down Scheduling
754//===----------------------------------------------------------------------===//
755
756/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
757/// the PendingQueue if the count reaches zero. Also update its cycle bound.
Dan Gohman54e4c362008-12-09 22:54:47 +0000758void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
759 SUnit *SuccSU = SuccEdge->getSUnit();
Dan Gohman343f0c02008-11-19 23:18:57 +0000760 --SuccSU->NumPredsLeft;
761
762#ifndef NDEBUG
763 if (SuccSU->NumPredsLeft < 0) {
764 cerr << "*** Scheduling failed! ***\n";
765 SuccSU->dump(this);
766 cerr << " has been released too many times!\n";
767 assert(0);
768 }
769#endif
770
771 // Compute how many cycles it will be before this actually becomes
772 // available. This is the max of the start time of all predecessors plus
773 // their latencies.
Dan Gohman3f237442008-12-16 03:25:46 +0000774 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
Dan Gohman343f0c02008-11-19 23:18:57 +0000775
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000776 // If all the node's predecessors are scheduled, this node is ready
777 // to be scheduled. Ignore the special ExitSU node.
778 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
Dan Gohman343f0c02008-11-19 23:18:57 +0000779 PendingQueue.push_back(SuccSU);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000780}
781
782/// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
783void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
784 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
785 I != E; ++I)
786 ReleaseSucc(SU, &*I);
Dan Gohman343f0c02008-11-19 23:18:57 +0000787}
788
789/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
790/// count of its successors. If a successor pending count is zero, add it to
791/// the Available queue.
792void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
793 DOUT << "*** Scheduling [" << CurCycle << "]: ";
794 DEBUG(SU->dump(this));
795
796 Sequence.push_back(SU);
Dan Gohman3f237442008-12-16 03:25:46 +0000797 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
798 SU->setDepthToAtLeast(CurCycle);
Dan Gohman343f0c02008-11-19 23:18:57 +0000799
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000800 ReleaseSuccessors(SU);
Dan Gohman343f0c02008-11-19 23:18:57 +0000801 SU->isScheduled = true;
802 AvailableQueue.ScheduledNode(SU);
803}
804
805/// ListScheduleTopDown - The main loop of list scheduling for top-down
806/// schedulers.
807void SchedulePostRATDList::ListScheduleTopDown() {
808 unsigned CurCycle = 0;
809
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000810 // Release any successors of the special Entry node.
811 ReleaseSuccessors(&EntrySU);
812
Dan Gohman343f0c02008-11-19 23:18:57 +0000813 // All leaves to Available queue.
814 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
815 // It is available if it has no predecessors.
816 if (SUnits[i].Preds.empty()) {
817 AvailableQueue.push(&SUnits[i]);
818 SUnits[i].isAvailable = true;
819 }
820 }
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000821
Dan Gohman343f0c02008-11-19 23:18:57 +0000822 // While Available queue is not empty, grab the node with the highest
823 // priority. If it is not ready put it back. Schedule the node.
Dan Gohman2836c282009-01-16 01:33:36 +0000824 std::vector<SUnit*> NotReady;
Dan Gohman343f0c02008-11-19 23:18:57 +0000825 Sequence.reserve(SUnits.size());
826 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
827 // Check to see if any of the pending instructions are ready to issue. If
828 // so, add them to the available queue.
Dan Gohman3f237442008-12-16 03:25:46 +0000829 unsigned MinDepth = ~0u;
Dan Gohman343f0c02008-11-19 23:18:57 +0000830 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
Dan Gohman3f237442008-12-16 03:25:46 +0000831 if (PendingQueue[i]->getDepth() <= CurCycle) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000832 AvailableQueue.push(PendingQueue[i]);
833 PendingQueue[i]->isAvailable = true;
834 PendingQueue[i] = PendingQueue.back();
835 PendingQueue.pop_back();
836 --i; --e;
Dan Gohman3f237442008-12-16 03:25:46 +0000837 } else if (PendingQueue[i]->getDepth() < MinDepth)
838 MinDepth = PendingQueue[i]->getDepth();
Dan Gohman343f0c02008-11-19 23:18:57 +0000839 }
840
Dan Gohman2836c282009-01-16 01:33:36 +0000841 // If there are no instructions available, don't try to issue anything, and
842 // don't advance the hazard recognizer.
Dan Gohman343f0c02008-11-19 23:18:57 +0000843 if (AvailableQueue.empty()) {
Dan Gohman3f237442008-12-16 03:25:46 +0000844 CurCycle = MinDepth != ~0u ? MinDepth : CurCycle + 1;
Dan Gohman343f0c02008-11-19 23:18:57 +0000845 continue;
846 }
847
Dan Gohman2836c282009-01-16 01:33:36 +0000848 SUnit *FoundSUnit = 0;
849
850 bool HasNoopHazards = false;
851 while (!AvailableQueue.empty()) {
852 SUnit *CurSUnit = AvailableQueue.pop();
853
854 ScheduleHazardRecognizer::HazardType HT =
855 HazardRec->getHazardType(CurSUnit);
856 if (HT == ScheduleHazardRecognizer::NoHazard) {
857 FoundSUnit = CurSUnit;
858 break;
859 }
860
861 // Remember if this is a noop hazard.
862 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
863
864 NotReady.push_back(CurSUnit);
865 }
866
867 // Add the nodes that aren't ready back onto the available list.
868 if (!NotReady.empty()) {
869 AvailableQueue.push_all(NotReady);
870 NotReady.clear();
871 }
872
Dan Gohman343f0c02008-11-19 23:18:57 +0000873 // If we found a node to schedule, do it now.
874 if (FoundSUnit) {
875 ScheduleNodeTopDown(FoundSUnit, CurCycle);
Dan Gohman2836c282009-01-16 01:33:36 +0000876 HazardRec->EmitInstruction(FoundSUnit);
Dan Gohman343f0c02008-11-19 23:18:57 +0000877
878 // If this is a pseudo-op node, we don't want to increment the current
879 // cycle.
880 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
Dan Gohman2836c282009-01-16 01:33:36 +0000881 ++CurCycle;
882 } else if (!HasNoopHazards) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000883 // Otherwise, we have a pipeline stall, but no other problem, just advance
884 // the current cycle and try again.
885 DOUT << "*** Advancing cycle, no work to do\n";
Dan Gohman2836c282009-01-16 01:33:36 +0000886 HazardRec->AdvanceCycle();
Dan Gohman343f0c02008-11-19 23:18:57 +0000887 ++NumStalls;
888 ++CurCycle;
Dan Gohman2836c282009-01-16 01:33:36 +0000889 } else {
890 // Otherwise, we have no instructions to issue and we have instructions
891 // that will fault if we don't do this right. This is the case for
892 // processors without pipeline interlocks and other cases.
893 DOUT << "*** Emitting noop\n";
894 HazardRec->EmitNoop();
895 Sequence.push_back(0); // NULL here means noop
896 ++NumNoops;
897 ++CurCycle;
Dan Gohman343f0c02008-11-19 23:18:57 +0000898 }
899 }
900
901#ifndef NDEBUG
Dan Gohmana1e6d362008-11-20 01:26:25 +0000902 VerifySchedule(/*isBottomUp=*/false);
Dan Gohman343f0c02008-11-19 23:18:57 +0000903#endif
904}
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000905
906//===----------------------------------------------------------------------===//
907// Public Constructor Functions
908//===----------------------------------------------------------------------===//
909
910FunctionPass *llvm::createPostRAScheduler() {
Dan Gohman343f0c02008-11-19 23:18:57 +0000911 return new PostRAScheduler();
Dale Johannesene7e7d0d2007-07-13 17:13:54 +0000912}