1 //===----- ScheduleDAGFast.cpp - Fast poor list scheduler -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements a fast scheduler.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "pre-RA-sched"
15 #include "llvm/CodeGen/ScheduleDAG.h"
16 #include "llvm/CodeGen/SchedulerRegistry.h"
17 #include "llvm/Target/TargetRegisterInfo.h"
18 #include "llvm/Target/TargetData.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetInstrInfo.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/CommandLine.h"
29 STATISTIC(NumUnfolds, "Number of nodes unfolded");
30 STATISTIC(NumDups, "Number of duplicated nodes");
31 STATISTIC(NumCCCopies, "Number of cross class copies");
33 static RegisterScheduler
34 fastDAGScheduler("fast", " Fast suboptimal list scheduling",
35 createFastDAGScheduler);
38 /// FastPriorityQueue - A degenerate priority queue that considers
39 /// all nodes to have the same priority.
41 struct VISIBILITY_HIDDEN FastPriorityQueue {
42 std::vector<SUnit *> Queue;
44 bool empty() const { return Queue.empty(); }
51 if (empty()) return NULL;
52 SUnit *V = Queue.back();
58 //===----------------------------------------------------------------------===//
59 /// ScheduleDAGFast - The actual "fast" list scheduler implementation.
61 class VISIBILITY_HIDDEN ScheduleDAGFast : public ScheduleDAG {
63 /// AvailableQueue - The priority queue to use for the available SUnits.
64 FastPriorityQueue AvailableQueue;
66 /// LiveRegs / LiveRegDefs - A set of physical registers and their definition
67 /// that are "live". These nodes must be scheduled before any other nodes that
68 /// modifies the registers can be scheduled.
69 SmallSet<unsigned, 4> LiveRegs;
70 std::vector<SUnit*> LiveRegDefs;
71 std::vector<unsigned> LiveRegCycles;
74 ScheduleDAGFast(SelectionDAG &dag, MachineBasicBlock *bb,
75 const TargetMachine &tm)
76 : ScheduleDAG(dag, bb, tm) {}
80 /// AddPred - This adds the specified node X as a predecessor of
81 /// the current node Y if not already.
82 /// This returns true if this is a new predecessor.
83 bool AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
84 unsigned PhyReg = 0, int Cost = 1);
86 /// RemovePred - This removes the specified node N from the predecessors of
87 /// the current node M.
88 bool RemovePred(SUnit *M, SUnit *N, bool isCtrl, bool isSpecial);
91 void ReleasePred(SUnit*, bool, unsigned);
92 void ScheduleNodeBottomUp(SUnit*, unsigned);
93 SUnit *CopyAndMoveSuccessors(SUnit*);
94 void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
95 const TargetRegisterClass*,
96 const TargetRegisterClass*,
97 SmallVector<SUnit*, 2>&);
98 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
99 void ListScheduleBottomUp();
101 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
102 SUnit *CreateNewSUnit(SDNode *N) {
103 SUnit *NewNode = NewSUnit(N);
107 /// CreateClone - Creates a new SUnit from an existing one.
108 SUnit *CreateClone(SUnit *N) {
109 SUnit *NewNode = Clone(N);
113 } // end anonymous namespace
116 /// Schedule - Schedule the DAG using list scheduling.
117 void ScheduleDAGFast::Schedule() {
118 DOUT << "********** List Scheduling **********\n";
120 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
121 LiveRegCycles.resize(TRI->getNumRegs(), 0);
123 // Build scheduling units.
126 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
127 SUnits[su].dumpAll(&DAG));
129 // Execute the actual scheduling loop.
130 ListScheduleBottomUp();
133 //===----------------------------------------------------------------------===//
134 // Bottom-Up Scheduling
135 //===----------------------------------------------------------------------===//
137 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
138 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
139 void ScheduleDAGFast::ReleasePred(SUnit *PredSU, bool isChain,
141 // FIXME: the distance between two nodes is not always == the predecessor's
142 // latency. For example, the reader can very well read the register written
143 // by the predecessor later than the issue cycle. It also depends on the
144 // interrupt model (drain vs. freeze).
145 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
147 --PredSU->NumSuccsLeft;
150 if (PredSU->NumSuccsLeft < 0) {
151 cerr << "*** List scheduling failed! ***\n";
153 cerr << " has been released too many times!\n";
158 if (PredSU->NumSuccsLeft == 0) {
159 PredSU->isAvailable = true;
160 AvailableQueue.push(PredSU);
164 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
165 /// count of its predecessors. If a predecessor pending count is zero, add it to
166 /// the Available queue.
167 void ScheduleDAGFast::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
168 DOUT << "*** Scheduling [" << CurCycle << "]: ";
169 DEBUG(SU->dump(&DAG));
170 SU->Cycle = CurCycle;
172 // Bottom up: release predecessors
173 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
175 ReleasePred(I->Dep, I->isCtrl, CurCycle);
177 // This is a physical register dependency and it's impossible or
178 // expensive to copy the register. Make sure nothing that can
179 // clobber the register is scheduled between the predecessor and
181 if (LiveRegs.insert(I->Reg)) {
182 LiveRegDefs[I->Reg] = I->Dep;
183 LiveRegCycles[I->Reg] = CurCycle;
188 // Release all the implicit physical register defs that are live.
189 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
192 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
193 LiveRegs.erase(I->Reg);
194 assert(LiveRegDefs[I->Reg] == SU &&
195 "Physical register dependency violated?");
196 LiveRegDefs[I->Reg] = NULL;
197 LiveRegCycles[I->Reg] = 0;
202 SU->isScheduled = true;
205 /// AddPred - adds an edge from SUnit X to SUnit Y.
206 bool ScheduleDAGFast::AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
207 unsigned PhyReg, int Cost) {
208 return Y->addPred(X, isCtrl, isSpecial, PhyReg, Cost);
211 /// RemovePred - This removes the specified node N from the predecessors of
212 /// the current node M.
213 bool ScheduleDAGFast::RemovePred(SUnit *M, SUnit *N,
214 bool isCtrl, bool isSpecial) {
215 return M->removePred(N, isCtrl, isSpecial);
218 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
219 /// successors to the newly created node.
220 SUnit *ScheduleDAGFast::CopyAndMoveSuccessors(SUnit *SU) {
221 if (SU->FlaggedNodes.size())
224 SDNode *N = SU->Node;
229 bool TryUnfold = false;
230 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
231 MVT VT = N->getValueType(i);
234 else if (VT == MVT::Other)
237 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
238 const SDValue &Op = N->getOperand(i);
239 MVT VT = Op.getNode()->getValueType(Op.getResNo());
245 SmallVector<SDNode*, 2> NewNodes;
246 if (!TII->unfoldMemoryOperand(DAG, N, NewNodes))
249 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
250 assert(NewNodes.size() == 2 && "Expected a load folding node!");
253 SDNode *LoadNode = NewNodes[0];
254 unsigned NumVals = N->getNumValues();
255 unsigned OldNumVals = SU->Node->getNumValues();
256 for (unsigned i = 0; i != NumVals; ++i)
257 DAG.ReplaceAllUsesOfValueWith(SDValue(SU->Node, i), SDValue(N, i));
258 DAG.ReplaceAllUsesOfValueWith(SDValue(SU->Node, OldNumVals-1),
259 SDValue(LoadNode, 1));
261 SUnit *NewSU = CreateNewSUnit(N);
262 assert(N->getNodeId() == -1 && "Node already inserted!");
263 N->setNodeId(NewSU->NodeNum);
265 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
266 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
267 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
268 NewSU->isTwoAddress = true;
272 if (TID.isCommutable())
273 NewSU->isCommutable = true;
274 // FIXME: Calculate height / depth and propagate the changes?
275 NewSU->Depth = SU->Depth;
276 NewSU->Height = SU->Height;
277 ComputeLatency(NewSU);
279 // LoadNode may already exist. This can happen when there is another
280 // load from the same location and producing the same type of value
281 // but it has different alignment or volatileness.
282 bool isNewLoad = true;
284 if (LoadNode->getNodeId() != -1) {
285 LoadSU = &SUnits[LoadNode->getNodeId()];
288 LoadSU = CreateNewSUnit(LoadNode);
289 LoadNode->setNodeId(LoadSU->NodeNum);
291 LoadSU->Depth = SU->Depth;
292 LoadSU->Height = SU->Height;
293 ComputeLatency(LoadSU);
296 SUnit *ChainPred = NULL;
297 SmallVector<SDep, 4> ChainSuccs;
298 SmallVector<SDep, 4> LoadPreds;
299 SmallVector<SDep, 4> NodePreds;
300 SmallVector<SDep, 4> NodeSuccs;
301 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
305 else if (I->Dep->Node && I->Dep->Node->isOperandOf(LoadNode))
306 LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
308 NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
310 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
313 ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
314 I->isCtrl, I->isSpecial));
316 NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
317 I->isCtrl, I->isSpecial));
321 RemovePred(SU, ChainPred, true, false);
323 AddPred(LoadSU, ChainPred, true, false);
325 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
326 SDep *Pred = &LoadPreds[i];
327 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
329 AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
330 Pred->Reg, Pred->Cost);
333 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
334 SDep *Pred = &NodePreds[i];
335 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
336 AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
337 Pred->Reg, Pred->Cost);
339 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
340 SDep *Succ = &NodeSuccs[i];
341 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
342 AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isSpecial,
343 Succ->Reg, Succ->Cost);
345 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
346 SDep *Succ = &ChainSuccs[i];
347 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
349 AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isSpecial,
350 Succ->Reg, Succ->Cost);
354 AddPred(NewSU, LoadSU, false, false);
359 if (NewSU->NumSuccsLeft == 0) {
360 NewSU->isAvailable = true;
366 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
367 NewSU = CreateClone(SU);
369 // New SUnit has the exact same predecessors.
370 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
373 AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
374 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
377 // Only copy scheduled successors. Cut them from old node's successor
378 // list and move them over.
379 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
380 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
384 if (I->Dep->isScheduled) {
385 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
386 AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
387 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
390 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
391 SUnit *Succ = DelDeps[i].first;
392 bool isCtrl = DelDeps[i].second;
393 RemovePred(Succ, SU, isCtrl, false);
400 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
401 /// and move all scheduled successors of the given SUnit to the last copy.
402 void ScheduleDAGFast::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
403 const TargetRegisterClass *DestRC,
404 const TargetRegisterClass *SrcRC,
405 SmallVector<SUnit*, 2> &Copies) {
406 SUnit *CopyFromSU = CreateNewSUnit(NULL);
407 CopyFromSU->CopySrcRC = SrcRC;
408 CopyFromSU->CopyDstRC = DestRC;
410 SUnit *CopyToSU = CreateNewSUnit(NULL);
411 CopyToSU->CopySrcRC = DestRC;
412 CopyToSU->CopyDstRC = SrcRC;
414 // Only copy scheduled successors. Cut them from old node's successor
415 // list and move them over.
416 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
417 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
421 if (I->Dep->isScheduled) {
422 AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
423 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
426 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
427 SUnit *Succ = DelDeps[i].first;
428 bool isCtrl = DelDeps[i].second;
429 RemovePred(Succ, SU, isCtrl, false);
432 AddPred(CopyFromSU, SU, false, false, Reg, -1);
433 AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
435 Copies.push_back(CopyFromSU);
436 Copies.push_back(CopyToSU);
441 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
442 /// definition of the specified node.
443 /// FIXME: Move to SelectionDAG?
444 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
445 const TargetInstrInfo *TII) {
446 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
447 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
448 unsigned NumRes = TID.getNumDefs();
449 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
454 return N->getValueType(NumRes);
457 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
458 /// scheduling of the given node to satisfy live physical register dependencies.
459 /// If the specific node is the last one that's available to schedule, do
460 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
461 bool ScheduleDAGFast::DelayForLiveRegsBottomUp(SUnit *SU,
462 SmallVector<unsigned, 4> &LRegs){
463 if (LiveRegs.empty())
466 SmallSet<unsigned, 4> RegAdded;
467 // If this node would clobber any "live" register, then it's not ready.
468 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
471 unsigned Reg = I->Reg;
472 if (LiveRegs.count(Reg) && LiveRegDefs[Reg] != I->Dep) {
473 if (RegAdded.insert(Reg))
474 LRegs.push_back(Reg);
476 for (const unsigned *Alias = TRI->getAliasSet(Reg);
478 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != I->Dep) {
479 if (RegAdded.insert(*Alias))
480 LRegs.push_back(*Alias);
485 for (unsigned i = 0, e = SU->FlaggedNodes.size()+1; i != e; ++i) {
486 SDNode *Node = (i == 0) ? SU->Node : SU->FlaggedNodes[i-1];
487 if (!Node || !Node->isMachineOpcode())
489 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
490 if (!TID.ImplicitDefs)
492 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
493 if (LiveRegs.count(*Reg) && LiveRegDefs[*Reg] != SU) {
494 if (RegAdded.insert(*Reg))
495 LRegs.push_back(*Reg);
497 for (const unsigned *Alias = TRI->getAliasSet(*Reg);
499 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != SU) {
500 if (RegAdded.insert(*Alias))
501 LRegs.push_back(*Alias);
505 return !LRegs.empty();
509 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
511 void ScheduleDAGFast::ListScheduleBottomUp() {
512 unsigned CurCycle = 0;
513 // Add root to Available queue.
514 if (!SUnits.empty()) {
515 SUnit *RootSU = &SUnits[DAG.getRoot().getNode()->getNodeId()];
516 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
517 RootSU->isAvailable = true;
518 AvailableQueue.push(RootSU);
521 // While Available queue is not empty, grab the node with the highest
522 // priority. If it is not ready put it back. Schedule the node.
523 SmallVector<SUnit*, 4> NotReady;
524 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
525 Sequence.reserve(SUnits.size());
526 while (!AvailableQueue.empty()) {
527 bool Delayed = false;
529 SUnit *CurSU = AvailableQueue.pop();
531 if (CurSU->CycleBound <= CurCycle) {
532 SmallVector<unsigned, 4> LRegs;
533 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
536 LRegsMap.insert(std::make_pair(CurSU, LRegs));
539 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
540 NotReady.push_back(CurSU);
541 CurSU = AvailableQueue.pop();
544 // All candidates are delayed due to live physical reg dependencies.
545 // Try code duplication or inserting cross class copies
547 if (Delayed && !CurSU) {
549 // Try duplicating the nodes that produces these
550 // "expensive to copy" values to break the dependency. In case even
551 // that doesn't work, insert cross class copies.
552 SUnit *TrySU = NotReady[0];
553 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
554 assert(LRegs.size() == 1 && "Can't handle this yet!");
555 unsigned Reg = LRegs[0];
556 SUnit *LRDef = LiveRegDefs[Reg];
557 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
559 // Issue expensive cross register class copies.
560 MVT VT = getPhysicalRegisterVT(LRDef->Node, Reg, TII);
561 const TargetRegisterClass *RC =
562 TRI->getPhysicalRegisterRegClass(Reg, VT);
563 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
565 assert(false && "Don't know how to copy this physical register!");
568 SmallVector<SUnit*, 2> Copies;
569 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
570 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
571 << " to SU #" << Copies.front()->NodeNum << "\n";
572 AddPred(TrySU, Copies.front(), true, true);
573 NewDef = Copies.back();
576 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
577 << " to SU #" << TrySU->NodeNum << "\n";
578 LiveRegDefs[Reg] = NewDef;
579 AddPred(NewDef, TrySU, true, true);
580 TrySU->isAvailable = false;
585 assert(false && "Unable to resolve live physical register dependencies!");
590 // Add the nodes that aren't ready back onto the available list.
591 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
592 NotReady[i]->isPending = false;
593 // May no longer be available due to backtracking.
594 if (NotReady[i]->isAvailable)
595 AvailableQueue.push(NotReady[i]);
600 Sequence.push_back(0);
602 ScheduleNodeBottomUp(CurSU, CurCycle);
603 Sequence.push_back(CurSU);
608 // Reverse the order if it is bottom up.
609 std::reverse(Sequence.begin(), Sequence.end());
613 // Verify that all SUnits were scheduled.
614 bool AnyNotSched = false;
615 unsigned DeadNodes = 0;
617 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
618 if (!SUnits[i].isScheduled) {
619 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
624 cerr << "*** List scheduling failed! ***\n";
625 SUnits[i].dump(&DAG);
626 cerr << "has not been scheduled!\n";
629 if (SUnits[i].NumSuccsLeft != 0) {
631 cerr << "*** List scheduling failed! ***\n";
632 SUnits[i].dump(&DAG);
633 cerr << "has successors left!\n";
637 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
640 assert(!AnyNotSched);
641 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
642 "The number of nodes scheduled doesn't match the expected number!");
646 //===----------------------------------------------------------------------===//
647 // Public Constructor Functions
648 //===----------------------------------------------------------------------===//
650 llvm::ScheduleDAG* llvm::createFastDAGScheduler(SelectionDAGISel *IS,
652 MachineBasicBlock *BB, bool) {
653 return new ScheduleDAGFast(*DAG, BB, DAG->getTarget());