blob: 23ff9c5807ccc179a12bdc8fb600d86992549da7 [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)
Evan Cheng3ef1c872010-09-10 01:29:16 +000037 : ScheduleDAG(mf),
38 InstrItins(mf.getTarget().getInstrItineraryData()) {}
Dan Gohman343f0c02008-11-19 23:18:57 +000039
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 Chengc120af42010-08-10 02:39:45 +000062 if (!N ||
63 (N->isMachineOpcode() &&
64 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
Evan Cheng046fa3f2010-05-28 23:26:21 +000065 SU->SchedulingPref = Sched::None;
66 else
67 SU->SchedulingPref = TLI.getSchedulingPreference(N);
Evan Cheng1cc39842010-05-20 23:26:43 +000068 return SU;
69}
70
Dan Gohman343f0c02008-11-19 23:18:57 +000071SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
72 SUnit *SU = NewSUnit(Old->getNode());
73 SU->OrigNode = Old->OrigNode;
74 SU->Latency = Old->Latency;
75 SU->isTwoAddress = Old->isTwoAddress;
76 SU->isCommutable = Old->isCommutable;
77 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
Dan Gohman39746672009-03-23 16:10:52 +000078 SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
Evan Cheng1cc39842010-05-20 23:26:43 +000079 SU->SchedulingPref = Old->SchedulingPref;
Evan Chenge57187c2009-01-16 20:57:18 +000080 Old->isCloned = true;
Dan Gohman343f0c02008-11-19 23:18:57 +000081 return SU;
82}
83
84/// CheckForPhysRegDependency - Check if the dependency between def and use of
85/// a specified operand is a physical register dependency. If so, returns the
Evan Chengc29a56d2009-01-12 03:19:55 +000086/// register and the cost of copying the register.
Dan Gohman343f0c02008-11-19 23:18:57 +000087static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
88 const TargetRegisterInfo *TRI,
89 const TargetInstrInfo *TII,
Evan Chengc29a56d2009-01-12 03:19:55 +000090 unsigned &PhysReg, int &Cost) {
Dan Gohman343f0c02008-11-19 23:18:57 +000091 if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
92 return;
93
94 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
95 if (TargetRegisterInfo::isVirtualRegister(Reg))
96 return;
97
98 unsigned ResNo = User->getOperand(2).getResNo();
99 if (Def->isMachineOpcode()) {
100 const TargetInstrDesc &II = TII->get(Def->getMachineOpcode());
101 if (ResNo >= II.getNumDefs() &&
Evan Chengc29a56d2009-01-12 03:19:55 +0000102 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000103 PhysReg = Reg;
Evan Chengc29a56d2009-01-12 03:19:55 +0000104 const TargetRegisterClass *RC =
Rafael Espindolad31f9722010-06-29 14:02:34 +0000105 TRI->getMinimalPhysRegClass(Reg, Def->getValueType(ResNo));
Evan Chengc29a56d2009-01-12 03:19:55 +0000106 Cost = RC->getCopyCost();
107 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000108 }
109}
110
Evan Chengc589e032010-01-22 03:36:51 +0000111static void AddFlags(SDNode *N, SDValue Flag, bool AddFlag,
112 SelectionDAG *DAG) {
113 SmallVector<EVT, 4> VTs;
Bill Wendling10707f32010-06-24 22:00:37 +0000114 SDNode *FlagDestNode = Flag.getNode();
Bill Wendling151d26d2010-06-23 18:16:24 +0000115
Bill Wendling10707f32010-06-24 22:00:37 +0000116 // Don't add a flag from a node to itself.
117 if (FlagDestNode == N) return;
118
119 // Don't add a flag to something which already has a flag.
120 if (N->getValueType(N->getNumValues() - 1) == MVT::Flag) return;
121
122 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
123 VTs.push_back(N->getValueType(I));
Bill Wendling151d26d2010-06-23 18:16:24 +0000124
Evan Chengc589e032010-01-22 03:36:51 +0000125 if (AddFlag)
126 VTs.push_back(MVT::Flag);
Bill Wendling151d26d2010-06-23 18:16:24 +0000127
Evan Chengc589e032010-01-22 03:36:51 +0000128 SmallVector<SDValue, 4> Ops;
Bill Wendling10707f32010-06-24 22:00:37 +0000129 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I)
130 Ops.push_back(N->getOperand(I));
Bill Wendling151d26d2010-06-23 18:16:24 +0000131
Bill Wendling10707f32010-06-24 22:00:37 +0000132 if (FlagDestNode)
Evan Chengc589e032010-01-22 03:36:51 +0000133 Ops.push_back(Flag);
Bill Wendling151d26d2010-06-23 18:16:24 +0000134
Evan Chengc589e032010-01-22 03:36:51 +0000135 SDVTList VTList = DAG->getVTList(&VTs[0], VTs.size());
Bill Wendling151d26d2010-06-23 18:16:24 +0000136 MachineSDNode::mmo_iterator Begin = 0, End = 0;
137 MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
138
139 // Store memory references.
140 if (MN) {
141 Begin = MN->memoperands_begin();
142 End = MN->memoperands_end();
143 }
144
Evan Chengc589e032010-01-22 03:36:51 +0000145 DAG->MorphNodeTo(N, N->getOpcode(), VTList, &Ops[0], Ops.size());
Bill Wendling151d26d2010-06-23 18:16:24 +0000146
147 // Reset the memory references
148 if (MN)
149 MN->setMemRefs(Begin, End);
Evan Chengc589e032010-01-22 03:36:51 +0000150}
151
152/// ClusterNeighboringLoads - Force nearby loads together by "flagging" them.
153/// This function finds loads of the same base and different offsets. If the
154/// offsets are not far apart (target specific), it add MVT::Flag inputs and
155/// outputs to ensure they are scheduled together and in order. This
156/// optimization may benefit some targets by improving cache locality.
Evan Cheng302ef832010-06-10 02:09:31 +0000157void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
158 SDNode *Chain = 0;
159 unsigned NumOps = Node->getNumOperands();
160 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
161 Chain = Node->getOperand(NumOps-1).getNode();
162 if (!Chain)
163 return;
164
165 // Look for other loads of the same chain. Find loads that are loading from
166 // the same base pointer and different offsets.
Evan Chengc589e032010-01-22 03:36:51 +0000167 SmallPtrSet<SDNode*, 16> Visited;
168 SmallVector<int64_t, 4> Offsets;
169 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
Evan Cheng302ef832010-06-10 02:09:31 +0000170 bool Cluster = false;
171 SDNode *Base = Node;
Evan Cheng302ef832010-06-10 02:09:31 +0000172 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
173 I != E; ++I) {
174 SDNode *User = *I;
175 if (User == Node || !Visited.insert(User))
176 continue;
177 int64_t Offset1, Offset2;
178 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
179 Offset1 == Offset2)
180 // FIXME: Should be ok if they addresses are identical. But earlier
181 // optimizations really should have eliminated one of the loads.
182 continue;
183 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
184 Offsets.push_back(Offset1);
185 O2SMap.insert(std::make_pair(Offset2, User));
186 Offsets.push_back(Offset2);
Duncan Sandsb447c4e2010-06-25 14:48:39 +0000187 if (Offset2 < Offset1)
Evan Cheng302ef832010-06-10 02:09:31 +0000188 Base = User;
Evan Cheng302ef832010-06-10 02:09:31 +0000189 Cluster = true;
190 }
191
192 if (!Cluster)
193 return;
194
195 // Sort them in increasing order.
196 std::sort(Offsets.begin(), Offsets.end());
197
198 // Check if the loads are close enough.
199 SmallVector<SDNode*, 4> Loads;
200 unsigned NumLoads = 0;
201 int64_t BaseOff = Offsets[0];
202 SDNode *BaseLoad = O2SMap[BaseOff];
203 Loads.push_back(BaseLoad);
204 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
205 int64_t Offset = Offsets[i];
206 SDNode *Load = O2SMap[Offset];
207 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
208 break; // Stop right here. Ignore loads that are further away.
209 Loads.push_back(Load);
210 ++NumLoads;
211 }
212
213 if (NumLoads == 0)
214 return;
215
216 // Cluster loads by adding MVT::Flag outputs and inputs. This also
217 // ensure they are scheduled in order of increasing addresses.
218 SDNode *Lead = Loads[0];
Bill Wendling10707f32010-06-24 22:00:37 +0000219 AddFlags(Lead, SDValue(0, 0), true, DAG);
Bill Wendling151d26d2010-06-23 18:16:24 +0000220
Bill Wendling10707f32010-06-24 22:00:37 +0000221 SDValue InFlag = SDValue(Lead, Lead->getNumValues() - 1);
222 for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
223 bool OutFlag = I < E - 1;
224 SDNode *Load = Loads[I];
225
Evan Cheng302ef832010-06-10 02:09:31 +0000226 AddFlags(Load, InFlag, OutFlag, DAG);
Bill Wendling151d26d2010-06-23 18:16:24 +0000227
Evan Cheng302ef832010-06-10 02:09:31 +0000228 if (OutFlag)
Bill Wendling10707f32010-06-24 22:00:37 +0000229 InFlag = SDValue(Load, Load->getNumValues() - 1);
Bill Wendling151d26d2010-06-23 18:16:24 +0000230
Evan Cheng302ef832010-06-10 02:09:31 +0000231 ++LoadsClustered;
232 }
233}
234
235/// ClusterNodes - Cluster certain nodes which should be scheduled together.
236///
237void ScheduleDAGSDNodes::ClusterNodes() {
Evan Chengc589e032010-01-22 03:36:51 +0000238 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
239 E = DAG->allnodes_end(); NI != E; ++NI) {
240 SDNode *Node = &*NI;
241 if (!Node || !Node->isMachineOpcode())
242 continue;
243
244 unsigned Opc = Node->getMachineOpcode();
245 const TargetInstrDesc &TID = TII->get(Opc);
Evan Cheng302ef832010-06-10 02:09:31 +0000246 if (TID.mayLoad())
247 // Cluster loads from "near" addresses into combined SUnits.
248 ClusterNeighboringLoads(Node);
Evan Chengc589e032010-01-22 03:36:51 +0000249 }
250}
251
Dan Gohman343f0c02008-11-19 23:18:57 +0000252void ScheduleDAGSDNodes::BuildSchedUnits() {
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000253 // During scheduling, the NodeId field of SDNode is used to map SDNodes
254 // to their associated SUnits by holding SUnits table indices. A value
255 // of -1 means the SDNode does not yet have an associated SUnit.
256 unsigned NumNodes = 0;
257 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
258 E = DAG->allnodes_end(); NI != E; ++NI) {
259 NI->setNodeId(-1);
260 ++NumNodes;
261 }
262
Dan Gohman343f0c02008-11-19 23:18:57 +0000263 // Reserve entries in the vector for each of the SUnits we are creating. This
264 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
265 // invalidated.
Dan Gohman89b64bd2008-12-17 04:30:46 +0000266 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
267 // This is a temporary workaround.
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000268 SUnits.reserve(NumNodes * 2);
Dan Gohman343f0c02008-11-19 23:18:57 +0000269
Chris Lattner736a6ea2010-02-24 06:11:37 +0000270 // Add all nodes in depth first order.
271 SmallVector<SDNode*, 64> Worklist;
272 SmallPtrSet<SDNode*, 64> Visited;
273 Worklist.push_back(DAG->getRoot().getNode());
274 Visited.insert(DAG->getRoot().getNode());
275
276 while (!Worklist.empty()) {
277 SDNode *NI = Worklist.pop_back_val();
278
279 // Add all operands to the worklist unless they've already been added.
280 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
281 if (Visited.insert(NI->getOperand(i).getNode()))
282 Worklist.push_back(NI->getOperand(i).getNode());
283
Dan Gohman343f0c02008-11-19 23:18:57 +0000284 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
285 continue;
286
287 // If this node has already been processed, stop now.
288 if (NI->getNodeId() != -1) continue;
289
290 SUnit *NodeSUnit = NewSUnit(NI);
291
292 // See if anything is flagged to this node, if so, add them to flagged
293 // nodes. Nodes can have at most one flag input and one flag output. Flags
Dan Gohmandb95fa12009-03-20 20:42:23 +0000294 // are required to be the last operand and result of a node.
Dan Gohman343f0c02008-11-19 23:18:57 +0000295
296 // Scan up to find flagged preds.
297 SDNode *N = NI;
Dan Gohmandb95fa12009-03-20 20:42:23 +0000298 while (N->getNumOperands() &&
Owen Anderson825b72b2009-08-11 20:47:22 +0000299 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
Dan Gohmandb95fa12009-03-20 20:42:23 +0000300 N = N->getOperand(N->getNumOperands()-1).getNode();
301 assert(N->getNodeId() == -1 && "Node already inserted!");
302 N->setNodeId(NodeSUnit->NodeNum);
Dan Gohman343f0c02008-11-19 23:18:57 +0000303 }
304
305 // Scan down to find any flagged succs.
306 N = NI;
Owen Anderson825b72b2009-08-11 20:47:22 +0000307 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000308 SDValue FlagVal(N, N->getNumValues()-1);
309
310 // There are either zero or one users of the Flag result.
311 bool HasFlagUse = false;
312 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
313 UI != E; ++UI)
314 if (FlagVal.isOperandOf(*UI)) {
315 HasFlagUse = true;
316 assert(N->getNodeId() == -1 && "Node already inserted!");
317 N->setNodeId(NodeSUnit->NodeNum);
318 N = *UI;
319 break;
320 }
321 if (!HasFlagUse) break;
322 }
323
324 // If there are flag operands involved, N is now the bottom-most node
325 // of the sequence of nodes that are flagged together.
326 // Update the SUnit.
327 NodeSUnit->setNode(N);
328 assert(N->getNodeId() == -1 && "Node already inserted!");
329 N->setNodeId(NodeSUnit->NodeNum);
330
Dan Gohman787782f2008-11-21 01:44:51 +0000331 // Assign the Latency field of NodeSUnit using target-provided information.
Evan Chenge1631682010-05-19 22:42:23 +0000332 ComputeLatency(NodeSUnit);
Dan Gohman343f0c02008-11-19 23:18:57 +0000333 }
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000334}
335
336void ScheduleDAGSDNodes::AddSchedEdges() {
David Goodwin71046162009-08-13 16:05:04 +0000337 const TargetSubtarget &ST = TM.getSubtarget<TargetSubtarget>();
338
David Goodwindc4bdcd2009-08-19 16:08:58 +0000339 // Check to see if the scheduler cares about latencies.
340 bool UnitLatencies = ForceUnitLatencies();
341
Dan Gohman343f0c02008-11-19 23:18:57 +0000342 // Pass 2: add the preds, succs, etc.
343 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
344 SUnit *SU = &SUnits[su];
345 SDNode *MainNode = SU->getNode();
346
347 if (MainNode->isMachineOpcode()) {
348 unsigned Opc = MainNode->getMachineOpcode();
349 const TargetInstrDesc &TID = TII->get(Opc);
350 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
351 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
352 SU->isTwoAddress = true;
353 break;
354 }
355 }
356 if (TID.isCommutable())
357 SU->isCommutable = true;
358 }
359
360 // Find all predecessors and successors of the group.
361 for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode()) {
362 if (N->isMachineOpcode() &&
Dan Gohman39746672009-03-23 16:10:52 +0000363 TII->get(N->getMachineOpcode()).getImplicitDefs()) {
364 SU->hasPhysRegClobbers = true;
Dan Gohmanbcea8592009-10-10 01:32:21 +0000365 unsigned NumUsed = InstrEmitter::CountResults(N);
Dan Gohman8cccf0e2009-03-23 17:39:36 +0000366 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
367 --NumUsed; // Skip over unused values at the end.
368 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
Dan Gohman39746672009-03-23 16:10:52 +0000369 SU->hasPhysRegDefs = true;
370 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000371
372 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
373 SDNode *OpN = N->getOperand(i).getNode();
374 if (isPassiveNode(OpN)) continue; // Not scheduled.
375 SUnit *OpSU = &SUnits[OpN->getNodeId()];
376 assert(OpSU && "Node has no SUnit!");
377 if (OpSU == SU) continue; // In the same group.
378
Owen Andersone50ed302009-08-10 22:56:29 +0000379 EVT OpVT = N->getOperand(i).getValueType();
Owen Anderson825b72b2009-08-11 20:47:22 +0000380 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
381 bool isChain = OpVT == MVT::Other;
Dan Gohman343f0c02008-11-19 23:18:57 +0000382
383 unsigned PhysReg = 0;
Evan Chengc29a56d2009-01-12 03:19:55 +0000384 int Cost = 1;
Dan Gohman343f0c02008-11-19 23:18:57 +0000385 // Determine if this is a physical register dependency.
Evan Chengc29a56d2009-01-12 03:19:55 +0000386 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
Dan Gohman54e4c362008-12-09 22:54:47 +0000387 assert((PhysReg == 0 || !isChain) &&
388 "Chain dependence via physreg data?");
Evan Chengc29a56d2009-01-12 03:19:55 +0000389 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
390 // emits a copy from the physical register to a virtual register unless
391 // it requires a cross class copy (cost < 0). That means we are only
392 // treating "expensive to copy" register dependency as physical register
393 // dependency. This may change in the future though.
394 if (Cost >= 0)
395 PhysReg = 0;
David Goodwin71046162009-08-13 16:05:04 +0000396
Evan Cheng046fa3f2010-05-28 23:26:21 +0000397 // If this is a ctrl dep, latency is 1.
398 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
399 const SDep &dep = SDep(OpSU, isChain ? SDep::Order : SDep::Data,
400 OpLatency, PhysReg);
David Goodwindc4bdcd2009-08-19 16:08:58 +0000401 if (!isChain && !UnitLatencies) {
Evan Cheng15a16de2010-05-20 06:13:19 +0000402 ComputeOperandLatency(OpN, N, i, const_cast<SDep &>(dep));
Dan Gohman3fb150a2010-04-17 17:42:52 +0000403 ST.adjustSchedDependency(OpSU, SU, const_cast<SDep &>(dep));
David Goodwindc4bdcd2009-08-19 16:08:58 +0000404 }
David Goodwin71046162009-08-13 16:05:04 +0000405
406 SU->addPred(dep);
Dan Gohman343f0c02008-11-19 23:18:57 +0000407 }
408 }
409 }
410}
411
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000412/// BuildSchedGraph - Build the SUnit graph from the selection dag that we
413/// are input. This SUnit graph is similar to the SelectionDAG, but
414/// excludes nodes that aren't interesting to scheduling, and represents
415/// flagged together nodes with a single SUnit.
Dan Gohman98976e42009-10-09 23:33:48 +0000416void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
Evan Cheng302ef832010-06-10 02:09:31 +0000417 // Cluster certain nodes which should be scheduled together.
418 ClusterNodes();
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000419 // Populate the SUnits array.
420 BuildSchedUnits();
421 // Compute all the scheduling dependencies between nodes.
422 AddSchedEdges();
423}
424
Dan Gohman343f0c02008-11-19 23:18:57 +0000425void ScheduleDAGSDNodes::ComputeLatency(SUnit *SU) {
Evan Chenge1631682010-05-19 22:42:23 +0000426 // Check to see if the scheduler cares about latencies.
427 if (ForceUnitLatencies()) {
428 SU->Latency = 1;
429 return;
430 }
431
Evan Cheng3ef1c872010-09-10 01:29:16 +0000432 if (!InstrItins || InstrItins->isEmpty()) {
Evan Cheng15a16de2010-05-20 06:13:19 +0000433 SU->Latency = 1;
434 return;
435 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000436
437 // Compute the latency for the node. We use the sum of the latencies for
438 // all nodes flagged together into this SUnit.
Dan Gohman343f0c02008-11-19 23:18:57 +0000439 SU->Latency = 0;
Dan Gohmanc8c28272008-11-21 00:12:10 +0000440 for (SDNode *N = SU->getNode(); N; N = N->getFlaggedNode())
Dan Gohman343f0c02008-11-19 23:18:57 +0000441 if (N->isMachineOpcode()) {
Evan Cheng3ef1c872010-09-10 01:29:16 +0000442 SU->Latency += InstrItins->
David Goodwindc4bdcd2009-08-19 16:08:58 +0000443 getStageLatency(TII->get(N->getMachineOpcode()).getSchedClass());
Dan Gohman343f0c02008-11-19 23:18:57 +0000444 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000445}
446
Evan Cheng15a16de2010-05-20 06:13:19 +0000447void ScheduleDAGSDNodes::ComputeOperandLatency(SDNode *Def, SDNode *Use,
448 unsigned OpIdx, SDep& dep) const{
449 // Check to see if the scheduler cares about latencies.
450 if (ForceUnitLatencies())
451 return;
452
Evan Cheng3ef1c872010-09-10 01:29:16 +0000453 if (!InstrItins || InstrItins->isEmpty())
Evan Cheng15a16de2010-05-20 06:13:19 +0000454 return;
455
456 if (dep.getKind() != SDep::Data)
457 return;
458
459 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
Evan Cheng3881cb72010-09-29 22:42:35 +0000460 if (!Def->isMachineOpcode())
461 return;
462
463 const TargetInstrDesc &II = TII->get(Def->getMachineOpcode());
464 if (DefIdx >= II.getNumDefs())
465 return;
466
467 int Latency = 0;
468 if (!Use->isMachineOpcode()) {
469 Latency = InstrItins->getOperandCycle(II.getSchedClass(), DefIdx);
470 } else {
471 unsigned DefClass = II.getSchedClass();
472 unsigned UseClass = TII->get(Use->getMachineOpcode()).getSchedClass();
473 Latency = InstrItins->getOperandLatency(DefClass, DefIdx, UseClass, OpIdx);
Evan Cheng15a16de2010-05-20 06:13:19 +0000474 }
Evan Cheng3881cb72010-09-29 22:42:35 +0000475
476 if (Latency >= 0)
477 dep.setLatency(Latency);
Evan Cheng15a16de2010-05-20 06:13:19 +0000478}
479
Dan Gohman343f0c02008-11-19 23:18:57 +0000480void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
Evan Chengc29a56d2009-01-12 03:19:55 +0000481 if (!SU->getNode()) {
David Greene84fa8222010-01-05 01:25:11 +0000482 dbgs() << "PHYS REG COPY\n";
Evan Chengc29a56d2009-01-12 03:19:55 +0000483 return;
484 }
485
486 SU->getNode()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000487 dbgs() << "\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000488 SmallVector<SDNode *, 4> FlaggedNodes;
489 for (SDNode *N = SU->getNode()->getFlaggedNode(); N; N = N->getFlaggedNode())
490 FlaggedNodes.push_back(N);
491 while (!FlaggedNodes.empty()) {
David Greene84fa8222010-01-05 01:25:11 +0000492 dbgs() << " ";
Dan Gohman343f0c02008-11-19 23:18:57 +0000493 FlaggedNodes.back()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000494 dbgs() << "\n";
Dan Gohman343f0c02008-11-19 23:18:57 +0000495 FlaggedNodes.pop_back();
496 }
497}
Dan Gohmanbcea8592009-10-10 01:32:21 +0000498
Evan Chengbfcb3052010-03-25 01:38:16 +0000499namespace {
500 struct OrderSorter {
501 bool operator()(const std::pair<unsigned, MachineInstr*> &A,
502 const std::pair<unsigned, MachineInstr*> &B) {
503 return A.first < B.first;
504 }
505 };
506}
507
508// ProcessSourceNode - Process nodes with source order numbers. These are added
Jim Grosbachd27946d2010-06-30 21:27:56 +0000509// to a vector which EmitSchedule uses to determine how to insert dbg_value
Evan Chengbfcb3052010-03-25 01:38:16 +0000510// instructions in the right order.
511static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG,
512 InstrEmitter &Emitter,
Evan Chengbfcb3052010-03-25 01:38:16 +0000513 DenseMap<SDValue, unsigned> &VRBaseMap,
514 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
515 SmallSet<unsigned, 8> &Seen) {
516 unsigned Order = DAG->GetOrdering(N);
517 if (!Order || !Seen.insert(Order))
518 return;
519
520 MachineBasicBlock *BB = Emitter.getBlock();
Dan Gohman84023e02010-07-10 09:00:22 +0000521 if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI()) {
Evan Chengbfcb3052010-03-25 01:38:16 +0000522 // Did not insert any instruction.
523 Orders.push_back(std::make_pair(Order, (MachineInstr*)0));
524 return;
525 }
526
Dan Gohman84023e02010-07-10 09:00:22 +0000527 Orders.push_back(std::make_pair(Order, prior(Emitter.getInsertPos())));
Evan Chengbfcb3052010-03-25 01:38:16 +0000528 if (!N->getHasDebugValue())
529 return;
530 // Opportunistically insert immediate dbg_value uses, i.e. those with source
531 // order number right after the N.
532 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
533 SmallVector<SDDbgValue*,2> &DVs = DAG->GetDbgValues(N);
534 for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
535 if (DVs[i]->isInvalidated())
536 continue;
537 unsigned DVOrder = DVs[i]->getOrder();
538 if (DVOrder == ++Order) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000539 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000540 if (DbgMI) {
541 Orders.push_back(std::make_pair(DVOrder, DbgMI));
542 BB->insert(InsertPos, DbgMI);
543 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000544 DVs[i]->setIsInvalidated();
545 }
546 }
547}
548
549
Dan Gohmanbcea8592009-10-10 01:32:21 +0000550/// EmitSchedule - Emit the machine code in scheduled order.
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000551MachineBasicBlock *ScheduleDAGSDNodes::EmitSchedule() {
Dan Gohmanbcea8592009-10-10 01:32:21 +0000552 InstrEmitter Emitter(BB, InsertPos);
553 DenseMap<SDValue, unsigned> VRBaseMap;
554 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
Evan Chengbfcb3052010-03-25 01:38:16 +0000555 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
556 SmallSet<unsigned, 8> Seen;
557 bool HasDbg = DAG->hasDebugValues();
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000558
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000559 // If this is the first BB, emit byval parameter dbg_value's.
560 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
561 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
562 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
563 for (; PDI != PDE; ++PDI) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000564 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000565 if (DbgMI)
Dan Gohman84023e02010-07-10 09:00:22 +0000566 BB->insert(InsertPos, DbgMI);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000567 }
568 }
569
Dan Gohmanbcea8592009-10-10 01:32:21 +0000570 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
571 SUnit *SU = Sequence[i];
572 if (!SU) {
573 // Null SUnit* is a noop.
574 EmitNoop();
575 continue;
576 }
577
578 // For pre-regalloc scheduling, create instructions corresponding to the
579 // SDNode and any flagged SDNodes and append them to the block.
580 if (!SU->getNode()) {
581 // Emit a copy.
582 EmitPhysRegCopy(SU, CopyVRBaseMap);
583 continue;
584 }
585
586 SmallVector<SDNode *, 4> FlaggedNodes;
587 for (SDNode *N = SU->getNode()->getFlaggedNode(); N;
588 N = N->getFlaggedNode())
589 FlaggedNodes.push_back(N);
590 while (!FlaggedNodes.empty()) {
Evan Chengbfcb3052010-03-25 01:38:16 +0000591 SDNode *N = FlaggedNodes.back();
Dan Gohmanbcea8592009-10-10 01:32:21 +0000592 Emitter.EmitNode(FlaggedNodes.back(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000593 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000594 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000595 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000596 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
Dan Gohmanbcea8592009-10-10 01:32:21 +0000597 FlaggedNodes.pop_back();
598 }
599 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000600 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000601 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000602 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000603 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
Evan Chengbfcb3052010-03-25 01:38:16 +0000604 Seen);
605 }
606
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000607 // Insert all the dbg_values which have not already been inserted in source
Evan Chengbfcb3052010-03-25 01:38:16 +0000608 // order sequence.
609 if (HasDbg) {
Dan Gohman84023e02010-07-10 09:00:22 +0000610 MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
Evan Chengbfcb3052010-03-25 01:38:16 +0000611
612 // Sort the source order instructions and use the order to insert debug
613 // values.
614 std::sort(Orders.begin(), Orders.end(), OrderSorter());
615
616 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
617 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
618 // Now emit the rest according to source order.
619 unsigned LastOrder = 0;
Evan Chengbfcb3052010-03-25 01:38:16 +0000620 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
621 unsigned Order = Orders[i].first;
622 MachineInstr *MI = Orders[i].second;
623 // Insert all SDDbgValue's whose order(s) are before "Order".
624 if (!MI)
625 continue;
Evan Cheng4ec9bd92010-03-25 07:16:57 +0000626#ifndef NDEBUG
627 unsigned LastDIOrder = 0;
628#endif
Evan Chengbfcb3052010-03-25 01:38:16 +0000629 for (; DI != DE &&
630 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
Evan Cheng4ec9bd92010-03-25 07:16:57 +0000631#ifndef NDEBUG
632 assert((*DI)->getOrder() >= LastDIOrder &&
633 "SDDbgValue nodes must be in source order!");
634 LastDIOrder = (*DI)->getOrder();
635#endif
Evan Chengbfcb3052010-03-25 01:38:16 +0000636 if ((*DI)->isInvalidated())
637 continue;
Dan Gohman891ff8f2010-04-30 19:35:33 +0000638 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000639 if (DbgMI) {
640 if (!LastOrder)
641 // Insert to start of the BB (after PHIs).
642 BB->insert(BBBegin, DbgMI);
643 else {
Dan Gohmana8dab362010-07-10 22:42:31 +0000644 // Insert at the instruction, which may be in a different
645 // block, if the block was split by a custom inserter.
Evan Cheng962021b2010-04-26 07:38:55 +0000646 MachineBasicBlock::iterator Pos = MI;
Dan Gohmana8dab362010-07-10 22:42:31 +0000647 MI->getParent()->insert(llvm::next(Pos), DbgMI);
Evan Cheng962021b2010-04-26 07:38:55 +0000648 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000649 }
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000650 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000651 LastOrder = Order;
Evan Chengbfcb3052010-03-25 01:38:16 +0000652 }
653 // Add trailing DbgValue's before the terminator. FIXME: May want to add
654 // some of them before one or more conditional branches?
655 while (DI != DE) {
656 MachineBasicBlock *InsertBB = Emitter.getBlock();
657 MachineBasicBlock::iterator Pos= Emitter.getBlock()->getFirstTerminator();
658 if (!(*DI)->isInvalidated()) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000659 MachineInstr *DbgMI= Emitter.EmitDbgValue(*DI, VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000660 if (DbgMI)
661 InsertBB->insert(Pos, DbgMI);
Evan Chengbfcb3052010-03-25 01:38:16 +0000662 }
663 ++DI;
664 }
Dan Gohmanbcea8592009-10-10 01:32:21 +0000665 }
666
667 BB = Emitter.getBlock();
668 InsertPos = Emitter.getInsertPos();
669 return BB;
670}