blob: 742304187defe2d0a2036c6d123d4cd252264521 [file] [log] [blame]
Chris Lattnerd32b2362005-08-18 18:45:24 +00001//===-- ScheduleDAG.cpp - Implement a trivial DAG scheduler ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Jim Laskeye6b90fb2005-09-26 21:57:04 +000010// 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.
Chris Lattnerd32b2362005-08-18 18:45:24 +000013//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "sched"
Chris Lattner5839bf22005-08-26 17:15:30 +000017#include "llvm/CodeGen/MachineConstantPool.h"
Chris Lattner4ccd4062005-08-19 20:45:43 +000018#include "llvm/CodeGen/MachineFunction.h"
Chris Lattnerd32b2362005-08-18 18:45:24 +000019#include "llvm/CodeGen/SelectionDAGISel.h"
Chris Lattner2d973e42005-08-18 20:07:59 +000020#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattner4ccd4062005-08-19 20:45:43 +000021#include "llvm/CodeGen/SSARegMap.h"
Chris Lattner2d973e42005-08-18 20:07:59 +000022#include "llvm/Target/TargetMachine.h"
23#include "llvm/Target/TargetInstrInfo.h"
Chris Lattner025c39b2005-08-26 20:54:47 +000024#include "llvm/Target/TargetLowering.h"
Chris Lattner068ca152005-08-18 20:11:49 +000025#include "llvm/Support/CommandLine.h"
Jim Laskeye6b90fb2005-09-26 21:57:04 +000026#include "llvm/Support/Debug.h"
27#include <iostream>
Chris Lattnerd32b2362005-08-18 18:45:24 +000028using namespace llvm;
29
Jim Laskeye6b90fb2005-09-26 21:57:04 +000030namespace {
31 // Style of scheduling to use.
32 enum ScheduleChoices {
33 noScheduling,
34 simpleScheduling,
35 };
36} // namespace
37
38cl::opt<ScheduleChoices> ScheduleStyle("sched",
39 cl::desc("Choose scheduling style"),
40 cl::init(noScheduling),
41 cl::values(
42 clEnumValN(noScheduling, "none",
43 "Trivial emission with no analysis"),
44 clEnumValN(simpleScheduling, "simple",
45 "Minimize critical path and maximize processor utilization"),
46 clEnumValEnd));
47
48
Chris Lattnerda8abb02005-09-01 18:44:10 +000049#ifndef NDEBUG
Chris Lattner068ca152005-08-18 20:11:49 +000050static cl::opt<bool>
51ViewDAGs("view-sched-dags", cl::Hidden,
52 cl::desc("Pop up a window to show sched dags as they are processed"));
53#else
Chris Lattnera639a432005-09-02 07:09:28 +000054static const bool ViewDAGs = 0;
Chris Lattner068ca152005-08-18 20:11:49 +000055#endif
56
Chris Lattner2d973e42005-08-18 20:07:59 +000057namespace {
Jim Laskeye6b90fb2005-09-26 21:57:04 +000058//===----------------------------------------------------------------------===//
59///
60/// BitsIterator - Provides iteration through individual bits in a bit vector.
61///
62template<class T>
63class BitsIterator {
64private:
65 T Bits; // Bits left to iterate through
66
67public:
68 /// Ctor.
69 BitsIterator(T Initial) : Bits(Initial) {}
70
71 /// Next - Returns the next bit set or zero if exhausted.
72 inline T Next() {
73 // Get the rightmost bit set
74 T Result = Bits & -Bits;
75 // Remove from rest
76 Bits &= ~Result;
77 // Return single bit or zero
78 return Result;
79 }
80};
81
82//===----------------------------------------------------------------------===//
83
84
85//===----------------------------------------------------------------------===//
86///
87/// ResourceTally - Manages the use of resources over time intervals. Each
88/// item (slot) in the tally vector represents the resources used at a given
89/// moment. A bit set to 1 indicates that a resource is in use, otherwise
90/// available. An assumption is made that the tally is large enough to schedule
91/// all current instructions (asserts otherwise.)
92///
93template<class T>
94class ResourceTally {
95private:
96 std::vector<T> Tally; // Resources used per slot
97 typedef typename std::vector<T>::iterator Iter;
98 // Tally iterator
99
100 /// AllInUse - Test to see if all of the resources in the slot are busy (set.)
101 inline bool AllInUse(Iter Cursor, unsigned ResourceSet) {
102 return (*Cursor & ResourceSet) == ResourceSet;
103 }
104
105 /// Skip - Skip over slots that use all of the specified resource (all are
106 /// set.)
107 Iter Skip(Iter Cursor, unsigned ResourceSet) {
108 assert(ResourceSet && "At least one resource bit needs to bet set");
Chris Lattner2d973e42005-08-18 20:07:59 +0000109
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000110 // Continue to the end
111 while (true) {
112 // Break out if one of the resource bits is not set
113 if (!AllInUse(Cursor, ResourceSet)) return Cursor;
114 // Try next slot
115 Cursor++;
116 assert(Cursor < Tally.end() && "Tally is not large enough for schedule");
Chris Lattner2d973e42005-08-18 20:07:59 +0000117 }
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000118 }
119
120 /// FindSlots - Starting from Begin, locate N consecutive slots where at least
121 /// one of the resource bits is available. Returns the address of first slot.
122 Iter FindSlots(Iter Begin, unsigned N, unsigned ResourceSet,
123 unsigned &Resource) {
124 // Track position
125 Iter Cursor = Begin;
Chris Lattner2d973e42005-08-18 20:07:59 +0000126
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000127 // Try all possible slots forward
128 while (true) {
129 // Skip full slots
130 Cursor = Skip(Cursor, ResourceSet);
131 // Determine end of interval
132 Iter End = Cursor + N;
133 assert(End <= Tally.end() && "Tally is not large enough for schedule");
134
135 // Iterate thru each resource
136 BitsIterator<T> Resources(ResourceSet & ~*Cursor);
137 while (unsigned Res = Resources.Next()) {
138 // Check if resource is available for next N slots
139 // Break out if resource is busy
140 Iter Interval = Cursor;
141 for (; Interval < End && !(*Interval & Res); Interval++) {}
142
143 // If available for interval, return where and which resource
144 if (Interval == End) {
145 Resource = Res;
146 return Cursor;
147 }
148 // Otherwise, check if worth checking other resources
149 if (AllInUse(Interval, ResourceSet)) {
150 // Start looking beyond interval
151 Cursor = Interval;
152 break;
153 }
154 }
155 Cursor++;
Chris Lattner2d973e42005-08-18 20:07:59 +0000156 }
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000157 }
158
159 /// Reserve - Mark busy (set) the specified N slots.
160 void Reserve(Iter Begin, unsigned N, unsigned Resource) {
161 // Determine end of interval
162 Iter End = Begin + N;
163 assert(End <= Tally.end() && "Tally is not large enough for schedule");
164
165 // Set resource bit in each slot
166 for (; Begin < End; Begin++)
167 *Begin |= Resource;
168 }
169
170public:
171 /// Initialize - Resize and zero the tally to the specified number of time
172 /// slots.
173 inline void Initialize(unsigned N) {
174 Tally.assign(N, 0); // Initialize tally to all zeros.
175 }
176
177 // FindAndReserve - Locate and mark busy (set) N bits started at slot I, using
178 // ResourceSet for choices.
179 unsigned FindAndReserve(unsigned I, unsigned N, unsigned ResourceSet) {
180 // Which resource used
181 unsigned Resource;
182 // Find slots for instruction.
183 Iter Where = FindSlots(Tally.begin() + I, N, ResourceSet, Resource);
184 // Reserve the slots
185 Reserve(Where, N, Resource);
186 // Return time slot (index)
187 return Where - Tally.begin();
188 }
189
190};
191//===----------------------------------------------------------------------===//
192
193
194//===----------------------------------------------------------------------===//
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000195///
196/// Node group - This struct is used to manage flagged node groups.
197///
198class NodeInfo;
199class NodeGroup : public std::vector<NodeInfo *> {
200private:
201 int Pending; // Number of visits pending before
202 // adding to order
203
204public:
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000205 // Ctor.
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000206 NodeGroup() : Pending(0) {}
207
208 // Accessors
209 inline NodeInfo *getLeader() { return empty() ? NULL : front(); }
210 inline int getPending() const { return Pending; }
211 inline void setPending(int P) { Pending = P; }
212 inline int addPending(int I) { return Pending += I; }
213
214 static void Add(NodeInfo *D, NodeInfo *U);
215 static unsigned CountInternalUses(NodeInfo *D, NodeInfo *U);
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000216};
217//===----------------------------------------------------------------------===//
218
219
220//===----------------------------------------------------------------------===//
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000221///
222/// NodeInfo - This struct tracks information used to schedule the a node.
223///
224class NodeInfo {
225private:
226 int Pending; // Number of visits pending before
227 // adding to order
228public:
229 SDNode *Node; // DAG node
230 unsigned Latency; // Cycles to complete instruction
231 unsigned ResourceSet; // Bit vector of usable resources
232 unsigned Slot; // Node's time slot
233 NodeGroup *Group; // Grouping information
234 unsigned VRBase; // Virtual register base
235
236 // Ctor.
237 NodeInfo(SDNode *N = NULL)
238 : Pending(0)
239 , Node(N)
240 , Latency(0)
241 , ResourceSet(0)
242 , Slot(0)
243 , Group(NULL)
244 , VRBase(0)
245 {}
246
247 // Accessors
248 inline bool isInGroup() const {
249 assert(!Group || !Group->empty() && "Group with no members");
250 return Group != NULL;
251 }
252 inline bool isGroupLeader() const {
253 return isInGroup() && Group->getLeader() == this;
254 }
255 inline int getPending() const {
256 return Group ? Group->getPending() : Pending;
257 }
258 inline void setPending(int P) {
259 if (Group) Group->setPending(P);
260 else Pending = P;
261 }
262 inline int addPending(int I) {
263 if (Group) return Group->addPending(I);
264 else return Pending += I;
265 }
266};
267typedef std::vector<NodeInfo *>::iterator NIIterator;
268//===----------------------------------------------------------------------===//
269
270
271//===----------------------------------------------------------------------===//
272///
273/// NodeGroupIterator - Iterates over all the nodes indicated by the node info.
274/// If the node is in a group then iterate over the members of the group,
275/// otherwise just the node info.
276///
277class NodeGroupIterator {
278private:
279 NodeInfo *NI; // Node info
280 NIIterator NGI; // Node group iterator
281 NIIterator NGE; // Node group iterator end
282
283public:
284 // Ctor.
285 NodeGroupIterator(NodeInfo *N) : NI(N) {
286 // If the node is in a group then set up the group iterator. Otherwise
287 // the group iterators will trip first time out.
288 if (N->isInGroup()) {
289 // get Group
290 NodeGroup *Group = NI->Group;
291 NGI = Group->begin();
292 NGE = Group->end();
293 // Prevent this node from being used (will be in members list
294 NI = NULL;
295 }
296 }
297
298 /// next - Return the next node info, otherwise NULL.
299 ///
300 NodeInfo *next() {
301 // If members list
302 if (NGI != NGE) return *NGI++;
303 // Use node as the result (may be NULL)
304 NodeInfo *Result = NI;
305 // Only use once
306 NI = NULL;
307 // Return node or NULL
308 return Result;
309 }
310};
311//===----------------------------------------------------------------------===//
312
313
314//===----------------------------------------------------------------------===//
315///
316/// NodeGroupOpIterator - Iterates over all the operands of a node. If the node
317/// is a member of a group, this iterates over all the operands of all the
318/// members of the group.
319///
320class NodeGroupOpIterator {
321private:
322 NodeInfo *NI; // Node containing operands
323 NodeGroupIterator GI; // Node group iterator
324 SDNode::op_iterator OI; // Operand iterator
325 SDNode::op_iterator OE; // Operand iterator end
326
327 /// CheckNode - Test if node has more operands. If not get the next node
328 /// skipping over nodes that have no operands.
329 void CheckNode() {
330 // Only if operands are exhausted first
331 while (OI == OE) {
332 // Get next node info
333 NodeInfo *NI = GI.next();
334 // Exit if nodes are exhausted
335 if (!NI) return;
336 // Get node itself
337 SDNode *Node = NI->Node;
338 // Set up the operand iterators
339 OI = Node->op_begin();
340 OE = Node->op_end();
341 }
342 }
343
344public:
345 // Ctor.
346 NodeGroupOpIterator(NodeInfo *N) : NI(N), GI(N) {}
347
348 /// isEnd - Returns true when not more operands are available.
349 ///
350 inline bool isEnd() { CheckNode(); return OI == OE; }
351
352 /// next - Returns the next available operand.
353 ///
354 inline SDOperand next() {
355 assert(OI != OE && "Not checking for end of NodeGroupOpIterator correctly");
356 return *OI++;
357 }
358};
359//===----------------------------------------------------------------------===//
360
361
362//===----------------------------------------------------------------------===//
363///
364/// SimpleSched - Simple two pass scheduler.
365///
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000366class SimpleSched {
367private:
368 // TODO - get ResourceSet from TII
369 enum {
370 RSInteger = 0x3, // Two integer units
371 RSFloat = 0xC, // Two float units
372 RSLoadStore = 0x30, // Two load store units
373 RSOther = 0 // Processing unit independent
Chris Lattner2d973e42005-08-18 20:07:59 +0000374 };
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000375
376 MachineBasicBlock *BB; // Current basic block
377 SelectionDAG &DAG; // DAG of the current basic block
378 const TargetMachine &TM; // Target processor
379 const TargetInstrInfo &TII; // Target instruction information
380 const MRegisterInfo &MRI; // Target processor register information
381 SSARegMap *RegMap; // Virtual/real register map
382 MachineConstantPool *ConstPool; // Target constant pool
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000383 unsigned NodeCount; // Number of nodes in DAG
384 NodeInfo *Info; // Info for nodes being scheduled
385 std::map<SDNode *, NodeInfo *> Map; // Map nodes to info
386 std::vector<NodeInfo*> Ordering; // Emit ordering of nodes
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000387 ResourceTally<unsigned> Tally; // Resource usage tally
388 unsigned NSlots; // Total latency
Jim Laskey9d528dc2005-10-04 16:41:51 +0000389 std::map<SDNode *, unsigned> VRMap; // Node to VR map
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000390 static const unsigned NotFound = ~0U; // Search marker
391
392public:
393
394 // Ctor.
395 SimpleSched(SelectionDAG &D, MachineBasicBlock *bb)
396 : BB(bb), DAG(D), TM(D.getTarget()), TII(*TM.getInstrInfo()),
397 MRI(*TM.getRegisterInfo()), RegMap(BB->getParent()->getSSARegMap()),
398 ConstPool(BB->getParent()->getConstantPool()),
399 NSlots(0) {
400 assert(&TII && "Target doesn't provide instr info?");
401 assert(&MRI && "Target doesn't provide register info?");
402 }
403
404 // Run - perform scheduling.
405 MachineBasicBlock *Run() {
406 Schedule();
407 return BB;
408 }
409
410private:
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000411 /// getNI - Returns the node info for the specified node.
412 ///
413 inline NodeInfo *getNI(SDNode *Node) { return Map[Node]; }
414
415 /// getVR - Returns the virtual register number of the node.
416 ///
417 inline unsigned getVR(SDOperand Op) {
418 NodeInfo *NI = getNI(Op.Val);
419 assert(NI->VRBase != 0 && "Node emitted out of order - late");
420 return NI->VRBase + Op.ResNo;
421 }
422
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000423 static bool isFlagDefiner(SDNode *A);
424 static bool isFlagUser(SDNode *A);
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000425 static bool isDefiner(NodeInfo *A, NodeInfo *B);
426 static bool isPassiveNode(SDNode *Node);
427 void IncludeNode(NodeInfo *NI);
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000428 void VisitAll();
429 void Schedule();
Jim Laskey9d528dc2005-10-04 16:41:51 +0000430 void GatherNodeInfo();
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000431 bool isStrongDependency(NodeInfo *A, NodeInfo *B);
432 bool isWeakDependency(NodeInfo *A, NodeInfo *B);
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000433 void ScheduleBackward();
434 void ScheduleForward();
435 void EmitAll();
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000436 void EmitNode(NodeInfo *NI);
437 static unsigned CountResults(SDNode *Node);
438 static unsigned CountOperands(SDNode *Node);
439 unsigned CreateVirtualRegisters(MachineInstr *MI,
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000440 unsigned NumResults,
441 const TargetInstrDescriptor &II);
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000442 unsigned EmitDAG(SDOperand A);
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000443
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000444 void printSI(std::ostream &O, NodeInfo *NI) const;
445 void print(std::ostream &O) const;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000446 inline void dump(const char *tag) const { std::cerr << tag; dump(); }
447 void dump() const;
448};
449//===----------------------------------------------------------------------===//
450
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000451} // namespace
Jim Laskey41755e22005-10-01 00:03:07 +0000452
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000453//===----------------------------------------------------------------------===//
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000454
455
456//===----------------------------------------------------------------------===//
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000457/// Add - Adds a definer and user pair to a node group.
458///
459void NodeGroup::Add(NodeInfo *D, NodeInfo *U) {
460 // Get current groups
461 NodeGroup *DGroup = D->Group;
462 NodeGroup *UGroup = U->Group;
463 // If both are members of groups
464 if (DGroup && UGroup) {
465 // There may have been another edge connecting
466 if (DGroup == UGroup) return;
467 // Add the pending users count
468 DGroup->addPending(UGroup->getPending());
469 // For each member of the users group
470 NodeGroupIterator UNGI(U);
471 while (NodeInfo *UNI = UNGI.next() ) {
472 // Change the group
473 UNI->Group = DGroup;
474 // For each member of the definers group
475 NodeGroupIterator DNGI(D);
476 while (NodeInfo *DNI = DNGI.next() ) {
477 // Remove internal edges
478 DGroup->addPending(-CountInternalUses(DNI, UNI));
479 }
480 }
481 // Merge the two lists
482 DGroup->insert(DGroup->end(), UGroup->begin(), UGroup->end());
483 } else if (DGroup) {
484 // Make user member of definers group
485 U->Group = DGroup;
486 // Add users uses to definers group pending
487 DGroup->addPending(U->Node->use_size());
488 // For each member of the definers group
489 NodeGroupIterator DNGI(D);
490 while (NodeInfo *DNI = DNGI.next() ) {
491 // Remove internal edges
492 DGroup->addPending(-CountInternalUses(DNI, U));
493 }
494 DGroup->push_back(U);
495 } else if (UGroup) {
496 // Make definer member of users group
497 D->Group = UGroup;
498 // Add definers uses to users group pending
499 UGroup->addPending(D->Node->use_size());
500 // For each member of the users group
501 NodeGroupIterator UNGI(U);
502 while (NodeInfo *UNI = UNGI.next() ) {
503 // Remove internal edges
504 UGroup->addPending(-CountInternalUses(D, UNI));
505 }
506 UGroup->insert(UGroup->begin(), D);
507 } else {
508 D->Group = U->Group = DGroup = new NodeGroup();
509 DGroup->addPending(D->Node->use_size() + U->Node->use_size() -
510 CountInternalUses(D, U));
511 DGroup->push_back(D);
512 DGroup->push_back(U);
513 }
514}
515
516/// CountInternalUses - Returns the number of edges between the two nodes.
517///
518unsigned NodeGroup::CountInternalUses(NodeInfo *D, NodeInfo *U) {
519 unsigned N = 0;
520 for (SDNode:: use_iterator UI = D->Node->use_begin(),
521 E = D->Node->use_end(); UI != E; UI++) {
522 if (*UI == U->Node) N++;
523 }
524 return N;
525}
526//===----------------------------------------------------------------------===//
527
528
529//===----------------------------------------------------------------------===//
530/// isFlagDefiner - Returns true if the node defines a flag result.
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000531bool SimpleSched::isFlagDefiner(SDNode *A) {
532 unsigned N = A->getNumValues();
533 return N && A->getValueType(N - 1) == MVT::Flag;
Chris Lattner2d973e42005-08-18 20:07:59 +0000534}
535
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000536/// isFlagUser - Returns true if the node uses a flag result.
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000537///
538bool SimpleSched::isFlagUser(SDNode *A) {
539 unsigned N = A->getNumOperands();
540 return N && A->getOperand(N - 1).getValueType() == MVT::Flag;
541}
542
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000543/// isDefiner - Return true if node A is a definer for B.
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000544///
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000545bool SimpleSched::isDefiner(NodeInfo *A, NodeInfo *B) {
546 // While there are A nodes
547 NodeGroupIterator NII(A);
548 while (NodeInfo *NI = NII.next()) {
549 // Extract node
550 SDNode *Node = NI->Node;
551 // While there operands in nodes of B
552 NodeGroupOpIterator NGOI(B);
553 while (!NGOI.isEnd()) {
554 SDOperand Op = NGOI.next();
555 // If node from A defines a node in B
556 if (Node == Op.Val) return true;
557 }
Chris Lattner2d973e42005-08-18 20:07:59 +0000558 }
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000559 return false;
560}
561
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000562/// isPassiveNode - Return true if the node is a non-scheduled leaf.
563///
564bool SimpleSched::isPassiveNode(SDNode *Node) {
565 if (isa<ConstantSDNode>(Node)) return true;
566 if (isa<RegisterSDNode>(Node)) return true;
567 if (isa<GlobalAddressSDNode>(Node)) return true;
568 if (isa<BasicBlockSDNode>(Node)) return true;
569 if (isa<FrameIndexSDNode>(Node)) return true;
570 if (isa<ConstantPoolSDNode>(Node)) return true;
571 if (isa<ExternalSymbolSDNode>(Node)) return true;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000572 return false;
573}
574
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000575/// IncludeNode - Add node to NodeInfo vector.
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000576///
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000577void SimpleSched::IncludeNode(NodeInfo *NI) {
578 // Get node
579 SDNode *Node = NI->Node;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000580 // Ignore entry node
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000581if (Node->getOpcode() == ISD::EntryToken) return;
582 // Check current count for node
583 int Count = NI->getPending();
584 // If the node is already in list
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000585 if (Count < 0) return;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000586 // Decrement count to indicate a visit
587 Count--;
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000588 // If count has gone to zero then add node to list
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000589 if (!Count) {
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000590 // Add node
591 if (NI->isInGroup()) {
592 Ordering.push_back(NI->Group->getLeader());
593 } else {
594 Ordering.push_back(NI);
595 }
596 // indicate node has been added
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000597 Count--;
598 }
599 // Mark as visited with new count
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000600 NI->setPending(Count);
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000601}
602
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000603/// VisitAll - Visit each node breadth-wise to produce an initial ordering.
604/// Note that the ordering in the Nodes vector is reversed.
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000605void SimpleSched::VisitAll() {
606 // Add first element to list
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000607 Ordering.push_back(getNI(DAG.getRoot().Val));
608
609 // Iterate through all nodes that have been added
610 for (unsigned i = 0; i < Ordering.size(); i++) { // note: size() varies
611 // Visit all operands
612 NodeGroupOpIterator NGI(Ordering[i]);
613 while (!NGI.isEnd()) {
614 // Get next operand
615 SDOperand Op = NGI.next();
616 // Get node
617 SDNode *Node = Op.Val;
618 // Ignore passive nodes
619 if (isPassiveNode(Node)) continue;
620 // Check out node
621 IncludeNode(getNI(Node));
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000622 }
623 }
624
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000625 // Add entry node last (IncludeNode filters entry nodes)
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000626 if (DAG.getEntryNode().Val != DAG.getRoot().Val)
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000627 Ordering.push_back(getNI(DAG.getEntryNode().Val));
628
629 // FIXME - Reverse the order
630 for (unsigned i = 0, N = Ordering.size(), Half = N >> 1; i < Half; i++) {
631 unsigned j = N - i - 1;
632 NodeInfo *tmp = Ordering[i];
633 Ordering[i] = Ordering[j];
634 Ordering[j] = tmp;
635 }
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000636}
637
Jim Laskey9d528dc2005-10-04 16:41:51 +0000638/// GatherNodeInfo - Get latency and resource information about each node.
639///
640void SimpleSched::GatherNodeInfo() {
641 // Allocate node information
642 Info = new NodeInfo[NodeCount];
643 // Get base of all nodes table
644 SelectionDAG::allnodes_iterator AllNodes = DAG.allnodes_begin();
645
646 // For each node being scheduled
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000647 for (unsigned i = 0, N = NodeCount; i < N; i++) {
Jim Laskey9d528dc2005-10-04 16:41:51 +0000648 // Get next node from DAG all nodes table
649 SDNode *Node = AllNodes[i];
650 // Fast reference to node schedule info
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000651 NodeInfo* NI = &Info[i];
Jim Laskey9d528dc2005-10-04 16:41:51 +0000652 // Set up map
653 Map[Node] = NI;
654 // Set node
655 NI->Node = Node;
656 // Set pending visit count
657 NI->setPending(Node->use_size());
Jim Laskey8ba732b2005-10-03 12:30:32 +0000658
Jim Laskey9d528dc2005-10-04 16:41:51 +0000659 MVT::ValueType VT = Node->getValueType(0);
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000660 if (Node->isTargetOpcode()) {
661 MachineOpCode TOpc = Node->getTargetOpcode();
662 // FIXME: This is an ugly (but temporary!) hack to test the scheduler
663 // before we have real target info.
664 // FIXME NI->Latency = std::max(1, TII.maxLatency(TOpc));
665 // FIXME NI->ResourceSet = TII.resources(TOpc);
Jim Laskey5324fec2005-09-27 17:32:45 +0000666 if (TII.isCall(TOpc)) {
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000667 NI->ResourceSet = RSInteger;
668 NI->Latency = 40;
Jim Laskey5324fec2005-09-27 17:32:45 +0000669 } else if (TII.isLoad(TOpc)) {
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000670 NI->ResourceSet = RSLoadStore;
671 NI->Latency = 5;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000672 } else if (TII.isStore(TOpc)) {
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000673 NI->ResourceSet = RSLoadStore;
674 NI->Latency = 2;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000675 } else if (MVT::isInteger(VT)) {
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000676 NI->ResourceSet = RSInteger;
677 NI->Latency = 2;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000678 } else if (MVT::isFloatingPoint(VT)) {
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000679 NI->ResourceSet = RSFloat;
680 NI->Latency = 3;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000681 } else {
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000682 NI->ResourceSet = RSOther;
683 NI->Latency = 0;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000684 }
685 } else {
686 if (MVT::isInteger(VT)) {
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000687 NI->ResourceSet = RSInteger;
688 NI->Latency = 2;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000689 } else if (MVT::isFloatingPoint(VT)) {
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000690 NI->ResourceSet = RSFloat;
691 NI->Latency = 3;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000692 } else {
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000693 NI->ResourceSet = RSOther;
694 NI->Latency = 0;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000695 }
696 }
697
698 // Add one slot for the instruction itself
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000699 NI->Latency++;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000700
701 // Sum up all the latencies for max tally size
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000702 NSlots += NI->Latency;
703 }
Jim Laskey41755e22005-10-01 00:03:07 +0000704
Jim Laskey9d528dc2005-10-04 16:41:51 +0000705 // Put flagged nodes into groups
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000706 for (unsigned i = 0, N = NodeCount; i < N; i++) {
707 NodeInfo* NI = &Info[i];
Jim Laskey9d528dc2005-10-04 16:41:51 +0000708 SDNode *Node = NI->Node;
709
710 // For each operand (in reverse to only look at flags)
711 for (unsigned N = Node->getNumOperands(); 0 < N--;) {
712 // Get operand
713 SDOperand Op = Node->getOperand(N);
714 // No more flags to walk
715 if (Op.getValueType() != MVT::Flag) break;
716 // Add to node group
717 NodeGroup::Add(getNI(Op.Val), NI);
718 }
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000719 }
720}
721
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000722/// isStrongDependency - Return true if node A has results used by node B.
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000723/// I.E., B must wait for latency of A.
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000724bool SimpleSched::isStrongDependency(NodeInfo *A, NodeInfo *B) {
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000725 // If A defines for B then it's a strong dependency
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000726 return isDefiner(A, B);
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000727}
728
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000729/// isWeakDependency Return true if node A produces a result that will
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000730/// conflict with operands of B.
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000731bool SimpleSched::isWeakDependency(NodeInfo *A, NodeInfo *B) {
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000732 // TODO check for conflicting real registers and aliases
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000733#if 0 // FIXME - Since we are in SSA form and not checking register aliasing
734 return A->Node->getOpcode() == ISD::EntryToken || isStrongDependency(B, A);
Jim Laskey5324fec2005-09-27 17:32:45 +0000735#else
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000736 return A->Node->getOpcode() == ISD::EntryToken;
Jim Laskey5324fec2005-09-27 17:32:45 +0000737#endif
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000738}
739
740/// ScheduleBackward - Schedule instructions so that any long latency
741/// instructions and the critical path get pushed back in time. Time is run in
742/// reverse to allow code reuse of the Tally and eliminate the overhead of
743/// biasing every slot indices against NSlots.
744void SimpleSched::ScheduleBackward() {
745 // Size and clear the resource tally
746 Tally.Initialize(NSlots);
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000747 // Get number of nodes to schedule
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000748 unsigned N = Ordering.size();
749
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000750 // For each node being scheduled
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000751 for (unsigned i = N; 0 < i--;) {
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000752 NodeInfo *NI = Ordering[i];
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000753 // Track insertion
754 unsigned Slot = NotFound;
755
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000756 // Compare against those previously scheduled nodes
Jeff Cohenfef80f42005-09-29 01:59:49 +0000757 unsigned j = i + 1;
758 for (; j < N; j++) {
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000759 // Get following instruction
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000760 NodeInfo *Other = Ordering[j];
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000761
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000762 // Check dependency against previously inserted nodes
763 if (isStrongDependency(NI, Other)) {
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000764 Slot = Other->Slot + Other->Latency;
765 break;
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000766 } else if (isWeakDependency(NI, Other)) {
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000767 Slot = Other->Slot;
768 break;
769 }
770 }
771
772 // If independent of others (or first entry)
773 if (Slot == NotFound) Slot = 0;
774
775 // Find a slot where the needed resources are available
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000776 if (NI->ResourceSet)
777 Slot = Tally.FindAndReserve(Slot, NI->Latency, NI->ResourceSet);
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000778
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000779 // Set node slot
780 NI->Slot = Slot;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000781
782 // Insert sort based on slot
Jeff Cohenfef80f42005-09-29 01:59:49 +0000783 j = i + 1;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000784 for (; j < N; j++) {
785 // Get following instruction
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000786 NodeInfo *Other = Ordering[j];
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000787 // Should we look further
788 if (Slot >= Other->Slot) break;
789 // Shuffle other into ordering
790 Ordering[j - 1] = Other;
791 }
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000792 // Insert node in proper slot
793 if (j != i + 1) Ordering[j - 1] = NI;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000794 }
795}
796
797/// ScheduleForward - Schedule instructions to maximize packing.
798///
799void SimpleSched::ScheduleForward() {
800 // Size and clear the resource tally
801 Tally.Initialize(NSlots);
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000802 // Get number of nodes to schedule
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000803 unsigned N = Ordering.size();
804
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000805 // For each node being scheduled
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000806 for (unsigned i = 0; i < N; i++) {
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000807 NodeInfo *NI = Ordering[i];
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000808 // Track insertion
809 unsigned Slot = NotFound;
810
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000811 // Compare against those previously scheduled nodes
Jeff Cohenfef80f42005-09-29 01:59:49 +0000812 unsigned j = i;
813 for (; 0 < j--;) {
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000814 // Get following instruction
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000815 NodeInfo *Other = Ordering[j];
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000816
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000817 // Check dependency against previously inserted nodes
818 if (isStrongDependency(Other, NI)) {
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000819 Slot = Other->Slot + Other->Latency;
820 break;
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000821 } else if (isWeakDependency(Other, NI)) {
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000822 Slot = Other->Slot;
823 break;
824 }
825 }
826
827 // If independent of others (or first entry)
828 if (Slot == NotFound) Slot = 0;
829
830 // Find a slot where the needed resources are available
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000831 if (NI->ResourceSet)
832 Slot = Tally.FindAndReserve(Slot, NI->Latency, NI->ResourceSet);
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000833
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000834 // Set node slot
835 NI->Slot = Slot;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000836
837 // Insert sort based on slot
Jeff Cohenfef80f42005-09-29 01:59:49 +0000838 j = i;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000839 for (; 0 < j--;) {
840 // Get following instruction
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000841 NodeInfo *Other = Ordering[j];
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000842 // Should we look further
843 if (Slot >= Other->Slot) break;
844 // Shuffle other into ordering
845 Ordering[j + 1] = Other;
846 }
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000847 // Insert node in proper slot
848 if (j != i) Ordering[j + 1] = NI;
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000849 }
850}
851
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000852/// EmitAll - Emit all nodes in schedule sorted order.
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000853///
854void SimpleSched::EmitAll() {
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000855 // For each node in the ordering
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000856 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
857 // Get the scheduling info
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000858 NodeInfo *NI = Ordering[i];
859#if 0
860 // Iterate through nodes
861 NodeGroupIterator NGI(Ordering[i]);
862 while (NodeInfo *NI = NGI.next()) EmitNode(NI);
863#else
864 if (NI->isInGroup()) {
865 if (NI->isGroupLeader()) {
866 NodeGroupIterator NGI(Ordering[i]);
867 while (NodeInfo *NI = NGI.next()) EmitNode(NI);
868 }
869 } else {
870 EmitNode(NI);
871 }
872#endif
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000873 }
874}
875
876/// CountResults - The results of target nodes have register or immediate
877/// operands first, then an optional chain, and optional flag operands (which do
878/// not go into the machine instrs.)
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000879unsigned SimpleSched::CountResults(SDNode *Node) {
880 unsigned N = Node->getNumValues();
881 while (N && Node->getValueType(N - 1) == MVT::Flag)
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000882 --N;
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000883 if (N && Node->getValueType(N - 1) == MVT::Other)
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000884 --N; // Skip over chain result.
885 return N;
886}
887
888/// CountOperands The inputs to target nodes have any actual inputs first,
889/// followed by an optional chain operand, then flag operands. Compute the
890/// number of actual operands that will go into the machine instr.
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000891unsigned SimpleSched::CountOperands(SDNode *Node) {
892 unsigned N = Node->getNumOperands();
893 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000894 --N;
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000895 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000896 --N; // Ignore chain if it exists.
897 return N;
898}
899
900/// CreateVirtualRegisters - Add result register values for things that are
901/// defined by this instruction.
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000902unsigned SimpleSched::CreateVirtualRegisters(MachineInstr *MI,
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000903 unsigned NumResults,
904 const TargetInstrDescriptor &II) {
905 // Create the result registers for this node and add the result regs to
906 // the machine instruction.
907 const TargetOperandInfo *OpInfo = II.OpInfo;
908 unsigned ResultReg = RegMap->createVirtualRegister(OpInfo[0].RegClass);
909 MI->addRegOperand(ResultReg, MachineOperand::Def);
910 for (unsigned i = 1; i != NumResults; ++i) {
911 assert(OpInfo[i].RegClass && "Isn't a register operand!");
Chris Lattner505277a2005-10-01 07:45:09 +0000912 MI->addRegOperand(RegMap->createVirtualRegister(OpInfo[i].RegClass),
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000913 MachineOperand::Def);
914 }
915 return ResultReg;
916}
917
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000918/// EmitNode - Generate machine code for an node and needed dependencies.
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000919///
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000920void SimpleSched::EmitNode(NodeInfo *NI) {
921 unsigned VRBase = 0; // First virtual register for node
922 SDNode *Node = NI->Node;
Chris Lattner2d973e42005-08-18 20:07:59 +0000923
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000924 // If machine instruction
925 if (Node->isTargetOpcode()) {
926 unsigned Opc = Node->getTargetOpcode();
Chris Lattner2d973e42005-08-18 20:07:59 +0000927 const TargetInstrDescriptor &II = TII.get(Opc);
928
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000929 unsigned NumResults = CountResults(Node);
930 unsigned NodeOperands = CountOperands(Node);
Jim Laskeye6b90fb2005-09-26 21:57:04 +0000931 unsigned NumMIOperands = NodeOperands + NumResults;
Chris Lattnerda8abb02005-09-01 18:44:10 +0000932#ifndef NDEBUG
Chris Lattner14b392a2005-08-24 22:02:41 +0000933 assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&&
Chris Lattner2d973e42005-08-18 20:07:59 +0000934 "#operands for dag node doesn't match .td file!");
Chris Lattnerca6aa2f2005-08-19 01:01:34 +0000935#endif
Chris Lattner2d973e42005-08-18 20:07:59 +0000936
937 // Create the new machine instruction.
Chris Lattner14b392a2005-08-24 22:02:41 +0000938 MachineInstr *MI = new MachineInstr(Opc, NumMIOperands, true, true);
Chris Lattner2d973e42005-08-18 20:07:59 +0000939
940 // Add result register values for things that are defined by this
941 // instruction.
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000942 if (NumResults) VRBase = CreateVirtualRegisters(MI, NumResults, II);
943
944 // Emit all of the actual operands of this instruction, adding them to the
945 // instruction as appropriate.
946 for (unsigned i = 0; i != NodeOperands; ++i) {
947 if (Node->getOperand(i).isTargetOpcode()) {
948 // Note that this case is redundant with the final else block, but we
949 // include it because it is the most common and it makes the logic
950 // simpler here.
951 assert(Node->getOperand(i).getValueType() != MVT::Other &&
952 Node->getOperand(i).getValueType() != MVT::Flag &&
953 "Chain and flag operands should occur at end of operand list!");
Chris Lattner505277a2005-10-01 07:45:09 +0000954
955 // Get/emit the operand.
956 unsigned VReg = getVR(Node->getOperand(i));
957 MI->addRegOperand(VReg, MachineOperand::Use);
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000958
Chris Lattner505277a2005-10-01 07:45:09 +0000959 // Verify that it is right.
960 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
961 assert(II.OpInfo[i+NumResults].RegClass &&
962 "Don't have operand info for this instruction!");
963 assert(RegMap->getRegClass(VReg) == II.OpInfo[i+NumResults].RegClass &&
964 "Register class of operand and regclass of use don't agree!");
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +0000965 } else if (ConstantSDNode *C =
966 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
967 MI->addZeroExtImm64Operand(C->getValue());
968 } else if (RegisterSDNode*R =
969 dyn_cast<RegisterSDNode>(Node->getOperand(i))) {
970 MI->addRegOperand(R->getReg(), MachineOperand::Use);
971 } else if (GlobalAddressSDNode *TGA =
972 dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
973 MI->addGlobalAddressOperand(TGA->getGlobal(), false, 0);
974 } else if (BasicBlockSDNode *BB =
975 dyn_cast<BasicBlockSDNode>(Node->getOperand(i))) {
976 MI->addMachineBasicBlockOperand(BB->getBasicBlock());
977 } else if (FrameIndexSDNode *FI =
978 dyn_cast<FrameIndexSDNode>(Node->getOperand(i))) {
979 MI->addFrameIndexOperand(FI->getIndex());
980 } else if (ConstantPoolSDNode *CP =
981 dyn_cast<ConstantPoolSDNode>(Node->getOperand(i))) {
982 unsigned Idx = ConstPool->getConstantPoolIndex(CP->get());
983 MI->addConstantPoolIndexOperand(Idx);
984 } else if (ExternalSymbolSDNode *ES =
985 dyn_cast<ExternalSymbolSDNode>(Node->getOperand(i))) {
986 MI->addExternalSymbolOperand(ES->getSymbol(), false);
987 } else {
988 assert(Node->getOperand(i).getValueType() != MVT::Other &&
989 Node->getOperand(i).getValueType() != MVT::Flag &&
990 "Chain and flag operands should occur at end of operand list!");
Chris Lattner505277a2005-10-01 07:45:09 +0000991 unsigned VReg = getVR(Node->getOperand(i));
992 MI->addRegOperand(VReg, MachineOperand::Use);
993
994 // Verify that it is right.
995 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
996 assert(II.OpInfo[i+NumResults].RegClass &&
997 "Don't have operand info for this instruction!");
998 assert(RegMap->getRegClass(VReg) == II.OpInfo[i+NumResults].RegClass &&
999 "Register class of operand and regclass of use don't agree!");
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +00001000 }
1001 }
1002
1003 // Now that we have emitted all operands, emit this instruction itself.
1004 if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
1005 BB->insert(BB->end(), MI);
1006 } else {
1007 // Insert this instruction into the end of the basic block, potentially
1008 // taking some custom action.
1009 BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
1010 }
1011 } else {
1012 switch (Node->getOpcode()) {
1013 default:
1014 Node->dump();
1015 assert(0 && "This target-independent node should have been selected!");
1016 case ISD::EntryToken: // fall thru
1017 case ISD::TokenFactor:
1018 break;
1019 case ISD::CopyToReg: {
1020 unsigned Val = getVR(Node->getOperand(2));
1021 MRI.copyRegToReg(*BB, BB->end(),
1022 cast<RegisterSDNode>(Node->getOperand(1))->getReg(), Val,
1023 RegMap->getRegClass(Val));
1024 break;
1025 }
1026 case ISD::CopyFromReg: {
1027 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
Chris Lattner089c25c2005-10-09 05:58:56 +00001028 if (MRegisterInfo::isVirtualRegister(SrcReg)) {
1029 VRBase = SrcReg; // Just use the input register directly!
1030 break;
1031 }
1032
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +00001033 // Figure out the register class to create for the destreg.
1034 const TargetRegisterClass *TRC = 0;
Chris Lattner089c25c2005-10-09 05:58:56 +00001035
1036 // Pick the register class of the right type that contains this physreg.
1037 for (MRegisterInfo::regclass_iterator I = MRI.regclass_begin(),
1038 E = MRI.regclass_end(); I != E; ++I)
1039 if ((*I)->getType() == Node->getValueType(0) &&
1040 (*I)->contains(SrcReg)) {
1041 TRC = *I;
1042 break;
1043 }
1044 assert(TRC && "Couldn't find register class for reg copy!");
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +00001045
1046 // Create the reg, emit the copy.
1047 VRBase = RegMap->createVirtualRegister(TRC);
1048 MRI.copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
1049 break;
1050 }
1051 }
1052 }
1053
1054 assert(NI->VRBase == 0 && "Node emitted out of order - early");
1055 NI->VRBase = VRBase;
1056}
1057
Jim Laskey9d528dc2005-10-04 16:41:51 +00001058/// EmitDag - Generate machine code for an operand and needed dependencies.
1059///
1060unsigned SimpleSched::EmitDAG(SDOperand Op) {
1061 std::map<SDNode *, unsigned>::iterator OpI = VRMap.lower_bound(Op.Val);
1062 if (OpI != VRMap.end() && OpI->first == Op.Val)
1063 return OpI->second + Op.ResNo;
1064 unsigned &OpSlot = VRMap.insert(OpI, std::make_pair(Op.Val, 0))->second;
1065
1066 unsigned ResultReg = 0;
1067 if (Op.isTargetOpcode()) {
1068 unsigned Opc = Op.getTargetOpcode();
1069 const TargetInstrDescriptor &II = TII.get(Opc);
1070
1071 unsigned NumResults = CountResults(Op.Val);
1072 unsigned NodeOperands = CountOperands(Op.Val);
1073 unsigned NumMIOperands = NodeOperands + NumResults;
1074#ifndef NDEBUG
1075 assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&&
1076 "#operands for dag node doesn't match .td file!");
1077#endif
1078
1079 // Create the new machine instruction.
1080 MachineInstr *MI = new MachineInstr(Opc, NumMIOperands, true, true);
1081
1082 // Add result register values for things that are defined by this
1083 // instruction.
1084 if (NumResults) ResultReg = CreateVirtualRegisters(MI, NumResults, II);
1085
1086 // If there is a token chain operand, emit it first, as a hack to get avoid
1087 // really bad cases.
1088 if (Op.getNumOperands() > NodeOperands &&
1089 Op.getOperand(NodeOperands).getValueType() == MVT::Other) {
1090 EmitDAG(Op.getOperand(NodeOperands));
1091 }
1092
1093 // Emit all of the actual operands of this instruction, adding them to the
1094 // instruction as appropriate.
1095 for (unsigned i = 0; i != NodeOperands; ++i) {
1096 if (Op.getOperand(i).isTargetOpcode()) {
1097 // Note that this case is redundant with the final else block, but we
1098 // include it because it is the most common and it makes the logic
1099 // simpler here.
1100 assert(Op.getOperand(i).getValueType() != MVT::Other &&
1101 Op.getOperand(i).getValueType() != MVT::Flag &&
1102 "Chain and flag operands should occur at end of operand list!");
1103
1104 unsigned VReg = EmitDAG(Op.getOperand(i));
1105 MI->addRegOperand(VReg, MachineOperand::Use);
1106
1107 // Verify that it is right.
1108 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
1109 assert(II.OpInfo[i+NumResults].RegClass &&
1110 "Don't have operand info for this instruction!");
1111#ifndef NDEBUG
1112 if (RegMap->getRegClass(VReg) != II.OpInfo[i+NumResults].RegClass) {
1113 std::cerr << "OP: ";
1114 Op.getOperand(i).Val->dump(&DAG); std::cerr << "\nUSE: ";
1115 Op.Val->dump(&DAG); std::cerr << "\n";
1116 }
1117#endif
1118 assert(RegMap->getRegClass(VReg) == II.OpInfo[i+NumResults].RegClass &&
1119 "Register class of operand and regclass of use don't agree!");
1120 } else if (ConstantSDNode *C =
1121 dyn_cast<ConstantSDNode>(Op.getOperand(i))) {
1122 MI->addZeroExtImm64Operand(C->getValue());
1123 } else if (RegisterSDNode*R =dyn_cast<RegisterSDNode>(Op.getOperand(i))) {
1124 MI->addRegOperand(R->getReg(), MachineOperand::Use);
1125 } else if (GlobalAddressSDNode *TGA =
1126 dyn_cast<GlobalAddressSDNode>(Op.getOperand(i))) {
1127 MI->addGlobalAddressOperand(TGA->getGlobal(), false, 0);
1128 } else if (BasicBlockSDNode *BB =
1129 dyn_cast<BasicBlockSDNode>(Op.getOperand(i))) {
1130 MI->addMachineBasicBlockOperand(BB->getBasicBlock());
1131 } else if (FrameIndexSDNode *FI =
1132 dyn_cast<FrameIndexSDNode>(Op.getOperand(i))) {
1133 MI->addFrameIndexOperand(FI->getIndex());
1134 } else if (ConstantPoolSDNode *CP =
1135 dyn_cast<ConstantPoolSDNode>(Op.getOperand(i))) {
1136 unsigned Idx = ConstPool->getConstantPoolIndex(CP->get());
1137 MI->addConstantPoolIndexOperand(Idx);
1138 } else if (ExternalSymbolSDNode *ES =
1139 dyn_cast<ExternalSymbolSDNode>(Op.getOperand(i))) {
1140 MI->addExternalSymbolOperand(ES->getSymbol(), false);
1141 } else {
1142 assert(Op.getOperand(i).getValueType() != MVT::Other &&
1143 Op.getOperand(i).getValueType() != MVT::Flag &&
1144 "Chain and flag operands should occur at end of operand list!");
1145 unsigned VReg = EmitDAG(Op.getOperand(i));
1146 MI->addRegOperand(VReg, MachineOperand::Use);
1147
1148 // Verify that it is right.
1149 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
1150 assert(II.OpInfo[i+NumResults].RegClass &&
1151 "Don't have operand info for this instruction!");
1152 assert(RegMap->getRegClass(VReg) == II.OpInfo[i+NumResults].RegClass &&
1153 "Register class of operand and regclass of use don't agree!");
1154 }
1155 }
1156
1157 // Finally, if this node has any flag operands, we *must* emit them last, to
1158 // avoid emitting operations that might clobber the flags.
1159 if (Op.getNumOperands() > NodeOperands) {
1160 unsigned i = NodeOperands;
1161 if (Op.getOperand(i).getValueType() == MVT::Other)
1162 ++i; // the chain is already selected.
1163 for (unsigned N = Op.getNumOperands(); i < N; i++) {
1164 assert(Op.getOperand(i).getValueType() == MVT::Flag &&
1165 "Must be flag operands!");
1166 EmitDAG(Op.getOperand(i));
1167 }
1168 }
1169
1170 // Now that we have emitted all operands, emit this instruction itself.
1171 if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
1172 BB->insert(BB->end(), MI);
1173 } else {
1174 // Insert this instruction into the end of the basic block, potentially
1175 // taking some custom action.
1176 BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
1177 }
1178 } else {
1179 switch (Op.getOpcode()) {
1180 default:
1181 Op.Val->dump();
1182 assert(0 && "This target-independent node should have been selected!");
1183 case ISD::EntryToken: break;
1184 case ISD::TokenFactor:
1185 for (unsigned i = 0, N = Op.getNumOperands(); i < N; i++) {
1186 EmitDAG(Op.getOperand(i));
1187 }
1188 break;
1189 case ISD::CopyToReg: {
1190 SDOperand FlagOp; FlagOp.ResNo = 0;
1191 if (Op.getNumOperands() == 4) {
1192 FlagOp = Op.getOperand(3);
1193 }
1194 if (Op.getOperand(0).Val != FlagOp.Val) {
1195 EmitDAG(Op.getOperand(0)); // Emit the chain.
1196 }
1197 unsigned Val = EmitDAG(Op.getOperand(2));
1198 if (FlagOp.Val) {
1199 EmitDAG(FlagOp);
1200 }
1201 MRI.copyRegToReg(*BB, BB->end(),
1202 cast<RegisterSDNode>(Op.getOperand(1))->getReg(), Val,
1203 RegMap->getRegClass(Val));
1204 break;
1205 }
1206 case ISD::CopyFromReg: {
1207 EmitDAG(Op.getOperand(0)); // Emit the chain.
1208 unsigned SrcReg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
1209
Chris Lattner089c25c2005-10-09 05:58:56 +00001210 // If the input is already a virtual register, just use it.
1211 if (MRegisterInfo::isVirtualRegister(SrcReg)) {
1212 ResultReg = SrcReg;
1213 break;
1214 }
1215
Jim Laskey9d528dc2005-10-04 16:41:51 +00001216 // Figure out the register class to create for the destreg.
1217 const TargetRegisterClass *TRC = 0;
Chris Lattner089c25c2005-10-09 05:58:56 +00001218
1219 // Pick the register class of the right type that contains this physreg.
1220 for (MRegisterInfo::regclass_iterator I = MRI.regclass_begin(),
1221 E = MRI.regclass_end(); I != E; ++I)
1222 if ((*I)->getType() == Op.Val->getValueType(0) &&
1223 (*I)->contains(SrcReg)) {
1224 TRC = *I;
1225 break;
1226 }
1227 assert(TRC && "Couldn't find register class for reg copy!");
Jim Laskey9d528dc2005-10-04 16:41:51 +00001228
1229 // Create the reg, emit the copy.
1230 ResultReg = RegMap->createVirtualRegister(TRC);
1231 MRI.copyRegToReg(*BB, BB->end(), ResultReg, SrcReg, TRC);
1232 break;
1233 }
1234 }
1235 }
1236
1237 OpSlot = ResultReg;
1238 return ResultReg+Op.ResNo;
1239}
1240
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +00001241/// Schedule - Order nodes according to selected style.
Jim Laskeye6b90fb2005-09-26 21:57:04 +00001242///
1243void SimpleSched::Schedule() {
Jim Laskey9d528dc2005-10-04 16:41:51 +00001244 switch (ScheduleStyle) {
1245 case simpleScheduling:
1246 // Number the nodes
1247 NodeCount = DAG.allnodes_size();
1248 // Don't waste time if is only entry and return
1249 if (NodeCount > 3) {
1250 // Get latency and resource requirements
1251 GatherNodeInfo();
1252 // Breadth first walk of DAG
1253 VisitAll();
1254 DEBUG(dump("Pre-"));
1255 // Push back long instructions and critical path
1256 ScheduleBackward();
1257 DEBUG(dump("Mid-"));
1258 // Pack instructions to maximize resource utilization
1259 ScheduleForward();
1260 DEBUG(dump("Post-"));
1261 // Emit in scheduled order
1262 EmitAll();
1263 break;
1264 } // fall thru
1265 case noScheduling:
1266 // Emit instructions in using a DFS from the exit root
1267 EmitDAG(DAG.getRoot());
1268 break;
Jim Laskeye6b90fb2005-09-26 21:57:04 +00001269 }
1270}
Chris Lattner2d973e42005-08-18 20:07:59 +00001271
Jim Laskeye6b90fb2005-09-26 21:57:04 +00001272/// printSI - Print schedule info.
1273///
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +00001274void SimpleSched::printSI(std::ostream &O, NodeInfo *NI) const {
Jim Laskeye6b90fb2005-09-26 21:57:04 +00001275#ifndef NDEBUG
1276 using namespace std;
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +00001277 SDNode *Node = NI->Node;
Jim Laskeye6b90fb2005-09-26 21:57:04 +00001278 O << " "
Jim Laskeyb6d4c2c2005-09-30 19:15:27 +00001279 << hex << Node
1280 << ", RS=" << NI->ResourceSet
1281 << ", Lat=" << NI->Latency
1282 << ", Slot=" << NI->Slot
1283 << ", ARITY=(" << Node->getNumOperands() << ","
1284 << Node->getNumValues() << ")"
1285 << " " << Node->getOperationName(&DAG);
1286 if (isFlagDefiner(Node)) O << "<#";
1287 if (isFlagUser(Node)) O << ">#";
Jim Laskeye6b90fb2005-09-26 21:57:04 +00001288#endif
1289}
1290
1291/// print - Print ordering to specified output stream.
1292///
1293void SimpleSched::print(std::ostream &O) const {
1294#ifndef NDEBUG
1295 using namespace std;
1296 O << "Ordering\n";
1297 for (unsigned i = 0, N = Ordering.size(); i < N; i++) {
Jim Laskey41755e22005-10-01 00:03:07 +00001298 NodeInfo *NI = Ordering[i];
1299 printSI(O, NI);
Jim Laskeye6b90fb2005-09-26 21:57:04 +00001300 O << "\n";
Jim Laskey41755e22005-10-01 00:03:07 +00001301 if (NI->isGroupLeader()) {
1302 NodeGroup *Group = NI->Group;
1303 for (NIIterator NII = Group->begin(), E = Group->end();
1304 NII != E; NII++) {
1305 O << " ";
1306 printSI(O, *NII);
1307 O << "\n";
1308 }
1309 }
Jim Laskeye6b90fb2005-09-26 21:57:04 +00001310 }
1311#endif
1312}
1313
1314/// dump - Print ordering to std::cerr.
1315///
1316void SimpleSched::dump() const {
1317 print(std::cerr);
1318}
1319//===----------------------------------------------------------------------===//
1320
1321
1322//===----------------------------------------------------------------------===//
1323/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
1324/// target node in the graph.
Chris Lattnerd32b2362005-08-18 18:45:24 +00001325void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &SD) {
Chris Lattner068ca152005-08-18 20:11:49 +00001326 if (ViewDAGs) SD.viewGraph();
Chris Lattner620c93c2005-08-27 00:58:02 +00001327 BB = SimpleSched(SD, BB).Run();
Chris Lattnerd32b2362005-08-18 18:45:24 +00001328}