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 #include "llvm/CodeGen/SchedulerRegistry.h"
15 #include "InstrEmitter.h"
16 #include "ScheduleDAGSDNodes.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/SelectionDAGISel.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
30 #define DEBUG_TYPE "pre-RA-sched"
32 STATISTIC(NumUnfolds, "Number of nodes unfolded");
33 STATISTIC(NumDups, "Number of duplicated nodes");
34 STATISTIC(NumPRCopies, "Number of physical copies");
36 static RegisterScheduler
37 fastDAGScheduler("fast", "Fast suboptimal list scheduling",
38 createFastDAGScheduler);
39 static RegisterScheduler
40 linearizeDAGScheduler("linearize", "Linearize DAG, no scheduling",
45 /// FastPriorityQueue - A degenerate priority queue that considers
46 /// all nodes to have the same priority.
48 struct FastPriorityQueue {
49 SmallVector<SUnit *, 16> Queue;
51 bool empty() const { return Queue.empty(); }
58 if (empty()) return nullptr;
59 SUnit *V = Queue.back();
65 //===----------------------------------------------------------------------===//
66 /// ScheduleDAGFast - The actual "fast" list scheduler implementation.
68 class ScheduleDAGFast : public ScheduleDAGSDNodes {
70 /// AvailableQueue - The priority queue to use for the available SUnits.
71 FastPriorityQueue AvailableQueue;
73 /// LiveRegDefs - A set of physical registers and their definition
74 /// that are "live". These nodes must be scheduled before any other nodes that
75 /// modifies the registers can be scheduled.
77 std::vector<SUnit*> LiveRegDefs;
78 std::vector<unsigned> LiveRegCycles;
81 ScheduleDAGFast(MachineFunction &mf)
82 : ScheduleDAGSDNodes(mf) {}
84 void Schedule() override;
86 /// AddPred - adds a predecessor edge to SUnit SU.
87 /// This returns true if this is a new predecessor.
88 void AddPred(SUnit *SU, const SDep &D) {
92 /// RemovePred - removes a predecessor edge from SUnit SU.
93 /// This returns true if an edge was removed.
94 void RemovePred(SUnit *SU, const SDep &D) {
99 void ReleasePred(SUnit *SU, SDep *PredEdge);
100 void ReleasePredecessors(SUnit *SU, unsigned CurCycle);
101 void ScheduleNodeBottomUp(SUnit*, unsigned);
102 SUnit *CopyAndMoveSuccessors(SUnit*);
103 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
104 const TargetRegisterClass*,
105 const TargetRegisterClass*,
106 SmallVectorImpl<SUnit*>&);
107 bool DelayForLiveRegsBottomUp(SUnit*, SmallVectorImpl<unsigned>&);
108 void ListScheduleBottomUp();
110 /// forceUnitLatencies - The fast scheduler doesn't care about real latencies.
111 bool forceUnitLatencies() const override { return true; }
113 } // end anonymous namespace
116 /// Schedule - Schedule the DAG using list scheduling.
117 void ScheduleDAGFast::Schedule() {
118 DEBUG(dbgs() << "********** List Scheduling **********\n");
121 LiveRegDefs.resize(TRI->getNumRegs(), nullptr);
122 LiveRegCycles.resize(TRI->getNumRegs(), 0);
124 // Build the scheduling graph.
125 BuildSchedGraph(nullptr);
127 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
128 SUnits[su].dumpAll(this));
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 *SU, SDep *PredEdge) {
141 SUnit *PredSU = PredEdge->getSUnit();
144 if (PredSU->NumSuccsLeft == 0) {
145 dbgs() << "*** Scheduling failed! ***\n";
147 dbgs() << " has been released too many times!\n";
148 llvm_unreachable(nullptr);
151 --PredSU->NumSuccsLeft;
153 // If all the node's successors are scheduled, this node is ready
154 // to be scheduled. Ignore the special EntrySU node.
155 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
156 PredSU->isAvailable = true;
157 AvailableQueue.push(PredSU);
161 void ScheduleDAGFast::ReleasePredecessors(SUnit *SU, unsigned CurCycle) {
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;
180 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
181 /// count of its predecessors. If a predecessor pending count is zero, add it to
182 /// the Available queue.
183 void ScheduleDAGFast::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
184 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
185 DEBUG(SU->dump(this));
187 assert(CurCycle >= SU->getHeight() && "Node scheduled below its height!");
188 SU->setHeightToAtLeast(CurCycle);
189 Sequence.push_back(SU);
191 ReleasePredecessors(SU, CurCycle);
193 // Release all the implicit physical register defs that are live.
194 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
196 if (I->isAssignedRegDep()) {
197 if (LiveRegCycles[I->getReg()] == I->getSUnit()->getHeight()) {
198 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
199 assert(LiveRegDefs[I->getReg()] == SU &&
200 "Physical register dependency violated?");
202 LiveRegDefs[I->getReg()] = nullptr;
203 LiveRegCycles[I->getReg()] = 0;
208 SU->isScheduled = true;
211 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
212 /// successors to the newly created node.
213 SUnit *ScheduleDAGFast::CopyAndMoveSuccessors(SUnit *SU) {
214 if (SU->getNode()->getGluedNode())
217 SDNode *N = SU->getNode();
222 bool TryUnfold = false;
223 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
224 MVT VT = N->getSimpleValueType(i);
227 else if (VT == MVT::Other)
230 for (const SDValue &Op : N->op_values()) {
231 MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
237 SmallVector<SDNode*, 2> NewNodes;
238 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
241 DEBUG(dbgs() << "Unfolding SU # " << SU->NodeNum << "\n");
242 assert(NewNodes.size() == 2 && "Expected a load folding node!");
245 SDNode *LoadNode = NewNodes[0];
246 unsigned NumVals = N->getNumValues();
247 unsigned OldNumVals = SU->getNode()->getNumValues();
248 for (unsigned i = 0; i != NumVals; ++i)
249 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
250 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
251 SDValue(LoadNode, 1));
253 SUnit *NewSU = newSUnit(N);
254 assert(N->getNodeId() == -1 && "Node already inserted!");
255 N->setNodeId(NewSU->NodeNum);
257 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
258 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
259 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
260 NewSU->isTwoAddress = true;
264 if (MCID.isCommutable())
265 NewSU->isCommutable = true;
267 // LoadNode may already exist. This can happen when there is another
268 // load from the same location and producing the same type of value
269 // but it has different alignment or volatileness.
270 bool isNewLoad = true;
272 if (LoadNode->getNodeId() != -1) {
273 LoadSU = &SUnits[LoadNode->getNodeId()];
276 LoadSU = newSUnit(LoadNode);
277 LoadNode->setNodeId(LoadSU->NodeNum);
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->getSUnit()->getNode() &&
290 I->getSUnit()->getNode()->isOperandOf(LoadNode))
291 LoadPreds.push_back(*I);
293 NodePreds.push_back(*I);
295 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
298 ChainSuccs.push_back(*I);
300 NodeSuccs.push_back(*I);
303 if (ChainPred.getSUnit()) {
304 RemovePred(SU, ChainPred);
306 AddPred(LoadSU, ChainPred);
308 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
309 const SDep &Pred = LoadPreds[i];
310 RemovePred(SU, Pred);
312 AddPred(LoadSU, Pred);
315 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
316 const SDep &Pred = NodePreds[i];
317 RemovePred(SU, Pred);
318 AddPred(NewSU, Pred);
320 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
321 SDep D = NodeSuccs[i];
322 SUnit *SuccDep = D.getSUnit();
324 RemovePred(SuccDep, D);
328 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
329 SDep D = ChainSuccs[i];
330 SUnit *SuccDep = D.getSUnit();
332 RemovePred(SuccDep, D);
339 SDep D(LoadSU, SDep::Barrier);
340 D.setLatency(LoadSU->Latency);
346 if (NewSU->NumSuccsLeft == 0) {
347 NewSU->isAvailable = true;
353 DEBUG(dbgs() << "Duplicating SU # " << SU->NodeNum << "\n");
356 // New SUnit has the exact same predecessors.
357 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
359 if (!I->isArtificial())
362 // Only copy scheduled successors. Cut them from old node's successor
363 // list and move them over.
364 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
365 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
367 if (I->isArtificial())
369 SUnit *SuccSU = I->getSUnit();
370 if (SuccSU->isScheduled) {
375 DelDeps.push_back(std::make_pair(SuccSU, D));
378 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i)
379 RemovePred(DelDeps[i].first, DelDeps[i].second);
385 /// InsertCopiesAndMoveSuccs - Insert register copies and move all
386 /// scheduled successors of the given SUnit to the last copy.
387 void ScheduleDAGFast::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
388 const TargetRegisterClass *DestRC,
389 const TargetRegisterClass *SrcRC,
390 SmallVectorImpl<SUnit*> &Copies) {
391 SUnit *CopyFromSU = newSUnit(static_cast<SDNode *>(nullptr));
392 CopyFromSU->CopySrcRC = SrcRC;
393 CopyFromSU->CopyDstRC = DestRC;
395 SUnit *CopyToSU = newSUnit(static_cast<SDNode *>(nullptr));
396 CopyToSU->CopySrcRC = DestRC;
397 CopyToSU->CopyDstRC = SrcRC;
399 // Only copy scheduled successors. Cut them from old node's successor
400 // list and move them over.
401 SmallVector<std::pair<SUnit *, SDep>, 4> DelDeps;
402 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
404 if (I->isArtificial())
406 SUnit *SuccSU = I->getSUnit();
407 if (SuccSU->isScheduled) {
409 D.setSUnit(CopyToSU);
411 DelDeps.push_back(std::make_pair(SuccSU, *I));
414 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
415 RemovePred(DelDeps[i].first, DelDeps[i].second);
417 SDep FromDep(SU, SDep::Data, Reg);
418 FromDep.setLatency(SU->Latency);
419 AddPred(CopyFromSU, FromDep);
420 SDep ToDep(CopyFromSU, SDep::Data, 0);
421 ToDep.setLatency(CopyFromSU->Latency);
422 AddPred(CopyToSU, ToDep);
424 Copies.push_back(CopyFromSU);
425 Copies.push_back(CopyToSU);
430 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
431 /// definition of the specified node.
432 /// FIXME: Move to SelectionDAG?
433 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
434 const TargetInstrInfo *TII) {
436 if (N->getOpcode() == ISD::CopyFromReg) {
437 // CopyFromReg has: "chain, Val, glue" so operand 1 gives the type.
440 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
441 assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def list!");
442 NumRes = MCID.getNumDefs();
443 for (const uint16_t *ImpDef = MCID.getImplicitDefs(); *ImpDef; ++ImpDef) {
449 return N->getSimpleValueType(NumRes);
452 /// CheckForLiveRegDef - Return true and update live register vector if the
453 /// specified register def of the specified SUnit clobbers any "live" registers.
454 static bool CheckForLiveRegDef(SUnit *SU, unsigned Reg,
455 std::vector<SUnit*> &LiveRegDefs,
456 SmallSet<unsigned, 4> &RegAdded,
457 SmallVectorImpl<unsigned> &LRegs,
458 const TargetRegisterInfo *TRI) {
460 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
461 if (LiveRegDefs[*AI] && LiveRegDefs[*AI] != SU) {
462 if (RegAdded.insert(*AI).second) {
463 LRegs.push_back(*AI);
471 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
472 /// scheduling of the given node to satisfy live physical register dependencies.
473 /// If the specific node is the last one that's available to schedule, do
474 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
475 bool ScheduleDAGFast::DelayForLiveRegsBottomUp(SUnit *SU,
476 SmallVectorImpl<unsigned> &LRegs){
477 if (NumLiveRegs == 0)
480 SmallSet<unsigned, 4> RegAdded;
481 // If this node would clobber any "live" register, then it's not ready.
482 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
484 if (I->isAssignedRegDep()) {
485 CheckForLiveRegDef(I->getSUnit(), I->getReg(), LiveRegDefs,
486 RegAdded, LRegs, TRI);
490 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
491 if (Node->getOpcode() == ISD::INLINEASM) {
492 // Inline asm can clobber physical defs.
493 unsigned NumOps = Node->getNumOperands();
494 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
495 --NumOps; // Ignore the glue operand.
497 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
499 cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
500 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
502 ++i; // Skip the ID value.
503 if (InlineAsm::isRegDefKind(Flags) ||
504 InlineAsm::isRegDefEarlyClobberKind(Flags) ||
505 InlineAsm::isClobberKind(Flags)) {
506 // Check for def of register or earlyclobber register.
507 for (; NumVals; --NumVals, ++i) {
508 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
509 if (TargetRegisterInfo::isPhysicalRegister(Reg))
510 CheckForLiveRegDef(SU, Reg, LiveRegDefs, RegAdded, LRegs, TRI);
517 if (!Node->isMachineOpcode())
519 const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
520 if (!MCID.ImplicitDefs)
522 for (const uint16_t *Reg = MCID.getImplicitDefs(); *Reg; ++Reg) {
523 CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
526 return !LRegs.empty();
530 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
532 void ScheduleDAGFast::ListScheduleBottomUp() {
533 unsigned CurCycle = 0;
535 // Release any predecessors of the special Exit node.
536 ReleasePredecessors(&ExitSU, CurCycle);
538 // Add root to Available queue.
539 if (!SUnits.empty()) {
540 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
541 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
542 RootSU->isAvailable = true;
543 AvailableQueue.push(RootSU);
546 // While Available queue is not empty, grab the node with the highest
547 // priority. If it is not ready put it back. Schedule the node.
548 SmallVector<SUnit*, 4> NotReady;
549 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
550 Sequence.reserve(SUnits.size());
551 while (!AvailableQueue.empty()) {
552 bool Delayed = false;
554 SUnit *CurSU = AvailableQueue.pop();
556 SmallVector<unsigned, 4> LRegs;
557 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
560 LRegsMap.insert(std::make_pair(CurSU, LRegs));
562 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
563 NotReady.push_back(CurSU);
564 CurSU = AvailableQueue.pop();
567 // All candidates are delayed due to live physical reg dependencies.
568 // Try code duplication or inserting cross class copies
570 if (Delayed && !CurSU) {
572 // Try duplicating the nodes that produces these
573 // "expensive to copy" values to break the dependency. In case even
574 // that doesn't work, insert cross class copies.
575 SUnit *TrySU = NotReady[0];
576 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
577 assert(LRegs.size() == 1 && "Can't handle this yet!");
578 unsigned Reg = LRegs[0];
579 SUnit *LRDef = LiveRegDefs[Reg];
580 MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
581 const TargetRegisterClass *RC =
582 TRI->getMinimalPhysRegClass(Reg, VT);
583 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
585 // If cross copy register class is the same as RC, then it must be
586 // possible copy the value directly. Do not try duplicate the def.
587 // If cross copy register class is not the same as RC, then it's
588 // possible to copy the value but it require cross register class copies
589 // and it is expensive.
590 // If cross copy register class is null, then it's not possible to copy
592 SUnit *NewDef = nullptr;
594 NewDef = CopyAndMoveSuccessors(LRDef);
595 if (!DestRC && !NewDef)
596 report_fatal_error("Can't handle live physical "
597 "register dependency!");
600 // Issue copies, these can be expensive cross register class copies.
601 SmallVector<SUnit*, 2> Copies;
602 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
603 DEBUG(dbgs() << "Adding an edge from SU # " << TrySU->NodeNum
604 << " to SU #" << Copies.front()->NodeNum << "\n");
605 AddPred(TrySU, SDep(Copies.front(), SDep::Artificial));
606 NewDef = Copies.back();
609 DEBUG(dbgs() << "Adding an edge from SU # " << NewDef->NodeNum
610 << " to SU #" << TrySU->NodeNum << "\n");
611 LiveRegDefs[Reg] = NewDef;
612 AddPred(NewDef, SDep(TrySU, SDep::Artificial));
613 TrySU->isAvailable = false;
618 llvm_unreachable("Unable to resolve live physical register dependencies!");
622 // Add the nodes that aren't ready back onto the available list.
623 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
624 NotReady[i]->isPending = false;
625 // May no longer be available due to backtracking.
626 if (NotReady[i]->isAvailable)
627 AvailableQueue.push(NotReady[i]);
632 ScheduleNodeBottomUp(CurSU, CurCycle);
636 // Reverse the order since it is bottom up.
637 std::reverse(Sequence.begin(), Sequence.end());
640 VerifyScheduledSequence(/*isBottomUp=*/true);
646 //===----------------------------------------------------------------------===//
647 // ScheduleDAGLinearize - No scheduling scheduler, it simply linearize the
648 // DAG in topological order.
649 // IMPORTANT: this may not work for targets with phyreg dependency.
651 class ScheduleDAGLinearize : public ScheduleDAGSDNodes {
653 ScheduleDAGLinearize(MachineFunction &mf) : ScheduleDAGSDNodes(mf) {}
655 void Schedule() override;
658 EmitSchedule(MachineBasicBlock::iterator &InsertPos) override;
661 std::vector<SDNode*> Sequence;
662 DenseMap<SDNode*, SDNode*> GluedMap; // Cache glue to its user
664 void ScheduleNode(SDNode *N);
666 } // end anonymous namespace
668 void ScheduleDAGLinearize::ScheduleNode(SDNode *N) {
669 if (N->getNodeId() != 0)
670 llvm_unreachable(nullptr);
672 if (!N->isMachineOpcode() &&
673 (N->getOpcode() == ISD::EntryToken || isPassiveNode(N)))
674 // These nodes do not need to be translated into MIs.
677 DEBUG(dbgs() << "\n*** Scheduling: ");
679 Sequence.push_back(N);
681 unsigned NumOps = N->getNumOperands();
682 if (unsigned NumLeft = NumOps) {
683 SDNode *GluedOpN = nullptr;
685 const SDValue &Op = N->getOperand(NumLeft-1);
686 SDNode *OpN = Op.getNode();
688 if (NumLeft == NumOps && Op.getValueType() == MVT::Glue) {
689 // Schedule glue operand right above N.
691 assert(OpN->getNodeId() != 0 && "Glue operand not ready?");
698 // Glue operand is already scheduled.
701 DenseMap<SDNode*, SDNode*>::iterator DI = GluedMap.find(OpN);
702 if (DI != GluedMap.end() && DI->second != N)
703 // Users of glues are counted against the glued users.
706 unsigned Degree = OpN->getNodeId();
707 assert(Degree > 0 && "Predecessor over-released!");
708 OpN->setNodeId(--Degree);
715 /// findGluedUser - Find the representative use of a glue value by walking
717 static SDNode *findGluedUser(SDNode *N) {
718 while (SDNode *Glued = N->getGluedUser())
723 void ScheduleDAGLinearize::Schedule() {
724 DEBUG(dbgs() << "********** DAG Linearization **********\n");
726 SmallVector<SDNode*, 8> Glues;
727 unsigned DAGSize = 0;
728 for (SelectionDAG::allnodes_iterator I = DAG->allnodes_begin(),
729 E = DAG->allnodes_end(); I != E; ++I) {
732 // Use node id to record degree.
733 unsigned Degree = N->use_size();
734 N->setNodeId(Degree);
735 unsigned NumVals = N->getNumValues();
736 if (NumVals && N->getValueType(NumVals-1) == MVT::Glue &&
737 N->hasAnyUseOfValue(NumVals-1)) {
738 SDNode *User = findGluedUser(N);
741 GluedMap.insert(std::make_pair(N, User));
745 if (N->isMachineOpcode() ||
746 (N->getOpcode() != ISD::EntryToken && !isPassiveNode(N)))
750 for (unsigned i = 0, e = Glues.size(); i != e; ++i) {
751 SDNode *Glue = Glues[i];
752 SDNode *GUser = GluedMap[Glue];
753 unsigned Degree = Glue->getNodeId();
754 unsigned UDegree = GUser->getNodeId();
756 // Glue user must be scheduled together with the glue operand. So other
757 // users of the glue operand must be treated as its users.
758 SDNode *ImmGUser = Glue->getGluedUser();
759 for (SDNode::use_iterator ui = Glue->use_begin(), ue = Glue->use_end();
763 GUser->setNodeId(UDegree + Degree);
767 Sequence.reserve(DAGSize);
768 ScheduleNode(DAG->getRoot().getNode());
772 ScheduleDAGLinearize::EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
773 InstrEmitter Emitter(BB, InsertPos);
774 DenseMap<SDValue, unsigned> VRBaseMap;
777 dbgs() << "\n*** Final schedule ***\n";
780 // FIXME: Handle dbg_values.
781 unsigned NumNodes = Sequence.size();
782 for (unsigned i = 0; i != NumNodes; ++i) {
783 SDNode *N = Sequence[NumNodes-i-1];
785 Emitter.EmitNode(N, false, false, VRBaseMap);
788 DEBUG(dbgs() << '\n');
790 InsertPos = Emitter.getInsertPos();
791 return Emitter.getBlock();
794 //===----------------------------------------------------------------------===//
795 // Public Constructor Functions
796 //===----------------------------------------------------------------------===//
798 llvm::ScheduleDAGSDNodes *
799 llvm::createFastDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level) {
800 return new ScheduleDAGFast(*IS->MF);
803 llvm::ScheduleDAGSDNodes *
804 llvm::createDAGLinearizer(SelectionDAGISel *IS, CodeGenOpt::Level) {
805 return new ScheduleDAGLinearize(*IS->MF);