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 SmallVector<SUnit *, 16> 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 /// 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.
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";
121 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
122 LiveRegCycles.resize(TRI->getNumRegs(), 0);
124 // Build scheduling units.
127 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
128 SUnits[su].dumpAll(DAG));
130 // Execute the actual scheduling loop.
131 ListScheduleBottomUp();
134 //===----------------------------------------------------------------------===//
135 // Bottom-Up Scheduling
136 //===----------------------------------------------------------------------===//
138 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
139 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
140 void ScheduleDAGFast::ReleasePred(SUnit *PredSU, bool isChain,
142 --PredSU->NumSuccsLeft;
145 if (PredSU->NumSuccsLeft < 0) {
146 cerr << "*** List scheduling failed! ***\n";
148 cerr << " has been released too many times!\n";
153 if (PredSU->NumSuccsLeft == 0) {
154 PredSU->isAvailable = true;
155 AvailableQueue.push(PredSU);
159 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
160 /// count of its predecessors. If a predecessor pending count is zero, add it to
161 /// the Available queue.
162 void ScheduleDAGFast::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
163 DOUT << "*** Scheduling [" << CurCycle << "]: ";
164 DEBUG(SU->dump(DAG));
165 SU->Cycle = CurCycle;
167 // Bottom up: release predecessors
168 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
170 ReleasePred(I->Dep, I->isCtrl, CurCycle);
172 // This is a physical register dependency and it's impossible or
173 // expensive to copy the register. Make sure nothing that can
174 // clobber the register is scheduled between the predecessor and
176 if (!LiveRegDefs[I->Reg]) {
178 LiveRegDefs[I->Reg] = I->Dep;
179 LiveRegCycles[I->Reg] = CurCycle;
184 // Release all the implicit physical register defs that are live.
185 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
188 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
189 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
190 assert(LiveRegDefs[I->Reg] == SU &&
191 "Physical register dependency violated?");
193 LiveRegDefs[I->Reg] = NULL;
194 LiveRegCycles[I->Reg] = 0;
199 SU->isScheduled = true;
202 /// AddPred - adds an edge from SUnit X to SUnit Y.
203 bool ScheduleDAGFast::AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
204 unsigned PhyReg, int Cost) {
205 return Y->addPred(X, isCtrl, isSpecial, PhyReg, Cost);
208 /// RemovePred - This removes the specified node N from the predecessors of
209 /// the current node M.
210 bool ScheduleDAGFast::RemovePred(SUnit *M, SUnit *N,
211 bool isCtrl, bool isSpecial) {
212 return M->removePred(N, isCtrl, isSpecial);
215 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
216 /// successors to the newly created node.
217 SUnit *ScheduleDAGFast::CopyAndMoveSuccessors(SUnit *SU) {
218 if (SU->getNode()->getFlaggedNode())
221 SDNode *N = SU->getNode();
226 bool TryUnfold = false;
227 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
228 MVT VT = N->getValueType(i);
231 else if (VT == MVT::Other)
234 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
235 const SDValue &Op = N->getOperand(i);
236 MVT VT = Op.getNode()->getValueType(Op.getResNo());
242 SmallVector<SDNode*, 2> NewNodes;
243 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
246 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
247 assert(NewNodes.size() == 2 && "Expected a load folding node!");
250 SDNode *LoadNode = NewNodes[0];
251 unsigned NumVals = N->getNumValues();
252 unsigned OldNumVals = SU->getNode()->getNumValues();
253 for (unsigned i = 0; i != NumVals; ++i)
254 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
255 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
256 SDValue(LoadNode, 1));
258 SUnit *NewSU = CreateNewSUnit(N);
259 assert(N->getNodeId() == -1 && "Node already inserted!");
260 N->setNodeId(NewSU->NodeNum);
262 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
263 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
264 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
265 NewSU->isTwoAddress = true;
269 if (TID.isCommutable())
270 NewSU->isCommutable = true;
271 // FIXME: Calculate height / depth and propagate the changes?
272 NewSU->Depth = SU->Depth;
273 NewSU->Height = SU->Height;
275 // LoadNode may already exist. This can happen when there is another
276 // load from the same location and producing the same type of value
277 // but it has different alignment or volatileness.
278 bool isNewLoad = true;
280 if (LoadNode->getNodeId() != -1) {
281 LoadSU = &SUnits[LoadNode->getNodeId()];
284 LoadSU = CreateNewSUnit(LoadNode);
285 LoadNode->setNodeId(LoadSU->NodeNum);
287 LoadSU->Depth = SU->Depth;
288 LoadSU->Height = SU->Height;
291 SUnit *ChainPred = NULL;
292 SmallVector<SDep, 4> ChainSuccs;
293 SmallVector<SDep, 4> LoadPreds;
294 SmallVector<SDep, 4> NodePreds;
295 SmallVector<SDep, 4> NodeSuccs;
296 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
300 else if (I->Dep->getNode() && I->Dep->getNode()->isOperandOf(LoadNode))
301 LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
303 NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
305 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
308 ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
309 I->isCtrl, I->isSpecial));
311 NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
312 I->isCtrl, I->isSpecial));
316 RemovePred(SU, ChainPred, true, false);
318 AddPred(LoadSU, ChainPred, true, false);
320 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
321 SDep *Pred = &LoadPreds[i];
322 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
324 AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
325 Pred->Reg, Pred->Cost);
328 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
329 SDep *Pred = &NodePreds[i];
330 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
331 AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
332 Pred->Reg, Pred->Cost);
334 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
335 SDep *Succ = &NodeSuccs[i];
336 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
337 AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isSpecial,
338 Succ->Reg, Succ->Cost);
340 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
341 SDep *Succ = &ChainSuccs[i];
342 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
344 AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isSpecial,
345 Succ->Reg, Succ->Cost);
349 AddPred(NewSU, LoadSU, false, false);
354 if (NewSU->NumSuccsLeft == 0) {
355 NewSU->isAvailable = true;
361 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
362 NewSU = CreateClone(SU);
364 // New SUnit has the exact same predecessors.
365 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
368 AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
369 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
372 // Only copy scheduled successors. Cut them from old node's successor
373 // list and move them over.
374 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
375 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
379 if (I->Dep->isScheduled) {
380 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
381 AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
382 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
385 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
386 SUnit *Succ = DelDeps[i].first;
387 bool isCtrl = DelDeps[i].second;
388 RemovePred(Succ, SU, isCtrl, false);
395 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
396 /// and move all scheduled successors of the given SUnit to the last copy.
397 void ScheduleDAGFast::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
398 const TargetRegisterClass *DestRC,
399 const TargetRegisterClass *SrcRC,
400 SmallVector<SUnit*, 2> &Copies) {
401 SUnit *CopyFromSU = CreateNewSUnit(NULL);
402 CopyFromSU->CopySrcRC = SrcRC;
403 CopyFromSU->CopyDstRC = DestRC;
405 SUnit *CopyToSU = CreateNewSUnit(NULL);
406 CopyToSU->CopySrcRC = DestRC;
407 CopyToSU->CopyDstRC = SrcRC;
409 // Only copy scheduled successors. Cut them from old node's successor
410 // list and move them over.
411 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
412 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
416 if (I->Dep->isScheduled) {
417 AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
418 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
421 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
422 SUnit *Succ = DelDeps[i].first;
423 bool isCtrl = DelDeps[i].second;
424 RemovePred(Succ, SU, isCtrl, false);
427 AddPred(CopyFromSU, SU, false, false, Reg, -1);
428 AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
430 Copies.push_back(CopyFromSU);
431 Copies.push_back(CopyToSU);
436 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
437 /// definition of the specified node.
438 /// FIXME: Move to SelectionDAG?
439 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
440 const TargetInstrInfo *TII) {
441 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
442 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
443 unsigned NumRes = TID.getNumDefs();
444 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
449 return N->getValueType(NumRes);
452 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
453 /// scheduling of the given node to satisfy live physical register dependencies.
454 /// If the specific node is the last one that's available to schedule, do
455 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
456 bool ScheduleDAGFast::DelayForLiveRegsBottomUp(SUnit *SU,
457 SmallVector<unsigned, 4> &LRegs){
458 if (NumLiveRegs == 0)
461 SmallSet<unsigned, 4> RegAdded;
462 // If this node would clobber any "live" register, then it's not ready.
463 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
466 unsigned Reg = I->Reg;
467 if (LiveRegDefs[Reg] && LiveRegDefs[Reg] != I->Dep) {
468 if (RegAdded.insert(Reg))
469 LRegs.push_back(Reg);
471 for (const unsigned *Alias = TRI->getAliasSet(Reg);
473 if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != I->Dep) {
474 if (RegAdded.insert(*Alias))
475 LRegs.push_back(*Alias);
480 for (SDNode *Node = SU->getNode(); Node; Node = Node->getFlaggedNode()) {
481 if (!Node->isMachineOpcode())
483 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
484 if (!TID.ImplicitDefs)
486 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
487 if (LiveRegDefs[*Reg] && LiveRegDefs[*Reg] != SU) {
488 if (RegAdded.insert(*Reg))
489 LRegs.push_back(*Reg);
491 for (const unsigned *Alias = TRI->getAliasSet(*Reg);
493 if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != SU) {
494 if (RegAdded.insert(*Alias))
495 LRegs.push_back(*Alias);
499 return !LRegs.empty();
503 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
505 void ScheduleDAGFast::ListScheduleBottomUp() {
506 unsigned CurCycle = 0;
507 // Add root to Available queue.
508 if (!SUnits.empty()) {
509 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
510 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
511 RootSU->isAvailable = true;
512 AvailableQueue.push(RootSU);
515 // While Available queue is not empty, grab the node with the highest
516 // priority. If it is not ready put it back. Schedule the node.
517 SmallVector<SUnit*, 4> NotReady;
518 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
519 Sequence.reserve(SUnits.size());
520 while (!AvailableQueue.empty()) {
521 bool Delayed = false;
523 SUnit *CurSU = AvailableQueue.pop();
525 SmallVector<unsigned, 4> LRegs;
526 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
529 LRegsMap.insert(std::make_pair(CurSU, LRegs));
531 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
532 NotReady.push_back(CurSU);
533 CurSU = AvailableQueue.pop();
536 // All candidates are delayed due to live physical reg dependencies.
537 // Try code duplication or inserting cross class copies
539 if (Delayed && !CurSU) {
541 // Try duplicating the nodes that produces these
542 // "expensive to copy" values to break the dependency. In case even
543 // that doesn't work, insert cross class copies.
544 SUnit *TrySU = NotReady[0];
545 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
546 assert(LRegs.size() == 1 && "Can't handle this yet!");
547 unsigned Reg = LRegs[0];
548 SUnit *LRDef = LiveRegDefs[Reg];
549 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
551 // Issue expensive cross register class copies.
552 MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
553 const TargetRegisterClass *RC =
554 TRI->getPhysicalRegisterRegClass(Reg, VT);
555 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
557 assert(false && "Don't know how to copy this physical register!");
560 SmallVector<SUnit*, 2> Copies;
561 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
562 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
563 << " to SU #" << Copies.front()->NodeNum << "\n";
564 AddPred(TrySU, Copies.front(), true, true);
565 NewDef = Copies.back();
568 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
569 << " to SU #" << TrySU->NodeNum << "\n";
570 LiveRegDefs[Reg] = NewDef;
571 AddPred(NewDef, TrySU, true, true);
572 TrySU->isAvailable = false;
577 assert(false && "Unable to resolve live physical register dependencies!");
582 // Add the nodes that aren't ready back onto the available list.
583 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
584 NotReady[i]->isPending = false;
585 // May no longer be available due to backtracking.
586 if (NotReady[i]->isAvailable)
587 AvailableQueue.push(NotReady[i]);
592 Sequence.push_back(0);
594 ScheduleNodeBottomUp(CurSU, CurCycle);
595 Sequence.push_back(CurSU);
600 // Reverse the order if it is bottom up.
601 std::reverse(Sequence.begin(), Sequence.end());
605 // Verify that all SUnits were scheduled.
606 bool AnyNotSched = false;
607 unsigned DeadNodes = 0;
609 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
610 if (!SUnits[i].isScheduled) {
611 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
616 cerr << "*** List scheduling failed! ***\n";
618 cerr << "has not been scheduled!\n";
621 if (SUnits[i].NumSuccsLeft != 0) {
623 cerr << "*** List scheduling failed! ***\n";
625 cerr << "has successors left!\n";
629 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
632 assert(!AnyNotSched);
633 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
634 "The number of nodes scheduled doesn't match the expected number!");
638 //===----------------------------------------------------------------------===//
639 // Public Constructor Functions
640 //===----------------------------------------------------------------------===//
642 llvm::ScheduleDAG* llvm::createFastDAGScheduler(SelectionDAGISel *IS,
644 const TargetMachine *TM,
645 MachineBasicBlock *BB, bool) {
646 return new ScheduleDAGFast(DAG, BB, *TM);