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/CodeGen/SelectionDAGISel.h"
18 #include "llvm/Target/TargetRegisterInfo.h"
19 #include "llvm/Target/TargetData.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(NumPRCopies, "Number of physical 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(MachineFunction &mf)
75 : ScheduleDAGSDNodes(mf) {}
79 /// AddPred - adds a predecessor edge to SUnit SU.
80 /// This returns true if this is a new predecessor.
81 void AddPred(SUnit *SU, const SDep &D) {
85 /// RemovePred - removes a predecessor edge from SUnit SU.
86 /// This returns true if an edge was removed.
87 void RemovePred(SUnit *SU, const SDep &D) {
92 void ReleasePred(SUnit *SU, SDep *PredEdge);
93 void ScheduleNodeBottomUp(SUnit*, unsigned);
94 SUnit *CopyAndMoveSuccessors(SUnit*);
95 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
96 const TargetRegisterClass*,
97 const TargetRegisterClass*,
98 SmallVector<SUnit*, 2>&);
99 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
100 void ListScheduleBottomUp();
102 /// ForceUnitLatencies - The fast scheduler doesn't care about real latencies.
103 bool ForceUnitLatencies() const { return true; }
105 } // end anonymous namespace
108 /// Schedule - Schedule the DAG using list scheduling.
109 void ScheduleDAGFast::Schedule() {
110 DOUT << "********** List Scheduling **********\n";
113 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
114 LiveRegCycles.resize(TRI->getNumRegs(), 0);
116 // Build the scheduling graph.
119 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
120 SUnits[su].dumpAll(this));
122 // Execute the actual scheduling loop.
123 ListScheduleBottomUp();
126 //===----------------------------------------------------------------------===//
127 // Bottom-Up Scheduling
128 //===----------------------------------------------------------------------===//
130 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
131 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
132 void ScheduleDAGFast::ReleasePred(SUnit *SU, SDep *PredEdge) {
133 SUnit *PredSU = PredEdge->getSUnit();
134 --PredSU->NumSuccsLeft;
137 if (PredSU->NumSuccsLeft < 0) {
138 cerr << "*** Scheduling failed! ***\n";
140 cerr << " has been released too many times!\n";
145 if (PredSU->NumSuccsLeft == 0) {
146 PredSU->isAvailable = true;
147 AvailableQueue.push(PredSU);
151 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
152 /// count of its predecessors. If a predecessor pending count is zero, add it to
153 /// the Available queue.
154 void ScheduleDAGFast::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
155 DOUT << "*** Scheduling [" << CurCycle << "]: ";
156 DEBUG(SU->dump(this));
158 assert(CurCycle >= SU->getHeight() && "Node scheduled below its height!");
159 SU->setHeightToAtLeast(CurCycle);
160 Sequence.push_back(SU);
162 // Bottom up: release predecessors
163 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
165 ReleasePred(SU, &*I);
166 if (I->isAssignedRegDep()) {
167 // This is a physical register dependency and it's impossible or
168 // expensive to copy the register. Make sure nothing that can
169 // clobber the register is scheduled between the predecessor and
171 if (!LiveRegDefs[I->getReg()]) {
173 LiveRegDefs[I->getReg()] = I->getSUnit();
174 LiveRegCycles[I->getReg()] = CurCycle;
179 // Release all the implicit physical register defs that are live.
180 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
182 if (I->isAssignedRegDep()) {
183 if (LiveRegCycles[I->getReg()] == I->getSUnit()->getHeight()) {
184 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
185 assert(LiveRegDefs[I->getReg()] == SU &&
186 "Physical register dependency violated?");
188 LiveRegDefs[I->getReg()] = NULL;
189 LiveRegCycles[I->getReg()] = 0;
194 SU->isScheduled = true;
197 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
198 /// successors to the newly created node.
199 SUnit *ScheduleDAGFast::CopyAndMoveSuccessors(SUnit *SU) {
200 if (SU->getNode()->getFlaggedNode())
203 SDNode *N = SU->getNode();
208 bool TryUnfold = false;
209 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
210 MVT VT = N->getValueType(i);
213 else if (VT == MVT::Other)
216 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
217 const SDValue &Op = N->getOperand(i);
218 MVT VT = Op.getNode()->getValueType(Op.getResNo());
224 SmallVector<SDNode*, 2> NewNodes;
225 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
228 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
229 assert(NewNodes.size() == 2 && "Expected a load folding node!");
232 SDNode *LoadNode = NewNodes[0];
233 unsigned NumVals = N->getNumValues();
234 unsigned OldNumVals = SU->getNode()->getNumValues();
235 for (unsigned i = 0; i != NumVals; ++i)
236 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
237 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
238 SDValue(LoadNode, 1));
240 SUnit *NewSU = NewSUnit(N);
241 assert(N->getNodeId() == -1 && "Node already inserted!");
242 N->setNodeId(NewSU->NodeNum);
244 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
245 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
246 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
247 NewSU->isTwoAddress = true;
251 if (TID.isCommutable())
252 NewSU->isCommutable = true;
254 // LoadNode may already exist. This can happen when there is another
255 // load from the same location and producing the same type of value
256 // but it has different alignment or volatileness.
257 bool isNewLoad = true;
259 if (LoadNode->getNodeId() != -1) {
260 LoadSU = &SUnits[LoadNode->getNodeId()];
263 LoadSU = NewSUnit(LoadNode);
264 LoadNode->setNodeId(LoadSU->NodeNum);
268 SmallVector<SDep, 4> ChainSuccs;
269 SmallVector<SDep, 4> LoadPreds;
270 SmallVector<SDep, 4> NodePreds;
271 SmallVector<SDep, 4> NodeSuccs;
272 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
276 else if (I->getSUnit()->getNode() &&
277 I->getSUnit()->getNode()->isOperandOf(LoadNode))
278 LoadPreds.push_back(*I);
280 NodePreds.push_back(*I);
282 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
285 ChainSuccs.push_back(*I);
287 NodeSuccs.push_back(*I);
290 if (ChainPred.getSUnit()) {
291 RemovePred(SU, ChainPred);
293 AddPred(LoadSU, ChainPred);
295 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
296 const SDep &Pred = LoadPreds[i];
297 RemovePred(SU, Pred);
299 AddPred(LoadSU, Pred);
302 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
303 const SDep &Pred = NodePreds[i];
304 RemovePred(SU, Pred);
305 AddPred(NewSU, Pred);
307 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
308 SDep D = NodeSuccs[i];
309 SUnit *SuccDep = D.getSUnit();
311 RemovePred(SuccDep, D);
315 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
316 SDep D = ChainSuccs[i];
317 SUnit *SuccDep = D.getSUnit();
319 RemovePred(SuccDep, D);
326 AddPred(NewSU, SDep(LoadSU, SDep::Order, LoadSU->Latency));
331 if (NewSU->NumSuccsLeft == 0) {
332 NewSU->isAvailable = true;
338 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
341 // New SUnit has the exact same predecessors.
342 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
344 if (!I->isArtificial())
347 // Only copy scheduled successors. Cut them from old node's successor
348 // list and move them over.
349 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
350 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
352 if (I->isArtificial())
354 SUnit *SuccSU = I->getSUnit();
355 if (SuccSU->isScheduled) {
360 DelDeps.push_back(std::make_pair(SuccSU, D));
363 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
364 RemovePred(DelDeps[i].first, DelDeps[i].second);
370 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
371 /// scheduled successors of the given SUnit to the last copy.
372 void ScheduleDAGFast::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
373 const TargetRegisterClass *DestRC,
374 const TargetRegisterClass *SrcRC,
375 SmallVector<SUnit*, 2> &Copies) {
376 SUnit *CopyFromSU = NewSUnit(static_cast<SDNode *>(NULL));
377 CopyFromSU->CopySrcRC = SrcRC;
378 CopyFromSU->CopyDstRC = DestRC;
380 SUnit *CopyToSU = NewSUnit(static_cast<SDNode *>(NULL));
381 CopyToSU->CopySrcRC = DestRC;
382 CopyToSU->CopyDstRC = SrcRC;
384 // Only copy scheduled successors. Cut them from old node's successor
385 // list and move them over.
386 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
387 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
389 if (I->isArtificial())
391 SUnit *SuccSU = I->getSUnit();
392 if (SuccSU->isScheduled) {
394 D.setSUnit(CopyToSU);
396 DelDeps.push_back(std::make_pair(SuccSU, *I));
399 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
400 RemovePred(DelDeps[i].first, DelDeps[i].second);
403 AddPred(CopyFromSU, SDep(SU, SDep::Data, SU->Latency, Reg));
404 AddPred(CopyToSU, SDep(CopyFromSU, SDep::Data, CopyFromSU->Latency, 0));
406 Copies.push_back(CopyFromSU);
407 Copies.push_back(CopyToSU);
412 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
413 /// definition of the specified node.
414 /// FIXME: Move to SelectionDAG?
415 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
416 const TargetInstrInfo *TII) {
417 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
418 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
419 unsigned NumRes = TID.getNumDefs();
420 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
425 return N->getValueType(NumRes);
428 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
429 /// scheduling of the given node to satisfy live physical register dependencies.
430 /// If the specific node is the last one that's available to schedule, do
431 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
432 bool ScheduleDAGFast::DelayForLiveRegsBottomUp(SUnit *SU,
433 SmallVector<unsigned, 4> &LRegs){
434 if (NumLiveRegs == 0)
437 SmallSet<unsigned, 4> RegAdded;
438 // If this node would clobber any "live" register, then it's not ready.
439 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
441 if (I->isAssignedRegDep()) {
442 unsigned Reg = I->getReg();
443 if (LiveRegDefs[Reg] && LiveRegDefs[Reg] != I->getSUnit()) {
444 if (RegAdded.insert(Reg))
445 LRegs.push_back(Reg);
447 for (const unsigned *Alias = TRI->getAliasSet(Reg);
449 if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != I->getSUnit()) {
450 if (RegAdded.insert(*Alias))
451 LRegs.push_back(*Alias);
456 for (SDNode *Node = SU->getNode(); Node; Node = Node->getFlaggedNode()) {
457 if (!Node->isMachineOpcode())
459 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
460 if (!TID.ImplicitDefs)
462 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
463 if (LiveRegDefs[*Reg] && LiveRegDefs[*Reg] != SU) {
464 if (RegAdded.insert(*Reg))
465 LRegs.push_back(*Reg);
467 for (const unsigned *Alias = TRI->getAliasSet(*Reg);
469 if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != SU) {
470 if (RegAdded.insert(*Alias))
471 LRegs.push_back(*Alias);
475 return !LRegs.empty();
479 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
481 void ScheduleDAGFast::ListScheduleBottomUp() {
482 unsigned CurCycle = 0;
483 // Add root to Available queue.
484 if (!SUnits.empty()) {
485 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
486 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
487 RootSU->isAvailable = true;
488 AvailableQueue.push(RootSU);
491 // While Available queue is not empty, grab the node with the highest
492 // priority. If it is not ready put it back. Schedule the node.
493 SmallVector<SUnit*, 4> NotReady;
494 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
495 Sequence.reserve(SUnits.size());
496 while (!AvailableQueue.empty()) {
497 bool Delayed = false;
499 SUnit *CurSU = AvailableQueue.pop();
501 SmallVector<unsigned, 4> LRegs;
502 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
505 LRegsMap.insert(std::make_pair(CurSU, LRegs));
507 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
508 NotReady.push_back(CurSU);
509 CurSU = AvailableQueue.pop();
512 // All candidates are delayed due to live physical reg dependencies.
513 // Try code duplication or inserting cross class copies
515 if (Delayed && !CurSU) {
517 // Try duplicating the nodes that produces these
518 // "expensive to copy" values to break the dependency. In case even
519 // that doesn't work, insert cross class copies.
520 SUnit *TrySU = NotReady[0];
521 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
522 assert(LRegs.size() == 1 && "Can't handle this yet!");
523 unsigned Reg = LRegs[0];
524 SUnit *LRDef = LiveRegDefs[Reg];
525 MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
526 const TargetRegisterClass *RC =
527 TRI->getPhysicalRegisterRegClass(Reg, VT);
528 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
530 // If cross copy register class is null, then it must be possible copy
531 // the value directly. Do not try duplicate the def.
534 NewDef = CopyAndMoveSuccessors(LRDef);
538 // Issue copies, these can be expensive cross register class copies.
539 SmallVector<SUnit*, 2> Copies;
540 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
541 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
542 << " to SU #" << Copies.front()->NodeNum << "\n";
543 AddPred(TrySU, SDep(Copies.front(), SDep::Order, /*Latency=*/1,
544 /*Reg=*/0, /*isNormalMemory=*/false,
545 /*isMustAlias=*/false, /*isArtificial=*/true));
546 NewDef = Copies.back();
549 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
550 << " to SU #" << TrySU->NodeNum << "\n";
551 LiveRegDefs[Reg] = NewDef;
552 AddPred(NewDef, SDep(TrySU, SDep::Order, /*Latency=*/1,
553 /*Reg=*/0, /*isNormalMemory=*/false,
554 /*isMustAlias=*/false, /*isArtificial=*/true));
555 TrySU->isAvailable = false;
560 assert(false && "Unable to resolve live physical register dependencies!");
565 // Add the nodes that aren't ready back onto the available list.
566 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
567 NotReady[i]->isPending = false;
568 // May no longer be available due to backtracking.
569 if (NotReady[i]->isAvailable)
570 AvailableQueue.push(NotReady[i]);
575 ScheduleNodeBottomUp(CurSU, CurCycle);
579 // Reverse the order if it is bottom up.
580 std::reverse(Sequence.begin(), Sequence.end());
584 // Verify that all SUnits were scheduled.
585 bool AnyNotSched = false;
586 unsigned DeadNodes = 0;
588 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
589 if (!SUnits[i].isScheduled) {
590 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
595 cerr << "*** List scheduling failed! ***\n";
596 SUnits[i].dump(this);
597 cerr << "has not been scheduled!\n";
600 if (SUnits[i].NumSuccsLeft != 0) {
602 cerr << "*** List scheduling failed! ***\n";
603 SUnits[i].dump(this);
604 cerr << "has successors left!\n";
608 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
611 assert(!AnyNotSched);
612 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
613 "The number of nodes scheduled doesn't match the expected number!");
617 //===----------------------------------------------------------------------===//
618 // Public Constructor Functions
619 //===----------------------------------------------------------------------===//
621 llvm::ScheduleDAG* llvm::createFastDAGScheduler(SelectionDAGISel *IS, bool) {
622 return new ScheduleDAGFast(*IS->MF);