blob: de910b7c861bd9ab69851b79a29556908b63a495 [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
Dan Gohman84fbac52009-02-06 17:22:58 +000015#include "ScheduleDAGSDNodes.h"
Dan Gohmanbcea8592009-10-10 01:32:21 +000016#include "InstrEmitter.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "SDNodeDbgValue.h"
Evan Chengc589e032010-01-22 03:36:51 +000018#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SmallPtrSet.h"
Evan Chengbfcb3052010-03-25 01:38:16 +000020#include "llvm/ADT/SmallSet.h"
Evan Chengc589e032010-01-22 03:36:51 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/CodeGen/SelectionDAG.h"
26#include "llvm/MC/MCInstrItineraries.h"
Andrew Tricke0ef5092011-03-05 08:00:22 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000030#include "llvm/Target/TargetInstrInfo.h"
31#include "llvm/Target/TargetLowering.h"
32#include "llvm/Target/TargetMachine.h"
33#include "llvm/Target/TargetRegisterInfo.h"
34#include "llvm/Target/TargetSubtargetInfo.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000035using namespace llvm;
36
Stephen Hinesdce4a402014-05-29 02:49:00 -070037#define DEBUG_TYPE "pre-RA-sched"
38
Evan Chengc589e032010-01-22 03:36:51 +000039STATISTIC(LoadsClustered, "Number of loads clustered together");
40
Andrew Tricke0ef5092011-03-05 08:00:22 +000041// This allows latency based scheduler to notice high latency instructions
42// without a target itinerary. The choise if number here has more to do with
43// balancing scheduler heursitics than with the actual machine latency.
44static cl::opt<int> HighLatencyCycles(
45 "sched-high-latency-cycles", cl::Hidden, cl::init(10),
46 cl::desc("Roughly estimate the number of cycles that 'long latency'"
47 "instructions take for targets with no itinerary"));
48
Dan Gohman79ce2762009-01-15 19:20:50 +000049ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
Stephen Hinesdce4a402014-05-29 02:49:00 -070050 : ScheduleDAG(mf), BB(nullptr), DAG(nullptr),
Evan Cheng3ef1c872010-09-10 01:29:16 +000051 InstrItins(mf.getTarget().getInstrItineraryData()) {}
Dan Gohman343f0c02008-11-19 23:18:57 +000052
Dan Gohman47ac0f02009-02-11 04:27:20 +000053/// Run - perform scheduling.
54///
Andrew Trick47c14452012-03-07 05:21:52 +000055void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
56 BB = bb;
Dan Gohman47ac0f02009-02-11 04:27:20 +000057 DAG = dag;
Andrew Trick47c14452012-03-07 05:21:52 +000058
59 // Clear the scheduler's SUnit DAG.
60 ScheduleDAG::clearDAG();
61 Sequence.clear();
62
63 // Invoke the target's selection of scheduler.
64 Schedule();
Dan Gohman47ac0f02009-02-11 04:27:20 +000065}
66
Evan Cheng1cc39842010-05-20 23:26:43 +000067/// NewSUnit - Creates a new SUnit and return a ptr to it.
68///
Andrew Trick953be892012-03-07 23:00:49 +000069SUnit *ScheduleDAGSDNodes::newSUnit(SDNode *N) {
Evan Cheng1cc39842010-05-20 23:26:43 +000070#ifndef NDEBUG
Stephen Hinesdce4a402014-05-29 02:49:00 -070071 const SUnit *Addr = nullptr;
Evan Cheng1cc39842010-05-20 23:26:43 +000072 if (!SUnits.empty())
73 Addr = &SUnits[0];
74#endif
75 SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
Stephen Hinesdce4a402014-05-29 02:49:00 -070076 assert((Addr == nullptr || Addr == &SUnits[0]) &&
Evan Cheng1cc39842010-05-20 23:26:43 +000077 "SUnits std::vector reallocated on the fly!");
78 SUnits.back().OrigNode = &SUnits.back();
79 SUnit *SU = &SUnits.back();
80 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
Evan Chengc120af42010-08-10 02:39:45 +000081 if (!N ||
82 (N->isMachineOpcode() &&
83 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
Evan Cheng046fa3f2010-05-28 23:26:21 +000084 SU->SchedulingPref = Sched::None;
85 else
86 SU->SchedulingPref = TLI.getSchedulingPreference(N);
Evan Cheng1cc39842010-05-20 23:26:43 +000087 return SU;
88}
89
Dan Gohman343f0c02008-11-19 23:18:57 +000090SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
Andrew Trick953be892012-03-07 23:00:49 +000091 SUnit *SU = newSUnit(Old->getNode());
Dan Gohman343f0c02008-11-19 23:18:57 +000092 SU->OrigNode = Old->OrigNode;
93 SU->Latency = Old->Latency;
Andrew Trick54699762011-04-07 19:54:57 +000094 SU->isVRegCycle = Old->isVRegCycle;
Evan Cheng8239daf2010-11-03 00:45:17 +000095 SU->isCall = Old->isCall;
Evan Cheng554daa62011-04-26 21:31:35 +000096 SU->isCallOp = Old->isCallOp;
Dan Gohman343f0c02008-11-19 23:18:57 +000097 SU->isTwoAddress = Old->isTwoAddress;
98 SU->isCommutable = Old->isCommutable;
99 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
Dan Gohman39746672009-03-23 16:10:52 +0000100 SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
Andrew Trick12f0dc62011-04-14 05:15:06 +0000101 SU->isScheduleHigh = Old->isScheduleHigh;
102 SU->isScheduleLow = Old->isScheduleLow;
Evan Cheng1cc39842010-05-20 23:26:43 +0000103 SU->SchedulingPref = Old->SchedulingPref;
Evan Chenge57187c2009-01-16 20:57:18 +0000104 Old->isCloned = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000105 return SU;
106}
107
108/// CheckForPhysRegDependency - Check if the dependency between def and use of
109/// a specified operand is a physical register dependency. If so, returns the
Evan Chengc29a56d2009-01-12 03:19:55 +0000110/// register and the cost of copying the register.
Dan Gohman343f0c02008-11-19 23:18:57 +0000111static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
Andrew Trickcd5af072011-02-03 23:00:17 +0000112 const TargetRegisterInfo *TRI,
Dan Gohman343f0c02008-11-19 23:18:57 +0000113 const TargetInstrInfo *TII,
Evan Chengc29a56d2009-01-12 03:19:55 +0000114 unsigned &PhysReg, int &Cost) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000115 if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
116 return;
117
118 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
119 if (TargetRegisterInfo::isVirtualRegister(Reg))
120 return;
121
122 unsigned ResNo = User->getOperand(2).getResNo();
123 if (Def->isMachineOpcode()) {
Evan Chenge837dea2011-06-28 19:10:37 +0000124 const MCInstrDesc &II = TII->get(Def->getMachineOpcode());
Dan Gohman343f0c02008-11-19 23:18:57 +0000125 if (ResNo >= II.getNumDefs() &&
Evan Chengc29a56d2009-01-12 03:19:55 +0000126 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000127 PhysReg = Reg;
Evan Chengc29a56d2009-01-12 03:19:55 +0000128 const TargetRegisterClass *RC =
Rafael Espindolad31f9722010-06-29 14:02:34 +0000129 TRI->getMinimalPhysRegClass(Reg, Def->getValueType(ResNo));
Evan Chengc29a56d2009-01-12 03:19:55 +0000130 Cost = RC->getCopyCost();
131 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000132 }
133}
134
Andrew Trick2674a4a2012-04-28 01:03:23 +0000135// Helper for AddGlue to clone node operands.
136static void CloneNodeWithValues(SDNode *N, SelectionDAG *DAG,
137 SmallVectorImpl<EVT> &VTs,
138 SDValue ExtraOper = SDValue()) {
Evan Chengc589e032010-01-22 03:36:51 +0000139 SmallVector<SDValue, 4> Ops;
Bill Wendling10707f32010-06-24 22:00:37 +0000140 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I)
141 Ops.push_back(N->getOperand(I));
Bill Wendling151d26d2010-06-23 18:16:24 +0000142
Andrew Trick2674a4a2012-04-28 01:03:23 +0000143 if (ExtraOper.getNode())
144 Ops.push_back(ExtraOper);
Bill Wendling151d26d2010-06-23 18:16:24 +0000145
Stephen Hinesdce4a402014-05-29 02:49:00 -0700146 SDVTList VTList = DAG->getVTList(VTs);
147 MachineSDNode::mmo_iterator Begin = nullptr, End = nullptr;
Bill Wendling151d26d2010-06-23 18:16:24 +0000148 MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
149
150 // Store memory references.
151 if (MN) {
152 Begin = MN->memoperands_begin();
153 End = MN->memoperands_end();
154 }
155
Stephen Hinesdce4a402014-05-29 02:49:00 -0700156 DAG->MorphNodeTo(N, N->getOpcode(), VTList, Ops);
Bill Wendling151d26d2010-06-23 18:16:24 +0000157
158 // Reset the memory references
159 if (MN)
160 MN->setMemRefs(Begin, End);
Evan Chengc589e032010-01-22 03:36:51 +0000161}
162
Andrew Trick2674a4a2012-04-28 01:03:23 +0000163static bool AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
164 SmallVector<EVT, 4> VTs;
165 SDNode *GlueDestNode = Glue.getNode();
166
167 // Don't add glue from a node to itself.
168 if (GlueDestNode == N) return false;
169
170 // Don't add a glue operand to something that already uses glue.
171 if (GlueDestNode &&
172 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
173 return false;
174 }
175 // Don't add glue to something that already has a glue value.
176 if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return false;
177
178 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
179 VTs.push_back(N->getValueType(I));
180
181 if (AddGlue)
182 VTs.push_back(MVT::Glue);
183
184 CloneNodeWithValues(N, DAG, VTs, Glue);
185
186 return true;
187}
188
189// Cleanup after unsuccessful AddGlue. Use the standard method of morphing the
190// node even though simply shrinking the value list is sufficient.
191static void RemoveUnusedGlue(SDNode *N, SelectionDAG *DAG) {
192 assert((N->getValueType(N->getNumValues() - 1) == MVT::Glue &&
193 !N->hasAnyUseOfValue(N->getNumValues() - 1)) &&
194 "expected an unused glue value");
195
196 SmallVector<EVT, 4> VTs;
197 for (unsigned I = 0, E = N->getNumValues()-1; I != E; ++I)
198 VTs.push_back(N->getValueType(I));
199
200 CloneNodeWithValues(N, DAG, VTs);
201}
202
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000203/// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
Evan Chengc589e032010-01-22 03:36:51 +0000204/// This function finds loads of the same base and different offsets. If the
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000205/// offsets are not far apart (target specific), it add MVT::Glue inputs and
Evan Chengc589e032010-01-22 03:36:51 +0000206/// outputs to ensure they are scheduled together and in order. This
207/// optimization may benefit some targets by improving cache locality.
Evan Cheng302ef832010-06-10 02:09:31 +0000208void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700209 SDNode *Chain = nullptr;
Evan Cheng302ef832010-06-10 02:09:31 +0000210 unsigned NumOps = Node->getNumOperands();
211 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
212 Chain = Node->getOperand(NumOps-1).getNode();
213 if (!Chain)
214 return;
215
216 // Look for other loads of the same chain. Find loads that are loading from
217 // the same base pointer and different offsets.
Evan Chengc589e032010-01-22 03:36:51 +0000218 SmallPtrSet<SDNode*, 16> Visited;
219 SmallVector<int64_t, 4> Offsets;
220 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
Evan Cheng302ef832010-06-10 02:09:31 +0000221 bool Cluster = false;
222 SDNode *Base = Node;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700223 // This algorithm requires a reasonably low use count before finding a match
224 // to avoid uselessly blowing up compile time in large blocks.
225 unsigned UseCount = 0;
Evan Cheng302ef832010-06-10 02:09:31 +0000226 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700227 I != E && UseCount < 100; ++I, ++UseCount) {
Evan Cheng302ef832010-06-10 02:09:31 +0000228 SDNode *User = *I;
229 if (User == Node || !Visited.insert(User))
230 continue;
231 int64_t Offset1, Offset2;
232 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
233 Offset1 == Offset2)
234 // FIXME: Should be ok if they addresses are identical. But earlier
235 // optimizations really should have eliminated one of the loads.
236 continue;
237 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
238 Offsets.push_back(Offset1);
239 O2SMap.insert(std::make_pair(Offset2, User));
240 Offsets.push_back(Offset2);
Duncan Sandsb447c4e2010-06-25 14:48:39 +0000241 if (Offset2 < Offset1)
Evan Cheng302ef832010-06-10 02:09:31 +0000242 Base = User;
Evan Cheng302ef832010-06-10 02:09:31 +0000243 Cluster = true;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700244 // Reset UseCount to allow more matches.
245 UseCount = 0;
Evan Cheng302ef832010-06-10 02:09:31 +0000246 }
247
248 if (!Cluster)
249 return;
250
251 // Sort them in increasing order.
252 std::sort(Offsets.begin(), Offsets.end());
253
254 // Check if the loads are close enough.
255 SmallVector<SDNode*, 4> Loads;
256 unsigned NumLoads = 0;
257 int64_t BaseOff = Offsets[0];
258 SDNode *BaseLoad = O2SMap[BaseOff];
259 Loads.push_back(BaseLoad);
260 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
261 int64_t Offset = Offsets[i];
262 SDNode *Load = O2SMap[Offset];
263 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
264 break; // Stop right here. Ignore loads that are further away.
265 Loads.push_back(Load);
266 ++NumLoads;
267 }
268
269 if (NumLoads == 0)
270 return;
271
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000272 // Cluster loads by adding MVT::Glue outputs and inputs. This also
Evan Cheng302ef832010-06-10 02:09:31 +0000273 // ensure they are scheduled in order of increasing addresses.
274 SDNode *Lead = Loads[0];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700275 SDValue InGlue = SDValue(nullptr, 0);
Andrew Trick2674a4a2012-04-28 01:03:23 +0000276 if (AddGlue(Lead, InGlue, true, DAG))
277 InGlue = SDValue(Lead, Lead->getNumValues() - 1);
Bill Wendling10707f32010-06-24 22:00:37 +0000278 for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000279 bool OutGlue = I < E - 1;
Bill Wendling10707f32010-06-24 22:00:37 +0000280 SDNode *Load = Loads[I];
281
Andrew Trick2674a4a2012-04-28 01:03:23 +0000282 // If AddGlue fails, we could leave an unsused glue value. This should not
283 // cause any
284 if (AddGlue(Load, InGlue, OutGlue, DAG)) {
285 if (OutGlue)
286 InGlue = SDValue(Load, Load->getNumValues() - 1);
Bill Wendling151d26d2010-06-23 18:16:24 +0000287
Andrew Trick2674a4a2012-04-28 01:03:23 +0000288 ++LoadsClustered;
289 }
290 else if (!OutGlue && InGlue.getNode())
291 RemoveUnusedGlue(InGlue.getNode(), DAG);
Evan Cheng302ef832010-06-10 02:09:31 +0000292 }
293}
294
295/// ClusterNodes - Cluster certain nodes which should be scheduled together.
296///
297void ScheduleDAGSDNodes::ClusterNodes() {
Evan Chengc589e032010-01-22 03:36:51 +0000298 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
299 E = DAG->allnodes_end(); NI != E; ++NI) {
300 SDNode *Node = &*NI;
301 if (!Node || !Node->isMachineOpcode())
302 continue;
303
304 unsigned Opc = Node->getMachineOpcode();
Evan Chenge837dea2011-06-28 19:10:37 +0000305 const MCInstrDesc &MCID = TII->get(Opc);
306 if (MCID.mayLoad())
Evan Cheng302ef832010-06-10 02:09:31 +0000307 // Cluster loads from "near" addresses into combined SUnits.
308 ClusterNeighboringLoads(Node);
Evan Chengc589e032010-01-22 03:36:51 +0000309 }
310}
311
Dan Gohman343f0c02008-11-19 23:18:57 +0000312void ScheduleDAGSDNodes::BuildSchedUnits() {
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000313 // During scheduling, the NodeId field of SDNode is used to map SDNodes
314 // to their associated SUnits by holding SUnits table indices. A value
315 // of -1 means the SDNode does not yet have an associated SUnit.
316 unsigned NumNodes = 0;
317 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
318 E = DAG->allnodes_end(); NI != E; ++NI) {
319 NI->setNodeId(-1);
320 ++NumNodes;
321 }
322
Dan Gohman343f0c02008-11-19 23:18:57 +0000323 // Reserve entries in the vector for each of the SUnits we are creating. This
324 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
325 // invalidated.
Dan Gohman89b64bd2008-12-17 04:30:46 +0000326 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
327 // This is a temporary workaround.
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000328 SUnits.reserve(NumNodes * 2);
Andrew Trickcd5af072011-02-03 23:00:17 +0000329
Chris Lattner736a6ea2010-02-24 06:11:37 +0000330 // Add all nodes in depth first order.
331 SmallVector<SDNode*, 64> Worklist;
332 SmallPtrSet<SDNode*, 64> Visited;
333 Worklist.push_back(DAG->getRoot().getNode());
334 Visited.insert(DAG->getRoot().getNode());
Andrew Trickcd5af072011-02-03 23:00:17 +0000335
Evan Cheng554daa62011-04-26 21:31:35 +0000336 SmallVector<SUnit*, 8> CallSUnits;
Chris Lattner736a6ea2010-02-24 06:11:37 +0000337 while (!Worklist.empty()) {
338 SDNode *NI = Worklist.pop_back_val();
Andrew Trickcd5af072011-02-03 23:00:17 +0000339
Chris Lattner736a6ea2010-02-24 06:11:37 +0000340 // Add all operands to the worklist unless they've already been added.
341 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
342 if (Visited.insert(NI->getOperand(i).getNode()))
343 Worklist.push_back(NI->getOperand(i).getNode());
Andrew Trickcd5af072011-02-03 23:00:17 +0000344
Dan Gohman343f0c02008-11-19 23:18:57 +0000345 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
346 continue;
Andrew Trickcd5af072011-02-03 23:00:17 +0000347
Dan Gohman343f0c02008-11-19 23:18:57 +0000348 // If this node has already been processed, stop now.
349 if (NI->getNodeId() != -1) continue;
Andrew Trickcd5af072011-02-03 23:00:17 +0000350
Andrew Trick953be892012-03-07 23:00:49 +0000351 SUnit *NodeSUnit = newSUnit(NI);
Andrew Trickcd5af072011-02-03 23:00:17 +0000352
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000353 // See if anything is glued to this node, if so, add them to glued
354 // nodes. Nodes can have at most one glue input and one glue output. Glue
355 // is required to be the last operand and result of a node.
Andrew Trickcd5af072011-02-03 23:00:17 +0000356
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000357 // Scan up to find glued preds.
Dan Gohman343f0c02008-11-19 23:18:57 +0000358 SDNode *N = NI;
Dan Gohmandb95fa12009-03-20 20:42:23 +0000359 while (N->getNumOperands() &&
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000360 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
Dan Gohmandb95fa12009-03-20 20:42:23 +0000361 N = N->getOperand(N->getNumOperands()-1).getNode();
362 assert(N->getNodeId() == -1 && "Node already inserted!");
363 N->setNodeId(NodeSUnit->NodeNum);
Evan Cheng8239daf2010-11-03 00:45:17 +0000364 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
365 NodeSUnit->isCall = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000366 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000367
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000368 // Scan down to find any glued succs.
Dan Gohman343f0c02008-11-19 23:18:57 +0000369 N = NI;
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000370 while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000371 SDValue GlueVal(N, N->getNumValues()-1);
Andrew Trickcd5af072011-02-03 23:00:17 +0000372
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000373 // There are either zero or one users of the Glue result.
374 bool HasGlueUse = false;
Andrew Trickcd5af072011-02-03 23:00:17 +0000375 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000376 UI != E; ++UI)
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000377 if (GlueVal.isOperandOf(*UI)) {
378 HasGlueUse = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000379 assert(N->getNodeId() == -1 && "Node already inserted!");
380 N->setNodeId(NodeSUnit->NodeNum);
381 N = *UI;
Evan Cheng8239daf2010-11-03 00:45:17 +0000382 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
383 NodeSUnit->isCall = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000384 break;
385 }
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000386 if (!HasGlueUse) break;
Dan Gohman343f0c02008-11-19 23:18:57 +0000387 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000388
Evan Cheng554daa62011-04-26 21:31:35 +0000389 if (NodeSUnit->isCall)
390 CallSUnits.push_back(NodeSUnit);
391
Andrew Trick12f0dc62011-04-14 05:15:06 +0000392 // Schedule zero-latency TokenFactor below any nodes that may increase the
393 // schedule height. Otherwise, ancestors of the TokenFactor may appear to
394 // have false stalls.
395 if (NI->getOpcode() == ISD::TokenFactor)
396 NodeSUnit->isScheduleLow = true;
397
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000398 // If there are glue operands involved, N is now the bottom-most node
399 // of the sequence of nodes that are glued together.
Dan Gohman343f0c02008-11-19 23:18:57 +0000400 // Update the SUnit.
401 NodeSUnit->setNode(N);
402 assert(N->getNodeId() == -1 && "Node already inserted!");
403 N->setNodeId(NodeSUnit->NodeNum);
404
Andrew Trick92e94662011-02-04 03:18:17 +0000405 // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
406 InitNumRegDefsLeft(NodeSUnit);
407
Dan Gohman787782f2008-11-21 01:44:51 +0000408 // Assign the Latency field of NodeSUnit using target-provided information.
Andrew Trick953be892012-03-07 23:00:49 +0000409 computeLatency(NodeSUnit);
Dan Gohman343f0c02008-11-19 23:18:57 +0000410 }
Evan Cheng554daa62011-04-26 21:31:35 +0000411
412 // Find all call operands.
413 while (!CallSUnits.empty()) {
414 SUnit *SU = CallSUnits.pop_back_val();
415 for (const SDNode *SUNode = SU->getNode(); SUNode;
416 SUNode = SUNode->getGluedNode()) {
417 if (SUNode->getOpcode() != ISD::CopyToReg)
418 continue;
419 SDNode *SrcN = SUNode->getOperand(2).getNode();
420 if (isPassiveNode(SrcN)) continue; // Not scheduled.
421 SUnit *SrcSU = &SUnits[SrcN->getNodeId()];
422 SrcSU->isCallOp = true;
423 }
424 }
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000425}
426
427void ScheduleDAGSDNodes::AddSchedEdges() {
Evan Cheng5b1b44892011-07-01 21:01:15 +0000428 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
David Goodwin71046162009-08-13 16:05:04 +0000429
David Goodwindc4bdcd2009-08-19 16:08:58 +0000430 // Check to see if the scheduler cares about latencies.
Andrew Trick953be892012-03-07 23:00:49 +0000431 bool UnitLatencies = forceUnitLatencies();
David Goodwindc4bdcd2009-08-19 16:08:58 +0000432
Dan Gohman343f0c02008-11-19 23:18:57 +0000433 // Pass 2: add the preds, succs, etc.
434 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
435 SUnit *SU = &SUnits[su];
436 SDNode *MainNode = SU->getNode();
Andrew Trickcd5af072011-02-03 23:00:17 +0000437
Dan Gohman343f0c02008-11-19 23:18:57 +0000438 if (MainNode->isMachineOpcode()) {
439 unsigned Opc = MainNode->getMachineOpcode();
Evan Chenge837dea2011-06-28 19:10:37 +0000440 const MCInstrDesc &MCID = TII->get(Opc);
441 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
442 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000443 SU->isTwoAddress = true;
444 break;
445 }
446 }
Evan Chenge837dea2011-06-28 19:10:37 +0000447 if (MCID.isCommutable())
Dan Gohman343f0c02008-11-19 23:18:57 +0000448 SU->isCommutable = true;
449 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000450
Dan Gohman343f0c02008-11-19 23:18:57 +0000451 // Find all predecessors and successors of the group.
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000452 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000453 if (N->isMachineOpcode() &&
Dan Gohman39746672009-03-23 16:10:52 +0000454 TII->get(N->getMachineOpcode()).getImplicitDefs()) {
455 SU->hasPhysRegClobbers = true;
Dan Gohmanbcea8592009-10-10 01:32:21 +0000456 unsigned NumUsed = InstrEmitter::CountResults(N);
Dan Gohman8cccf0e2009-03-23 17:39:36 +0000457 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
458 --NumUsed; // Skip over unused values at the end.
459 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
Dan Gohman39746672009-03-23 16:10:52 +0000460 SU->hasPhysRegDefs = true;
461 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000462
Dan Gohman343f0c02008-11-19 23:18:57 +0000463 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
464 SDNode *OpN = N->getOperand(i).getNode();
465 if (isPassiveNode(OpN)) continue; // Not scheduled.
466 SUnit *OpSU = &SUnits[OpN->getNodeId()];
467 assert(OpSU && "Node has no SUnit!");
468 if (OpSU == SU) continue; // In the same group.
469
Owen Andersone50ed302009-08-10 22:56:29 +0000470 EVT OpVT = N->getOperand(i).getValueType();
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000471 assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000472 bool isChain = OpVT == MVT::Other;
Dan Gohman343f0c02008-11-19 23:18:57 +0000473
474 unsigned PhysReg = 0;
Evan Chengc29a56d2009-01-12 03:19:55 +0000475 int Cost = 1;
Dan Gohman343f0c02008-11-19 23:18:57 +0000476 // Determine if this is a physical register dependency.
Evan Chengc29a56d2009-01-12 03:19:55 +0000477 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
Dan Gohman54e4c362008-12-09 22:54:47 +0000478 assert((PhysReg == 0 || !isChain) &&
479 "Chain dependence via physreg data?");
Evan Chengc29a56d2009-01-12 03:19:55 +0000480 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
481 // emits a copy from the physical register to a virtual register unless
482 // it requires a cross class copy (cost < 0). That means we are only
483 // treating "expensive to copy" register dependency as physical register
484 // dependency. This may change in the future though.
Andrew Trick4cb971c2011-06-15 17:16:12 +0000485 if (Cost >= 0 && !StressSched)
Evan Chengc29a56d2009-01-12 03:19:55 +0000486 PhysReg = 0;
David Goodwin71046162009-08-13 16:05:04 +0000487
Evan Cheng046fa3f2010-05-28 23:26:21 +0000488 // If this is a ctrl dep, latency is 1.
Andrew Trickc558bf32011-04-12 20:14:07 +0000489 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
Andrew Trick87896d92011-04-13 00:38:32 +0000490 // Special-case TokenFactor chains as zero-latency.
491 if(isChain && OpN->getOpcode() == ISD::TokenFactor)
492 OpLatency = 0;
493
Andrew Tricka78d3222012-11-06 03:13:46 +0000494 SDep Dep = isChain ? SDep(OpSU, SDep::Barrier)
495 : SDep(OpSU, SDep::Data, PhysReg);
496 Dep.setLatency(OpLatency);
David Goodwindc4bdcd2009-08-19 16:08:58 +0000497 if (!isChain && !UnitLatencies) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000498 computeOperandLatency(OpN, N, i, Dep);
499 ST.adjustSchedDependency(OpSU, SU, Dep);
David Goodwindc4bdcd2009-08-19 16:08:58 +0000500 }
David Goodwin71046162009-08-13 16:05:04 +0000501
Andrew Tricka78d3222012-11-06 03:13:46 +0000502 if (!SU->addPred(Dep) && !Dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
Andrew Trick92e94662011-02-04 03:18:17 +0000503 // Multiple register uses are combined in the same SUnit. For example,
504 // we could have a set of glued nodes with all their defs consumed by
505 // another set of glued nodes. Register pressure tracking sees this as
506 // a single use, so to keep pressure balanced we reduce the defs.
Andrew Trick4bbf4672011-03-09 19:12:43 +0000507 //
508 // We can't tell (without more book-keeping) if this results from
509 // glued nodes or duplicate operands. As long as we don't reduce
510 // NumRegDefsLeft to zero, we handle the common cases well.
Andrew Trick92e94662011-02-04 03:18:17 +0000511 --OpSU->NumRegDefsLeft;
512 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000513 }
514 }
515 }
516}
517
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000518/// BuildSchedGraph - Build the SUnit graph from the selection dag that we
519/// are input. This SUnit graph is similar to the SelectionDAG, but
520/// excludes nodes that aren't interesting to scheduling, and represents
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000521/// glued together nodes with a single SUnit.
Dan Gohman98976e42009-10-09 23:33:48 +0000522void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
Evan Cheng302ef832010-06-10 02:09:31 +0000523 // Cluster certain nodes which should be scheduled together.
524 ClusterNodes();
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000525 // Populate the SUnits array.
526 BuildSchedUnits();
527 // Compute all the scheduling dependencies between nodes.
528 AddSchedEdges();
529}
530
Andrew Trick92e94662011-02-04 03:18:17 +0000531// Initialize NumNodeDefs for the current Node's opcode.
532void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
Eric Christopher29449442011-03-08 19:35:47 +0000533 // Check for phys reg copy.
534 if (!Node)
535 return;
536
Andrew Trick92e94662011-02-04 03:18:17 +0000537 if (!Node->isMachineOpcode()) {
538 if (Node->getOpcode() == ISD::CopyFromReg)
539 NodeNumDefs = 1;
540 else
541 NodeNumDefs = 0;
542 return;
543 }
544 unsigned POpc = Node->getMachineOpcode();
545 if (POpc == TargetOpcode::IMPLICIT_DEF) {
546 // No register need be allocated for this.
547 NodeNumDefs = 0;
548 return;
549 }
550 unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
551 // Some instructions define regs that are not represented in the selection DAG
552 // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
553 NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
554 DefIdx = 0;
555}
556
557// Construct a RegDefIter for this SUnit and find the first valid value.
558ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
559 const ScheduleDAGSDNodes *SD)
560 : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
561 InitNodeNumDefs();
562 Advance();
563}
564
565// Advance to the next valid value defined by the SUnit.
566void ScheduleDAGSDNodes::RegDefIter::Advance() {
567 for (;Node;) { // Visit all glued nodes.
568 for (;DefIdx < NodeNumDefs; ++DefIdx) {
569 if (!Node->hasAnyUseOfValue(DefIdx))
570 continue;
Patrik Hagglund860e7cd2012-12-13 18:45:35 +0000571 ValueType = Node->getSimpleValueType(DefIdx);
Andrew Trick92e94662011-02-04 03:18:17 +0000572 ++DefIdx;
573 return; // Found a normal regdef.
574 }
575 Node = Node->getGluedNode();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700576 if (!Node) {
Andrew Trick92e94662011-02-04 03:18:17 +0000577 return; // No values left to visit.
578 }
579 InitNodeNumDefs();
580 }
581}
582
583void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
584 assert(SU->NumRegDefsLeft == 0 && "expect a new node");
585 for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
586 assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
587 ++SU->NumRegDefsLeft;
588 }
589}
590
Andrew Trick953be892012-03-07 23:00:49 +0000591void ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
Andrew Trick87896d92011-04-13 00:38:32 +0000592 SDNode *N = SU->getNode();
593
594 // TokenFactor operands are considered zero latency, and some schedulers
595 // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
596 // whenever node latency is nonzero.
597 if (N && N->getOpcode() == ISD::TokenFactor) {
598 SU->Latency = 0;
599 return;
600 }
601
Evan Chenge1631682010-05-19 22:42:23 +0000602 // Check to see if the scheduler cares about latencies.
Andrew Trick953be892012-03-07 23:00:49 +0000603 if (forceUnitLatencies()) {
Evan Chenge1631682010-05-19 22:42:23 +0000604 SU->Latency = 1;
605 return;
606 }
607
Evan Cheng3ef1c872010-09-10 01:29:16 +0000608 if (!InstrItins || InstrItins->isEmpty()) {
Andrew Trick5e84e3c2011-03-05 09:18:16 +0000609 if (N && N->isMachineOpcode() &&
610 TII->isHighLatencyDef(N->getMachineOpcode()))
Andrew Tricke0ef5092011-03-05 08:00:22 +0000611 SU->Latency = HighLatencyCycles;
612 else
613 SU->Latency = 1;
Evan Cheng15a16de2010-05-20 06:13:19 +0000614 return;
615 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000616
Dan Gohman343f0c02008-11-19 23:18:57 +0000617 // Compute the latency for the node. We use the sum of the latencies for
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000618 // all nodes glued together into this SUnit.
Dan Gohman343f0c02008-11-19 23:18:57 +0000619 SU->Latency = 0;
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000620 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
Evan Cheng8239daf2010-11-03 00:45:17 +0000621 if (N->isMachineOpcode())
622 SU->Latency += TII->getInstrLatency(InstrItins, N);
Dan Gohman343f0c02008-11-19 23:18:57 +0000623}
624
Andrew Trick953be892012-03-07 23:00:49 +0000625void ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
Evan Cheng15a16de2010-05-20 06:13:19 +0000626 unsigned OpIdx, SDep& dep) const{
627 // Check to see if the scheduler cares about latencies.
Andrew Trick953be892012-03-07 23:00:49 +0000628 if (forceUnitLatencies())
Evan Cheng15a16de2010-05-20 06:13:19 +0000629 return;
630
Evan Cheng15a16de2010-05-20 06:13:19 +0000631 if (dep.getKind() != SDep::Data)
632 return;
633
634 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
Evan Cheng7e2fe912010-10-28 06:47:08 +0000635 if (Use->isMachineOpcode())
636 // Adjust the use operand index by num of defs.
637 OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
Evan Chenga0792de2010-10-06 06:27:31 +0000638 int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
Evan Cheng08975152010-10-29 18:09:28 +0000639 if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
640 !BB->succ_empty()) {
641 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
642 if (TargetRegisterInfo::isVirtualRegister(Reg))
643 // This copy is a liveout value. It is likely coalesced, so reduce the
644 // latency so not to penalize the def.
645 // FIXME: need target specific adjustment here?
646 Latency = (Latency > 1) ? Latency - 1 : 1;
647 }
Evan Cheng3881cb72010-09-29 22:42:35 +0000648 if (Latency >= 0)
649 dep.setLatency(Latency);
Evan Cheng15a16de2010-05-20 06:13:19 +0000650}
651
Dan Gohman343f0c02008-11-19 23:18:57 +0000652void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
Manman Renb720be62012-09-11 22:23:19 +0000653#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Evan Chengc29a56d2009-01-12 03:19:55 +0000654 if (!SU->getNode()) {
David Greene84fa8222010-01-05 01:25:11 +0000655 dbgs() << "PHYS REG COPY\n";
Evan Chengc29a56d2009-01-12 03:19:55 +0000656 return;
657 }
658
659 SU->getNode()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000660 dbgs() << "\n";
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000661 SmallVector<SDNode *, 4> GluedNodes;
662 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
663 GluedNodes.push_back(N);
664 while (!GluedNodes.empty()) {
David Greene84fa8222010-01-05 01:25:11 +0000665 dbgs() << " ";
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000666 GluedNodes.back()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000667 dbgs() << "\n";
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000668 GluedNodes.pop_back();
Dan Gohman343f0c02008-11-19 23:18:57 +0000669 }
Manman Ren77e300e2012-09-06 19:06:06 +0000670#endif
Dan Gohman343f0c02008-11-19 23:18:57 +0000671}
Dan Gohmanbcea8592009-10-10 01:32:21 +0000672
Manman Renb720be62012-09-11 22:23:19 +0000673#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick73ba69b2012-03-07 05:21:40 +0000674void ScheduleDAGSDNodes::dumpSchedule() const {
675 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
676 if (SUnit *SU = Sequence[i])
677 SU->dump(this);
678 else
679 dbgs() << "**** NOOP ****\n";
680 }
681}
Manman Ren77e300e2012-09-06 19:06:06 +0000682#endif
Andrew Trick73ba69b2012-03-07 05:21:40 +0000683
Andrew Trick4c727202012-03-07 05:21:36 +0000684#ifndef NDEBUG
685/// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
686/// their state is consistent with the nodes listed in Sequence.
687///
688void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
689 unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
690 unsigned Noops = 0;
691 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
692 if (!Sequence[i])
693 ++Noops;
694 assert(Sequence.size() - Noops == ScheduledNodes &&
695 "The number of nodes scheduled doesn't match the expected number!");
696}
697#endif // NDEBUG
698
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000699/// ProcessSDDbgValues - Process SDDbgValues associated with this node.
Craig Toppera0ec3f92013-07-14 04:42:23 +0000700static void
701ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
702 SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
703 DenseMap<SDValue, unsigned> &VRBaseMap, unsigned Order) {
Devang Patel55d20e82011-01-26 18:20:04 +0000704 if (!N->getHasDebugValue())
705 return;
706
707 // Opportunistically insert immediate dbg_value uses, i.e. those with source
708 // order number right after the N.
709 MachineBasicBlock *BB = Emitter.getBlock();
710 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
Benjamin Kramer22a54c12011-06-18 13:13:44 +0000711 ArrayRef<SDDbgValue*> DVs = DAG->GetDbgValues(N);
Devang Patel55d20e82011-01-26 18:20:04 +0000712 for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
713 if (DVs[i]->isInvalidated())
714 continue;
715 unsigned DVOrder = DVs[i]->getOrder();
716 if (!Order || DVOrder == ++Order) {
717 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
718 if (DbgMI) {
719 Orders.push_back(std::make_pair(DVOrder, DbgMI));
720 BB->insert(InsertPos, DbgMI);
721 }
722 DVs[i]->setIsInvalidated();
723 }
724 }
725}
726
Evan Chengbfcb3052010-03-25 01:38:16 +0000727// ProcessSourceNode - Process nodes with source order numbers. These are added
Jim Grosbachd27946d2010-06-30 21:27:56 +0000728// to a vector which EmitSchedule uses to determine how to insert dbg_value
Evan Chengbfcb3052010-03-25 01:38:16 +0000729// instructions in the right order.
Craig Toppera0ec3f92013-07-14 04:42:23 +0000730static void
731ProcessSourceNode(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
732 DenseMap<SDValue, unsigned> &VRBaseMap,
733 SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
734 SmallSet<unsigned, 8> &Seen) {
Andrew Trickdd0fb012013-05-25 03:08:10 +0000735 unsigned Order = N->getIROrder();
Devang Patel39078a82011-01-27 00:13:27 +0000736 if (!Order || !Seen.insert(Order)) {
737 // Process any valid SDDbgValues even if node does not have any order
738 // assigned.
739 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
Evan Chengbfcb3052010-03-25 01:38:16 +0000740 return;
Devang Patel39078a82011-01-27 00:13:27 +0000741 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000742
743 MachineBasicBlock *BB = Emitter.getBlock();
Bill Schmidt6cd04fd2013-10-18 14:20:11 +0000744 if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI() ||
745 // Fast-isel may have inserted some instructions, in which case the
746 // BB->back().isPHI() test will not fire when we want it to.
Stephen Hines36b56882014-04-23 16:57:46 -0700747 std::prev(Emitter.getInsertPos())->isPHI()) {
Evan Chengbfcb3052010-03-25 01:38:16 +0000748 // Did not insert any instruction.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700749 Orders.push_back(std::make_pair(Order, (MachineInstr*)nullptr));
Evan Chengbfcb3052010-03-25 01:38:16 +0000750 return;
751 }
752
Stephen Hines36b56882014-04-23 16:57:46 -0700753 Orders.push_back(std::make_pair(Order, std::prev(Emitter.getInsertPos())));
Devang Patel55d20e82011-01-26 18:20:04 +0000754 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
Evan Chengbfcb3052010-03-25 01:38:16 +0000755}
756
Andrew Trick84b454d2012-03-07 05:21:44 +0000757void ScheduleDAGSDNodes::
758EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
759 MachineBasicBlock::iterator InsertPos) {
760 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
761 I != E; ++I) {
762 if (I->isCtrl()) continue; // ignore chain preds
763 if (I->getSUnit()->CopyDstRC) {
764 // Copy to physical register.
765 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->getSUnit());
766 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
767 // Find the destination physical register.
768 unsigned Reg = 0;
769 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
770 EE = SU->Succs.end(); II != EE; ++II) {
771 if (II->isCtrl()) continue; // ignore chain preds
772 if (II->getReg()) {
773 Reg = II->getReg();
774 break;
775 }
776 }
777 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
778 .addReg(VRI->second);
779 } else {
780 // Copy from physical register.
781 assert(I->getReg() && "Unknown physical register!");
782 unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
783 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
784 (void)isNew; // Silence compiler warning.
785 assert(isNew && "Node emitted out of order - early");
786 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
787 .addReg(I->getReg());
788 }
789 break;
790 }
791}
Evan Chengbfcb3052010-03-25 01:38:16 +0000792
Andrew Trick84b454d2012-03-07 05:21:44 +0000793/// EmitSchedule - Emit the machine code in scheduled order. Return the new
794/// InsertPos and MachineBasicBlock that contains this insertion
795/// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
796/// not necessarily refer to returned BB. The emitter may split blocks.
Andrew Trick47c14452012-03-07 05:21:52 +0000797MachineBasicBlock *ScheduleDAGSDNodes::
798EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
Dan Gohmanbcea8592009-10-10 01:32:21 +0000799 InstrEmitter Emitter(BB, InsertPos);
800 DenseMap<SDValue, unsigned> VRBaseMap;
801 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
Evan Chengbfcb3052010-03-25 01:38:16 +0000802 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
803 SmallSet<unsigned, 8> Seen;
804 bool HasDbg = DAG->hasDebugValues();
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000805
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000806 // If this is the first BB, emit byval parameter dbg_value's.
807 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
808 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
809 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
810 for (; PDI != PDE; ++PDI) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000811 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000812 if (DbgMI)
Dan Gohman84023e02010-07-10 09:00:22 +0000813 BB->insert(InsertPos, DbgMI);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000814 }
815 }
816
Dan Gohmanbcea8592009-10-10 01:32:21 +0000817 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
818 SUnit *SU = Sequence[i];
819 if (!SU) {
820 // Null SUnit* is a noop.
Andrew Trick84b454d2012-03-07 05:21:44 +0000821 TII->insertNoop(*Emitter.getBlock(), InsertPos);
Dan Gohmanbcea8592009-10-10 01:32:21 +0000822 continue;
823 }
824
825 // For pre-regalloc scheduling, create instructions corresponding to the
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000826 // SDNode and any glued SDNodes and append them to the block.
Dan Gohmanbcea8592009-10-10 01:32:21 +0000827 if (!SU->getNode()) {
828 // Emit a copy.
Andrew Trick84b454d2012-03-07 05:21:44 +0000829 EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
Dan Gohmanbcea8592009-10-10 01:32:21 +0000830 continue;
831 }
832
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000833 SmallVector<SDNode *, 4> GluedNodes;
Evan Chengd4f75962012-10-17 19:39:36 +0000834 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000835 GluedNodes.push_back(N);
836 while (!GluedNodes.empty()) {
837 SDNode *N = GluedNodes.back();
838 Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000839 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000840 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000841 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000842 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000843 GluedNodes.pop_back();
Dan Gohmanbcea8592009-10-10 01:32:21 +0000844 }
845 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000846 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000847 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000848 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000849 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
Evan Chengbfcb3052010-03-25 01:38:16 +0000850 Seen);
851 }
852
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000853 // Insert all the dbg_values which have not already been inserted in source
Evan Chengbfcb3052010-03-25 01:38:16 +0000854 // order sequence.
855 if (HasDbg) {
Dan Gohman84023e02010-07-10 09:00:22 +0000856 MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
Evan Chengbfcb3052010-03-25 01:38:16 +0000857
858 // Sort the source order instructions and use the order to insert debug
859 // values.
Benjamin Kramer0b6962f2013-08-24 12:54:27 +0000860 std::sort(Orders.begin(), Orders.end(), less_first());
Evan Chengbfcb3052010-03-25 01:38:16 +0000861
862 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
863 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
864 // Now emit the rest according to source order.
865 unsigned LastOrder = 0;
Evan Chengbfcb3052010-03-25 01:38:16 +0000866 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
867 unsigned Order = Orders[i].first;
868 MachineInstr *MI = Orders[i].second;
869 // Insert all SDDbgValue's whose order(s) are before "Order".
870 if (!MI)
871 continue;
Evan Chengbfcb3052010-03-25 01:38:16 +0000872 for (; DI != DE &&
873 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
874 if ((*DI)->isInvalidated())
875 continue;
Dan Gohman891ff8f2010-04-30 19:35:33 +0000876 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000877 if (DbgMI) {
878 if (!LastOrder)
879 // Insert to start of the BB (after PHIs).
880 BB->insert(BBBegin, DbgMI);
881 else {
Dan Gohmana8dab362010-07-10 22:42:31 +0000882 // Insert at the instruction, which may be in a different
883 // block, if the block was split by a custom inserter.
Evan Cheng962021b2010-04-26 07:38:55 +0000884 MachineBasicBlock::iterator Pos = MI;
Andrew Trick9edb37f2013-05-26 08:58:50 +0000885 MI->getParent()->insert(Pos, DbgMI);
Evan Cheng962021b2010-04-26 07:38:55 +0000886 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000887 }
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000888 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000889 LastOrder = Order;
Evan Chengbfcb3052010-03-25 01:38:16 +0000890 }
891 // Add trailing DbgValue's before the terminator. FIXME: May want to add
892 // some of them before one or more conditional branches?
Bill Wendling7bf116a2012-03-14 07:14:25 +0000893 SmallVector<MachineInstr*, 8> DbgMIs;
Evan Chengbfcb3052010-03-25 01:38:16 +0000894 while (DI != DE) {
Bill Wendling7bf116a2012-03-14 07:14:25 +0000895 if (!(*DI)->isInvalidated())
896 if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
897 DbgMIs.push_back(DbgMI);
Evan Chengbfcb3052010-03-25 01:38:16 +0000898 ++DI;
899 }
Bill Wendling7bf116a2012-03-14 07:14:25 +0000900
901 MachineBasicBlock *InsertBB = Emitter.getBlock();
902 MachineBasicBlock::iterator Pos = InsertBB->getFirstTerminator();
903 InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
Dan Gohmanbcea8592009-10-10 01:32:21 +0000904 }
905
Dan Gohmanbcea8592009-10-10 01:32:21 +0000906 InsertPos = Emitter.getInsertPos();
Andrew Trick47c14452012-03-07 05:21:52 +0000907 return Emitter.getBlock();
Dan Gohmanbcea8592009-10-10 01:32:21 +0000908}
Andrew Trick56b94c52012-03-07 00:18:22 +0000909
910/// Return the basic block label.
911std::string ScheduleDAGSDNodes::getDAGName() const {
912 return "sunit-dag." + BB->getFullName();
913}