blob: 8ec1ae8620f7ff4293444e2c103af639a5181531 [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"
Andrew Trick84b454d2012-03-07 05:21:44 +000020#include "llvm/CodeGen/MachineInstrBuilder.h"
21#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Chengab8be962011-06-29 01:14:12 +000022#include "llvm/MC/MCInstrItineraries.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000023#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng1cc39842010-05-20 23:26:43 +000025#include "llvm/Target/TargetLowering.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000026#include "llvm/Target/TargetRegisterInfo.h"
Evan Cheng5b1b44892011-07-01 21:01:15 +000027#include "llvm/Target/TargetSubtargetInfo.h"
Evan Chengc589e032010-01-22 03:36:51 +000028#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/SmallPtrSet.h"
Evan Chengbfcb3052010-03-25 01:38:16 +000030#include "llvm/ADT/SmallSet.h"
Evan Chengc589e032010-01-22 03:36:51 +000031#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/Statistic.h"
Andrew Tricke0ef5092011-03-05 08:00:22 +000033#include "llvm/Support/CommandLine.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
36using namespace llvm;
37
Evan Chengc589e032010-01-22 03:36:51 +000038STATISTIC(LoadsClustered, "Number of loads clustered together");
39
Andrew Tricke0ef5092011-03-05 08:00:22 +000040// This allows latency based scheduler to notice high latency instructions
41// without a target itinerary. The choise if number here has more to do with
42// balancing scheduler heursitics than with the actual machine latency.
43static cl::opt<int> HighLatencyCycles(
44 "sched-high-latency-cycles", cl::Hidden, cl::init(10),
45 cl::desc("Roughly estimate the number of cycles that 'long latency'"
46 "instructions take for targets with no itinerary"));
47
Dan Gohman79ce2762009-01-15 19:20:50 +000048ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
Andrew Trick47c14452012-03-07 05:21:52 +000049 : ScheduleDAG(mf), BB(0), DAG(0),
Evan Cheng3ef1c872010-09-10 01:29:16 +000050 InstrItins(mf.getTarget().getInstrItineraryData()) {}
Dan Gohman343f0c02008-11-19 23:18:57 +000051
Dan Gohman47ac0f02009-02-11 04:27:20 +000052/// Run - perform scheduling.
53///
Andrew Trick47c14452012-03-07 05:21:52 +000054void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
55 BB = bb;
Dan Gohman47ac0f02009-02-11 04:27:20 +000056 DAG = dag;
Andrew Trick47c14452012-03-07 05:21:52 +000057
58 // Clear the scheduler's SUnit DAG.
59 ScheduleDAG::clearDAG();
60 Sequence.clear();
61
62 // Invoke the target's selection of scheduler.
63 Schedule();
Dan Gohman47ac0f02009-02-11 04:27:20 +000064}
65
Evan Cheng1cc39842010-05-20 23:26:43 +000066/// NewSUnit - Creates a new SUnit and return a ptr to it.
67///
Andrew Trick953be892012-03-07 23:00:49 +000068SUnit *ScheduleDAGSDNodes::newSUnit(SDNode *N) {
Evan Cheng1cc39842010-05-20 23:26:43 +000069#ifndef NDEBUG
70 const SUnit *Addr = 0;
71 if (!SUnits.empty())
72 Addr = &SUnits[0];
73#endif
74 SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
75 assert((Addr == 0 || Addr == &SUnits[0]) &&
76 "SUnits std::vector reallocated on the fly!");
77 SUnits.back().OrigNode = &SUnits.back();
78 SUnit *SU = &SUnits.back();
79 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
Evan Chengc120af42010-08-10 02:39:45 +000080 if (!N ||
81 (N->isMachineOpcode() &&
82 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
Evan Cheng046fa3f2010-05-28 23:26:21 +000083 SU->SchedulingPref = Sched::None;
84 else
85 SU->SchedulingPref = TLI.getSchedulingPreference(N);
Evan Cheng1cc39842010-05-20 23:26:43 +000086 return SU;
87}
88
Dan Gohman343f0c02008-11-19 23:18:57 +000089SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
Andrew Trick953be892012-03-07 23:00:49 +000090 SUnit *SU = newSUnit(Old->getNode());
Dan Gohman343f0c02008-11-19 23:18:57 +000091 SU->OrigNode = Old->OrigNode;
92 SU->Latency = Old->Latency;
Andrew Trick54699762011-04-07 19:54:57 +000093 SU->isVRegCycle = Old->isVRegCycle;
Evan Cheng8239daf2010-11-03 00:45:17 +000094 SU->isCall = Old->isCall;
Evan Cheng554daa62011-04-26 21:31:35 +000095 SU->isCallOp = Old->isCallOp;
Dan Gohman343f0c02008-11-19 23:18:57 +000096 SU->isTwoAddress = Old->isTwoAddress;
97 SU->isCommutable = Old->isCommutable;
98 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
Dan Gohman39746672009-03-23 16:10:52 +000099 SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
Andrew Trick12f0dc62011-04-14 05:15:06 +0000100 SU->isScheduleHigh = Old->isScheduleHigh;
101 SU->isScheduleLow = Old->isScheduleLow;
Evan Cheng1cc39842010-05-20 23:26:43 +0000102 SU->SchedulingPref = Old->SchedulingPref;
Evan Chenge57187c2009-01-16 20:57:18 +0000103 Old->isCloned = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000104 return SU;
105}
106
107/// CheckForPhysRegDependency - Check if the dependency between def and use of
108/// a specified operand is a physical register dependency. If so, returns the
Evan Chengc29a56d2009-01-12 03:19:55 +0000109/// register and the cost of copying the register.
Dan Gohman343f0c02008-11-19 23:18:57 +0000110static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
Andrew Trickcd5af072011-02-03 23:00:17 +0000111 const TargetRegisterInfo *TRI,
Dan Gohman343f0c02008-11-19 23:18:57 +0000112 const TargetInstrInfo *TII,
Evan Chengc29a56d2009-01-12 03:19:55 +0000113 unsigned &PhysReg, int &Cost) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000114 if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
115 return;
116
117 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
118 if (TargetRegisterInfo::isVirtualRegister(Reg))
119 return;
120
121 unsigned ResNo = User->getOperand(2).getResNo();
122 if (Def->isMachineOpcode()) {
Evan Chenge837dea2011-06-28 19:10:37 +0000123 const MCInstrDesc &II = TII->get(Def->getMachineOpcode());
Dan Gohman343f0c02008-11-19 23:18:57 +0000124 if (ResNo >= II.getNumDefs() &&
Evan Chengc29a56d2009-01-12 03:19:55 +0000125 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000126 PhysReg = Reg;
Evan Chengc29a56d2009-01-12 03:19:55 +0000127 const TargetRegisterClass *RC =
Rafael Espindolad31f9722010-06-29 14:02:34 +0000128 TRI->getMinimalPhysRegClass(Reg, Def->getValueType(ResNo));
Evan Chengc29a56d2009-01-12 03:19:55 +0000129 Cost = RC->getCopyCost();
130 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000131 }
132}
133
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000134static void AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
Evan Chengc589e032010-01-22 03:36:51 +0000135 SmallVector<EVT, 4> VTs;
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000136 SDNode *GlueDestNode = Glue.getNode();
Bill Wendling151d26d2010-06-23 18:16:24 +0000137
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000138 // Don't add glue from a node to itself.
139 if (GlueDestNode == N) return;
Bill Wendling10707f32010-06-24 22:00:37 +0000140
Andrew Trickaec92402012-04-26 21:48:25 +0000141 // Don't add glue to something that already has it, either as a use or value.
142 if (N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue ||
143 N->getValueType(N->getNumValues() - 1) == MVT::Glue) {
144 return;
145 }
Bill Wendling10707f32010-06-24 22:00:37 +0000146 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
147 VTs.push_back(N->getValueType(I));
Bill Wendling151d26d2010-06-23 18:16:24 +0000148
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000149 if (AddGlue)
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000150 VTs.push_back(MVT::Glue);
Bill Wendling151d26d2010-06-23 18:16:24 +0000151
Evan Chengc589e032010-01-22 03:36:51 +0000152 SmallVector<SDValue, 4> Ops;
Bill Wendling10707f32010-06-24 22:00:37 +0000153 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I)
154 Ops.push_back(N->getOperand(I));
Bill Wendling151d26d2010-06-23 18:16:24 +0000155
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000156 if (GlueDestNode)
157 Ops.push_back(Glue);
Bill Wendling151d26d2010-06-23 18:16:24 +0000158
Evan Chengc589e032010-01-22 03:36:51 +0000159 SDVTList VTList = DAG->getVTList(&VTs[0], VTs.size());
Bill Wendling151d26d2010-06-23 18:16:24 +0000160 MachineSDNode::mmo_iterator Begin = 0, End = 0;
161 MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
162
163 // Store memory references.
164 if (MN) {
165 Begin = MN->memoperands_begin();
166 End = MN->memoperands_end();
167 }
168
Evan Chengc589e032010-01-22 03:36:51 +0000169 DAG->MorphNodeTo(N, N->getOpcode(), VTList, &Ops[0], Ops.size());
Bill Wendling151d26d2010-06-23 18:16:24 +0000170
171 // Reset the memory references
172 if (MN)
173 MN->setMemRefs(Begin, End);
Evan Chengc589e032010-01-22 03:36:51 +0000174}
175
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000176/// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
Evan Chengc589e032010-01-22 03:36:51 +0000177/// This function finds loads of the same base and different offsets. If the
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000178/// offsets are not far apart (target specific), it add MVT::Glue inputs and
Evan Chengc589e032010-01-22 03:36:51 +0000179/// outputs to ensure they are scheduled together and in order. This
180/// optimization may benefit some targets by improving cache locality.
Evan Cheng302ef832010-06-10 02:09:31 +0000181void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
182 SDNode *Chain = 0;
183 unsigned NumOps = Node->getNumOperands();
184 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
185 Chain = Node->getOperand(NumOps-1).getNode();
186 if (!Chain)
187 return;
188
189 // Look for other loads of the same chain. Find loads that are loading from
190 // the same base pointer and different offsets.
Evan Chengc589e032010-01-22 03:36:51 +0000191 SmallPtrSet<SDNode*, 16> Visited;
192 SmallVector<int64_t, 4> Offsets;
193 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
Evan Cheng302ef832010-06-10 02:09:31 +0000194 bool Cluster = false;
195 SDNode *Base = Node;
Evan Cheng302ef832010-06-10 02:09:31 +0000196 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
197 I != E; ++I) {
198 SDNode *User = *I;
199 if (User == Node || !Visited.insert(User))
200 continue;
201 int64_t Offset1, Offset2;
202 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
203 Offset1 == Offset2)
204 // FIXME: Should be ok if they addresses are identical. But earlier
205 // optimizations really should have eliminated one of the loads.
206 continue;
207 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
208 Offsets.push_back(Offset1);
209 O2SMap.insert(std::make_pair(Offset2, User));
210 Offsets.push_back(Offset2);
Duncan Sandsb447c4e2010-06-25 14:48:39 +0000211 if (Offset2 < Offset1)
Evan Cheng302ef832010-06-10 02:09:31 +0000212 Base = User;
Evan Cheng302ef832010-06-10 02:09:31 +0000213 Cluster = true;
214 }
215
216 if (!Cluster)
217 return;
218
219 // Sort them in increasing order.
220 std::sort(Offsets.begin(), Offsets.end());
221
222 // Check if the loads are close enough.
223 SmallVector<SDNode*, 4> Loads;
224 unsigned NumLoads = 0;
225 int64_t BaseOff = Offsets[0];
226 SDNode *BaseLoad = O2SMap[BaseOff];
227 Loads.push_back(BaseLoad);
228 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
229 int64_t Offset = Offsets[i];
230 SDNode *Load = O2SMap[Offset];
231 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
232 break; // Stop right here. Ignore loads that are further away.
233 Loads.push_back(Load);
234 ++NumLoads;
235 }
236
237 if (NumLoads == 0)
238 return;
239
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000240 // Cluster loads by adding MVT::Glue outputs and inputs. This also
Evan Cheng302ef832010-06-10 02:09:31 +0000241 // ensure they are scheduled in order of increasing addresses.
242 SDNode *Lead = Loads[0];
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000243 AddGlue(Lead, SDValue(0, 0), true, DAG);
Bill Wendling151d26d2010-06-23 18:16:24 +0000244
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000245 SDValue InGlue = SDValue(Lead, Lead->getNumValues() - 1);
Bill Wendling10707f32010-06-24 22:00:37 +0000246 for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000247 bool OutGlue = I < E - 1;
Bill Wendling10707f32010-06-24 22:00:37 +0000248 SDNode *Load = Loads[I];
249
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000250 AddGlue(Load, InGlue, OutGlue, DAG);
Bill Wendling151d26d2010-06-23 18:16:24 +0000251
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000252 if (OutGlue)
253 InGlue = SDValue(Load, Load->getNumValues() - 1);
Bill Wendling151d26d2010-06-23 18:16:24 +0000254
Evan Cheng302ef832010-06-10 02:09:31 +0000255 ++LoadsClustered;
256 }
257}
258
259/// ClusterNodes - Cluster certain nodes which should be scheduled together.
260///
261void ScheduleDAGSDNodes::ClusterNodes() {
Evan Chengc589e032010-01-22 03:36:51 +0000262 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
263 E = DAG->allnodes_end(); NI != E; ++NI) {
264 SDNode *Node = &*NI;
265 if (!Node || !Node->isMachineOpcode())
266 continue;
267
268 unsigned Opc = Node->getMachineOpcode();
Evan Chenge837dea2011-06-28 19:10:37 +0000269 const MCInstrDesc &MCID = TII->get(Opc);
270 if (MCID.mayLoad())
Evan Cheng302ef832010-06-10 02:09:31 +0000271 // Cluster loads from "near" addresses into combined SUnits.
272 ClusterNeighboringLoads(Node);
Evan Chengc589e032010-01-22 03:36:51 +0000273 }
274}
275
Dan Gohman343f0c02008-11-19 23:18:57 +0000276void ScheduleDAGSDNodes::BuildSchedUnits() {
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000277 // During scheduling, the NodeId field of SDNode is used to map SDNodes
278 // to their associated SUnits by holding SUnits table indices. A value
279 // of -1 means the SDNode does not yet have an associated SUnit.
280 unsigned NumNodes = 0;
281 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
282 E = DAG->allnodes_end(); NI != E; ++NI) {
283 NI->setNodeId(-1);
284 ++NumNodes;
285 }
286
Dan Gohman343f0c02008-11-19 23:18:57 +0000287 // Reserve entries in the vector for each of the SUnits we are creating. This
288 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
289 // invalidated.
Dan Gohman89b64bd2008-12-17 04:30:46 +0000290 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
291 // This is a temporary workaround.
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000292 SUnits.reserve(NumNodes * 2);
Andrew Trickcd5af072011-02-03 23:00:17 +0000293
Chris Lattner736a6ea2010-02-24 06:11:37 +0000294 // Add all nodes in depth first order.
295 SmallVector<SDNode*, 64> Worklist;
296 SmallPtrSet<SDNode*, 64> Visited;
297 Worklist.push_back(DAG->getRoot().getNode());
298 Visited.insert(DAG->getRoot().getNode());
Andrew Trickcd5af072011-02-03 23:00:17 +0000299
Evan Cheng554daa62011-04-26 21:31:35 +0000300 SmallVector<SUnit*, 8> CallSUnits;
Chris Lattner736a6ea2010-02-24 06:11:37 +0000301 while (!Worklist.empty()) {
302 SDNode *NI = Worklist.pop_back_val();
Andrew Trickcd5af072011-02-03 23:00:17 +0000303
Chris Lattner736a6ea2010-02-24 06:11:37 +0000304 // Add all operands to the worklist unless they've already been added.
305 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
306 if (Visited.insert(NI->getOperand(i).getNode()))
307 Worklist.push_back(NI->getOperand(i).getNode());
Andrew Trickcd5af072011-02-03 23:00:17 +0000308
Dan Gohman343f0c02008-11-19 23:18:57 +0000309 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
310 continue;
Andrew Trickcd5af072011-02-03 23:00:17 +0000311
Dan Gohman343f0c02008-11-19 23:18:57 +0000312 // If this node has already been processed, stop now.
313 if (NI->getNodeId() != -1) continue;
Andrew Trickcd5af072011-02-03 23:00:17 +0000314
Andrew Trick953be892012-03-07 23:00:49 +0000315 SUnit *NodeSUnit = newSUnit(NI);
Andrew Trickcd5af072011-02-03 23:00:17 +0000316
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000317 // See if anything is glued to this node, if so, add them to glued
318 // nodes. Nodes can have at most one glue input and one glue output. Glue
319 // is required to be the last operand and result of a node.
Andrew Trickcd5af072011-02-03 23:00:17 +0000320
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000321 // Scan up to find glued preds.
Dan Gohman343f0c02008-11-19 23:18:57 +0000322 SDNode *N = NI;
Dan Gohmandb95fa12009-03-20 20:42:23 +0000323 while (N->getNumOperands() &&
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000324 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
Dan Gohmandb95fa12009-03-20 20:42:23 +0000325 N = N->getOperand(N->getNumOperands()-1).getNode();
326 assert(N->getNodeId() == -1 && "Node already inserted!");
327 N->setNodeId(NodeSUnit->NodeNum);
Evan Cheng8239daf2010-11-03 00:45:17 +0000328 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
329 NodeSUnit->isCall = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000330 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000331
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000332 // Scan down to find any glued succs.
Dan Gohman343f0c02008-11-19 23:18:57 +0000333 N = NI;
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000334 while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000335 SDValue GlueVal(N, N->getNumValues()-1);
Andrew Trickcd5af072011-02-03 23:00:17 +0000336
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000337 // There are either zero or one users of the Glue result.
338 bool HasGlueUse = false;
Andrew Trickcd5af072011-02-03 23:00:17 +0000339 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000340 UI != E; ++UI)
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000341 if (GlueVal.isOperandOf(*UI)) {
342 HasGlueUse = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000343 assert(N->getNodeId() == -1 && "Node already inserted!");
344 N->setNodeId(NodeSUnit->NodeNum);
345 N = *UI;
Evan Cheng8239daf2010-11-03 00:45:17 +0000346 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
347 NodeSUnit->isCall = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000348 break;
349 }
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000350 if (!HasGlueUse) break;
Dan Gohman343f0c02008-11-19 23:18:57 +0000351 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000352
Evan Cheng554daa62011-04-26 21:31:35 +0000353 if (NodeSUnit->isCall)
354 CallSUnits.push_back(NodeSUnit);
355
Andrew Trick12f0dc62011-04-14 05:15:06 +0000356 // Schedule zero-latency TokenFactor below any nodes that may increase the
357 // schedule height. Otherwise, ancestors of the TokenFactor may appear to
358 // have false stalls.
359 if (NI->getOpcode() == ISD::TokenFactor)
360 NodeSUnit->isScheduleLow = true;
361
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000362 // If there are glue operands involved, N is now the bottom-most node
363 // of the sequence of nodes that are glued together.
Dan Gohman343f0c02008-11-19 23:18:57 +0000364 // Update the SUnit.
365 NodeSUnit->setNode(N);
366 assert(N->getNodeId() == -1 && "Node already inserted!");
367 N->setNodeId(NodeSUnit->NodeNum);
368
Andrew Trick92e94662011-02-04 03:18:17 +0000369 // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
370 InitNumRegDefsLeft(NodeSUnit);
371
Dan Gohman787782f2008-11-21 01:44:51 +0000372 // Assign the Latency field of NodeSUnit using target-provided information.
Andrew Trick953be892012-03-07 23:00:49 +0000373 computeLatency(NodeSUnit);
Dan Gohman343f0c02008-11-19 23:18:57 +0000374 }
Evan Cheng554daa62011-04-26 21:31:35 +0000375
376 // Find all call operands.
377 while (!CallSUnits.empty()) {
378 SUnit *SU = CallSUnits.pop_back_val();
379 for (const SDNode *SUNode = SU->getNode(); SUNode;
380 SUNode = SUNode->getGluedNode()) {
381 if (SUNode->getOpcode() != ISD::CopyToReg)
382 continue;
383 SDNode *SrcN = SUNode->getOperand(2).getNode();
384 if (isPassiveNode(SrcN)) continue; // Not scheduled.
385 SUnit *SrcSU = &SUnits[SrcN->getNodeId()];
386 SrcSU->isCallOp = true;
387 }
388 }
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000389}
390
391void ScheduleDAGSDNodes::AddSchedEdges() {
Evan Cheng5b1b44892011-07-01 21:01:15 +0000392 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
David Goodwin71046162009-08-13 16:05:04 +0000393
David Goodwindc4bdcd2009-08-19 16:08:58 +0000394 // Check to see if the scheduler cares about latencies.
Andrew Trick953be892012-03-07 23:00:49 +0000395 bool UnitLatencies = forceUnitLatencies();
David Goodwindc4bdcd2009-08-19 16:08:58 +0000396
Dan Gohman343f0c02008-11-19 23:18:57 +0000397 // Pass 2: add the preds, succs, etc.
398 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
399 SUnit *SU = &SUnits[su];
400 SDNode *MainNode = SU->getNode();
Andrew Trickcd5af072011-02-03 23:00:17 +0000401
Dan Gohman343f0c02008-11-19 23:18:57 +0000402 if (MainNode->isMachineOpcode()) {
403 unsigned Opc = MainNode->getMachineOpcode();
Evan Chenge837dea2011-06-28 19:10:37 +0000404 const MCInstrDesc &MCID = TII->get(Opc);
405 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
406 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000407 SU->isTwoAddress = true;
408 break;
409 }
410 }
Evan Chenge837dea2011-06-28 19:10:37 +0000411 if (MCID.isCommutable())
Dan Gohman343f0c02008-11-19 23:18:57 +0000412 SU->isCommutable = true;
413 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000414
Dan Gohman343f0c02008-11-19 23:18:57 +0000415 // Find all predecessors and successors of the group.
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000416 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000417 if (N->isMachineOpcode() &&
Dan Gohman39746672009-03-23 16:10:52 +0000418 TII->get(N->getMachineOpcode()).getImplicitDefs()) {
419 SU->hasPhysRegClobbers = true;
Dan Gohmanbcea8592009-10-10 01:32:21 +0000420 unsigned NumUsed = InstrEmitter::CountResults(N);
Dan Gohman8cccf0e2009-03-23 17:39:36 +0000421 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
422 --NumUsed; // Skip over unused values at the end.
423 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
Dan Gohman39746672009-03-23 16:10:52 +0000424 SU->hasPhysRegDefs = true;
425 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000426
Dan Gohman343f0c02008-11-19 23:18:57 +0000427 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
428 SDNode *OpN = N->getOperand(i).getNode();
429 if (isPassiveNode(OpN)) continue; // Not scheduled.
430 SUnit *OpSU = &SUnits[OpN->getNodeId()];
431 assert(OpSU && "Node has no SUnit!");
432 if (OpSU == SU) continue; // In the same group.
433
Owen Andersone50ed302009-08-10 22:56:29 +0000434 EVT OpVT = N->getOperand(i).getValueType();
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000435 assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000436 bool isChain = OpVT == MVT::Other;
Dan Gohman343f0c02008-11-19 23:18:57 +0000437
438 unsigned PhysReg = 0;
Evan Chengc29a56d2009-01-12 03:19:55 +0000439 int Cost = 1;
Dan Gohman343f0c02008-11-19 23:18:57 +0000440 // Determine if this is a physical register dependency.
Evan Chengc29a56d2009-01-12 03:19:55 +0000441 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
Dan Gohman54e4c362008-12-09 22:54:47 +0000442 assert((PhysReg == 0 || !isChain) &&
443 "Chain dependence via physreg data?");
Evan Chengc29a56d2009-01-12 03:19:55 +0000444 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
445 // emits a copy from the physical register to a virtual register unless
446 // it requires a cross class copy (cost < 0). That means we are only
447 // treating "expensive to copy" register dependency as physical register
448 // dependency. This may change in the future though.
Andrew Trick4cb971c2011-06-15 17:16:12 +0000449 if (Cost >= 0 && !StressSched)
Evan Chengc29a56d2009-01-12 03:19:55 +0000450 PhysReg = 0;
David Goodwin71046162009-08-13 16:05:04 +0000451
Evan Cheng046fa3f2010-05-28 23:26:21 +0000452 // If this is a ctrl dep, latency is 1.
Andrew Trickc558bf32011-04-12 20:14:07 +0000453 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
Andrew Trick87896d92011-04-13 00:38:32 +0000454 // Special-case TokenFactor chains as zero-latency.
455 if(isChain && OpN->getOpcode() == ISD::TokenFactor)
456 OpLatency = 0;
457
Evan Cheng046fa3f2010-05-28 23:26:21 +0000458 const SDep &dep = SDep(OpSU, isChain ? SDep::Order : SDep::Data,
459 OpLatency, PhysReg);
David Goodwindc4bdcd2009-08-19 16:08:58 +0000460 if (!isChain && !UnitLatencies) {
Andrew Trick953be892012-03-07 23:00:49 +0000461 computeOperandLatency(OpN, N, i, const_cast<SDep &>(dep));
Dan Gohman3fb150a2010-04-17 17:42:52 +0000462 ST.adjustSchedDependency(OpSU, SU, const_cast<SDep &>(dep));
David Goodwindc4bdcd2009-08-19 16:08:58 +0000463 }
David Goodwin71046162009-08-13 16:05:04 +0000464
Andrew Trick4bbf4672011-03-09 19:12:43 +0000465 if (!SU->addPred(dep) && !dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
Andrew Trick92e94662011-02-04 03:18:17 +0000466 // Multiple register uses are combined in the same SUnit. For example,
467 // we could have a set of glued nodes with all their defs consumed by
468 // another set of glued nodes. Register pressure tracking sees this as
469 // a single use, so to keep pressure balanced we reduce the defs.
Andrew Trick4bbf4672011-03-09 19:12:43 +0000470 //
471 // We can't tell (without more book-keeping) if this results from
472 // glued nodes or duplicate operands. As long as we don't reduce
473 // NumRegDefsLeft to zero, we handle the common cases well.
Andrew Trick92e94662011-02-04 03:18:17 +0000474 --OpSU->NumRegDefsLeft;
475 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000476 }
477 }
478 }
479}
480
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000481/// BuildSchedGraph - Build the SUnit graph from the selection dag that we
482/// are input. This SUnit graph is similar to the SelectionDAG, but
483/// excludes nodes that aren't interesting to scheduling, and represents
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000484/// glued together nodes with a single SUnit.
Dan Gohman98976e42009-10-09 23:33:48 +0000485void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
Evan Cheng302ef832010-06-10 02:09:31 +0000486 // Cluster certain nodes which should be scheduled together.
487 ClusterNodes();
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000488 // Populate the SUnits array.
489 BuildSchedUnits();
490 // Compute all the scheduling dependencies between nodes.
491 AddSchedEdges();
492}
493
Andrew Trick92e94662011-02-04 03:18:17 +0000494// Initialize NumNodeDefs for the current Node's opcode.
495void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
Eric Christopher29449442011-03-08 19:35:47 +0000496 // Check for phys reg copy.
497 if (!Node)
498 return;
499
Andrew Trick92e94662011-02-04 03:18:17 +0000500 if (!Node->isMachineOpcode()) {
501 if (Node->getOpcode() == ISD::CopyFromReg)
502 NodeNumDefs = 1;
503 else
504 NodeNumDefs = 0;
505 return;
506 }
507 unsigned POpc = Node->getMachineOpcode();
508 if (POpc == TargetOpcode::IMPLICIT_DEF) {
509 // No register need be allocated for this.
510 NodeNumDefs = 0;
511 return;
512 }
513 unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
514 // Some instructions define regs that are not represented in the selection DAG
515 // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
516 NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
517 DefIdx = 0;
518}
519
520// Construct a RegDefIter for this SUnit and find the first valid value.
521ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
522 const ScheduleDAGSDNodes *SD)
523 : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
524 InitNodeNumDefs();
525 Advance();
526}
527
528// Advance to the next valid value defined by the SUnit.
529void ScheduleDAGSDNodes::RegDefIter::Advance() {
530 for (;Node;) { // Visit all glued nodes.
531 for (;DefIdx < NodeNumDefs; ++DefIdx) {
532 if (!Node->hasAnyUseOfValue(DefIdx))
533 continue;
Andrew Trick4ef4c172011-06-27 18:01:20 +0000534 ValueType = Node->getValueType(DefIdx);
Andrew Trick92e94662011-02-04 03:18:17 +0000535 ++DefIdx;
536 return; // Found a normal regdef.
537 }
538 Node = Node->getGluedNode();
539 if (Node == NULL) {
540 return; // No values left to visit.
541 }
542 InitNodeNumDefs();
543 }
544}
545
546void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
547 assert(SU->NumRegDefsLeft == 0 && "expect a new node");
548 for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
549 assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
550 ++SU->NumRegDefsLeft;
551 }
552}
553
Andrew Trick953be892012-03-07 23:00:49 +0000554void ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
Andrew Trick87896d92011-04-13 00:38:32 +0000555 SDNode *N = SU->getNode();
556
557 // TokenFactor operands are considered zero latency, and some schedulers
558 // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
559 // whenever node latency is nonzero.
560 if (N && N->getOpcode() == ISD::TokenFactor) {
561 SU->Latency = 0;
562 return;
563 }
564
Evan Chenge1631682010-05-19 22:42:23 +0000565 // Check to see if the scheduler cares about latencies.
Andrew Trick953be892012-03-07 23:00:49 +0000566 if (forceUnitLatencies()) {
Evan Chenge1631682010-05-19 22:42:23 +0000567 SU->Latency = 1;
568 return;
569 }
570
Evan Cheng3ef1c872010-09-10 01:29:16 +0000571 if (!InstrItins || InstrItins->isEmpty()) {
Andrew Trick5e84e3c2011-03-05 09:18:16 +0000572 if (N && N->isMachineOpcode() &&
573 TII->isHighLatencyDef(N->getMachineOpcode()))
Andrew Tricke0ef5092011-03-05 08:00:22 +0000574 SU->Latency = HighLatencyCycles;
575 else
576 SU->Latency = 1;
Evan Cheng15a16de2010-05-20 06:13:19 +0000577 return;
578 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000579
Dan Gohman343f0c02008-11-19 23:18:57 +0000580 // Compute the latency for the node. We use the sum of the latencies for
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000581 // all nodes glued together into this SUnit.
Dan Gohman343f0c02008-11-19 23:18:57 +0000582 SU->Latency = 0;
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000583 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
Evan Cheng8239daf2010-11-03 00:45:17 +0000584 if (N->isMachineOpcode())
585 SU->Latency += TII->getInstrLatency(InstrItins, N);
Dan Gohman343f0c02008-11-19 23:18:57 +0000586}
587
Andrew Trick953be892012-03-07 23:00:49 +0000588void ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
Evan Cheng15a16de2010-05-20 06:13:19 +0000589 unsigned OpIdx, SDep& dep) const{
590 // Check to see if the scheduler cares about latencies.
Andrew Trick953be892012-03-07 23:00:49 +0000591 if (forceUnitLatencies())
Evan Cheng15a16de2010-05-20 06:13:19 +0000592 return;
593
Evan Cheng15a16de2010-05-20 06:13:19 +0000594 if (dep.getKind() != SDep::Data)
595 return;
596
597 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
Evan Cheng7e2fe912010-10-28 06:47:08 +0000598 if (Use->isMachineOpcode())
599 // Adjust the use operand index by num of defs.
600 OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
Evan Chenga0792de2010-10-06 06:27:31 +0000601 int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
Evan Cheng08975152010-10-29 18:09:28 +0000602 if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
603 !BB->succ_empty()) {
604 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
605 if (TargetRegisterInfo::isVirtualRegister(Reg))
606 // This copy is a liveout value. It is likely coalesced, so reduce the
607 // latency so not to penalize the def.
608 // FIXME: need target specific adjustment here?
609 Latency = (Latency > 1) ? Latency - 1 : 1;
610 }
Evan Cheng3881cb72010-09-29 22:42:35 +0000611 if (Latency >= 0)
612 dep.setLatency(Latency);
Evan Cheng15a16de2010-05-20 06:13:19 +0000613}
614
Dan Gohman343f0c02008-11-19 23:18:57 +0000615void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
Evan Chengc29a56d2009-01-12 03:19:55 +0000616 if (!SU->getNode()) {
David Greene84fa8222010-01-05 01:25:11 +0000617 dbgs() << "PHYS REG COPY\n";
Evan Chengc29a56d2009-01-12 03:19:55 +0000618 return;
619 }
620
621 SU->getNode()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000622 dbgs() << "\n";
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000623 SmallVector<SDNode *, 4> GluedNodes;
624 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
625 GluedNodes.push_back(N);
626 while (!GluedNodes.empty()) {
David Greene84fa8222010-01-05 01:25:11 +0000627 dbgs() << " ";
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000628 GluedNodes.back()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000629 dbgs() << "\n";
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000630 GluedNodes.pop_back();
Dan Gohman343f0c02008-11-19 23:18:57 +0000631 }
632}
Dan Gohmanbcea8592009-10-10 01:32:21 +0000633
Andrew Trick73ba69b2012-03-07 05:21:40 +0000634void ScheduleDAGSDNodes::dumpSchedule() const {
635 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
636 if (SUnit *SU = Sequence[i])
637 SU->dump(this);
638 else
639 dbgs() << "**** NOOP ****\n";
640 }
641}
642
Andrew Trick4c727202012-03-07 05:21:36 +0000643#ifndef NDEBUG
644/// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
645/// their state is consistent with the nodes listed in Sequence.
646///
647void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
648 unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
649 unsigned Noops = 0;
650 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
651 if (!Sequence[i])
652 ++Noops;
653 assert(Sequence.size() - Noops == ScheduledNodes &&
654 "The number of nodes scheduled doesn't match the expected number!");
655}
656#endif // NDEBUG
657
Evan Chengbfcb3052010-03-25 01:38:16 +0000658namespace {
659 struct OrderSorter {
660 bool operator()(const std::pair<unsigned, MachineInstr*> &A,
661 const std::pair<unsigned, MachineInstr*> &B) {
662 return A.first < B.first;
663 }
664 };
665}
666
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000667/// ProcessSDDbgValues - Process SDDbgValues associated with this node.
Andrew Trickcd5af072011-02-03 23:00:17 +0000668static void ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG,
Devang Patel55d20e82011-01-26 18:20:04 +0000669 InstrEmitter &Emitter,
670 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
671 DenseMap<SDValue, unsigned> &VRBaseMap,
672 unsigned Order) {
673 if (!N->getHasDebugValue())
674 return;
675
676 // Opportunistically insert immediate dbg_value uses, i.e. those with source
677 // order number right after the N.
678 MachineBasicBlock *BB = Emitter.getBlock();
679 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
Benjamin Kramer22a54c12011-06-18 13:13:44 +0000680 ArrayRef<SDDbgValue*> DVs = DAG->GetDbgValues(N);
Devang Patel55d20e82011-01-26 18:20:04 +0000681 for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
682 if (DVs[i]->isInvalidated())
683 continue;
684 unsigned DVOrder = DVs[i]->getOrder();
685 if (!Order || DVOrder == ++Order) {
686 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
687 if (DbgMI) {
688 Orders.push_back(std::make_pair(DVOrder, DbgMI));
689 BB->insert(InsertPos, DbgMI);
690 }
691 DVs[i]->setIsInvalidated();
692 }
693 }
694}
695
Evan Chengbfcb3052010-03-25 01:38:16 +0000696// ProcessSourceNode - Process nodes with source order numbers. These are added
Jim Grosbachd27946d2010-06-30 21:27:56 +0000697// to a vector which EmitSchedule uses to determine how to insert dbg_value
Evan Chengbfcb3052010-03-25 01:38:16 +0000698// instructions in the right order.
699static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG,
700 InstrEmitter &Emitter,
Evan Chengbfcb3052010-03-25 01:38:16 +0000701 DenseMap<SDValue, unsigned> &VRBaseMap,
702 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
703 SmallSet<unsigned, 8> &Seen) {
704 unsigned Order = DAG->GetOrdering(N);
Devang Patel39078a82011-01-27 00:13:27 +0000705 if (!Order || !Seen.insert(Order)) {
706 // Process any valid SDDbgValues even if node does not have any order
707 // assigned.
708 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
Evan Chengbfcb3052010-03-25 01:38:16 +0000709 return;
Devang Patel39078a82011-01-27 00:13:27 +0000710 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000711
712 MachineBasicBlock *BB = Emitter.getBlock();
Dan Gohman84023e02010-07-10 09:00:22 +0000713 if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI()) {
Evan Chengbfcb3052010-03-25 01:38:16 +0000714 // Did not insert any instruction.
715 Orders.push_back(std::make_pair(Order, (MachineInstr*)0));
716 return;
717 }
718
Dan Gohman84023e02010-07-10 09:00:22 +0000719 Orders.push_back(std::make_pair(Order, prior(Emitter.getInsertPos())));
Devang Patel55d20e82011-01-26 18:20:04 +0000720 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
Evan Chengbfcb3052010-03-25 01:38:16 +0000721}
722
Andrew Trick84b454d2012-03-07 05:21:44 +0000723void ScheduleDAGSDNodes::
724EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
725 MachineBasicBlock::iterator InsertPos) {
726 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
727 I != E; ++I) {
728 if (I->isCtrl()) continue; // ignore chain preds
729 if (I->getSUnit()->CopyDstRC) {
730 // Copy to physical register.
731 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->getSUnit());
732 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
733 // Find the destination physical register.
734 unsigned Reg = 0;
735 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
736 EE = SU->Succs.end(); II != EE; ++II) {
737 if (II->isCtrl()) continue; // ignore chain preds
738 if (II->getReg()) {
739 Reg = II->getReg();
740 break;
741 }
742 }
743 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
744 .addReg(VRI->second);
745 } else {
746 // Copy from physical register.
747 assert(I->getReg() && "Unknown physical register!");
748 unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
749 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
750 (void)isNew; // Silence compiler warning.
751 assert(isNew && "Node emitted out of order - early");
752 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
753 .addReg(I->getReg());
754 }
755 break;
756 }
757}
Evan Chengbfcb3052010-03-25 01:38:16 +0000758
Andrew Trick84b454d2012-03-07 05:21:44 +0000759/// EmitSchedule - Emit the machine code in scheduled order. Return the new
760/// InsertPos and MachineBasicBlock that contains this insertion
761/// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
762/// not necessarily refer to returned BB. The emitter may split blocks.
Andrew Trick47c14452012-03-07 05:21:52 +0000763MachineBasicBlock *ScheduleDAGSDNodes::
764EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
Dan Gohmanbcea8592009-10-10 01:32:21 +0000765 InstrEmitter Emitter(BB, InsertPos);
766 DenseMap<SDValue, unsigned> VRBaseMap;
767 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
Evan Chengbfcb3052010-03-25 01:38:16 +0000768 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
769 SmallSet<unsigned, 8> Seen;
770 bool HasDbg = DAG->hasDebugValues();
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000771
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000772 // If this is the first BB, emit byval parameter dbg_value's.
773 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
774 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
775 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
776 for (; PDI != PDE; ++PDI) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000777 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000778 if (DbgMI)
Dan Gohman84023e02010-07-10 09:00:22 +0000779 BB->insert(InsertPos, DbgMI);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000780 }
781 }
782
Dan Gohmanbcea8592009-10-10 01:32:21 +0000783 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
784 SUnit *SU = Sequence[i];
785 if (!SU) {
786 // Null SUnit* is a noop.
Andrew Trick84b454d2012-03-07 05:21:44 +0000787 TII->insertNoop(*Emitter.getBlock(), InsertPos);
Dan Gohmanbcea8592009-10-10 01:32:21 +0000788 continue;
789 }
790
791 // For pre-regalloc scheduling, create instructions corresponding to the
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000792 // SDNode and any glued SDNodes and append them to the block.
Dan Gohmanbcea8592009-10-10 01:32:21 +0000793 if (!SU->getNode()) {
794 // Emit a copy.
Andrew Trick84b454d2012-03-07 05:21:44 +0000795 EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
Dan Gohmanbcea8592009-10-10 01:32:21 +0000796 continue;
797 }
798
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000799 SmallVector<SDNode *, 4> GluedNodes;
800 for (SDNode *N = SU->getNode()->getGluedNode(); N;
801 N = N->getGluedNode())
802 GluedNodes.push_back(N);
803 while (!GluedNodes.empty()) {
804 SDNode *N = GluedNodes.back();
805 Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000806 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000807 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000808 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000809 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000810 GluedNodes.pop_back();
Dan Gohmanbcea8592009-10-10 01:32:21 +0000811 }
812 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000813 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000814 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000815 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000816 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
Evan Chengbfcb3052010-03-25 01:38:16 +0000817 Seen);
818 }
819
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000820 // Insert all the dbg_values which have not already been inserted in source
Evan Chengbfcb3052010-03-25 01:38:16 +0000821 // order sequence.
822 if (HasDbg) {
Dan Gohman84023e02010-07-10 09:00:22 +0000823 MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
Evan Chengbfcb3052010-03-25 01:38:16 +0000824
825 // Sort the source order instructions and use the order to insert debug
826 // values.
827 std::sort(Orders.begin(), Orders.end(), OrderSorter());
828
829 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
830 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
831 // Now emit the rest according to source order.
832 unsigned LastOrder = 0;
Evan Chengbfcb3052010-03-25 01:38:16 +0000833 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
834 unsigned Order = Orders[i].first;
835 MachineInstr *MI = Orders[i].second;
836 // Insert all SDDbgValue's whose order(s) are before "Order".
837 if (!MI)
838 continue;
Evan Chengbfcb3052010-03-25 01:38:16 +0000839 for (; DI != DE &&
840 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
841 if ((*DI)->isInvalidated())
842 continue;
Dan Gohman891ff8f2010-04-30 19:35:33 +0000843 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000844 if (DbgMI) {
845 if (!LastOrder)
846 // Insert to start of the BB (after PHIs).
847 BB->insert(BBBegin, DbgMI);
848 else {
Dan Gohmana8dab362010-07-10 22:42:31 +0000849 // Insert at the instruction, which may be in a different
850 // block, if the block was split by a custom inserter.
Evan Cheng962021b2010-04-26 07:38:55 +0000851 MachineBasicBlock::iterator Pos = MI;
Dan Gohmana8dab362010-07-10 22:42:31 +0000852 MI->getParent()->insert(llvm::next(Pos), DbgMI);
Evan Cheng962021b2010-04-26 07:38:55 +0000853 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000854 }
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000855 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000856 LastOrder = Order;
Evan Chengbfcb3052010-03-25 01:38:16 +0000857 }
858 // Add trailing DbgValue's before the terminator. FIXME: May want to add
859 // some of them before one or more conditional branches?
Bill Wendling7bf116a2012-03-14 07:14:25 +0000860 SmallVector<MachineInstr*, 8> DbgMIs;
Evan Chengbfcb3052010-03-25 01:38:16 +0000861 while (DI != DE) {
Bill Wendling7bf116a2012-03-14 07:14:25 +0000862 if (!(*DI)->isInvalidated())
863 if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
864 DbgMIs.push_back(DbgMI);
Evan Chengbfcb3052010-03-25 01:38:16 +0000865 ++DI;
866 }
Bill Wendling7bf116a2012-03-14 07:14:25 +0000867
868 MachineBasicBlock *InsertBB = Emitter.getBlock();
869 MachineBasicBlock::iterator Pos = InsertBB->getFirstTerminator();
870 InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
Dan Gohmanbcea8592009-10-10 01:32:21 +0000871 }
872
Dan Gohmanbcea8592009-10-10 01:32:21 +0000873 InsertPos = Emitter.getInsertPos();
Andrew Trick47c14452012-03-07 05:21:52 +0000874 return Emitter.getBlock();
Dan Gohmanbcea8592009-10-10 01:32:21 +0000875}
Andrew Trick56b94c52012-03-07 00:18:22 +0000876
877/// Return the basic block label.
878std::string ScheduleDAGSDNodes::getDAGName() const {
879 return "sunit-dag." + BB->getFullName();
880}