blob: 286ef1fa66860a05fededf96faa3d24b1dc6f370 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- ScheduleDAGSimple.cpp - Implement a trivial DAG scheduler ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by James M. Laskey and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements a simple two pass scheduler. The first pass attempts to push
11// backward any lengthy instructions and critical paths. The second pass packs
12// instructions into semi-optimal time slots.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "pre-RA-sched"
17#include "llvm/CodeGen/MachineFunction.h"
18#include "llvm/CodeGen/ScheduleDAG.h"
19#include "llvm/CodeGen/SchedulerRegistry.h"
20#include "llvm/CodeGen/SelectionDAG.h"
21#include "llvm/CodeGen/SSARegMap.h"
22#include "llvm/Target/TargetData.h"
23#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetInstrInfo.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/Compiler.h"
27#include <algorithm>
28using namespace llvm;
29
30namespace {
31
32static RegisterScheduler
33 bfsDAGScheduler("none", " No scheduling: breadth first sequencing",
34 createBFS_DAGScheduler);
35static RegisterScheduler
36 simpleDAGScheduler("simple",
37 " Simple two pass scheduling: minimize critical path "
38 "and maximize processor utilization",
39 createSimpleDAGScheduler);
40static RegisterScheduler
41 noitinDAGScheduler("simple-noitin",
42 " Simple two pass scheduling: Same as simple "
43 "except using generic latency",
44 createNoItinsDAGScheduler);
45
46class NodeInfo;
47typedef NodeInfo *NodeInfoPtr;
48typedef std::vector<NodeInfoPtr> NIVector;
49typedef std::vector<NodeInfoPtr>::iterator NIIterator;
50
51//===--------------------------------------------------------------------===//
52///
53/// Node group - This struct is used to manage flagged node groups.
54///
55class NodeGroup {
56public:
57 NodeGroup *Next;
58private:
59 NIVector Members; // Group member nodes
60 NodeInfo *Dominator; // Node with highest latency
61 unsigned Latency; // Total latency of the group
62 int Pending; // Number of visits pending before
63 // adding to order
64
65public:
66 // Ctor.
67 NodeGroup() : Next(NULL), Dominator(NULL), Pending(0) {}
68
69 // Accessors
70 inline void setDominator(NodeInfo *D) { Dominator = D; }
71 inline NodeInfo *getTop() { return Members.front(); }
72 inline NodeInfo *getBottom() { return Members.back(); }
73 inline NodeInfo *getDominator() { return Dominator; }
74 inline void setLatency(unsigned L) { Latency = L; }
75 inline unsigned getLatency() { return Latency; }
76 inline int getPending() const { return Pending; }
77 inline void setPending(int P) { Pending = P; }
78 inline int addPending(int I) { return Pending += I; }
79
80 // Pass thru
81 inline bool group_empty() { return Members.empty(); }
82 inline NIIterator group_begin() { return Members.begin(); }
83 inline NIIterator group_end() { return Members.end(); }
84 inline void group_push_back(const NodeInfoPtr &NI) {
85 Members.push_back(NI);
86 }
87 inline NIIterator group_insert(NIIterator Pos, const NodeInfoPtr &NI) {
88 return Members.insert(Pos, NI);
89 }
90 inline void group_insert(NIIterator Pos, NIIterator First,
91 NIIterator Last) {
92 Members.insert(Pos, First, Last);
93 }
94
95 static void Add(NodeInfo *D, NodeInfo *U);
96};
97
98//===--------------------------------------------------------------------===//
99///
100/// NodeInfo - This struct tracks information used to schedule the a node.
101///
102class NodeInfo {
103private:
104 int Pending; // Number of visits pending before
105 // adding to order
106public:
107 SDNode *Node; // DAG node
108 InstrStage *StageBegin; // First stage in itinerary
109 InstrStage *StageEnd; // Last+1 stage in itinerary
110 unsigned Latency; // Total cycles to complete instr
111 bool IsCall : 1; // Is function call
112 bool IsLoad : 1; // Is memory load
113 bool IsStore : 1; // Is memory store
114 unsigned Slot; // Node's time slot
115 NodeGroup *Group; // Grouping information
116#ifndef NDEBUG
117 unsigned Preorder; // Index before scheduling
118#endif
119
120 // Ctor.
121 NodeInfo(SDNode *N = NULL)
122 : Pending(0)
123 , Node(N)
124 , StageBegin(NULL)
125 , StageEnd(NULL)
126 , Latency(0)
127 , IsCall(false)
Chris Lattner696d2b42007-09-22 07:02:12 +0000128 , IsLoad(false)
129 , IsStore(false)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000130 , Slot(0)
131 , Group(NULL)
132#ifndef NDEBUG
133 , Preorder(0)
134#endif
135 {}
136
137 // Accessors
138 inline bool isInGroup() const {
139 assert(!Group || !Group->group_empty() && "Group with no members");
140 return Group != NULL;
141 }
142 inline bool isGroupDominator() const {
143 return isInGroup() && Group->getDominator() == this;
144 }
145 inline int getPending() const {
146 return Group ? Group->getPending() : Pending;
147 }
148 inline void setPending(int P) {
149 if (Group) Group->setPending(P);
150 else Pending = P;
151 }
152 inline int addPending(int I) {
153 if (Group) return Group->addPending(I);
154 else return Pending += I;
155 }
156};
157
158//===--------------------------------------------------------------------===//
159///
160/// NodeGroupIterator - Iterates over all the nodes indicated by the node
161/// info. If the node is in a group then iterate over the members of the
162/// group, otherwise just the node info.
163///
164class NodeGroupIterator {
165private:
166 NodeInfo *NI; // Node info
167 NIIterator NGI; // Node group iterator
168 NIIterator NGE; // Node group iterator end
David Greeneaa5912d2007-08-17 15:13:55 +0000169 bool iter_valid;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170
171public:
172 // Ctor.
David Greeneaa5912d2007-08-17 15:13:55 +0000173 NodeGroupIterator(NodeInfo *N) : NI(N), iter_valid(false) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174 // If the node is in a group then set up the group iterator. Otherwise
175 // the group iterators will trip first time out.
David Greeneaa5912d2007-08-17 15:13:55 +0000176 assert(N && "Bad node info");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 if (N->isInGroup()) {
178 // get Group
179 NodeGroup *Group = NI->Group;
180 NGI = Group->group_begin();
181 NGE = Group->group_end();
182 // Prevent this node from being used (will be in members list
183 NI = NULL;
David Greeneaa5912d2007-08-17 15:13:55 +0000184 iter_valid = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 }
186 }
187
188 /// next - Return the next node info, otherwise NULL.
189 ///
190 NodeInfo *next() {
David Greeneaa5912d2007-08-17 15:13:55 +0000191 if (iter_valid) {
192 // If members list
193 if (NGI != NGE) return *NGI++;
194 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 // Use node as the result (may be NULL)
196 NodeInfo *Result = NI;
197 // Only use once
198 NI = NULL;
199 // Return node or NULL
200 return Result;
201 }
202};
203//===--------------------------------------------------------------------===//
204
205
206//===--------------------------------------------------------------------===//
207///
208/// NodeGroupOpIterator - Iterates over all the operands of a node. If the
209/// node is a member of a group, this iterates over all the operands of all
210/// the members of the group.
211///
212class NodeGroupOpIterator {
213private:
214 NodeInfo *NI; // Node containing operands
215 NodeGroupIterator GI; // Node group iterator
216 SDNode::op_iterator OI; // Operand iterator
217 SDNode::op_iterator OE; // Operand iterator end
218
219 /// CheckNode - Test if node has more operands. If not get the next node
220 /// skipping over nodes that have no operands.
221 void CheckNode() {
222 // Only if operands are exhausted first
223 while (OI == OE) {
224 // Get next node info
225 NodeInfo *NI = GI.next();
226 // Exit if nodes are exhausted
227 if (!NI) return;
228 // Get node itself
229 SDNode *Node = NI->Node;
230 // Set up the operand iterators
231 OI = Node->op_begin();
232 OE = Node->op_end();
233 }
234 }
235
236public:
237 // Ctor.
238 NodeGroupOpIterator(NodeInfo *N)
239 : NI(N), GI(N), OI(SDNode::op_iterator()), OE(SDNode::op_iterator()) {}
240
241 /// isEnd - Returns true when not more operands are available.
242 ///
243 inline bool isEnd() { CheckNode(); return OI == OE; }
244
245 /// next - Returns the next available operand.
246 ///
247 inline SDOperand next() {
248 assert(OI != OE &&
249 "Not checking for end of NodeGroupOpIterator correctly");
250 return *OI++;
251 }
252};
253
254
255//===----------------------------------------------------------------------===//
256///
257/// BitsIterator - Provides iteration through individual bits in a bit vector.
258///
259template<class T>
260class BitsIterator {
261private:
262 T Bits; // Bits left to iterate through
263
264public:
265 /// Ctor.
266 BitsIterator(T Initial) : Bits(Initial) {}
267
268 /// Next - Returns the next bit set or zero if exhausted.
269 inline T Next() {
270 // Get the rightmost bit set
271 T Result = Bits & -Bits;
272 // Remove from rest
273 Bits &= ~Result;
274 // Return single bit or zero
275 return Result;
276 }
277};
278
279//===----------------------------------------------------------------------===//
280
281
282//===----------------------------------------------------------------------===//
283///
284/// ResourceTally - Manages the use of resources over time intervals. Each
285/// item (slot) in the tally vector represents the resources used at a given
286/// moment. A bit set to 1 indicates that a resource is in use, otherwise
287/// available. An assumption is made that the tally is large enough to schedule
288/// all current instructions (asserts otherwise.)
289///
290template<class T>
291class ResourceTally {
292private:
293 std::vector<T> Tally; // Resources used per slot
294 typedef typename std::vector<T>::iterator Iter;
295 // Tally iterator
296
297 /// SlotsAvailable - Returns true if all units are available.
298 ///
299 bool SlotsAvailable(Iter Begin, unsigned N, unsigned ResourceSet,
300 unsigned &Resource) {
301 assert(N && "Must check availability with N != 0");
302 // Determine end of interval
303 Iter End = Begin + N;
304 assert(End <= Tally.end() && "Tally is not large enough for schedule");
305
306 // Iterate thru each resource
307 BitsIterator<T> Resources(ResourceSet & ~*Begin);
308 while (unsigned Res = Resources.Next()) {
309 // Check if resource is available for next N slots
310 Iter Interval = End;
311 do {
312 Interval--;
313 if (*Interval & Res) break;
314 } while (Interval != Begin);
315
316 // If available for N
317 if (Interval == Begin) {
318 // Success
319 Resource = Res;
320 return true;
321 }
322 }
323
324 // No luck
325 Resource = 0;
326 return false;
327 }
328
329 /// RetrySlot - Finds a good candidate slot to retry search.
330 Iter RetrySlot(Iter Begin, unsigned N, unsigned ResourceSet) {
331 assert(N && "Must check availability with N != 0");
332 // Determine end of interval
333 Iter End = Begin + N;
334 assert(End <= Tally.end() && "Tally is not large enough for schedule");
335
336 while (Begin != End--) {
337 // Clear units in use
338 ResourceSet &= ~*End;
339 // If no units left then we should go no further
340 if (!ResourceSet) return End + 1;
341 }
342 // Made it all the way through
343 return Begin;
344 }
345
346 /// FindAndReserveStages - Return true if the stages can be completed. If
347 /// so mark as busy.
348 bool FindAndReserveStages(Iter Begin,
349 InstrStage *Stage, InstrStage *StageEnd) {
350 // If at last stage then we're done
351 if (Stage == StageEnd) return true;
352 // Get number of cycles for current stage
353 unsigned N = Stage->Cycles;
354 // Check to see if N slots are available, if not fail
355 unsigned Resource;
356 if (!SlotsAvailable(Begin, N, Stage->Units, Resource)) return false;
357 // Check to see if remaining stages are available, if not fail
358 if (!FindAndReserveStages(Begin + N, Stage + 1, StageEnd)) return false;
359 // Reserve resource
360 Reserve(Begin, N, Resource);
361 // Success
362 return true;
363 }
364
365 /// Reserve - Mark busy (set) the specified N slots.
366 void Reserve(Iter Begin, unsigned N, unsigned Resource) {
367 // Determine end of interval
368 Iter End = Begin + N;
369 assert(End <= Tally.end() && "Tally is not large enough for schedule");
370
371 // Set resource bit in each slot
372 for (; Begin < End; Begin++)
373 *Begin |= Resource;
374 }
375
376 /// FindSlots - Starting from Begin, locate consecutive slots where all stages
377 /// can be completed. Returns the address of first slot.
378 Iter FindSlots(Iter Begin, InstrStage *StageBegin, InstrStage *StageEnd) {
379 // Track position
380 Iter Cursor = Begin;
381
382 // Try all possible slots forward
383 while (true) {
384 // Try at cursor, if successful return position.
385 if (FindAndReserveStages(Cursor, StageBegin, StageEnd)) return Cursor;
386 // Locate a better position
387 Cursor = RetrySlot(Cursor + 1, StageBegin->Cycles, StageBegin->Units);
388 }
389 }
390
391public:
392 /// Initialize - Resize and zero the tally to the specified number of time
393 /// slots.
394 inline void Initialize(unsigned N) {
395 Tally.assign(N, 0); // Initialize tally to all zeros.
396 }
397
398 // FindAndReserve - Locate an ideal slot for the specified stages and mark
399 // as busy.
400 unsigned FindAndReserve(unsigned Slot, InstrStage *StageBegin,
401 InstrStage *StageEnd) {
402 // Where to begin
403 Iter Begin = Tally.begin() + Slot;
404 // Find a free slot
405 Iter Where = FindSlots(Begin, StageBegin, StageEnd);
406 // Distance is slot number
407 unsigned Final = Where - Tally.begin();
408 return Final;
409 }
410
411};
412
413//===----------------------------------------------------------------------===//
414///
415/// ScheduleDAGSimple - Simple two pass scheduler.
416///
417class VISIBILITY_HIDDEN ScheduleDAGSimple : public ScheduleDAG {
418private:
419 bool NoSched; // Just do a BFS schedule, nothing fancy
420 bool NoItins; // Don't use itineraries?
421 ResourceTally<unsigned> Tally; // Resource usage tally
422 unsigned NSlots; // Total latency
423 static const unsigned NotFound = ~0U; // Search marker
424
425 unsigned NodeCount; // Number of nodes in DAG
426 std::map<SDNode *, NodeInfo *> Map; // Map nodes to info
427 bool HasGroups; // True if there are any groups
428 NodeInfo *Info; // Info for nodes being scheduled
429 NIVector Ordering; // Emit ordering of nodes
430 NodeGroup *HeadNG, *TailNG; // Keep track of allocated NodeGroups
431
432public:
433
434 // Ctor.
435 ScheduleDAGSimple(bool noSched, bool noItins, SelectionDAG &dag,
436 MachineBasicBlock *bb, const TargetMachine &tm)
437 : ScheduleDAG(dag, bb, tm), NoSched(noSched), NoItins(noItins), NSlots(0),
438 NodeCount(0), HasGroups(false), Info(NULL), HeadNG(NULL), TailNG(NULL) {
439 assert(&TII && "Target doesn't provide instr info?");
440 assert(&MRI && "Target doesn't provide register info?");
441 }
442
443 virtual ~ScheduleDAGSimple() {
444 if (Info)
445 delete[] Info;
446
447 NodeGroup *NG = HeadNG;
448 while (NG) {
449 NodeGroup *NextSU = NG->Next;
450 delete NG;
451 NG = NextSU;
452 }
453 }
454
455 void Schedule();
456
457 /// getNI - Returns the node info for the specified node.
458 ///
459 NodeInfo *getNI(SDNode *Node) { return Map[Node]; }
460
461private:
462 static bool isDefiner(NodeInfo *A, NodeInfo *B);
463 void IncludeNode(NodeInfo *NI);
464 void VisitAll();
465 void GatherSchedulingInfo();
466 void FakeGroupDominators();
467 bool isStrongDependency(NodeInfo *A, NodeInfo *B);
468 bool isWeakDependency(NodeInfo *A, NodeInfo *B);
469 void ScheduleBackward();
470 void ScheduleForward();
471
472 void AddToGroup(NodeInfo *D, NodeInfo *U);
473 /// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
474 ///
475 void PrepareNodeInfo();
476
477 /// IdentifyGroups - Put flagged nodes into groups.
478 ///
479 void IdentifyGroups();
480
481 /// print - Print ordering to specified output stream.
482 ///
483 void print(std::ostream &O) const;
484 void print(std::ostream *O) const { if (O) print(*O); }
485
486 void dump(const char *tag) const;
487
488 virtual void dump() const;
489
490 /// EmitAll - Emit all nodes in schedule sorted order.
491 ///
492 void EmitAll();
493
494 /// printNI - Print node info.
495 ///
496 void printNI(std::ostream &O, NodeInfo *NI) const;
497 void printNI(std::ostream *O, NodeInfo *NI) const { if (O) printNI(*O, NI); }
498
499 /// printChanges - Hilight changes in order caused by scheduling.
500 ///
501 void printChanges(unsigned Index) const;
502};
503
504//===----------------------------------------------------------------------===//
505/// Special case itineraries.
506///
507enum {
508 CallLatency = 40, // To push calls back in time
509
510 RSInteger = 0xC0000000, // Two integer units
511 RSFloat = 0x30000000, // Two float units
512 RSLoadStore = 0x0C000000, // Two load store units
513 RSBranch = 0x02000000 // One branch unit
514};
515static InstrStage LoadStage = { 5, RSLoadStore };
516static InstrStage StoreStage = { 2, RSLoadStore };
517static InstrStage IntStage = { 2, RSInteger };
518static InstrStage FloatStage = { 3, RSFloat };
519//===----------------------------------------------------------------------===//
520
521} // namespace
522
523//===----------------------------------------------------------------------===//
524
525/// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
526///
527void ScheduleDAGSimple::PrepareNodeInfo() {
528 // Allocate node information
529 Info = new NodeInfo[NodeCount];
530
531 unsigned i = 0;
532 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
533 E = DAG.allnodes_end(); I != E; ++I, ++i) {
534 // Fast reference to node schedule info
535 NodeInfo* NI = &Info[i];
536 // Set up map
537 Map[I] = NI;
538 // Set node
539 NI->Node = I;
540 // Set pending visit count
541 NI->setPending(I->use_size());
542 }
543}
544
545/// IdentifyGroups - Put flagged nodes into groups.
546///
547void ScheduleDAGSimple::IdentifyGroups() {
548 for (unsigned i = 0, N = NodeCount; i < N; i++) {
549 NodeInfo* NI = &Info[i];
550 SDNode *Node = NI->Node;
551
552 // For each operand (in reverse to only look at flags)
553 for (unsigned N = Node->getNumOperands(); 0 < N--;) {
554 // Get operand
555 SDOperand Op = Node->getOperand(N);
556 // No more flags to walk
557 if (Op.getValueType() != MVT::Flag) break;
558 // Add to node group
559 AddToGroup(getNI(Op.Val), NI);
560 // Let everyone else know
561 HasGroups = true;
562 }
563 }
564}
565
566/// CountInternalUses - Returns the number of edges between the two nodes.
567///
568static unsigned CountInternalUses(NodeInfo *D, NodeInfo *U) {
569 unsigned N = 0;
570 for (unsigned M = U->Node->getNumOperands(); 0 < M--;) {
571 SDOperand Op = U->Node->getOperand(M);
572 if (Op.Val == D->Node) N++;
573 }
574
575 return N;
576}
577
578//===----------------------------------------------------------------------===//
579/// Add - Adds a definer and user pair to a node group.
580///
581void ScheduleDAGSimple::AddToGroup(NodeInfo *D, NodeInfo *U) {
582 // Get current groups
583 NodeGroup *DGroup = D->Group;
584 NodeGroup *UGroup = U->Group;
585 // If both are members of groups
586 if (DGroup && UGroup) {
587 // There may have been another edge connecting
588 if (DGroup == UGroup) return;
589 // Add the pending users count
590 DGroup->addPending(UGroup->getPending());
591 // For each member of the users group
592 NodeGroupIterator UNGI(U);
593 while (NodeInfo *UNI = UNGI.next() ) {
594 // Change the group
595 UNI->Group = DGroup;
596 // For each member of the definers group
597 NodeGroupIterator DNGI(D);
598 while (NodeInfo *DNI = DNGI.next() ) {
599 // Remove internal edges
600 DGroup->addPending(-CountInternalUses(DNI, UNI));
601 }
602 }
603 // Merge the two lists
604 DGroup->group_insert(DGroup->group_end(),
605 UGroup->group_begin(), UGroup->group_end());
606 } else if (DGroup) {
607 // Make user member of definers group
608 U->Group = DGroup;
609 // Add users uses to definers group pending
610 DGroup->addPending(U->Node->use_size());
611 // For each member of the definers group
612 NodeGroupIterator DNGI(D);
613 while (NodeInfo *DNI = DNGI.next() ) {
614 // Remove internal edges
615 DGroup->addPending(-CountInternalUses(DNI, U));
616 }
617 DGroup->group_push_back(U);
618 } else if (UGroup) {
619 // Make definer member of users group
620 D->Group = UGroup;
621 // Add definers uses to users group pending
622 UGroup->addPending(D->Node->use_size());
623 // For each member of the users group
624 NodeGroupIterator UNGI(U);
625 while (NodeInfo *UNI = UNGI.next() ) {
626 // Remove internal edges
627 UGroup->addPending(-CountInternalUses(D, UNI));
628 }
629 UGroup->group_insert(UGroup->group_begin(), D);
630 } else {
631 D->Group = U->Group = DGroup = new NodeGroup();
632 DGroup->addPending(D->Node->use_size() + U->Node->use_size() -
633 CountInternalUses(D, U));
634 DGroup->group_push_back(D);
635 DGroup->group_push_back(U);
636
637 if (HeadNG == NULL)
638 HeadNG = DGroup;
639 if (TailNG != NULL)
640 TailNG->Next = DGroup;
641 TailNG = DGroup;
642 }
643}
644
645
646/// print - Print ordering to specified output stream.
647///
648void ScheduleDAGSimple::print(std::ostream &O) const {
649#ifndef NDEBUG
650 O << "Ordering\n";
651 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
652 NodeInfo *NI = Ordering[i];
653 printNI(O, NI);
654 O << "\n";
655 if (NI->isGroupDominator()) {
656 NodeGroup *Group = NI->Group;
657 for (NIIterator NII = Group->group_begin(), E = Group->group_end();
658 NII != E; NII++) {
659 O << " ";
660 printNI(O, *NII);
661 O << "\n";
662 }
663 }
664 }
665#endif
666}
667
668void ScheduleDAGSimple::dump(const char *tag) const {
669 cerr << tag; dump();
670}
671
672void ScheduleDAGSimple::dump() const {
673 print(cerr);
674}
675
676
677/// EmitAll - Emit all nodes in schedule sorted order.
678///
679void ScheduleDAGSimple::EmitAll() {
680 // If this is the first basic block in the function, and if it has live ins
681 // that need to be copied into vregs, emit the copies into the top of the
682 // block before emitting the code for the block.
683 MachineFunction &MF = DAG.getMachineFunction();
684 if (&MF.front() == BB && MF.livein_begin() != MF.livein_end()) {
685 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
686 E = MF.livein_end(); LI != E; ++LI)
687 if (LI->second)
688 MRI->copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
689 LI->first, RegMap->getRegClass(LI->second));
690 }
691
692 DenseMap<SDOperand, unsigned> VRBaseMap;
693
694 // For each node in the ordering
695 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
696 // Get the scheduling info
697 NodeInfo *NI = Ordering[i];
698 if (NI->isInGroup()) {
699 NodeGroupIterator NGI(Ordering[i]);
Evan Cheng93f143e2007-09-25 01:54:36 +0000700 while (NodeInfo *NI = NGI.next()) EmitNode(NI->Node, 0, VRBaseMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701 } else {
Evan Cheng93f143e2007-09-25 01:54:36 +0000702 EmitNode(NI->Node, 0, VRBaseMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000703 }
704 }
705}
706
707/// isFlagDefiner - Returns true if the node defines a flag result.
708static bool isFlagDefiner(SDNode *A) {
709 unsigned N = A->getNumValues();
710 return N && A->getValueType(N - 1) == MVT::Flag;
711}
712
713/// isFlagUser - Returns true if the node uses a flag result.
714///
715static bool isFlagUser(SDNode *A) {
716 unsigned N = A->getNumOperands();
717 return N && A->getOperand(N - 1).getValueType() == MVT::Flag;
718}
719
720/// printNI - Print node info.
721///
722void ScheduleDAGSimple::printNI(std::ostream &O, NodeInfo *NI) const {
723#ifndef NDEBUG
724 SDNode *Node = NI->Node;
725 O << " "
726 << std::hex << Node << std::dec
727 << ", Lat=" << NI->Latency
728 << ", Slot=" << NI->Slot
729 << ", ARITY=(" << Node->getNumOperands() << ","
730 << Node->getNumValues() << ")"
731 << " " << Node->getOperationName(&DAG);
732 if (isFlagDefiner(Node)) O << "<#";
733 if (isFlagUser(Node)) O << ">#";
734#endif
735}
736
737/// printChanges - Hilight changes in order caused by scheduling.
738///
739void ScheduleDAGSimple::printChanges(unsigned Index) const {
740#ifndef NDEBUG
741 // Get the ordered node count
742 unsigned N = Ordering.size();
743 // Determine if any changes
744 unsigned i = 0;
745 for (; i < N; i++) {
746 NodeInfo *NI = Ordering[i];
747 if (NI->Preorder != i) break;
748 }
749
750 if (i < N) {
751 cerr << Index << ". New Ordering\n";
752
753 for (i = 0; i < N; i++) {
754 NodeInfo *NI = Ordering[i];
755 cerr << " " << NI->Preorder << ". ";
756 printNI(cerr, NI);
757 cerr << "\n";
758 if (NI->isGroupDominator()) {
759 NodeGroup *Group = NI->Group;
760 for (NIIterator NII = Group->group_begin(), E = Group->group_end();
761 NII != E; NII++) {
762 cerr << " ";
763 printNI(cerr, *NII);
764 cerr << "\n";
765 }
766 }
767 }
768 } else {
769 cerr << Index << ". No Changes\n";
770 }
771#endif
772}
773
774//===----------------------------------------------------------------------===//
775/// isDefiner - Return true if node A is a definer for B.
776///
777bool ScheduleDAGSimple::isDefiner(NodeInfo *A, NodeInfo *B) {
778 // While there are A nodes
779 NodeGroupIterator NII(A);
780 while (NodeInfo *NI = NII.next()) {
781 // Extract node
782 SDNode *Node = NI->Node;
783 // While there operands in nodes of B
784 NodeGroupOpIterator NGOI(B);
785 while (!NGOI.isEnd()) {
786 SDOperand Op = NGOI.next();
787 // If node from A defines a node in B
788 if (Node == Op.Val) return true;
789 }
790 }
791 return false;
792}
793
794/// IncludeNode - Add node to NodeInfo vector.
795///
796void ScheduleDAGSimple::IncludeNode(NodeInfo *NI) {
797 // Get node
798 SDNode *Node = NI->Node;
799 // Ignore entry node
800 if (Node->getOpcode() == ISD::EntryToken) return;
801 // Check current count for node
802 int Count = NI->getPending();
803 // If the node is already in list
804 if (Count < 0) return;
805 // Decrement count to indicate a visit
806 Count--;
807 // If count has gone to zero then add node to list
808 if (!Count) {
809 // Add node
810 if (NI->isInGroup()) {
811 Ordering.push_back(NI->Group->getDominator());
812 } else {
813 Ordering.push_back(NI);
814 }
815 // indicate node has been added
816 Count--;
817 }
818 // Mark as visited with new count
819 NI->setPending(Count);
820}
821
822/// GatherSchedulingInfo - Get latency and resource information about each node.
823///
824void ScheduleDAGSimple::GatherSchedulingInfo() {
825 // Get instruction itineraries for the target
826 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
827
828 // For each node
829 for (unsigned i = 0, N = NodeCount; i < N; i++) {
830 // Get node info
831 NodeInfo* NI = &Info[i];
832 SDNode *Node = NI->Node;
833
834 // If there are itineraries and it is a machine instruction
835 if (InstrItins.isEmpty() || NoItins) {
836 // If machine opcode
837 if (Node->isTargetOpcode()) {
838 // Get return type to guess which processing unit
839 MVT::ValueType VT = Node->getValueType(0);
840 // Get machine opcode
841 MachineOpCode TOpc = Node->getTargetOpcode();
842 NI->IsCall = TII->isCall(TOpc);
843 NI->IsLoad = TII->isLoad(TOpc);
844 NI->IsStore = TII->isStore(TOpc);
845
846 if (TII->isLoad(TOpc)) NI->StageBegin = &LoadStage;
847 else if (TII->isStore(TOpc)) NI->StageBegin = &StoreStage;
848 else if (MVT::isInteger(VT)) NI->StageBegin = &IntStage;
849 else if (MVT::isFloatingPoint(VT)) NI->StageBegin = &FloatStage;
850 if (NI->StageBegin) NI->StageEnd = NI->StageBegin + 1;
851 }
852 } else if (Node->isTargetOpcode()) {
853 // get machine opcode
854 MachineOpCode TOpc = Node->getTargetOpcode();
855 // Check to see if it is a call
856 NI->IsCall = TII->isCall(TOpc);
857 // Get itinerary stages for instruction
858 unsigned II = TII->getSchedClass(TOpc);
859 NI->StageBegin = InstrItins.begin(II);
860 NI->StageEnd = InstrItins.end(II);
861 }
862
863 // One slot for the instruction itself
864 NI->Latency = 1;
865
866 // Add long latency for a call to push it back in time
867 if (NI->IsCall) NI->Latency += CallLatency;
868
869 // Sum up all the latencies
870 for (InstrStage *Stage = NI->StageBegin, *E = NI->StageEnd;
871 Stage != E; Stage++) {
872 NI->Latency += Stage->Cycles;
873 }
874
875 // Sum up all the latencies for max tally size
876 NSlots += NI->Latency;
877 }
878
879 // Unify metrics if in a group
880 if (HasGroups) {
881 for (unsigned i = 0, N = NodeCount; i < N; i++) {
882 NodeInfo* NI = &Info[i];
883
884 if (NI->isInGroup()) {
885 NodeGroup *Group = NI->Group;
886
887 if (!Group->getDominator()) {
888 NIIterator NGI = Group->group_begin(), NGE = Group->group_end();
889 NodeInfo *Dominator = *NGI;
890 unsigned Latency = 0;
891
892 for (NGI++; NGI != NGE; NGI++) {
893 NodeInfo* NGNI = *NGI;
894 Latency += NGNI->Latency;
895 if (Dominator->Latency < NGNI->Latency) Dominator = NGNI;
896 }
897
898 Dominator->Latency = Latency;
899 Group->setDominator(Dominator);
900 }
901 }
902 }
903 }
904}
905
906/// VisitAll - Visit each node breadth-wise to produce an initial ordering.
907/// Note that the ordering in the Nodes vector is reversed.
908void ScheduleDAGSimple::VisitAll() {
909 // Add first element to list
910 NodeInfo *NI = getNI(DAG.getRoot().Val);
911 if (NI->isInGroup()) {
912 Ordering.push_back(NI->Group->getDominator());
913 } else {
914 Ordering.push_back(NI);
915 }
916
917 // Iterate through all nodes that have been added
918 for (unsigned i = 0; i < Ordering.size(); i++) { // note: size() varies
919 // Visit all operands
920 NodeGroupOpIterator NGI(Ordering[i]);
921 while (!NGI.isEnd()) {
922 // Get next operand
923 SDOperand Op = NGI.next();
924 // Get node
925 SDNode *Node = Op.Val;
926 // Ignore passive nodes
927 if (isPassiveNode(Node)) continue;
928 // Check out node
929 IncludeNode(getNI(Node));
930 }
931 }
932
933 // Add entry node last (IncludeNode filters entry nodes)
934 if (DAG.getEntryNode().Val != DAG.getRoot().Val)
935 Ordering.push_back(getNI(DAG.getEntryNode().Val));
936
937 // Reverse the order
938 std::reverse(Ordering.begin(), Ordering.end());
939}
940
941/// FakeGroupDominators - Set dominators for non-scheduling.
942///
943void ScheduleDAGSimple::FakeGroupDominators() {
944 for (unsigned i = 0, N = NodeCount; i < N; i++) {
945 NodeInfo* NI = &Info[i];
946
947 if (NI->isInGroup()) {
948 NodeGroup *Group = NI->Group;
949
950 if (!Group->getDominator()) {
951 Group->setDominator(NI);
952 }
953 }
954 }
955}
956
957/// isStrongDependency - Return true if node A has results used by node B.
958/// I.E., B must wait for latency of A.
959bool ScheduleDAGSimple::isStrongDependency(NodeInfo *A, NodeInfo *B) {
960 // If A defines for B then it's a strong dependency or
961 // if a load follows a store (may be dependent but why take a chance.)
962 return isDefiner(A, B) || (A->IsStore && B->IsLoad);
963}
964
965/// isWeakDependency Return true if node A produces a result that will
966/// conflict with operands of B. It is assumed that we have called
967/// isStrongDependency prior.
968bool ScheduleDAGSimple::isWeakDependency(NodeInfo *A, NodeInfo *B) {
969 // TODO check for conflicting real registers and aliases
970#if 0 // FIXME - Since we are in SSA form and not checking register aliasing
971 return A->Node->getOpcode() == ISD::EntryToken || isStrongDependency(B, A);
972#else
973 return A->Node->getOpcode() == ISD::EntryToken;
974#endif
975}
976
977/// ScheduleBackward - Schedule instructions so that any long latency
978/// instructions and the critical path get pushed back in time. Time is run in
979/// reverse to allow code reuse of the Tally and eliminate the overhead of
980/// biasing every slot indices against NSlots.
981void ScheduleDAGSimple::ScheduleBackward() {
982 // Size and clear the resource tally
983 Tally.Initialize(NSlots);
984 // Get number of nodes to schedule
985 unsigned N = Ordering.size();
986
987 // For each node being scheduled
988 for (unsigned i = N; 0 < i--;) {
989 NodeInfo *NI = Ordering[i];
990 // Track insertion
991 unsigned Slot = NotFound;
992
993 // Compare against those previously scheduled nodes
994 unsigned j = i + 1;
995 for (; j < N; j++) {
996 // Get following instruction
997 NodeInfo *Other = Ordering[j];
998
999 // Check dependency against previously inserted nodes
1000 if (isStrongDependency(NI, Other)) {
1001 Slot = Other->Slot + Other->Latency;
1002 break;
1003 } else if (isWeakDependency(NI, Other)) {
1004 Slot = Other->Slot;
1005 break;
1006 }
1007 }
1008
1009 // If independent of others (or first entry)
1010 if (Slot == NotFound) Slot = 0;
1011
1012#if 0 // FIXME - measure later
1013 // Find a slot where the needed resources are available
1014 if (NI->StageBegin != NI->StageEnd)
1015 Slot = Tally.FindAndReserve(Slot, NI->StageBegin, NI->StageEnd);
1016#endif
1017
1018 // Set node slot
1019 NI->Slot = Slot;
1020
1021 // Insert sort based on slot
1022 j = i + 1;
1023 for (; j < N; j++) {
1024 // Get following instruction
1025 NodeInfo *Other = Ordering[j];
1026 // Should we look further (remember slots are in reverse time)
1027 if (Slot >= Other->Slot) break;
1028 // Shuffle other into ordering
1029 Ordering[j - 1] = Other;
1030 }
1031 // Insert node in proper slot
1032 if (j != i + 1) Ordering[j - 1] = NI;
1033 }
1034}
1035
1036/// ScheduleForward - Schedule instructions to maximize packing.
1037///
1038void ScheduleDAGSimple::ScheduleForward() {
1039 // Size and clear the resource tally
1040 Tally.Initialize(NSlots);
1041 // Get number of nodes to schedule
1042 unsigned N = Ordering.size();
1043
1044 // For each node being scheduled
1045 for (unsigned i = 0; i < N; i++) {
1046 NodeInfo *NI = Ordering[i];
1047 // Track insertion
1048 unsigned Slot = NotFound;
1049
1050 // Compare against those previously scheduled nodes
1051 unsigned j = i;
1052 for (; 0 < j--;) {
1053 // Get following instruction
1054 NodeInfo *Other = Ordering[j];
1055
1056 // Check dependency against previously inserted nodes
1057 if (isStrongDependency(Other, NI)) {
1058 Slot = Other->Slot + Other->Latency;
1059 break;
1060 } else if (Other->IsCall || isWeakDependency(Other, NI)) {
1061 Slot = Other->Slot;
1062 break;
1063 }
1064 }
1065
1066 // If independent of others (or first entry)
1067 if (Slot == NotFound) Slot = 0;
1068
1069 // Find a slot where the needed resources are available
1070 if (NI->StageBegin != NI->StageEnd)
1071 Slot = Tally.FindAndReserve(Slot, NI->StageBegin, NI->StageEnd);
1072
1073 // Set node slot
1074 NI->Slot = Slot;
1075
1076 // Insert sort based on slot
1077 j = i;
1078 for (; 0 < j--;) {
1079 // Get prior instruction
1080 NodeInfo *Other = Ordering[j];
1081 // Should we look further
1082 if (Slot >= Other->Slot) break;
1083 // Shuffle other into ordering
1084 Ordering[j + 1] = Other;
1085 }
1086 // Insert node in proper slot
1087 if (j != i) Ordering[j + 1] = NI;
1088 }
1089}
1090
1091/// Schedule - Order nodes according to selected style.
1092///
1093void ScheduleDAGSimple::Schedule() {
1094 // Number the nodes
1095 NodeCount = std::distance(DAG.allnodes_begin(), DAG.allnodes_end());
1096
1097 // Set up minimum info for scheduling
1098 PrepareNodeInfo();
1099 // Construct node groups for flagged nodes
1100 IdentifyGroups();
1101
1102 // Test to see if scheduling should occur
1103 bool ShouldSchedule = NodeCount > 3 && !NoSched;
1104 // Don't waste time if is only entry and return
1105 if (ShouldSchedule) {
1106 // Get latency and resource requirements
1107 GatherSchedulingInfo();
1108 } else if (HasGroups) {
1109 // Make sure all the groups have dominators
1110 FakeGroupDominators();
1111 }
1112
1113 // Breadth first walk of DAG
1114 VisitAll();
1115
1116#ifndef NDEBUG
1117 static unsigned Count = 0;
1118 Count++;
1119 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
1120 NodeInfo *NI = Ordering[i];
1121 NI->Preorder = i;
1122 }
1123#endif
1124
1125 // Don't waste time if is only entry and return
1126 if (ShouldSchedule) {
1127 // Push back long instructions and critical path
1128 ScheduleBackward();
1129
1130 // Pack instructions to maximize resource utilization
1131 ScheduleForward();
1132 }
1133
1134 DEBUG(printChanges(Count));
1135
1136 // Emit in scheduled order
1137 EmitAll();
1138}
1139
1140
1141/// createSimpleDAGScheduler - This creates a simple two pass instruction
1142/// scheduler using instruction itinerary.
1143llvm::ScheduleDAG* llvm::createSimpleDAGScheduler(SelectionDAGISel *IS,
1144 SelectionDAG *DAG,
1145 MachineBasicBlock *BB) {
1146 return new ScheduleDAGSimple(false, false, *DAG, BB, DAG->getTarget());
1147}
1148
1149/// createNoItinsDAGScheduler - This creates a simple two pass instruction
1150/// scheduler without using instruction itinerary.
1151llvm::ScheduleDAG* llvm::createNoItinsDAGScheduler(SelectionDAGISel *IS,
1152 SelectionDAG *DAG,
1153 MachineBasicBlock *BB) {
1154 return new ScheduleDAGSimple(false, true, *DAG, BB, DAG->getTarget());
1155}
1156
1157/// createBFS_DAGScheduler - This creates a simple breadth first instruction
1158/// scheduler.
1159llvm::ScheduleDAG* llvm::createBFS_DAGScheduler(SelectionDAGISel *IS,
1160 SelectionDAG *DAG,
1161 MachineBasicBlock *BB) {
1162 return new ScheduleDAGSimple(true, false, *DAG, BB, DAG->getTarget());
1163}