blob: 5497ecf93bf7862cf8d519b06a4cbffa02d8062c [file] [log] [blame]
Evan Chenga9c20912006-01-21 02:32:06 +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 "sched"
17#include "llvm/CodeGen/ScheduleDAG.h"
18#include "llvm/CodeGen/SelectionDAG.h"
19#include "llvm/Target/TargetMachine.h"
20#include "llvm/Target/TargetInstrInfo.h"
Evan Chenga9c20912006-01-21 02:32:06 +000021#include "llvm/Support/Debug.h"
Jeff Cohen2aa750a2006-01-24 04:43:17 +000022#include <algorithm>
Chris Lattnere76074a2006-03-10 07:35:21 +000023#include <iostream>
Evan Chenga9c20912006-01-21 02:32:06 +000024using namespace llvm;
25
26namespace {
Evan Chenga9c20912006-01-21 02:32:06 +000027//===----------------------------------------------------------------------===//
28///
29/// BitsIterator - Provides iteration through individual bits in a bit vector.
30///
31template<class T>
32class BitsIterator {
33private:
34 T Bits; // Bits left to iterate through
35
36public:
37 /// Ctor.
38 BitsIterator(T Initial) : Bits(Initial) {}
39
40 /// Next - Returns the next bit set or zero if exhausted.
41 inline T Next() {
42 // Get the rightmost bit set
43 T Result = Bits & -Bits;
44 // Remove from rest
45 Bits &= ~Result;
46 // Return single bit or zero
47 return Result;
48 }
49};
50
51//===----------------------------------------------------------------------===//
52
53
54//===----------------------------------------------------------------------===//
55///
56/// ResourceTally - Manages the use of resources over time intervals. Each
57/// item (slot) in the tally vector represents the resources used at a given
58/// moment. A bit set to 1 indicates that a resource is in use, otherwise
59/// available. An assumption is made that the tally is large enough to schedule
60/// all current instructions (asserts otherwise.)
61///
62template<class T>
63class ResourceTally {
64private:
65 std::vector<T> Tally; // Resources used per slot
66 typedef typename std::vector<T>::iterator Iter;
67 // Tally iterator
68
69 /// SlotsAvailable - Returns true if all units are available.
70 ///
71 bool SlotsAvailable(Iter Begin, unsigned N, unsigned ResourceSet,
72 unsigned &Resource) {
73 assert(N && "Must check availability with N != 0");
74 // Determine end of interval
75 Iter End = Begin + N;
76 assert(End <= Tally.end() && "Tally is not large enough for schedule");
77
78 // Iterate thru each resource
79 BitsIterator<T> Resources(ResourceSet & ~*Begin);
80 while (unsigned Res = Resources.Next()) {
81 // Check if resource is available for next N slots
82 Iter Interval = End;
83 do {
84 Interval--;
85 if (*Interval & Res) break;
86 } while (Interval != Begin);
87
88 // If available for N
89 if (Interval == Begin) {
90 // Success
91 Resource = Res;
92 return true;
93 }
94 }
95
96 // No luck
97 Resource = 0;
98 return false;
99 }
100
101 /// RetrySlot - Finds a good candidate slot to retry search.
102 Iter RetrySlot(Iter Begin, unsigned N, unsigned ResourceSet) {
103 assert(N && "Must check availability with N != 0");
104 // Determine end of interval
105 Iter End = Begin + N;
106 assert(End <= Tally.end() && "Tally is not large enough for schedule");
107
108 while (Begin != End--) {
109 // Clear units in use
110 ResourceSet &= ~*End;
111 // If no units left then we should go no further
112 if (!ResourceSet) return End + 1;
113 }
114 // Made it all the way through
115 return Begin;
116 }
117
118 /// FindAndReserveStages - Return true if the stages can be completed. If
119 /// so mark as busy.
120 bool FindAndReserveStages(Iter Begin,
121 InstrStage *Stage, InstrStage *StageEnd) {
122 // If at last stage then we're done
123 if (Stage == StageEnd) return true;
124 // Get number of cycles for current stage
125 unsigned N = Stage->Cycles;
126 // Check to see if N slots are available, if not fail
127 unsigned Resource;
128 if (!SlotsAvailable(Begin, N, Stage->Units, Resource)) return false;
129 // Check to see if remaining stages are available, if not fail
130 if (!FindAndReserveStages(Begin + N, Stage + 1, StageEnd)) return false;
131 // Reserve resource
132 Reserve(Begin, N, Resource);
133 // Success
134 return true;
135 }
136
137 /// Reserve - Mark busy (set) the specified N slots.
138 void Reserve(Iter Begin, unsigned N, unsigned Resource) {
139 // Determine end of interval
140 Iter End = Begin + N;
141 assert(End <= Tally.end() && "Tally is not large enough for schedule");
142
143 // Set resource bit in each slot
144 for (; Begin < End; Begin++)
145 *Begin |= Resource;
146 }
147
148 /// FindSlots - Starting from Begin, locate consecutive slots where all stages
149 /// can be completed. Returns the address of first slot.
150 Iter FindSlots(Iter Begin, InstrStage *StageBegin, InstrStage *StageEnd) {
151 // Track position
152 Iter Cursor = Begin;
153
154 // Try all possible slots forward
155 while (true) {
156 // Try at cursor, if successful return position.
157 if (FindAndReserveStages(Cursor, StageBegin, StageEnd)) return Cursor;
158 // Locate a better position
159 Cursor = RetrySlot(Cursor + 1, StageBegin->Cycles, StageBegin->Units);
160 }
161 }
162
163public:
164 /// Initialize - Resize and zero the tally to the specified number of time
165 /// slots.
166 inline void Initialize(unsigned N) {
167 Tally.assign(N, 0); // Initialize tally to all zeros.
168 }
169
170 // FindAndReserve - Locate an ideal slot for the specified stages and mark
171 // as busy.
172 unsigned FindAndReserve(unsigned Slot, InstrStage *StageBegin,
173 InstrStage *StageEnd) {
174 // Where to begin
175 Iter Begin = Tally.begin() + Slot;
176 // Find a free slot
177 Iter Where = FindSlots(Begin, StageBegin, StageEnd);
178 // Distance is slot number
179 unsigned Final = Where - Tally.begin();
180 return Final;
181 }
182
183};
184
185//===----------------------------------------------------------------------===//
186///
187/// ScheduleDAGSimple - Simple two pass scheduler.
188///
189class ScheduleDAGSimple : public ScheduleDAG {
190private:
Evan Chenga9c20912006-01-21 02:32:06 +0000191 ResourceTally<unsigned> Tally; // Resource usage tally
192 unsigned NSlots; // Total latency
193 static const unsigned NotFound = ~0U; // Search marker
194
195public:
196
197 // Ctor.
Evan Cheng4ef10862006-01-23 07:01:07 +0000198 ScheduleDAGSimple(SchedHeuristics hstc, SelectionDAG &dag,
199 MachineBasicBlock *bb, const TargetMachine &tm)
200 : ScheduleDAG(hstc, dag, bb, tm), Tally(), NSlots(0) {
Evan Chenga9c20912006-01-21 02:32:06 +0000201 assert(&TII && "Target doesn't provide instr info?");
202 assert(&MRI && "Target doesn't provide register info?");
203 }
204
205 virtual ~ScheduleDAGSimple() {};
206
Evan Cheng41484292006-01-23 08:25:34 +0000207 void Schedule();
208
Evan Chenga9c20912006-01-21 02:32:06 +0000209private:
Evan Chenga9c20912006-01-21 02:32:06 +0000210 static bool isDefiner(NodeInfo *A, NodeInfo *B);
Evan Chenga9c20912006-01-21 02:32:06 +0000211 void IncludeNode(NodeInfo *NI);
212 void VisitAll();
Evan Chenga9c20912006-01-21 02:32:06 +0000213 void GatherSchedulingInfo();
214 void FakeGroupDominators();
Evan Chenga9c20912006-01-21 02:32:06 +0000215 bool isStrongDependency(NodeInfo *A, NodeInfo *B);
216 bool isWeakDependency(NodeInfo *A, NodeInfo *B);
217 void ScheduleBackward();
218 void ScheduleForward();
Chris Lattnere76074a2006-03-10 07:35:21 +0000219
220 void AddToGroup(NodeInfo *D, NodeInfo *U);
221 /// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
222 ///
223 void PrepareNodeInfo();
224
225 /// IdentifyGroups - Put flagged nodes into groups.
226 ///
227 void IdentifyGroups();
228
229 /// print - Print ordering to specified output stream.
230 ///
231 void print(std::ostream &O) const;
232
233 void dump(const char *tag) const;
234
235 virtual void dump() const;
236
237 /// EmitAll - Emit all nodes in schedule sorted order.
238 ///
239 void EmitAll();
240
241 /// printNI - Print node info.
242 ///
243 void printNI(std::ostream &O, NodeInfo *NI) const;
244
245 /// printChanges - Hilight changes in order caused by scheduling.
246 ///
247 void printChanges(unsigned Index) const;
Evan Chenga9c20912006-01-21 02:32:06 +0000248};
249
Evan Chenga9c20912006-01-21 02:32:06 +0000250//===----------------------------------------------------------------------===//
251/// Special case itineraries.
252///
253enum {
254 CallLatency = 40, // To push calls back in time
255
256 RSInteger = 0xC0000000, // Two integer units
257 RSFloat = 0x30000000, // Two float units
258 RSLoadStore = 0x0C000000, // Two load store units
259 RSBranch = 0x02000000 // One branch unit
260};
261static InstrStage CallStage = { CallLatency, RSBranch };
262static InstrStage LoadStage = { 5, RSLoadStore };
263static InstrStage StoreStage = { 2, RSLoadStore };
264static InstrStage IntStage = { 2, RSInteger };
265static InstrStage FloatStage = { 3, RSFloat };
266//===----------------------------------------------------------------------===//
267
Evan Chenga9c20912006-01-21 02:32:06 +0000268} // namespace
269
270//===----------------------------------------------------------------------===//
271
Chris Lattnere76074a2006-03-10 07:35:21 +0000272/// PrepareNodeInfo - Set up the basic minimum node info for scheduling.
273///
274void ScheduleDAGSimple::PrepareNodeInfo() {
275 // Allocate node information
276 Info = new NodeInfo[NodeCount];
277
278 unsigned i = 0;
279 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
280 E = DAG.allnodes_end(); I != E; ++I, ++i) {
281 // Fast reference to node schedule info
282 NodeInfo* NI = &Info[i];
283 // Set up map
284 Map[I] = NI;
285 // Set node
286 NI->Node = I;
287 // Set pending visit count
288 NI->setPending(I->use_size());
289 }
290}
291
292/// IdentifyGroups - Put flagged nodes into groups.
293///
294void ScheduleDAGSimple::IdentifyGroups() {
295 for (unsigned i = 0, N = NodeCount; i < N; i++) {
296 NodeInfo* NI = &Info[i];
297 SDNode *Node = NI->Node;
298
299 // For each operand (in reverse to only look at flags)
300 for (unsigned N = Node->getNumOperands(); 0 < N--;) {
301 // Get operand
302 SDOperand Op = Node->getOperand(N);
303 // No more flags to walk
304 if (Op.getValueType() != MVT::Flag) break;
305 // Add to node group
306 AddToGroup(getNI(Op.Val), NI);
307 // Let everyone else know
308 HasGroups = true;
309 }
310 }
311}
312
313/// CountInternalUses - Returns the number of edges between the two nodes.
314///
315static unsigned CountInternalUses(NodeInfo *D, NodeInfo *U) {
316 unsigned N = 0;
317 for (unsigned M = U->Node->getNumOperands(); 0 < M--;) {
318 SDOperand Op = U->Node->getOperand(M);
319 if (Op.Val == D->Node) N++;
320 }
321
322 return N;
323}
324
325//===----------------------------------------------------------------------===//
326/// Add - Adds a definer and user pair to a node group.
327///
328void ScheduleDAGSimple::AddToGroup(NodeInfo *D, NodeInfo *U) {
329 // Get current groups
330 NodeGroup *DGroup = D->Group;
331 NodeGroup *UGroup = U->Group;
332 // If both are members of groups
333 if (DGroup && UGroup) {
334 // There may have been another edge connecting
335 if (DGroup == UGroup) return;
336 // Add the pending users count
337 DGroup->addPending(UGroup->getPending());
338 // For each member of the users group
339 NodeGroupIterator UNGI(U);
340 while (NodeInfo *UNI = UNGI.next() ) {
341 // Change the group
342 UNI->Group = DGroup;
343 // For each member of the definers group
344 NodeGroupIterator DNGI(D);
345 while (NodeInfo *DNI = DNGI.next() ) {
346 // Remove internal edges
347 DGroup->addPending(-CountInternalUses(DNI, UNI));
348 }
349 }
350 // Merge the two lists
351 DGroup->group_insert(DGroup->group_end(),
352 UGroup->group_begin(), UGroup->group_end());
353 } else if (DGroup) {
354 // Make user member of definers group
355 U->Group = DGroup;
356 // Add users uses to definers group pending
357 DGroup->addPending(U->Node->use_size());
358 // For each member of the definers group
359 NodeGroupIterator DNGI(D);
360 while (NodeInfo *DNI = DNGI.next() ) {
361 // Remove internal edges
362 DGroup->addPending(-CountInternalUses(DNI, U));
363 }
364 DGroup->group_push_back(U);
365 } else if (UGroup) {
366 // Make definer member of users group
367 D->Group = UGroup;
368 // Add definers uses to users group pending
369 UGroup->addPending(D->Node->use_size());
370 // For each member of the users group
371 NodeGroupIterator UNGI(U);
372 while (NodeInfo *UNI = UNGI.next() ) {
373 // Remove internal edges
374 UGroup->addPending(-CountInternalUses(D, UNI));
375 }
376 UGroup->group_insert(UGroup->group_begin(), D);
377 } else {
378 D->Group = U->Group = DGroup = new NodeGroup();
379 DGroup->addPending(D->Node->use_size() + U->Node->use_size() -
380 CountInternalUses(D, U));
381 DGroup->group_push_back(D);
382 DGroup->group_push_back(U);
383
384 if (HeadNG == NULL)
385 HeadNG = DGroup;
386 if (TailNG != NULL)
387 TailNG->Next = DGroup;
388 TailNG = DGroup;
389 }
390}
391
392
393/// print - Print ordering to specified output stream.
394///
395void ScheduleDAGSimple::print(std::ostream &O) const {
396#ifndef NDEBUG
397 O << "Ordering\n";
398 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
399 NodeInfo *NI = Ordering[i];
400 printNI(O, NI);
401 O << "\n";
402 if (NI->isGroupDominator()) {
403 NodeGroup *Group = NI->Group;
404 for (NIIterator NII = Group->group_begin(), E = Group->group_end();
405 NII != E; NII++) {
406 O << " ";
407 printNI(O, *NII);
408 O << "\n";
409 }
410 }
411 }
412#endif
413}
414
415void ScheduleDAGSimple::dump(const char *tag) const {
416 std::cerr << tag; dump();
417}
418
419void ScheduleDAGSimple::dump() const {
420 print(std::cerr);
421}
422
423
424/// EmitAll - Emit all nodes in schedule sorted order.
425///
426void ScheduleDAGSimple::EmitAll() {
427 std::map<SDNode*, unsigned> VRBaseMap;
428
429 // For each node in the ordering
430 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
431 // Get the scheduling info
432 NodeInfo *NI = Ordering[i];
433 if (NI->isInGroup()) {
434 NodeGroupIterator NGI(Ordering[i]);
435 while (NodeInfo *NI = NGI.next()) EmitNode(NI->Node, VRBaseMap);
436 } else {
437 EmitNode(NI->Node, VRBaseMap);
438 }
439 }
440}
441
442/// isFlagDefiner - Returns true if the node defines a flag result.
443static bool isFlagDefiner(SDNode *A) {
444 unsigned N = A->getNumValues();
445 return N && A->getValueType(N - 1) == MVT::Flag;
446}
447
448/// isFlagUser - Returns true if the node uses a flag result.
449///
450static bool isFlagUser(SDNode *A) {
451 unsigned N = A->getNumOperands();
452 return N && A->getOperand(N - 1).getValueType() == MVT::Flag;
453}
454
455/// printNI - Print node info.
456///
457void ScheduleDAGSimple::printNI(std::ostream &O, NodeInfo *NI) const {
458#ifndef NDEBUG
459 SDNode *Node = NI->Node;
460 O << " "
461 << std::hex << Node << std::dec
462 << ", Lat=" << NI->Latency
463 << ", Slot=" << NI->Slot
464 << ", ARITY=(" << Node->getNumOperands() << ","
465 << Node->getNumValues() << ")"
466 << " " << Node->getOperationName(&DAG);
467 if (isFlagDefiner(Node)) O << "<#";
468 if (isFlagUser(Node)) O << ">#";
469#endif
470}
471
472/// printChanges - Hilight changes in order caused by scheduling.
473///
474void ScheduleDAGSimple::printChanges(unsigned Index) const {
475#ifndef NDEBUG
476 // Get the ordered node count
477 unsigned N = Ordering.size();
478 // Determine if any changes
479 unsigned i = 0;
480 for (; i < N; i++) {
481 NodeInfo *NI = Ordering[i];
482 if (NI->Preorder != i) break;
483 }
484
485 if (i < N) {
486 std::cerr << Index << ". New Ordering\n";
487
488 for (i = 0; i < N; i++) {
489 NodeInfo *NI = Ordering[i];
490 std::cerr << " " << NI->Preorder << ". ";
491 printNI(std::cerr, NI);
492 std::cerr << "\n";
493 if (NI->isGroupDominator()) {
494 NodeGroup *Group = NI->Group;
495 for (NIIterator NII = Group->group_begin(), E = Group->group_end();
496 NII != E; NII++) {
497 std::cerr << " ";
498 printNI(std::cerr, *NII);
499 std::cerr << "\n";
500 }
501 }
502 }
503 } else {
504 std::cerr << Index << ". No Changes\n";
505 }
506#endif
507}
Evan Chenga9c20912006-01-21 02:32:06 +0000508
509//===----------------------------------------------------------------------===//
Evan Chenga9c20912006-01-21 02:32:06 +0000510/// isDefiner - Return true if node A is a definer for B.
511///
512bool ScheduleDAGSimple::isDefiner(NodeInfo *A, NodeInfo *B) {
513 // While there are A nodes
514 NodeGroupIterator NII(A);
515 while (NodeInfo *NI = NII.next()) {
516 // Extract node
517 SDNode *Node = NI->Node;
518 // While there operands in nodes of B
519 NodeGroupOpIterator NGOI(B);
520 while (!NGOI.isEnd()) {
521 SDOperand Op = NGOI.next();
522 // If node from A defines a node in B
523 if (Node == Op.Val) return true;
524 }
525 }
526 return false;
527}
528
Evan Chenga9c20912006-01-21 02:32:06 +0000529/// IncludeNode - Add node to NodeInfo vector.
530///
531void ScheduleDAGSimple::IncludeNode(NodeInfo *NI) {
532 // Get node
533 SDNode *Node = NI->Node;
534 // Ignore entry node
535 if (Node->getOpcode() == ISD::EntryToken) return;
536 // Check current count for node
537 int Count = NI->getPending();
538 // If the node is already in list
539 if (Count < 0) return;
540 // Decrement count to indicate a visit
541 Count--;
542 // If count has gone to zero then add node to list
543 if (!Count) {
544 // Add node
545 if (NI->isInGroup()) {
546 Ordering.push_back(NI->Group->getDominator());
547 } else {
548 Ordering.push_back(NI);
549 }
550 // indicate node has been added
551 Count--;
552 }
553 // Mark as visited with new count
554 NI->setPending(Count);
555}
556
Evan Chenga9c20912006-01-21 02:32:06 +0000557/// GatherSchedulingInfo - Get latency and resource information about each node.
558///
559void ScheduleDAGSimple::GatherSchedulingInfo() {
560 // Get instruction itineraries for the target
Chris Lattnere70f6712006-03-09 07:13:00 +0000561 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
Evan Chenga9c20912006-01-21 02:32:06 +0000562
563 // For each node
564 for (unsigned i = 0, N = NodeCount; i < N; i++) {
565 // Get node info
566 NodeInfo* NI = &Info[i];
567 SDNode *Node = NI->Node;
568
569 // If there are itineraries and it is a machine instruction
Evan Cheng4ef10862006-01-23 07:01:07 +0000570 if (InstrItins.isEmpty() || Heuristic == simpleNoItinScheduling) {
Evan Chenga9c20912006-01-21 02:32:06 +0000571 // If machine opcode
572 if (Node->isTargetOpcode()) {
573 // Get return type to guess which processing unit
574 MVT::ValueType VT = Node->getValueType(0);
575 // Get machine opcode
576 MachineOpCode TOpc = Node->getTargetOpcode();
577 NI->IsCall = TII->isCall(TOpc);
578 NI->IsLoad = TII->isLoad(TOpc);
579 NI->IsStore = TII->isStore(TOpc);
580
581 if (TII->isLoad(TOpc)) NI->StageBegin = &LoadStage;
582 else if (TII->isStore(TOpc)) NI->StageBegin = &StoreStage;
583 else if (MVT::isInteger(VT)) NI->StageBegin = &IntStage;
584 else if (MVT::isFloatingPoint(VT)) NI->StageBegin = &FloatStage;
585 if (NI->StageBegin) NI->StageEnd = NI->StageBegin + 1;
586 }
587 } else if (Node->isTargetOpcode()) {
588 // get machine opcode
589 MachineOpCode TOpc = Node->getTargetOpcode();
590 // Check to see if it is a call
591 NI->IsCall = TII->isCall(TOpc);
592 // Get itinerary stages for instruction
593 unsigned II = TII->getSchedClass(TOpc);
594 NI->StageBegin = InstrItins.begin(II);
595 NI->StageEnd = InstrItins.end(II);
596 }
597
598 // One slot for the instruction itself
599 NI->Latency = 1;
600
601 // Add long latency for a call to push it back in time
602 if (NI->IsCall) NI->Latency += CallLatency;
603
604 // Sum up all the latencies
605 for (InstrStage *Stage = NI->StageBegin, *E = NI->StageEnd;
606 Stage != E; Stage++) {
607 NI->Latency += Stage->Cycles;
608 }
609
610 // Sum up all the latencies for max tally size
611 NSlots += NI->Latency;
612 }
613
614 // Unify metrics if in a group
615 if (HasGroups) {
616 for (unsigned i = 0, N = NodeCount; i < N; i++) {
617 NodeInfo* NI = &Info[i];
618
619 if (NI->isInGroup()) {
620 NodeGroup *Group = NI->Group;
621
622 if (!Group->getDominator()) {
623 NIIterator NGI = Group->group_begin(), NGE = Group->group_end();
624 NodeInfo *Dominator = *NGI;
625 unsigned Latency = 0;
626
627 for (NGI++; NGI != NGE; NGI++) {
628 NodeInfo* NGNI = *NGI;
629 Latency += NGNI->Latency;
630 if (Dominator->Latency < NGNI->Latency) Dominator = NGNI;
631 }
632
633 Dominator->Latency = Latency;
634 Group->setDominator(Dominator);
635 }
636 }
637 }
638 }
639}
640
Evan Cheng4ef10862006-01-23 07:01:07 +0000641/// VisitAll - Visit each node breadth-wise to produce an initial ordering.
642/// Note that the ordering in the Nodes vector is reversed.
643void ScheduleDAGSimple::VisitAll() {
644 // Add first element to list
645 NodeInfo *NI = getNI(DAG.getRoot().Val);
646 if (NI->isInGroup()) {
647 Ordering.push_back(NI->Group->getDominator());
648 } else {
649 Ordering.push_back(NI);
650 }
651
652 // Iterate through all nodes that have been added
653 for (unsigned i = 0; i < Ordering.size(); i++) { // note: size() varies
654 // Visit all operands
655 NodeGroupOpIterator NGI(Ordering[i]);
656 while (!NGI.isEnd()) {
657 // Get next operand
658 SDOperand Op = NGI.next();
659 // Get node
660 SDNode *Node = Op.Val;
661 // Ignore passive nodes
662 if (isPassiveNode(Node)) continue;
663 // Check out node
664 IncludeNode(getNI(Node));
665 }
666 }
667
668 // Add entry node last (IncludeNode filters entry nodes)
669 if (DAG.getEntryNode().Val != DAG.getRoot().Val)
670 Ordering.push_back(getNI(DAG.getEntryNode().Val));
671
672 // Reverse the order
673 std::reverse(Ordering.begin(), Ordering.end());
674}
675
Evan Chenga9c20912006-01-21 02:32:06 +0000676/// FakeGroupDominators - Set dominators for non-scheduling.
677///
678void ScheduleDAGSimple::FakeGroupDominators() {
679 for (unsigned i = 0, N = NodeCount; i < N; i++) {
680 NodeInfo* NI = &Info[i];
681
682 if (NI->isInGroup()) {
683 NodeGroup *Group = NI->Group;
684
685 if (!Group->getDominator()) {
686 Group->setDominator(NI);
687 }
688 }
689 }
690}
691
Evan Chenga9c20912006-01-21 02:32:06 +0000692/// isStrongDependency - Return true if node A has results used by node B.
693/// I.E., B must wait for latency of A.
694bool ScheduleDAGSimple::isStrongDependency(NodeInfo *A, NodeInfo *B) {
695 // If A defines for B then it's a strong dependency or
696 // if a load follows a store (may be dependent but why take a chance.)
697 return isDefiner(A, B) || (A->IsStore && B->IsLoad);
698}
699
700/// isWeakDependency Return true if node A produces a result that will
701/// conflict with operands of B. It is assumed that we have called
702/// isStrongDependency prior.
703bool ScheduleDAGSimple::isWeakDependency(NodeInfo *A, NodeInfo *B) {
704 // TODO check for conflicting real registers and aliases
705#if 0 // FIXME - Since we are in SSA form and not checking register aliasing
706 return A->Node->getOpcode() == ISD::EntryToken || isStrongDependency(B, A);
707#else
708 return A->Node->getOpcode() == ISD::EntryToken;
709#endif
710}
711
712/// ScheduleBackward - Schedule instructions so that any long latency
713/// instructions and the critical path get pushed back in time. Time is run in
714/// reverse to allow code reuse of the Tally and eliminate the overhead of
715/// biasing every slot indices against NSlots.
716void ScheduleDAGSimple::ScheduleBackward() {
717 // Size and clear the resource tally
718 Tally.Initialize(NSlots);
719 // Get number of nodes to schedule
720 unsigned N = Ordering.size();
721
722 // For each node being scheduled
723 for (unsigned i = N; 0 < i--;) {
724 NodeInfo *NI = Ordering[i];
725 // Track insertion
726 unsigned Slot = NotFound;
727
728 // Compare against those previously scheduled nodes
729 unsigned j = i + 1;
730 for (; j < N; j++) {
731 // Get following instruction
732 NodeInfo *Other = Ordering[j];
733
734 // Check dependency against previously inserted nodes
735 if (isStrongDependency(NI, Other)) {
736 Slot = Other->Slot + Other->Latency;
737 break;
738 } else if (isWeakDependency(NI, Other)) {
739 Slot = Other->Slot;
740 break;
741 }
742 }
743
744 // If independent of others (or first entry)
745 if (Slot == NotFound) Slot = 0;
746
747#if 0 // FIXME - measure later
748 // Find a slot where the needed resources are available
749 if (NI->StageBegin != NI->StageEnd)
750 Slot = Tally.FindAndReserve(Slot, NI->StageBegin, NI->StageEnd);
751#endif
752
753 // Set node slot
754 NI->Slot = Slot;
755
756 // Insert sort based on slot
757 j = i + 1;
758 for (; j < N; j++) {
759 // Get following instruction
760 NodeInfo *Other = Ordering[j];
761 // Should we look further (remember slots are in reverse time)
762 if (Slot >= Other->Slot) break;
763 // Shuffle other into ordering
764 Ordering[j - 1] = Other;
765 }
766 // Insert node in proper slot
767 if (j != i + 1) Ordering[j - 1] = NI;
768 }
769}
770
771/// ScheduleForward - Schedule instructions to maximize packing.
772///
773void ScheduleDAGSimple::ScheduleForward() {
774 // Size and clear the resource tally
775 Tally.Initialize(NSlots);
776 // Get number of nodes to schedule
777 unsigned N = Ordering.size();
778
779 // For each node being scheduled
780 for (unsigned i = 0; i < N; i++) {
781 NodeInfo *NI = Ordering[i];
782 // Track insertion
783 unsigned Slot = NotFound;
784
785 // Compare against those previously scheduled nodes
786 unsigned j = i;
787 for (; 0 < j--;) {
788 // Get following instruction
789 NodeInfo *Other = Ordering[j];
790
791 // Check dependency against previously inserted nodes
792 if (isStrongDependency(Other, NI)) {
793 Slot = Other->Slot + Other->Latency;
794 break;
795 } else if (Other->IsCall || isWeakDependency(Other, NI)) {
796 Slot = Other->Slot;
797 break;
798 }
799 }
800
801 // If independent of others (or first entry)
802 if (Slot == NotFound) Slot = 0;
803
804 // Find a slot where the needed resources are available
805 if (NI->StageBegin != NI->StageEnd)
806 Slot = Tally.FindAndReserve(Slot, NI->StageBegin, NI->StageEnd);
807
808 // Set node slot
809 NI->Slot = Slot;
810
811 // Insert sort based on slot
812 j = i;
813 for (; 0 < j--;) {
814 // Get prior instruction
815 NodeInfo *Other = Ordering[j];
816 // Should we look further
817 if (Slot >= Other->Slot) break;
818 // Shuffle other into ordering
819 Ordering[j + 1] = Other;
820 }
821 // Insert node in proper slot
822 if (j != i) Ordering[j + 1] = NI;
823 }
824}
825
Evan Chenga9c20912006-01-21 02:32:06 +0000826/// Schedule - Order nodes according to selected style.
827///
828void ScheduleDAGSimple::Schedule() {
Chris Lattnerbe24e592006-03-10 06:34:51 +0000829 // Set up minimum info for scheduling
830 PrepareNodeInfo();
831 // Construct node groups for flagged nodes
832 IdentifyGroups();
833
Evan Chenga9c20912006-01-21 02:32:06 +0000834 // Test to see if scheduling should occur
Evan Cheng4ef10862006-01-23 07:01:07 +0000835 bool ShouldSchedule = NodeCount > 3 && Heuristic != noScheduling;
Evan Chenga9c20912006-01-21 02:32:06 +0000836 // Don't waste time if is only entry and return
837 if (ShouldSchedule) {
838 // Get latency and resource requirements
839 GatherSchedulingInfo();
840 } else if (HasGroups) {
841 // Make sure all the groups have dominators
842 FakeGroupDominators();
843 }
844
845 // Breadth first walk of DAG
846 VisitAll();
847
848#ifndef NDEBUG
849 static unsigned Count = 0;
850 Count++;
851 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
852 NodeInfo *NI = Ordering[i];
853 NI->Preorder = i;
854 }
855#endif
856
857 // Don't waste time if is only entry and return
858 if (ShouldSchedule) {
859 // Push back long instructions and critical path
860 ScheduleBackward();
861
862 // Pack instructions to maximize resource utilization
863 ScheduleForward();
864 }
865
866 DEBUG(printChanges(Count));
867
868 // Emit in scheduled order
869 EmitAll();
870}
871
Evan Chenga9c20912006-01-21 02:32:06 +0000872
873/// createSimpleDAGScheduler - This creates a simple two pass instruction
874/// scheduler.
Evan Cheng4ef10862006-01-23 07:01:07 +0000875llvm::ScheduleDAG* llvm::createSimpleDAGScheduler(SchedHeuristics Heuristic,
876 SelectionDAG &DAG,
Evan Chenga9c20912006-01-21 02:32:06 +0000877 MachineBasicBlock *BB) {
Evan Cheng4ef10862006-01-23 07:01:07 +0000878 return new ScheduleDAGSimple(Heuristic, DAG, BB, DAG.getTarget());
Evan Chenga9c20912006-01-21 02:32:06 +0000879}