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/ScheduleDAGSDNodes.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 ScheduleDAGSDNodes {
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 : ScheduleDAGSDNodes(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 isArtificial,
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 isArtificial);
91 void ReleasePred(SUnit *SU, SUnit *PredSU, bool isChain);
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 } // end anonymous namespace
104 /// Schedule - Schedule the DAG using list scheduling.
105 void ScheduleDAGFast::Schedule() {
106 DOUT << "********** List Scheduling **********\n";
109 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
110 LiveRegCycles.resize(TRI->getNumRegs(), 0);
112 // Build scheduling units.
115 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
116 SUnits[su].dumpAll(this));
118 // Execute the actual scheduling loop.
119 ListScheduleBottomUp();
122 //===----------------------------------------------------------------------===//
123 // Bottom-Up Scheduling
124 //===----------------------------------------------------------------------===//
126 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
127 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
128 void ScheduleDAGFast::ReleasePred(SUnit *SU, SUnit *PredSU, bool isChain) {
129 --PredSU->NumSuccsLeft;
132 if (PredSU->NumSuccsLeft < 0) {
133 cerr << "*** Scheduling failed! ***\n";
135 cerr << " has been released too many times!\n";
140 if (PredSU->NumSuccsLeft == 0) {
141 PredSU->isAvailable = true;
142 AvailableQueue.push(PredSU);
146 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
147 /// count of its predecessors. If a predecessor pending count is zero, add it to
148 /// the Available queue.
149 void ScheduleDAGFast::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
150 DOUT << "*** Scheduling [" << CurCycle << "]: ";
151 DEBUG(SU->dump(this));
153 SU->Cycle = CurCycle;
154 Sequence.push_back(SU);
156 // Bottom up: release predecessors
157 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
159 ReleasePred(SU, I->Dep, I->isCtrl);
161 // This is a physical register dependency and it's impossible or
162 // expensive to copy the register. Make sure nothing that can
163 // clobber the register is scheduled between the predecessor and
165 if (!LiveRegDefs[I->Reg]) {
167 LiveRegDefs[I->Reg] = I->Dep;
168 LiveRegCycles[I->Reg] = CurCycle;
173 // Release all the implicit physical register defs that are live.
174 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
177 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
178 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
179 assert(LiveRegDefs[I->Reg] == SU &&
180 "Physical register dependency violated?");
182 LiveRegDefs[I->Reg] = NULL;
183 LiveRegCycles[I->Reg] = 0;
188 SU->isScheduled = true;
191 /// AddPred - adds an edge from SUnit X to SUnit Y.
192 bool ScheduleDAGFast::AddPred(SUnit *Y, SUnit *X, bool isCtrl,
193 bool isArtificial, unsigned PhyReg, int Cost) {
194 return Y->addPred(X, isCtrl, isArtificial, PhyReg, Cost);
197 /// RemovePred - This removes the specified node N from the predecessors of
198 /// the current node M.
199 bool ScheduleDAGFast::RemovePred(SUnit *M, SUnit *N,
200 bool isCtrl, bool isArtificial) {
201 return M->removePred(N, isCtrl, isArtificial, false);
204 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
205 /// successors to the newly created node.
206 SUnit *ScheduleDAGFast::CopyAndMoveSuccessors(SUnit *SU) {
207 if (SU->getNode()->getFlaggedNode())
210 SDNode *N = SU->getNode();
215 bool TryUnfold = false;
216 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
217 MVT VT = N->getValueType(i);
220 else if (VT == MVT::Other)
223 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
224 const SDValue &Op = N->getOperand(i);
225 MVT VT = Op.getNode()->getValueType(Op.getResNo());
231 SmallVector<SDNode*, 2> NewNodes;
232 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
235 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
236 assert(NewNodes.size() == 2 && "Expected a load folding node!");
239 SDNode *LoadNode = NewNodes[0];
240 unsigned NumVals = N->getNumValues();
241 unsigned OldNumVals = SU->getNode()->getNumValues();
242 for (unsigned i = 0; i != NumVals; ++i)
243 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
244 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
245 SDValue(LoadNode, 1));
247 SUnit *NewSU = NewSUnit(N);
248 assert(N->getNodeId() == -1 && "Node already inserted!");
249 N->setNodeId(NewSU->NodeNum);
251 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
252 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
253 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
254 NewSU->isTwoAddress = true;
258 if (TID.isCommutable())
259 NewSU->isCommutable = true;
260 // FIXME: Calculate height / depth and propagate the changes?
261 NewSU->Depth = SU->Depth;
262 NewSU->Height = SU->Height;
264 // LoadNode may already exist. This can happen when there is another
265 // load from the same location and producing the same type of value
266 // but it has different alignment or volatileness.
267 bool isNewLoad = true;
269 if (LoadNode->getNodeId() != -1) {
270 LoadSU = &SUnits[LoadNode->getNodeId()];
273 LoadSU = NewSUnit(LoadNode);
274 LoadNode->setNodeId(LoadSU->NodeNum);
276 LoadSU->Depth = SU->Depth;
277 LoadSU->Height = SU->Height;
280 SUnit *ChainPred = NULL;
281 SmallVector<SDep, 4> ChainSuccs;
282 SmallVector<SDep, 4> LoadPreds;
283 SmallVector<SDep, 4> NodePreds;
284 SmallVector<SDep, 4> NodeSuccs;
285 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
289 else if (I->Dep->getNode() && I->Dep->getNode()->isOperandOf(LoadNode))
290 LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false, false));
292 NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false, false));
294 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
297 ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
298 I->isCtrl, I->isArtificial, I->isAntiDep));
300 NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
301 I->isCtrl, I->isArtificial, I->isAntiDep));
305 RemovePred(SU, ChainPred, true, false);
307 AddPred(LoadSU, ChainPred, true, false);
309 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
310 SDep *Pred = &LoadPreds[i];
311 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isArtificial);
313 AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isArtificial,
314 Pred->Reg, Pred->Cost);
317 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
318 SDep *Pred = &NodePreds[i];
319 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isArtificial);
320 AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isArtificial,
321 Pred->Reg, Pred->Cost);
323 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
324 SDep *Succ = &NodeSuccs[i];
325 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isArtificial);
326 AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isArtificial,
327 Succ->Reg, Succ->Cost);
329 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
330 SDep *Succ = &ChainSuccs[i];
331 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isArtificial);
333 AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isArtificial,
334 Succ->Reg, Succ->Cost);
338 AddPred(NewSU, LoadSU, false, false);
343 if (NewSU->NumSuccsLeft == 0) {
344 NewSU->isAvailable = true;
350 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
353 // New SUnit has the exact same predecessors.
354 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
356 if (!I->isArtificial) {
357 AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
358 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
361 // Only copy scheduled successors. Cut them from old node's successor
362 // list and move them over.
363 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
364 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
368 if (I->Dep->isScheduled) {
369 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
370 AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
371 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
374 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
375 SUnit *Succ = DelDeps[i].first;
376 bool isCtrl = DelDeps[i].second;
377 RemovePred(Succ, SU, isCtrl, false);
384 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
385 /// and move all scheduled successors of the given SUnit to the last copy.
386 void ScheduleDAGFast::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
387 const TargetRegisterClass *DestRC,
388 const TargetRegisterClass *SrcRC,
389 SmallVector<SUnit*, 2> &Copies) {
390 SUnit *CopyFromSU = NewSUnit(static_cast<SDNode *>(NULL));
391 CopyFromSU->CopySrcRC = SrcRC;
392 CopyFromSU->CopyDstRC = DestRC;
394 SUnit *CopyToSU = NewSUnit(static_cast<SDNode *>(NULL));
395 CopyToSU->CopySrcRC = DestRC;
396 CopyToSU->CopyDstRC = SrcRC;
398 // Only copy scheduled successors. Cut them from old node's successor
399 // list and move them over.
400 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
401 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
405 if (I->Dep->isScheduled) {
406 AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
407 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
410 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
411 SUnit *Succ = DelDeps[i].first;
412 bool isCtrl = DelDeps[i].second;
413 RemovePred(Succ, SU, isCtrl, false);
416 AddPred(CopyFromSU, SU, false, false, Reg, -1);
417 AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
419 Copies.push_back(CopyFromSU);
420 Copies.push_back(CopyToSU);
425 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
426 /// definition of the specified node.
427 /// FIXME: Move to SelectionDAG?
428 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
429 const TargetInstrInfo *TII) {
430 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
431 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
432 unsigned NumRes = TID.getNumDefs();
433 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
438 return N->getValueType(NumRes);
441 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
442 /// scheduling of the given node to satisfy live physical register dependencies.
443 /// If the specific node is the last one that's available to schedule, do
444 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
445 bool ScheduleDAGFast::DelayForLiveRegsBottomUp(SUnit *SU,
446 SmallVector<unsigned, 4> &LRegs){
447 if (NumLiveRegs == 0)
450 SmallSet<unsigned, 4> RegAdded;
451 // If this node would clobber any "live" register, then it's not ready.
452 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
455 unsigned Reg = I->Reg;
456 if (LiveRegDefs[Reg] && LiveRegDefs[Reg] != I->Dep) {
457 if (RegAdded.insert(Reg))
458 LRegs.push_back(Reg);
460 for (const unsigned *Alias = TRI->getAliasSet(Reg);
462 if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != I->Dep) {
463 if (RegAdded.insert(*Alias))
464 LRegs.push_back(*Alias);
469 for (SDNode *Node = SU->getNode(); Node; Node = Node->getFlaggedNode()) {
470 if (!Node->isMachineOpcode())
472 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
473 if (!TID.ImplicitDefs)
475 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
476 if (LiveRegDefs[*Reg] && LiveRegDefs[*Reg] != SU) {
477 if (RegAdded.insert(*Reg))
478 LRegs.push_back(*Reg);
480 for (const unsigned *Alias = TRI->getAliasSet(*Reg);
482 if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != SU) {
483 if (RegAdded.insert(*Alias))
484 LRegs.push_back(*Alias);
488 return !LRegs.empty();
492 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
494 void ScheduleDAGFast::ListScheduleBottomUp() {
495 unsigned CurCycle = 0;
496 // Add root to Available queue.
497 if (!SUnits.empty()) {
498 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
499 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
500 RootSU->isAvailable = true;
501 AvailableQueue.push(RootSU);
504 // While Available queue is not empty, grab the node with the highest
505 // priority. If it is not ready put it back. Schedule the node.
506 SmallVector<SUnit*, 4> NotReady;
507 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
508 Sequence.reserve(SUnits.size());
509 while (!AvailableQueue.empty()) {
510 bool Delayed = false;
512 SUnit *CurSU = AvailableQueue.pop();
514 SmallVector<unsigned, 4> LRegs;
515 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
518 LRegsMap.insert(std::make_pair(CurSU, LRegs));
520 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
521 NotReady.push_back(CurSU);
522 CurSU = AvailableQueue.pop();
525 // All candidates are delayed due to live physical reg dependencies.
526 // Try code duplication or inserting cross class copies
528 if (Delayed && !CurSU) {
530 // Try duplicating the nodes that produces these
531 // "expensive to copy" values to break the dependency. In case even
532 // that doesn't work, insert cross class copies.
533 SUnit *TrySU = NotReady[0];
534 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
535 assert(LRegs.size() == 1 && "Can't handle this yet!");
536 unsigned Reg = LRegs[0];
537 SUnit *LRDef = LiveRegDefs[Reg];
538 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
540 // Issue expensive cross register class copies.
541 MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
542 const TargetRegisterClass *RC =
543 TRI->getPhysicalRegisterRegClass(Reg, VT);
544 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
546 assert(false && "Don't know how to copy this physical register!");
549 SmallVector<SUnit*, 2> Copies;
550 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
551 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
552 << " to SU #" << Copies.front()->NodeNum << "\n";
553 AddPred(TrySU, Copies.front(), true, true);
554 NewDef = Copies.back();
557 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
558 << " to SU #" << TrySU->NodeNum << "\n";
559 LiveRegDefs[Reg] = NewDef;
560 AddPred(NewDef, TrySU, true, true);
561 TrySU->isAvailable = false;
566 assert(false && "Unable to resolve live physical register dependencies!");
571 // Add the nodes that aren't ready back onto the available list.
572 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
573 NotReady[i]->isPending = false;
574 // May no longer be available due to backtracking.
575 if (NotReady[i]->isAvailable)
576 AvailableQueue.push(NotReady[i]);
581 ScheduleNodeBottomUp(CurSU, CurCycle);
585 // Reverse the order if it is bottom up.
586 std::reverse(Sequence.begin(), Sequence.end());
590 // Verify that all SUnits were scheduled.
591 bool AnyNotSched = false;
592 unsigned DeadNodes = 0;
594 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
595 if (!SUnits[i].isScheduled) {
596 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
601 cerr << "*** List scheduling failed! ***\n";
602 SUnits[i].dump(this);
603 cerr << "has not been scheduled!\n";
606 if (SUnits[i].NumSuccsLeft != 0) {
608 cerr << "*** List scheduling failed! ***\n";
609 SUnits[i].dump(this);
610 cerr << "has successors left!\n";
614 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
617 assert(!AnyNotSched);
618 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
619 "The number of nodes scheduled doesn't match the expected number!");
623 //===----------------------------------------------------------------------===//
624 // Public Constructor Functions
625 //===----------------------------------------------------------------------===//
627 llvm::ScheduleDAG* llvm::createFastDAGScheduler(SelectionDAGISel *IS,
629 const TargetMachine *TM,
630 MachineBasicBlock *BB, bool) {
631 return new ScheduleDAGFast(DAG, BB, *TM);