Add callback to allow target to adjust latency of schedule dependency edge.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGSDNodes.cpp
1 //===--- ScheduleDAGSDNodes.cpp - Implement the ScheduleDAGSDNodes class --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the ScheduleDAG class, which is a base class used by
11 // scheduling implementation classes.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "pre-RA-sched"
16 #include "ScheduleDAGSDNodes.h"
17 #include "llvm/CodeGen/SelectionDAG.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21 #include "llvm/Target/TargetSubtarget.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace llvm;
25
26 ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
27   : ScheduleDAG(mf) {
28 }
29
30 /// Run - perform scheduling.
31 ///
32 void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb,
33                              MachineBasicBlock::iterator insertPos) {
34   DAG = dag;
35   ScheduleDAG::Run(bb, insertPos);
36 }
37
38 SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
39   SUnit *SU = NewSUnit(Old->getNode());
40   SU->OrigNode = Old->OrigNode;
41   SU->Latency = Old->Latency;
42   SU->isTwoAddress = Old->isTwoAddress;
43   SU->isCommutable = Old->isCommutable;
44   SU->hasPhysRegDefs = Old->hasPhysRegDefs;
45   SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
46   Old->isCloned = true;
47   return SU;
48 }
49
50 /// CheckForPhysRegDependency - Check if the dependency between def and use of
51 /// a specified operand is a physical register dependency. If so, returns the
52 /// register and the cost of copying the register.
53 static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
54                                       const TargetRegisterInfo *TRI, 
55                                       const TargetInstrInfo *TII,
56                                       unsigned &PhysReg, int &Cost) {
57   if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
58     return;
59
60   unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
61   if (TargetRegisterInfo::isVirtualRegister(Reg))
62     return;
63
64   unsigned ResNo = User->getOperand(2).getResNo();
65   if (Def->isMachineOpcode()) {
66     const TargetInstrDesc &II = TII->get(Def->getMachineOpcode());
67     if (ResNo >= II.getNumDefs() &&
68         II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
69       PhysReg = Reg;
70       const TargetRegisterClass *RC =
71         TRI->getPhysicalRegisterRegClass(Reg, Def->getValueType(ResNo));
72       Cost = RC->getCopyCost();
73     }
74   }
75 }
76
77 void ScheduleDAGSDNodes::BuildSchedUnits() {
78   // During scheduling, the NodeId field of SDNode is used to map SDNodes
79   // to their associated SUnits by holding SUnits table indices. A value
80   // of -1 means the SDNode does not yet have an associated SUnit.
81   unsigned NumNodes = 0;
82   for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
83        E = DAG->allnodes_end(); NI != E; ++NI) {
84     NI->setNodeId(-1);
85     ++NumNodes;
86   }
87
88   // Reserve entries in the vector for each of the SUnits we are creating.  This
89   // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
90   // invalidated.
91   // FIXME: Multiply by 2 because we may clone nodes during scheduling.
92   // This is a temporary workaround.
93   SUnits.reserve(NumNodes * 2);
94   
95   // Check to see if the scheduler cares about latencies.
96   bool UnitLatencies = ForceUnitLatencies();
97
98   for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
99        E = DAG->allnodes_end(); NI != E; ++NI) {
100     if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
101       continue;
102     
103     // If this node has already been processed, stop now.
104     if (NI->getNodeId() != -1) continue;
105     
106     SUnit *NodeSUnit = NewSUnit(NI);
107     
108     // See if anything is flagged to this node, if so, add them to flagged
109     // nodes.  Nodes can have at most one flag input and one flag output.  Flags
110     // are required to be the last operand and result of a node.
111     
112     // Scan up to find flagged preds.
113     SDNode *N = NI;
114     while (N->getNumOperands() &&
115            N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
116       N = N->getOperand(N->getNumOperands()-1).getNode();
117       assert(N->getNodeId() == -1 && "Node already inserted!");
118       N->setNodeId(NodeSUnit->NodeNum);
119     }
120     
121     // Scan down to find any flagged succs.
122     N = NI;
123     while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
124       SDValue FlagVal(N, N->getNumValues()-1);
125       
126       // There are either zero or one users of the Flag result.
127       bool HasFlagUse = false;
128       for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 
129            UI != E; ++UI)
130         if (FlagVal.isOperandOf(*UI)) {
131           HasFlagUse = true;
132           assert(N->getNodeId() == -1 && "Node already inserted!");
133           N->setNodeId(NodeSUnit->NodeNum);
134           N = *UI;
135           break;
136         }
137       if (!HasFlagUse) break;
138     }
139     
140     // If there are flag operands involved, N is now the bottom-most node
141     // of the sequence of nodes that are flagged together.
142     // Update the SUnit.
143     NodeSUnit->setNode(N);
144     assert(N->getNodeId() == -1 && "Node already inserted!");
145     N->setNodeId(NodeSUnit->NodeNum);
146
147     // Assign the Latency field of NodeSUnit using target-provided information.
148     if (UnitLatencies)
149       NodeSUnit->Latency = 1;
150     else
151       ComputeLatency(NodeSUnit);
152   }
153 }
154
155 void ScheduleDAGSDNodes::AddSchedEdges() {
156   const TargetSubtarget &ST = TM.getSubtarget<TargetSubtarget>();
157
158   // Pass 2: add the preds, succs, etc.
159   for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
160     SUnit *SU = &SUnits[su];
161     SDNode *MainNode = SU->getNode();
162     
163     if (MainNode->isMachineOpcode()) {
164       unsigned Opc = MainNode->getMachineOpcode();
165       const TargetInstrDesc &TID = TII->get(Opc);
166       for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
167         if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
168           SU->isTwoAddress = true;
169           break;
170         }
171       }
172       if (TID.isCommutable())
173         SU->isCommutable = true;
174     }
175     
176     // Find all predecessors and successors of the group.
177     for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode()) {
178       if (N->isMachineOpcode() &&
179           TII->get(N->getMachineOpcode()).getImplicitDefs()) {
180         SU->hasPhysRegClobbers = true;
181         unsigned NumUsed = CountResults(N);
182         while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
183           --NumUsed;    // Skip over unused values at the end.
184         if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
185           SU->hasPhysRegDefs = true;
186       }
187       
188       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
189         SDNode *OpN = N->getOperand(i).getNode();
190         if (isPassiveNode(OpN)) continue;   // Not scheduled.
191         SUnit *OpSU = &SUnits[OpN->getNodeId()];
192         assert(OpSU && "Node has no SUnit!");
193         if (OpSU == SU) continue;           // In the same group.
194
195         EVT OpVT = N->getOperand(i).getValueType();
196         assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
197         bool isChain = OpVT == MVT::Other;
198
199         unsigned PhysReg = 0;
200         int Cost = 1;
201         // Determine if this is a physical register dependency.
202         CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
203         assert((PhysReg == 0 || !isChain) &&
204                "Chain dependence via physreg data?");
205         // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
206         // emits a copy from the physical register to a virtual register unless
207         // it requires a cross class copy (cost < 0). That means we are only
208         // treating "expensive to copy" register dependency as physical register
209         // dependency. This may change in the future though.
210         if (Cost >= 0)
211           PhysReg = 0;
212
213         const SDep& dep = SDep(OpSU, isChain ? SDep::Order : SDep::Data,
214                                OpSU->Latency, PhysReg);
215         if (!isChain)
216           ST.adjustSchedDependency((SDep &)dep);
217
218         SU->addPred(dep);
219       }
220     }
221   }
222 }
223
224 /// BuildSchedGraph - Build the SUnit graph from the selection dag that we
225 /// are input.  This SUnit graph is similar to the SelectionDAG, but
226 /// excludes nodes that aren't interesting to scheduling, and represents
227 /// flagged together nodes with a single SUnit.
228 void ScheduleDAGSDNodes::BuildSchedGraph() {
229   // Populate the SUnits array.
230   BuildSchedUnits();
231   // Compute all the scheduling dependencies between nodes.
232   AddSchedEdges();
233 }
234
235 void ScheduleDAGSDNodes::ComputeLatency(SUnit *SU) {
236   const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
237   
238   // Compute the latency for the node.  We use the sum of the latencies for
239   // all nodes flagged together into this SUnit.
240   SU->Latency = 0;
241   bool SawMachineOpcode = false;
242   for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode())
243     if (N->isMachineOpcode()) {
244       SawMachineOpcode = true;
245       SU->Latency +=
246         InstrItins.getLatency(TII->get(N->getMachineOpcode()).getSchedClass());
247     }
248 }
249
250 /// CountResults - The results of target nodes have register or immediate
251 /// operands first, then an optional chain, and optional flag operands (which do
252 /// not go into the resulting MachineInstr).
253 unsigned ScheduleDAGSDNodes::CountResults(SDNode *Node) {
254   unsigned N = Node->getNumValues();
255   while (N && Node->getValueType(N - 1) == MVT::Flag)
256     --N;
257   if (N && Node->getValueType(N - 1) == MVT::Other)
258     --N;    // Skip over chain result.
259   return N;
260 }
261
262 /// CountOperands - The inputs to target nodes have any actual inputs first,
263 /// followed by special operands that describe memory references, then an
264 /// optional chain operand, then an optional flag operand.  Compute the number
265 /// of actual operands that will go into the resulting MachineInstr.
266 unsigned ScheduleDAGSDNodes::CountOperands(SDNode *Node) {
267   unsigned N = ComputeMemOperandsEnd(Node);
268   while (N && isa<MemOperandSDNode>(Node->getOperand(N - 1).getNode()))
269     --N; // Ignore MEMOPERAND nodes
270   return N;
271 }
272
273 /// ComputeMemOperandsEnd - Find the index one past the last MemOperandSDNode
274 /// operand
275 unsigned ScheduleDAGSDNodes::ComputeMemOperandsEnd(SDNode *Node) {
276   unsigned N = Node->getNumOperands();
277   while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
278     --N;
279   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
280     --N; // Ignore chain if it exists.
281   return N;
282 }
283
284
285 void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
286   if (!SU->getNode()) {
287     errs() << "PHYS REG COPY\n";
288     return;
289   }
290
291   SU->getNode()->dump(DAG);
292   errs() << "\n";
293   SmallVector<SDNode *, 4> FlaggedNodes;
294   for (SDNode *N = SU->getNode()->getFlaggedNode(); N; N = N->getFlaggedNode())
295     FlaggedNodes.push_back(N);
296   while (!FlaggedNodes.empty()) {
297     errs() << "    ";
298     FlaggedNodes.back()->dump(DAG);
299     errs() << "\n";
300     FlaggedNodes.pop_back();
301   }
302 }