blob: 090f0a57d52c68f323c1d0feca65ca5492f73d9d [file] [log] [blame]
Dan Gohman343f0c02008-11-19 23:18:57 +00001//===--- 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"
Evan Chenga8efe282010-03-14 19:56:39 +000016#include "SDNodeDbgValue.h"
Dan Gohman84fbac52009-02-06 17:22:58 +000017#include "ScheduleDAGSDNodes.h"
Dan Gohmanbcea8592009-10-10 01:32:21 +000018#include "InstrEmitter.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000019#include "llvm/CodeGen/SelectionDAG.h"
20#include "llvm/Target/TargetMachine.h"
21#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng1cc39842010-05-20 23:26:43 +000022#include "llvm/Target/TargetLowering.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000023#include "llvm/Target/TargetRegisterInfo.h"
David Goodwin71046162009-08-13 16:05:04 +000024#include "llvm/Target/TargetSubtarget.h"
Evan Chengc589e032010-01-22 03:36:51 +000025#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/SmallPtrSet.h"
Evan Chengbfcb3052010-03-25 01:38:16 +000027#include "llvm/ADT/SmallSet.h"
Evan Chengc589e032010-01-22 03:36:51 +000028#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/Statistic.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000030#include "llvm/Support/Debug.h"
31#include "llvm/Support/raw_ostream.h"
32using namespace llvm;
33
Evan Chengc589e032010-01-22 03:36:51 +000034STATISTIC(LoadsClustered, "Number of loads clustered together");
35
Dan Gohman79ce2762009-01-15 19:20:50 +000036ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
37 : ScheduleDAG(mf) {
Dan Gohman343f0c02008-11-19 23:18:57 +000038}
39
Dan Gohman47ac0f02009-02-11 04:27:20 +000040/// Run - perform scheduling.
41///
42void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb,
43 MachineBasicBlock::iterator insertPos) {
44 DAG = dag;
45 ScheduleDAG::Run(bb, insertPos);
46}
47
Evan Cheng1cc39842010-05-20 23:26:43 +000048/// NewSUnit - Creates a new SUnit and return a ptr to it.
49///
50SUnit *ScheduleDAGSDNodes::NewSUnit(SDNode *N) {
51#ifndef NDEBUG
52 const SUnit *Addr = 0;
53 if (!SUnits.empty())
54 Addr = &SUnits[0];
55#endif
56 SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
57 assert((Addr == 0 || Addr == &SUnits[0]) &&
58 "SUnits std::vector reallocated on the fly!");
59 SUnits.back().OrigNode = &SUnits.back();
60 SUnit *SU = &SUnits.back();
61 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
Evan Cheng046fa3f2010-05-28 23:26:21 +000062 if (N->isMachineOpcode() &&
63 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF)
64 SU->SchedulingPref = Sched::None;
65 else
66 SU->SchedulingPref = TLI.getSchedulingPreference(N);
Evan Cheng1cc39842010-05-20 23:26:43 +000067 return SU;
68}
69
Dan Gohman343f0c02008-11-19 23:18:57 +000070SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
71 SUnit *SU = NewSUnit(Old->getNode());
72 SU->OrigNode = Old->OrigNode;
73 SU->Latency = Old->Latency;
74 SU->isTwoAddress = Old->isTwoAddress;
75 SU->isCommutable = Old->isCommutable;
76 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
Dan Gohman39746672009-03-23 16:10:52 +000077 SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
Evan Cheng1cc39842010-05-20 23:26:43 +000078 SU->SchedulingPref = Old->SchedulingPref;
Evan Chenge57187c2009-01-16 20:57:18 +000079 Old->isCloned = true;
Dan Gohman343f0c02008-11-19 23:18:57 +000080 return SU;
81}
82
83/// CheckForPhysRegDependency - Check if the dependency between def and use of
84/// a specified operand is a physical register dependency. If so, returns the
Evan Chengc29a56d2009-01-12 03:19:55 +000085/// register and the cost of copying the register.
Dan Gohman343f0c02008-11-19 23:18:57 +000086static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
87 const TargetRegisterInfo *TRI,
88 const TargetInstrInfo *TII,
Evan Chengc29a56d2009-01-12 03:19:55 +000089 unsigned &PhysReg, int &Cost) {
Dan Gohman343f0c02008-11-19 23:18:57 +000090 if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
91 return;
92
93 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
94 if (TargetRegisterInfo::isVirtualRegister(Reg))
95 return;
96
97 unsigned ResNo = User->getOperand(2).getResNo();
98 if (Def->isMachineOpcode()) {
99 const TargetInstrDesc &II = TII->get(Def->getMachineOpcode());
100 if (ResNo >= II.getNumDefs() &&
Evan Chengc29a56d2009-01-12 03:19:55 +0000101 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000102 PhysReg = Reg;
Evan Chengc29a56d2009-01-12 03:19:55 +0000103 const TargetRegisterClass *RC =
104 TRI->getPhysicalRegisterRegClass(Reg, Def->getValueType(ResNo));
105 Cost = RC->getCopyCost();
106 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000107 }
108}
109
Evan Chengc589e032010-01-22 03:36:51 +0000110static void AddFlags(SDNode *N, SDValue Flag, bool AddFlag,
111 SelectionDAG *DAG) {
112 SmallVector<EVT, 4> VTs;
113 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
114 VTs.push_back(N->getValueType(i));
115 if (AddFlag)
116 VTs.push_back(MVT::Flag);
117 SmallVector<SDValue, 4> Ops;
118 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
119 Ops.push_back(N->getOperand(i));
120 if (Flag.getNode())
121 Ops.push_back(Flag);
122 SDVTList VTList = DAG->getVTList(&VTs[0], VTs.size());
123 DAG->MorphNodeTo(N, N->getOpcode(), VTList, &Ops[0], Ops.size());
124}
125
126/// ClusterNeighboringLoads - Force nearby loads together by "flagging" them.
127/// This function finds loads of the same base and different offsets. If the
128/// offsets are not far apart (target specific), it add MVT::Flag inputs and
129/// outputs to ensure they are scheduled together and in order. This
130/// optimization may benefit some targets by improving cache locality.
Evan Cheng302ef832010-06-10 02:09:31 +0000131void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
132 SDNode *Chain = 0;
133 unsigned NumOps = Node->getNumOperands();
134 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
135 Chain = Node->getOperand(NumOps-1).getNode();
136 if (!Chain)
137 return;
138
139 // Look for other loads of the same chain. Find loads that are loading from
140 // the same base pointer and different offsets.
Evan Chengc589e032010-01-22 03:36:51 +0000141 SmallPtrSet<SDNode*, 16> Visited;
142 SmallVector<int64_t, 4> Offsets;
143 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
Evan Cheng302ef832010-06-10 02:09:31 +0000144 bool Cluster = false;
145 SDNode *Base = Node;
146 int64_t BaseOffset;
147 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
148 I != E; ++I) {
149 SDNode *User = *I;
150 if (User == Node || !Visited.insert(User))
151 continue;
152 int64_t Offset1, Offset2;
153 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
154 Offset1 == Offset2)
155 // FIXME: Should be ok if they addresses are identical. But earlier
156 // optimizations really should have eliminated one of the loads.
157 continue;
158 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
159 Offsets.push_back(Offset1);
160 O2SMap.insert(std::make_pair(Offset2, User));
161 Offsets.push_back(Offset2);
162 if (Offset2 < Offset1) {
163 Base = User;
164 BaseOffset = Offset2;
165 } else {
166 BaseOffset = Offset1;
167 }
168 Cluster = true;
169 }
170
171 if (!Cluster)
172 return;
173
174 // Sort them in increasing order.
175 std::sort(Offsets.begin(), Offsets.end());
176
177 // Check if the loads are close enough.
178 SmallVector<SDNode*, 4> Loads;
179 unsigned NumLoads = 0;
180 int64_t BaseOff = Offsets[0];
181 SDNode *BaseLoad = O2SMap[BaseOff];
182 Loads.push_back(BaseLoad);
183 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
184 int64_t Offset = Offsets[i];
185 SDNode *Load = O2SMap[Offset];
186 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
187 break; // Stop right here. Ignore loads that are further away.
188 Loads.push_back(Load);
189 ++NumLoads;
190 }
191
192 if (NumLoads == 0)
193 return;
194
195 // Cluster loads by adding MVT::Flag outputs and inputs. This also
196 // ensure they are scheduled in order of increasing addresses.
197 SDNode *Lead = Loads[0];
198 AddFlags(Lead, SDValue(0,0), true, DAG);
199 SDValue InFlag = SDValue(Lead, Lead->getNumValues()-1);
200 for (unsigned i = 1, e = Loads.size(); i != e; ++i) {
201 bool OutFlag = i < e-1;
202 SDNode *Load = Loads[i];
203 AddFlags(Load, InFlag, OutFlag, DAG);
204 if (OutFlag)
205 InFlag = SDValue(Load, Load->getNumValues()-1);
206 ++LoadsClustered;
207 }
208}
209
210/// ClusterNodes - Cluster certain nodes which should be scheduled together.
211///
212void ScheduleDAGSDNodes::ClusterNodes() {
Evan Chengc589e032010-01-22 03:36:51 +0000213 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
214 E = DAG->allnodes_end(); NI != E; ++NI) {
215 SDNode *Node = &*NI;
216 if (!Node || !Node->isMachineOpcode())
217 continue;
218
219 unsigned Opc = Node->getMachineOpcode();
220 const TargetInstrDesc &TID = TII->get(Opc);
Evan Cheng302ef832010-06-10 02:09:31 +0000221 if (TID.mayLoad())
222 // Cluster loads from "near" addresses into combined SUnits.
223 ClusterNeighboringLoads(Node);
Evan Chengc589e032010-01-22 03:36:51 +0000224 }
225}
226
Dan Gohman343f0c02008-11-19 23:18:57 +0000227void ScheduleDAGSDNodes::BuildSchedUnits() {
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000228 // During scheduling, the NodeId field of SDNode is used to map SDNodes
229 // to their associated SUnits by holding SUnits table indices. A value
230 // of -1 means the SDNode does not yet have an associated SUnit.
231 unsigned NumNodes = 0;
232 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
233 E = DAG->allnodes_end(); NI != E; ++NI) {
234 NI->setNodeId(-1);
235 ++NumNodes;
236 }
237
Dan Gohman343f0c02008-11-19 23:18:57 +0000238 // Reserve entries in the vector for each of the SUnits we are creating. This
239 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
240 // invalidated.
Dan Gohman89b64bd2008-12-17 04:30:46 +0000241 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
242 // This is a temporary workaround.
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000243 SUnits.reserve(NumNodes * 2);
Dan Gohman343f0c02008-11-19 23:18:57 +0000244
Chris Lattner736a6ea2010-02-24 06:11:37 +0000245 // Add all nodes in depth first order.
246 SmallVector<SDNode*, 64> Worklist;
247 SmallPtrSet<SDNode*, 64> Visited;
248 Worklist.push_back(DAG->getRoot().getNode());
249 Visited.insert(DAG->getRoot().getNode());
250
251 while (!Worklist.empty()) {
252 SDNode *NI = Worklist.pop_back_val();
253
254 // Add all operands to the worklist unless they've already been added.
255 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
256 if (Visited.insert(NI->getOperand(i).getNode()))
257 Worklist.push_back(NI->getOperand(i).getNode());
258
Dan Gohman343f0c02008-11-19 23:18:57 +0000259 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
260 continue;
261
262 // If this node has already been processed, stop now.
263 if (NI->getNodeId() != -1) continue;
264
265 SUnit *NodeSUnit = NewSUnit(NI);
266
267 // See if anything is flagged to this node, if so, add them to flagged
268 // nodes. Nodes can have at most one flag input and one flag output. Flags
Dan Gohmandb95fa12009-03-20 20:42:23 +0000269 // are required to be the last operand and result of a node.
Dan Gohman343f0c02008-11-19 23:18:57 +0000270
271 // Scan up to find flagged preds.
272 SDNode *N = NI;
Dan Gohmandb95fa12009-03-20 20:42:23 +0000273 while (N->getNumOperands() &&
Owen Anderson825b72b2009-08-11 20:47:22 +0000274 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
Dan Gohmandb95fa12009-03-20 20:42:23 +0000275 N = N->getOperand(N->getNumOperands()-1).getNode();
276 assert(N->getNodeId() == -1 && "Node already inserted!");
277 N->setNodeId(NodeSUnit->NodeNum);
Dan Gohman343f0c02008-11-19 23:18:57 +0000278 }
279
280 // Scan down to find any flagged succs.
281 N = NI;
Owen Anderson825b72b2009-08-11 20:47:22 +0000282 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000283 SDValue FlagVal(N, N->getNumValues()-1);
284
285 // There are either zero or one users of the Flag result.
286 bool HasFlagUse = false;
287 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
288 UI != E; ++UI)
289 if (FlagVal.isOperandOf(*UI)) {
290 HasFlagUse = true;
291 assert(N->getNodeId() == -1 && "Node already inserted!");
292 N->setNodeId(NodeSUnit->NodeNum);
293 N = *UI;
294 break;
295 }
296 if (!HasFlagUse) break;
297 }
298
299 // If there are flag operands involved, N is now the bottom-most node
300 // of the sequence of nodes that are flagged together.
301 // Update the SUnit.
302 NodeSUnit->setNode(N);
303 assert(N->getNodeId() == -1 && "Node already inserted!");
304 N->setNodeId(NodeSUnit->NodeNum);
305
Dan Gohman787782f2008-11-21 01:44:51 +0000306 // Assign the Latency field of NodeSUnit using target-provided information.
Evan Chenge1631682010-05-19 22:42:23 +0000307 ComputeLatency(NodeSUnit);
Dan Gohman343f0c02008-11-19 23:18:57 +0000308 }
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000309}
310
311void ScheduleDAGSDNodes::AddSchedEdges() {
David Goodwin71046162009-08-13 16:05:04 +0000312 const TargetSubtarget &ST = TM.getSubtarget<TargetSubtarget>();
313
David Goodwindc4bdcd2009-08-19 16:08:58 +0000314 // Check to see if the scheduler cares about latencies.
315 bool UnitLatencies = ForceUnitLatencies();
316
Dan Gohman343f0c02008-11-19 23:18:57 +0000317 // Pass 2: add the preds, succs, etc.
318 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
319 SUnit *SU = &SUnits[su];
320 SDNode *MainNode = SU->getNode();
321
322 if (MainNode->isMachineOpcode()) {
323 unsigned Opc = MainNode->getMachineOpcode();
324 const TargetInstrDesc &TID = TII->get(Opc);
325 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
326 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
327 SU->isTwoAddress = true;
328 break;
329 }
330 }
331 if (TID.isCommutable())
332 SU->isCommutable = true;
333 }
334
335 // Find all predecessors and successors of the group.
336 for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode()) {
337 if (N->isMachineOpcode() &&
Dan Gohman39746672009-03-23 16:10:52 +0000338 TII->get(N->getMachineOpcode()).getImplicitDefs()) {
339 SU->hasPhysRegClobbers = true;
Dan Gohmanbcea8592009-10-10 01:32:21 +0000340 unsigned NumUsed = InstrEmitter::CountResults(N);
Dan Gohman8cccf0e2009-03-23 17:39:36 +0000341 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
342 --NumUsed; // Skip over unused values at the end.
343 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
Dan Gohman39746672009-03-23 16:10:52 +0000344 SU->hasPhysRegDefs = true;
345 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000346
347 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
348 SDNode *OpN = N->getOperand(i).getNode();
349 if (isPassiveNode(OpN)) continue; // Not scheduled.
350 SUnit *OpSU = &SUnits[OpN->getNodeId()];
351 assert(OpSU && "Node has no SUnit!");
352 if (OpSU == SU) continue; // In the same group.
353
Owen Andersone50ed302009-08-10 22:56:29 +0000354 EVT OpVT = N->getOperand(i).getValueType();
Owen Anderson825b72b2009-08-11 20:47:22 +0000355 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
356 bool isChain = OpVT == MVT::Other;
Dan Gohman343f0c02008-11-19 23:18:57 +0000357
358 unsigned PhysReg = 0;
Evan Chengc29a56d2009-01-12 03:19:55 +0000359 int Cost = 1;
Dan Gohman343f0c02008-11-19 23:18:57 +0000360 // Determine if this is a physical register dependency.
Evan Chengc29a56d2009-01-12 03:19:55 +0000361 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
Dan Gohman54e4c362008-12-09 22:54:47 +0000362 assert((PhysReg == 0 || !isChain) &&
363 "Chain dependence via physreg data?");
Evan Chengc29a56d2009-01-12 03:19:55 +0000364 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
365 // emits a copy from the physical register to a virtual register unless
366 // it requires a cross class copy (cost < 0). That means we are only
367 // treating "expensive to copy" register dependency as physical register
368 // dependency. This may change in the future though.
369 if (Cost >= 0)
370 PhysReg = 0;
David Goodwin71046162009-08-13 16:05:04 +0000371
Evan Cheng046fa3f2010-05-28 23:26:21 +0000372 // If this is a ctrl dep, latency is 1.
373 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
374 const SDep &dep = SDep(OpSU, isChain ? SDep::Order : SDep::Data,
375 OpLatency, PhysReg);
David Goodwindc4bdcd2009-08-19 16:08:58 +0000376 if (!isChain && !UnitLatencies) {
Evan Cheng15a16de2010-05-20 06:13:19 +0000377 ComputeOperandLatency(OpN, N, i, const_cast<SDep &>(dep));
Dan Gohman3fb150a2010-04-17 17:42:52 +0000378 ST.adjustSchedDependency(OpSU, SU, const_cast<SDep &>(dep));
David Goodwindc4bdcd2009-08-19 16:08:58 +0000379 }
David Goodwin71046162009-08-13 16:05:04 +0000380
381 SU->addPred(dep);
Dan Gohman343f0c02008-11-19 23:18:57 +0000382 }
383 }
384 }
385}
386
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000387/// BuildSchedGraph - Build the SUnit graph from the selection dag that we
388/// are input. This SUnit graph is similar to the SelectionDAG, but
389/// excludes nodes that aren't interesting to scheduling, and represents
390/// flagged together nodes with a single SUnit.
Dan Gohman98976e42009-10-09 23:33:48 +0000391void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
Evan Cheng302ef832010-06-10 02:09:31 +0000392 // Cluster certain nodes which should be scheduled together.
393 ClusterNodes();
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000394 // Populate the SUnits array.
395 BuildSchedUnits();
396 // Compute all the scheduling dependencies between nodes.
397 AddSchedEdges();
398}
399
Dan Gohman343f0c02008-11-19 23:18:57 +0000400void ScheduleDAGSDNodes::ComputeLatency(SUnit *SU) {
Evan Chenge1631682010-05-19 22:42:23 +0000401 // Check to see if the scheduler cares about latencies.
402 if (ForceUnitLatencies()) {
403 SU->Latency = 1;
404 return;
405 }
406
Dan Gohman343f0c02008-11-19 23:18:57 +0000407 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
Evan Cheng15a16de2010-05-20 06:13:19 +0000408 if (InstrItins.isEmpty()) {
409 SU->Latency = 1;
410 return;
411 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000412
413 // Compute the latency for the node. We use the sum of the latencies for
414 // all nodes flagged together into this SUnit.
Dan Gohman343f0c02008-11-19 23:18:57 +0000415 SU->Latency = 0;
Dan Gohmanc8c28272008-11-21 00:12:10 +0000416 for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode())
Dan Gohman343f0c02008-11-19 23:18:57 +0000417 if (N->isMachineOpcode()) {
David Goodwindc4bdcd2009-08-19 16:08:58 +0000418 SU->Latency += InstrItins.
419 getStageLatency(TII->get(N->getMachineOpcode()).getSchedClass());
Dan Gohman343f0c02008-11-19 23:18:57 +0000420 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000421}
422
Evan Cheng15a16de2010-05-20 06:13:19 +0000423void ScheduleDAGSDNodes::ComputeOperandLatency(SDNode *Def, SDNode *Use,
424 unsigned OpIdx, SDep& dep) const{
425 // Check to see if the scheduler cares about latencies.
426 if (ForceUnitLatencies())
427 return;
428
429 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
430 if (InstrItins.isEmpty())
431 return;
432
433 if (dep.getKind() != SDep::Data)
434 return;
435
436 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
Evan Cheng046fa3f2010-05-28 23:26:21 +0000437 if (Def->isMachineOpcode()) {
Evan Cheng15a16de2010-05-20 06:13:19 +0000438 const TargetInstrDesc &II = TII->get(Def->getMachineOpcode());
439 if (DefIdx >= II.getNumDefs())
440 return;
441 int DefCycle = InstrItins.getOperandCycle(II.getSchedClass(), DefIdx);
442 if (DefCycle < 0)
443 return;
Evan Cheng046fa3f2010-05-28 23:26:21 +0000444 int UseCycle = 1;
445 if (Use->isMachineOpcode()) {
446 const unsigned UseClass = TII->get(Use->getMachineOpcode()).getSchedClass();
447 UseCycle = InstrItins.getOperandCycle(UseClass, OpIdx);
448 }
Evan Cheng15a16de2010-05-20 06:13:19 +0000449 if (UseCycle >= 0) {
450 int Latency = DefCycle - UseCycle + 1;
451 if (Latency >= 0)
452 dep.setLatency(Latency);
453 }
454 }
455}
456
Dan Gohman343f0c02008-11-19 23:18:57 +0000457void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
Evan Chengc29a56d2009-01-12 03:19:55 +0000458 if (!SU->getNode()) {
David Greene84fa8222010-01-05 01:25:11 +0000459 dbgs() << "PHYS REG COPY\n";
Evan Chengc29a56d2009-01-12 03:19:55 +0000460 return;
461 }
462
463 SU->getNode()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000464 dbgs() << "\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000465 SmallVector<SDNode *, 4> FlaggedNodes;
466 for (SDNode *N = SU->getNode()->getFlaggedNode(); N; N = N->getFlaggedNode())
467 FlaggedNodes.push_back(N);
468 while (!FlaggedNodes.empty()) {
David Greene84fa8222010-01-05 01:25:11 +0000469 dbgs() << " ";
Dan Gohman343f0c02008-11-19 23:18:57 +0000470 FlaggedNodes.back()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000471 dbgs() << "\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000472 FlaggedNodes.pop_back();
473 }
474}
Dan Gohmanbcea8592009-10-10 01:32:21 +0000475
Evan Chengbfcb3052010-03-25 01:38:16 +0000476namespace {
477 struct OrderSorter {
478 bool operator()(const std::pair<unsigned, MachineInstr*> &A,
479 const std::pair<unsigned, MachineInstr*> &B) {
480 return A.first < B.first;
481 }
482 };
483}
484
485// ProcessSourceNode - Process nodes with source order numbers. These are added
486// to a vector which EmitSchedule use to determine how to insert dbg_value
487// instructions in the right order.
488static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG,
489 InstrEmitter &Emitter,
Evan Chengbfcb3052010-03-25 01:38:16 +0000490 DenseMap<SDValue, unsigned> &VRBaseMap,
491 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
492 SmallSet<unsigned, 8> &Seen) {
493 unsigned Order = DAG->GetOrdering(N);
494 if (!Order || !Seen.insert(Order))
495 return;
496
497 MachineBasicBlock *BB = Emitter.getBlock();
498 if (BB->empty() || BB->back().isPHI()) {
499 // Did not insert any instruction.
500 Orders.push_back(std::make_pair(Order, (MachineInstr*)0));
501 return;
502 }
503
504 Orders.push_back(std::make_pair(Order, &BB->back()));
505 if (!N->getHasDebugValue())
506 return;
507 // Opportunistically insert immediate dbg_value uses, i.e. those with source
508 // order number right after the N.
509 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
510 SmallVector<SDDbgValue*,2> &DVs = DAG->GetDbgValues(N);
511 for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
512 if (DVs[i]->isInvalidated())
513 continue;
514 unsigned DVOrder = DVs[i]->getOrder();
515 if (DVOrder == ++Order) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000516 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000517 if (DbgMI) {
518 Orders.push_back(std::make_pair(DVOrder, DbgMI));
519 BB->insert(InsertPos, DbgMI);
520 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000521 DVs[i]->setIsInvalidated();
522 }
523 }
524}
525
526
Dan Gohmanbcea8592009-10-10 01:32:21 +0000527/// EmitSchedule - Emit the machine code in scheduled order.
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000528MachineBasicBlock *ScheduleDAGSDNodes::EmitSchedule() {
Dan Gohmanbcea8592009-10-10 01:32:21 +0000529 InstrEmitter Emitter(BB, InsertPos);
530 DenseMap<SDValue, unsigned> VRBaseMap;
531 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
Evan Chengbfcb3052010-03-25 01:38:16 +0000532 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
533 SmallSet<unsigned, 8> Seen;
534 bool HasDbg = DAG->hasDebugValues();
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000535
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000536 // If this is the first BB, emit byval parameter dbg_value's.
537 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
538 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
539 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
540 for (; PDI != PDE; ++PDI) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000541 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000542 if (DbgMI)
Dan Gohman403a8cd2010-06-21 19:47:52 +0000543 BB->push_back(DbgMI);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000544 }
545 }
546
Dan Gohmanbcea8592009-10-10 01:32:21 +0000547 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
548 SUnit *SU = Sequence[i];
549 if (!SU) {
550 // Null SUnit* is a noop.
551 EmitNoop();
552 continue;
553 }
554
555 // For pre-regalloc scheduling, create instructions corresponding to the
556 // SDNode and any flagged SDNodes and append them to the block.
557 if (!SU->getNode()) {
558 // Emit a copy.
559 EmitPhysRegCopy(SU, CopyVRBaseMap);
560 continue;
561 }
562
563 SmallVector<SDNode *, 4> FlaggedNodes;
564 for (SDNode *N = SU->getNode()->getFlaggedNode(); N;
565 N = N->getFlaggedNode())
566 FlaggedNodes.push_back(N);
567 while (!FlaggedNodes.empty()) {
Evan Chengbfcb3052010-03-25 01:38:16 +0000568 SDNode *N = FlaggedNodes.back();
Dan Gohmanbcea8592009-10-10 01:32:21 +0000569 Emitter.EmitNode(FlaggedNodes.back(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000570 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000571 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000572 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000573 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
Dan Gohmanbcea8592009-10-10 01:32:21 +0000574 FlaggedNodes.pop_back();
575 }
576 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000577 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000578 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000579 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000580 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
Evan Chengbfcb3052010-03-25 01:38:16 +0000581 Seen);
582 }
583
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000584 // Insert all the dbg_values which have not already been inserted in source
Evan Chengbfcb3052010-03-25 01:38:16 +0000585 // order sequence.
586 if (HasDbg) {
587 MachineBasicBlock::iterator BBBegin = BB->empty() ? BB->end() : BB->begin();
588 while (BBBegin != BB->end() && BBBegin->isPHI())
589 ++BBBegin;
590
591 // Sort the source order instructions and use the order to insert debug
592 // values.
593 std::sort(Orders.begin(), Orders.end(), OrderSorter());
594
595 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
596 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
597 // Now emit the rest according to source order.
598 unsigned LastOrder = 0;
599 MachineInstr *LastMI = 0;
600 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
601 unsigned Order = Orders[i].first;
602 MachineInstr *MI = Orders[i].second;
603 // Insert all SDDbgValue's whose order(s) are before "Order".
604 if (!MI)
605 continue;
606 MachineBasicBlock *MIBB = MI->getParent();
Evan Cheng4ec9bd92010-03-25 07:16:57 +0000607#ifndef NDEBUG
608 unsigned LastDIOrder = 0;
609#endif
Evan Chengbfcb3052010-03-25 01:38:16 +0000610 for (; DI != DE &&
611 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
Evan Cheng4ec9bd92010-03-25 07:16:57 +0000612#ifndef NDEBUG
613 assert((*DI)->getOrder() >= LastDIOrder &&
614 "SDDbgValue nodes must be in source order!");
615 LastDIOrder = (*DI)->getOrder();
616#endif
Evan Chengbfcb3052010-03-25 01:38:16 +0000617 if ((*DI)->isInvalidated())
618 continue;
Dan Gohman891ff8f2010-04-30 19:35:33 +0000619 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000620 if (DbgMI) {
621 if (!LastOrder)
622 // Insert to start of the BB (after PHIs).
623 BB->insert(BBBegin, DbgMI);
624 else {
625 MachineBasicBlock::iterator Pos = MI;
626 MIBB->insert(llvm::next(Pos), DbgMI);
627 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000628 }
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000629 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000630 LastOrder = Order;
631 LastMI = MI;
632 }
633 // Add trailing DbgValue's before the terminator. FIXME: May want to add
634 // some of them before one or more conditional branches?
635 while (DI != DE) {
636 MachineBasicBlock *InsertBB = Emitter.getBlock();
637 MachineBasicBlock::iterator Pos= Emitter.getBlock()->getFirstTerminator();
638 if (!(*DI)->isInvalidated()) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000639 MachineInstr *DbgMI= Emitter.EmitDbgValue(*DI, VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000640 if (DbgMI)
641 InsertBB->insert(Pos, DbgMI);
Evan Chengbfcb3052010-03-25 01:38:16 +0000642 }
643 ++DI;
644 }
Dan Gohmanbcea8592009-10-10 01:32:21 +0000645 }
646
647 BB = Emitter.getBlock();
648 InsertPos = Emitter.getInsertPos();
649 return BB;
650}