blob: a5de9db6af1048d38670fc40608b7712bc4a220b [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"
Dan Gohman84fbac52009-02-06 17:22:58 +000016#include "ScheduleDAGSDNodes.h"
Dan Gohmanbcea8592009-10-10 01:32:21 +000017#include "InstrEmitter.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "SDNodeDbgValue.h"
Evan Chengc589e032010-01-22 03:36:51 +000019#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/SmallPtrSet.h"
Evan Chengbfcb3052010-03-25 01:38:16 +000021#include "llvm/ADT/SmallSet.h"
Evan Chengc589e032010-01-22 03:36:51 +000022#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000024#include "llvm/CodeGen/MachineInstrBuilder.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/CodeGen/SelectionDAG.h"
27#include "llvm/MC/MCInstrItineraries.h"
Andrew Tricke0ef5092011-03-05 08:00:22 +000028#include "llvm/Support/CommandLine.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000029#include "llvm/Support/Debug.h"
30#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetLowering.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/Target/TargetRegisterInfo.h"
35#include "llvm/Target/TargetSubtargetInfo.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000036using 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
Andrew Trick2674a4a2012-04-28 01:03:23 +0000134// Helper for AddGlue to clone node operands.
135static void CloneNodeWithValues(SDNode *N, SelectionDAG *DAG,
136 SmallVectorImpl<EVT> &VTs,
137 SDValue ExtraOper = SDValue()) {
Evan Chengc589e032010-01-22 03:36:51 +0000138 SmallVector<SDValue, 4> Ops;
Bill Wendling10707f32010-06-24 22:00:37 +0000139 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I)
140 Ops.push_back(N->getOperand(I));
Bill Wendling151d26d2010-06-23 18:16:24 +0000141
Andrew Trick2674a4a2012-04-28 01:03:23 +0000142 if (ExtraOper.getNode())
143 Ops.push_back(ExtraOper);
Bill Wendling151d26d2010-06-23 18:16:24 +0000144
Evan Chengc589e032010-01-22 03:36:51 +0000145 SDVTList VTList = DAG->getVTList(&VTs[0], VTs.size());
Bill Wendling151d26d2010-06-23 18:16:24 +0000146 MachineSDNode::mmo_iterator Begin = 0, End = 0;
147 MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
148
149 // Store memory references.
150 if (MN) {
151 Begin = MN->memoperands_begin();
152 End = MN->memoperands_end();
153 }
154
Evan Chengc589e032010-01-22 03:36:51 +0000155 DAG->MorphNodeTo(N, N->getOpcode(), VTList, &Ops[0], Ops.size());
Bill Wendling151d26d2010-06-23 18:16:24 +0000156
157 // Reset the memory references
158 if (MN)
159 MN->setMemRefs(Begin, End);
Evan Chengc589e032010-01-22 03:36:51 +0000160}
161
Andrew Trick2674a4a2012-04-28 01:03:23 +0000162static bool AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
163 SmallVector<EVT, 4> VTs;
164 SDNode *GlueDestNode = Glue.getNode();
165
166 // Don't add glue from a node to itself.
167 if (GlueDestNode == N) return false;
168
169 // Don't add a glue operand to something that already uses glue.
170 if (GlueDestNode &&
171 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
172 return false;
173 }
174 // Don't add glue to something that already has a glue value.
175 if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return false;
176
177 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
178 VTs.push_back(N->getValueType(I));
179
180 if (AddGlue)
181 VTs.push_back(MVT::Glue);
182
183 CloneNodeWithValues(N, DAG, VTs, Glue);
184
185 return true;
186}
187
188// Cleanup after unsuccessful AddGlue. Use the standard method of morphing the
189// node even though simply shrinking the value list is sufficient.
190static void RemoveUnusedGlue(SDNode *N, SelectionDAG *DAG) {
191 assert((N->getValueType(N->getNumValues() - 1) == MVT::Glue &&
192 !N->hasAnyUseOfValue(N->getNumValues() - 1)) &&
193 "expected an unused glue value");
194
195 SmallVector<EVT, 4> VTs;
196 for (unsigned I = 0, E = N->getNumValues()-1; I != E; ++I)
197 VTs.push_back(N->getValueType(I));
198
199 CloneNodeWithValues(N, DAG, VTs);
200}
201
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000202/// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
Evan Chengc589e032010-01-22 03:36:51 +0000203/// This function finds loads of the same base and different offsets. If the
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000204/// offsets are not far apart (target specific), it add MVT::Glue inputs and
Evan Chengc589e032010-01-22 03:36:51 +0000205/// outputs to ensure they are scheduled together and in order. This
206/// optimization may benefit some targets by improving cache locality.
Evan Cheng302ef832010-06-10 02:09:31 +0000207void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
208 SDNode *Chain = 0;
209 unsigned NumOps = Node->getNumOperands();
210 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
211 Chain = Node->getOperand(NumOps-1).getNode();
212 if (!Chain)
213 return;
214
215 // Look for other loads of the same chain. Find loads that are loading from
216 // the same base pointer and different offsets.
Evan Chengc589e032010-01-22 03:36:51 +0000217 SmallPtrSet<SDNode*, 16> Visited;
218 SmallVector<int64_t, 4> Offsets;
219 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
Evan Cheng302ef832010-06-10 02:09:31 +0000220 bool Cluster = false;
221 SDNode *Base = Node;
Evan Cheng302ef832010-06-10 02:09:31 +0000222 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
223 I != E; ++I) {
224 SDNode *User = *I;
225 if (User == Node || !Visited.insert(User))
226 continue;
227 int64_t Offset1, Offset2;
228 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
229 Offset1 == Offset2)
230 // FIXME: Should be ok if they addresses are identical. But earlier
231 // optimizations really should have eliminated one of the loads.
232 continue;
233 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
234 Offsets.push_back(Offset1);
235 O2SMap.insert(std::make_pair(Offset2, User));
236 Offsets.push_back(Offset2);
Duncan Sandsb447c4e2010-06-25 14:48:39 +0000237 if (Offset2 < Offset1)
Evan Cheng302ef832010-06-10 02:09:31 +0000238 Base = User;
Evan Cheng302ef832010-06-10 02:09:31 +0000239 Cluster = true;
240 }
241
242 if (!Cluster)
243 return;
244
245 // Sort them in increasing order.
246 std::sort(Offsets.begin(), Offsets.end());
247
248 // Check if the loads are close enough.
249 SmallVector<SDNode*, 4> Loads;
250 unsigned NumLoads = 0;
251 int64_t BaseOff = Offsets[0];
252 SDNode *BaseLoad = O2SMap[BaseOff];
253 Loads.push_back(BaseLoad);
254 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
255 int64_t Offset = Offsets[i];
256 SDNode *Load = O2SMap[Offset];
257 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
258 break; // Stop right here. Ignore loads that are further away.
259 Loads.push_back(Load);
260 ++NumLoads;
261 }
262
263 if (NumLoads == 0)
264 return;
265
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000266 // Cluster loads by adding MVT::Glue outputs and inputs. This also
Evan Cheng302ef832010-06-10 02:09:31 +0000267 // ensure they are scheduled in order of increasing addresses.
268 SDNode *Lead = Loads[0];
Andrew Trick2674a4a2012-04-28 01:03:23 +0000269 SDValue InGlue = SDValue(0, 0);
270 if (AddGlue(Lead, InGlue, true, DAG))
271 InGlue = SDValue(Lead, Lead->getNumValues() - 1);
Bill Wendling10707f32010-06-24 22:00:37 +0000272 for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000273 bool OutGlue = I < E - 1;
Bill Wendling10707f32010-06-24 22:00:37 +0000274 SDNode *Load = Loads[I];
275
Andrew Trick2674a4a2012-04-28 01:03:23 +0000276 // If AddGlue fails, we could leave an unsused glue value. This should not
277 // cause any
278 if (AddGlue(Load, InGlue, OutGlue, DAG)) {
279 if (OutGlue)
280 InGlue = SDValue(Load, Load->getNumValues() - 1);
Bill Wendling151d26d2010-06-23 18:16:24 +0000281
Andrew Trick2674a4a2012-04-28 01:03:23 +0000282 ++LoadsClustered;
283 }
284 else if (!OutGlue && InGlue.getNode())
285 RemoveUnusedGlue(InGlue.getNode(), DAG);
Evan Cheng302ef832010-06-10 02:09:31 +0000286 }
287}
288
289/// ClusterNodes - Cluster certain nodes which should be scheduled together.
290///
291void ScheduleDAGSDNodes::ClusterNodes() {
Evan Chengc589e032010-01-22 03:36:51 +0000292 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
293 E = DAG->allnodes_end(); NI != E; ++NI) {
294 SDNode *Node = &*NI;
295 if (!Node || !Node->isMachineOpcode())
296 continue;
297
298 unsigned Opc = Node->getMachineOpcode();
Evan Chenge837dea2011-06-28 19:10:37 +0000299 const MCInstrDesc &MCID = TII->get(Opc);
300 if (MCID.mayLoad())
Evan Cheng302ef832010-06-10 02:09:31 +0000301 // Cluster loads from "near" addresses into combined SUnits.
302 ClusterNeighboringLoads(Node);
Evan Chengc589e032010-01-22 03:36:51 +0000303 }
304}
305
Dan Gohman343f0c02008-11-19 23:18:57 +0000306void ScheduleDAGSDNodes::BuildSchedUnits() {
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000307 // During scheduling, the NodeId field of SDNode is used to map SDNodes
308 // to their associated SUnits by holding SUnits table indices. A value
309 // of -1 means the SDNode does not yet have an associated SUnit.
310 unsigned NumNodes = 0;
311 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
312 E = DAG->allnodes_end(); NI != E; ++NI) {
313 NI->setNodeId(-1);
314 ++NumNodes;
315 }
316
Dan Gohman343f0c02008-11-19 23:18:57 +0000317 // Reserve entries in the vector for each of the SUnits we are creating. This
318 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
319 // invalidated.
Dan Gohman89b64bd2008-12-17 04:30:46 +0000320 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
321 // This is a temporary workaround.
Dan Gohmane1dfc7d2008-12-23 17:24:50 +0000322 SUnits.reserve(NumNodes * 2);
Andrew Trickcd5af072011-02-03 23:00:17 +0000323
Chris Lattner736a6ea2010-02-24 06:11:37 +0000324 // Add all nodes in depth first order.
325 SmallVector<SDNode*, 64> Worklist;
326 SmallPtrSet<SDNode*, 64> Visited;
327 Worklist.push_back(DAG->getRoot().getNode());
328 Visited.insert(DAG->getRoot().getNode());
Andrew Trickcd5af072011-02-03 23:00:17 +0000329
Evan Cheng554daa62011-04-26 21:31:35 +0000330 SmallVector<SUnit*, 8> CallSUnits;
Chris Lattner736a6ea2010-02-24 06:11:37 +0000331 while (!Worklist.empty()) {
332 SDNode *NI = Worklist.pop_back_val();
Andrew Trickcd5af072011-02-03 23:00:17 +0000333
Chris Lattner736a6ea2010-02-24 06:11:37 +0000334 // Add all operands to the worklist unless they've already been added.
335 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
336 if (Visited.insert(NI->getOperand(i).getNode()))
337 Worklist.push_back(NI->getOperand(i).getNode());
Andrew Trickcd5af072011-02-03 23:00:17 +0000338
Dan Gohman343f0c02008-11-19 23:18:57 +0000339 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
340 continue;
Andrew Trickcd5af072011-02-03 23:00:17 +0000341
Dan Gohman343f0c02008-11-19 23:18:57 +0000342 // If this node has already been processed, stop now.
343 if (NI->getNodeId() != -1) continue;
Andrew Trickcd5af072011-02-03 23:00:17 +0000344
Andrew Trick953be892012-03-07 23:00:49 +0000345 SUnit *NodeSUnit = newSUnit(NI);
Andrew Trickcd5af072011-02-03 23:00:17 +0000346
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000347 // See if anything is glued to this node, if so, add them to glued
348 // nodes. Nodes can have at most one glue input and one glue output. Glue
349 // is required to be the last operand and result of a node.
Andrew Trickcd5af072011-02-03 23:00:17 +0000350
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000351 // Scan up to find glued preds.
Dan Gohman343f0c02008-11-19 23:18:57 +0000352 SDNode *N = NI;
Dan Gohmandb95fa12009-03-20 20:42:23 +0000353 while (N->getNumOperands() &&
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000354 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
Dan Gohmandb95fa12009-03-20 20:42:23 +0000355 N = N->getOperand(N->getNumOperands()-1).getNode();
356 assert(N->getNodeId() == -1 && "Node already inserted!");
357 N->setNodeId(NodeSUnit->NodeNum);
Evan Cheng8239daf2010-11-03 00:45:17 +0000358 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
359 NodeSUnit->isCall = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000360 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000361
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000362 // Scan down to find any glued succs.
Dan Gohman343f0c02008-11-19 23:18:57 +0000363 N = NI;
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +0000364 while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000365 SDValue GlueVal(N, N->getNumValues()-1);
Andrew Trickcd5af072011-02-03 23:00:17 +0000366
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000367 // There are either zero or one users of the Glue result.
368 bool HasGlueUse = false;
Andrew Trickcd5af072011-02-03 23:00:17 +0000369 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
Dan Gohman343f0c02008-11-19 23:18:57 +0000370 UI != E; ++UI)
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000371 if (GlueVal.isOperandOf(*UI)) {
372 HasGlueUse = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000373 assert(N->getNodeId() == -1 && "Node already inserted!");
374 N->setNodeId(NodeSUnit->NodeNum);
375 N = *UI;
Evan Cheng8239daf2010-11-03 00:45:17 +0000376 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
377 NodeSUnit->isCall = true;
Dan Gohman343f0c02008-11-19 23:18:57 +0000378 break;
379 }
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000380 if (!HasGlueUse) break;
Dan Gohman343f0c02008-11-19 23:18:57 +0000381 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000382
Evan Cheng554daa62011-04-26 21:31:35 +0000383 if (NodeSUnit->isCall)
384 CallSUnits.push_back(NodeSUnit);
385
Andrew Trick12f0dc62011-04-14 05:15:06 +0000386 // Schedule zero-latency TokenFactor below any nodes that may increase the
387 // schedule height. Otherwise, ancestors of the TokenFactor may appear to
388 // have false stalls.
389 if (NI->getOpcode() == ISD::TokenFactor)
390 NodeSUnit->isScheduleLow = true;
391
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000392 // If there are glue operands involved, N is now the bottom-most node
393 // of the sequence of nodes that are glued together.
Dan Gohman343f0c02008-11-19 23:18:57 +0000394 // Update the SUnit.
395 NodeSUnit->setNode(N);
396 assert(N->getNodeId() == -1 && "Node already inserted!");
397 N->setNodeId(NodeSUnit->NodeNum);
398
Andrew Trick92e94662011-02-04 03:18:17 +0000399 // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
400 InitNumRegDefsLeft(NodeSUnit);
401
Dan Gohman787782f2008-11-21 01:44:51 +0000402 // Assign the Latency field of NodeSUnit using target-provided information.
Andrew Trick953be892012-03-07 23:00:49 +0000403 computeLatency(NodeSUnit);
Dan Gohman343f0c02008-11-19 23:18:57 +0000404 }
Evan Cheng554daa62011-04-26 21:31:35 +0000405
406 // Find all call operands.
407 while (!CallSUnits.empty()) {
408 SUnit *SU = CallSUnits.pop_back_val();
409 for (const SDNode *SUNode = SU->getNode(); SUNode;
410 SUNode = SUNode->getGluedNode()) {
411 if (SUNode->getOpcode() != ISD::CopyToReg)
412 continue;
413 SDNode *SrcN = SUNode->getOperand(2).getNode();
414 if (isPassiveNode(SrcN)) continue; // Not scheduled.
415 SUnit *SrcSU = &SUnits[SrcN->getNodeId()];
416 SrcSU->isCallOp = true;
417 }
418 }
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000419}
420
421void ScheduleDAGSDNodes::AddSchedEdges() {
Evan Cheng5b1b44892011-07-01 21:01:15 +0000422 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
David Goodwin71046162009-08-13 16:05:04 +0000423
David Goodwindc4bdcd2009-08-19 16:08:58 +0000424 // Check to see if the scheduler cares about latencies.
Andrew Trick953be892012-03-07 23:00:49 +0000425 bool UnitLatencies = forceUnitLatencies();
David Goodwindc4bdcd2009-08-19 16:08:58 +0000426
Dan Gohman343f0c02008-11-19 23:18:57 +0000427 // Pass 2: add the preds, succs, etc.
428 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
429 SUnit *SU = &SUnits[su];
430 SDNode *MainNode = SU->getNode();
Andrew Trickcd5af072011-02-03 23:00:17 +0000431
Dan Gohman343f0c02008-11-19 23:18:57 +0000432 if (MainNode->isMachineOpcode()) {
433 unsigned Opc = MainNode->getMachineOpcode();
Evan Chenge837dea2011-06-28 19:10:37 +0000434 const MCInstrDesc &MCID = TII->get(Opc);
435 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
436 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000437 SU->isTwoAddress = true;
438 break;
439 }
440 }
Evan Chenge837dea2011-06-28 19:10:37 +0000441 if (MCID.isCommutable())
Dan Gohman343f0c02008-11-19 23:18:57 +0000442 SU->isCommutable = true;
443 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000444
Dan Gohman343f0c02008-11-19 23:18:57 +0000445 // Find all predecessors and successors of the group.
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000446 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
Dan Gohman343f0c02008-11-19 23:18:57 +0000447 if (N->isMachineOpcode() &&
Dan Gohman39746672009-03-23 16:10:52 +0000448 TII->get(N->getMachineOpcode()).getImplicitDefs()) {
449 SU->hasPhysRegClobbers = true;
Dan Gohmanbcea8592009-10-10 01:32:21 +0000450 unsigned NumUsed = InstrEmitter::CountResults(N);
Dan Gohman8cccf0e2009-03-23 17:39:36 +0000451 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
452 --NumUsed; // Skip over unused values at the end.
453 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
Dan Gohman39746672009-03-23 16:10:52 +0000454 SU->hasPhysRegDefs = true;
455 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000456
Dan Gohman343f0c02008-11-19 23:18:57 +0000457 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
458 SDNode *OpN = N->getOperand(i).getNode();
459 if (isPassiveNode(OpN)) continue; // Not scheduled.
460 SUnit *OpSU = &SUnits[OpN->getNodeId()];
461 assert(OpSU && "Node has no SUnit!");
462 if (OpSU == SU) continue; // In the same group.
463
Owen Andersone50ed302009-08-10 22:56:29 +0000464 EVT OpVT = N->getOperand(i).getValueType();
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000465 assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
Owen Anderson825b72b2009-08-11 20:47:22 +0000466 bool isChain = OpVT == MVT::Other;
Dan Gohman343f0c02008-11-19 23:18:57 +0000467
468 unsigned PhysReg = 0;
Evan Chengc29a56d2009-01-12 03:19:55 +0000469 int Cost = 1;
Dan Gohman343f0c02008-11-19 23:18:57 +0000470 // Determine if this is a physical register dependency.
Evan Chengc29a56d2009-01-12 03:19:55 +0000471 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
Dan Gohman54e4c362008-12-09 22:54:47 +0000472 assert((PhysReg == 0 || !isChain) &&
473 "Chain dependence via physreg data?");
Evan Chengc29a56d2009-01-12 03:19:55 +0000474 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
475 // emits a copy from the physical register to a virtual register unless
476 // it requires a cross class copy (cost < 0). That means we are only
477 // treating "expensive to copy" register dependency as physical register
478 // dependency. This may change in the future though.
Andrew Trick4cb971c2011-06-15 17:16:12 +0000479 if (Cost >= 0 && !StressSched)
Evan Chengc29a56d2009-01-12 03:19:55 +0000480 PhysReg = 0;
David Goodwin71046162009-08-13 16:05:04 +0000481
Evan Cheng046fa3f2010-05-28 23:26:21 +0000482 // If this is a ctrl dep, latency is 1.
Andrew Trickc558bf32011-04-12 20:14:07 +0000483 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
Andrew Trick87896d92011-04-13 00:38:32 +0000484 // Special-case TokenFactor chains as zero-latency.
485 if(isChain && OpN->getOpcode() == ISD::TokenFactor)
486 OpLatency = 0;
487
Andrew Tricka78d3222012-11-06 03:13:46 +0000488 SDep Dep = isChain ? SDep(OpSU, SDep::Barrier)
489 : SDep(OpSU, SDep::Data, PhysReg);
490 Dep.setLatency(OpLatency);
David Goodwindc4bdcd2009-08-19 16:08:58 +0000491 if (!isChain && !UnitLatencies) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000492 computeOperandLatency(OpN, N, i, Dep);
493 ST.adjustSchedDependency(OpSU, SU, Dep);
David Goodwindc4bdcd2009-08-19 16:08:58 +0000494 }
David Goodwin71046162009-08-13 16:05:04 +0000495
Andrew Tricka78d3222012-11-06 03:13:46 +0000496 if (!SU->addPred(Dep) && !Dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
Andrew Trick92e94662011-02-04 03:18:17 +0000497 // Multiple register uses are combined in the same SUnit. For example,
498 // we could have a set of glued nodes with all their defs consumed by
499 // another set of glued nodes. Register pressure tracking sees this as
500 // a single use, so to keep pressure balanced we reduce the defs.
Andrew Trick4bbf4672011-03-09 19:12:43 +0000501 //
502 // We can't tell (without more book-keeping) if this results from
503 // glued nodes or duplicate operands. As long as we don't reduce
504 // NumRegDefsLeft to zero, we handle the common cases well.
Andrew Trick92e94662011-02-04 03:18:17 +0000505 --OpSU->NumRegDefsLeft;
506 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000507 }
508 }
509 }
510}
511
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000512/// BuildSchedGraph - Build the SUnit graph from the selection dag that we
513/// are input. This SUnit graph is similar to the SelectionDAG, but
514/// excludes nodes that aren't interesting to scheduling, and represents
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000515/// glued together nodes with a single SUnit.
Dan Gohman98976e42009-10-09 23:33:48 +0000516void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
Evan Cheng302ef832010-06-10 02:09:31 +0000517 // Cluster certain nodes which should be scheduled together.
518 ClusterNodes();
Dan Gohmanc9a5b9e2008-12-23 18:36:58 +0000519 // Populate the SUnits array.
520 BuildSchedUnits();
521 // Compute all the scheduling dependencies between nodes.
522 AddSchedEdges();
523}
524
Andrew Trick92e94662011-02-04 03:18:17 +0000525// Initialize NumNodeDefs for the current Node's opcode.
526void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
Eric Christopher29449442011-03-08 19:35:47 +0000527 // Check for phys reg copy.
528 if (!Node)
529 return;
530
Andrew Trick92e94662011-02-04 03:18:17 +0000531 if (!Node->isMachineOpcode()) {
532 if (Node->getOpcode() == ISD::CopyFromReg)
533 NodeNumDefs = 1;
534 else
535 NodeNumDefs = 0;
536 return;
537 }
538 unsigned POpc = Node->getMachineOpcode();
539 if (POpc == TargetOpcode::IMPLICIT_DEF) {
540 // No register need be allocated for this.
541 NodeNumDefs = 0;
542 return;
543 }
544 unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
545 // Some instructions define regs that are not represented in the selection DAG
546 // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
547 NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
548 DefIdx = 0;
549}
550
551// Construct a RegDefIter for this SUnit and find the first valid value.
552ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
553 const ScheduleDAGSDNodes *SD)
554 : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
555 InitNodeNumDefs();
556 Advance();
557}
558
559// Advance to the next valid value defined by the SUnit.
560void ScheduleDAGSDNodes::RegDefIter::Advance() {
561 for (;Node;) { // Visit all glued nodes.
562 for (;DefIdx < NodeNumDefs; ++DefIdx) {
563 if (!Node->hasAnyUseOfValue(DefIdx))
564 continue;
Patrik Hagglund860e7cd2012-12-13 18:45:35 +0000565 ValueType = Node->getSimpleValueType(DefIdx);
Andrew Trick92e94662011-02-04 03:18:17 +0000566 ++DefIdx;
567 return; // Found a normal regdef.
568 }
569 Node = Node->getGluedNode();
570 if (Node == NULL) {
571 return; // No values left to visit.
572 }
573 InitNodeNumDefs();
574 }
575}
576
577void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
578 assert(SU->NumRegDefsLeft == 0 && "expect a new node");
579 for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
580 assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
581 ++SU->NumRegDefsLeft;
582 }
583}
584
Andrew Trick953be892012-03-07 23:00:49 +0000585void ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
Andrew Trick87896d92011-04-13 00:38:32 +0000586 SDNode *N = SU->getNode();
587
588 // TokenFactor operands are considered zero latency, and some schedulers
589 // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
590 // whenever node latency is nonzero.
591 if (N && N->getOpcode() == ISD::TokenFactor) {
592 SU->Latency = 0;
593 return;
594 }
595
Evan Chenge1631682010-05-19 22:42:23 +0000596 // Check to see if the scheduler cares about latencies.
Andrew Trick953be892012-03-07 23:00:49 +0000597 if (forceUnitLatencies()) {
Evan Chenge1631682010-05-19 22:42:23 +0000598 SU->Latency = 1;
599 return;
600 }
601
Evan Cheng3ef1c872010-09-10 01:29:16 +0000602 if (!InstrItins || InstrItins->isEmpty()) {
Andrew Trick5e84e3c2011-03-05 09:18:16 +0000603 if (N && N->isMachineOpcode() &&
604 TII->isHighLatencyDef(N->getMachineOpcode()))
Andrew Tricke0ef5092011-03-05 08:00:22 +0000605 SU->Latency = HighLatencyCycles;
606 else
607 SU->Latency = 1;
Evan Cheng15a16de2010-05-20 06:13:19 +0000608 return;
609 }
Andrew Trickcd5af072011-02-03 23:00:17 +0000610
Dan Gohman343f0c02008-11-19 23:18:57 +0000611 // Compute the latency for the node. We use the sum of the latencies for
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000612 // all nodes glued together into this SUnit.
Dan Gohman343f0c02008-11-19 23:18:57 +0000613 SU->Latency = 0;
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000614 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
Evan Cheng8239daf2010-11-03 00:45:17 +0000615 if (N->isMachineOpcode())
616 SU->Latency += TII->getInstrLatency(InstrItins, N);
Dan Gohman343f0c02008-11-19 23:18:57 +0000617}
618
Andrew Trick953be892012-03-07 23:00:49 +0000619void ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
Evan Cheng15a16de2010-05-20 06:13:19 +0000620 unsigned OpIdx, SDep& dep) const{
621 // Check to see if the scheduler cares about latencies.
Andrew Trick953be892012-03-07 23:00:49 +0000622 if (forceUnitLatencies())
Evan Cheng15a16de2010-05-20 06:13:19 +0000623 return;
624
Evan Cheng15a16de2010-05-20 06:13:19 +0000625 if (dep.getKind() != SDep::Data)
626 return;
627
628 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
Evan Cheng7e2fe912010-10-28 06:47:08 +0000629 if (Use->isMachineOpcode())
630 // Adjust the use operand index by num of defs.
631 OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
Evan Chenga0792de2010-10-06 06:27:31 +0000632 int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
Evan Cheng08975152010-10-29 18:09:28 +0000633 if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
634 !BB->succ_empty()) {
635 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
636 if (TargetRegisterInfo::isVirtualRegister(Reg))
637 // This copy is a liveout value. It is likely coalesced, so reduce the
638 // latency so not to penalize the def.
639 // FIXME: need target specific adjustment here?
640 Latency = (Latency > 1) ? Latency - 1 : 1;
641 }
Evan Cheng3881cb72010-09-29 22:42:35 +0000642 if (Latency >= 0)
643 dep.setLatency(Latency);
Evan Cheng15a16de2010-05-20 06:13:19 +0000644}
645
Dan Gohman343f0c02008-11-19 23:18:57 +0000646void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
Manman Renb720be62012-09-11 22:23:19 +0000647#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Evan Chengc29a56d2009-01-12 03:19:55 +0000648 if (!SU->getNode()) {
David Greene84fa8222010-01-05 01:25:11 +0000649 dbgs() << "PHYS REG COPY\n";
Evan Chengc29a56d2009-01-12 03:19:55 +0000650 return;
651 }
652
653 SU->getNode()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000654 dbgs() << "\n";
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000655 SmallVector<SDNode *, 4> GluedNodes;
656 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
657 GluedNodes.push_back(N);
658 while (!GluedNodes.empty()) {
David Greene84fa8222010-01-05 01:25:11 +0000659 dbgs() << " ";
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000660 GluedNodes.back()->dump(DAG);
David Greene84fa8222010-01-05 01:25:11 +0000661 dbgs() << "\n";
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000662 GluedNodes.pop_back();
Dan Gohman343f0c02008-11-19 23:18:57 +0000663 }
Manman Ren77e300e2012-09-06 19:06:06 +0000664#endif
Dan Gohman343f0c02008-11-19 23:18:57 +0000665}
Dan Gohmanbcea8592009-10-10 01:32:21 +0000666
Manman Renb720be62012-09-11 22:23:19 +0000667#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Andrew Trick73ba69b2012-03-07 05:21:40 +0000668void ScheduleDAGSDNodes::dumpSchedule() const {
669 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
670 if (SUnit *SU = Sequence[i])
671 SU->dump(this);
672 else
673 dbgs() << "**** NOOP ****\n";
674 }
675}
Manman Ren77e300e2012-09-06 19:06:06 +0000676#endif
Andrew Trick73ba69b2012-03-07 05:21:40 +0000677
Andrew Trick4c727202012-03-07 05:21:36 +0000678#ifndef NDEBUG
679/// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
680/// their state is consistent with the nodes listed in Sequence.
681///
682void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
683 unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
684 unsigned Noops = 0;
685 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
686 if (!Sequence[i])
687 ++Noops;
688 assert(Sequence.size() - Noops == ScheduledNodes &&
689 "The number of nodes scheduled doesn't match the expected number!");
690}
691#endif // NDEBUG
692
Evan Chengbfcb3052010-03-25 01:38:16 +0000693namespace {
694 struct OrderSorter {
695 bool operator()(const std::pair<unsigned, MachineInstr*> &A,
696 const std::pair<unsigned, MachineInstr*> &B) {
697 return A.first < B.first;
698 }
699 };
700}
701
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000702/// ProcessSDDbgValues - Process SDDbgValues associated with this node.
Andrew Trickcd5af072011-02-03 23:00:17 +0000703static void ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG,
Devang Patel55d20e82011-01-26 18:20:04 +0000704 InstrEmitter &Emitter,
705 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
706 DenseMap<SDValue, unsigned> &VRBaseMap,
707 unsigned Order) {
708 if (!N->getHasDebugValue())
709 return;
710
711 // Opportunistically insert immediate dbg_value uses, i.e. those with source
712 // order number right after the N.
713 MachineBasicBlock *BB = Emitter.getBlock();
714 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
Benjamin Kramer22a54c12011-06-18 13:13:44 +0000715 ArrayRef<SDDbgValue*> DVs = DAG->GetDbgValues(N);
Devang Patel55d20e82011-01-26 18:20:04 +0000716 for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
717 if (DVs[i]->isInvalidated())
718 continue;
719 unsigned DVOrder = DVs[i]->getOrder();
720 if (!Order || DVOrder == ++Order) {
721 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
722 if (DbgMI) {
723 Orders.push_back(std::make_pair(DVOrder, DbgMI));
724 BB->insert(InsertPos, DbgMI);
725 }
726 DVs[i]->setIsInvalidated();
727 }
728 }
729}
730
Evan Chengbfcb3052010-03-25 01:38:16 +0000731// ProcessSourceNode - Process nodes with source order numbers. These are added
Jim Grosbachd27946d2010-06-30 21:27:56 +0000732// to a vector which EmitSchedule uses to determine how to insert dbg_value
Evan Chengbfcb3052010-03-25 01:38:16 +0000733// instructions in the right order.
734static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG,
735 InstrEmitter &Emitter,
Evan Chengbfcb3052010-03-25 01:38:16 +0000736 DenseMap<SDValue, unsigned> &VRBaseMap,
737 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
738 SmallSet<unsigned, 8> &Seen) {
Andrew Trickdd0fb012013-05-25 03:08:10 +0000739 unsigned Order = N->getIROrder();
Devang Patel39078a82011-01-27 00:13:27 +0000740 if (!Order || !Seen.insert(Order)) {
741 // Process any valid SDDbgValues even if node does not have any order
742 // assigned.
743 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
Evan Chengbfcb3052010-03-25 01:38:16 +0000744 return;
Devang Patel39078a82011-01-27 00:13:27 +0000745 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000746
747 MachineBasicBlock *BB = Emitter.getBlock();
Dan Gohman84023e02010-07-10 09:00:22 +0000748 if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI()) {
Evan Chengbfcb3052010-03-25 01:38:16 +0000749 // Did not insert any instruction.
750 Orders.push_back(std::make_pair(Order, (MachineInstr*)0));
751 return;
752 }
753
Dan Gohman84023e02010-07-10 09:00:22 +0000754 Orders.push_back(std::make_pair(Order, prior(Emitter.getInsertPos())));
Devang Patel55d20e82011-01-26 18:20:04 +0000755 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
Evan Chengbfcb3052010-03-25 01:38:16 +0000756}
757
Andrew Trick84b454d2012-03-07 05:21:44 +0000758void ScheduleDAGSDNodes::
759EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
760 MachineBasicBlock::iterator InsertPos) {
761 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
762 I != E; ++I) {
763 if (I->isCtrl()) continue; // ignore chain preds
764 if (I->getSUnit()->CopyDstRC) {
765 // Copy to physical register.
766 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->getSUnit());
767 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
768 // Find the destination physical register.
769 unsigned Reg = 0;
770 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
771 EE = SU->Succs.end(); II != EE; ++II) {
772 if (II->isCtrl()) continue; // ignore chain preds
773 if (II->getReg()) {
774 Reg = II->getReg();
775 break;
776 }
777 }
778 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
779 .addReg(VRI->second);
780 } else {
781 // Copy from physical register.
782 assert(I->getReg() && "Unknown physical register!");
783 unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
784 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
785 (void)isNew; // Silence compiler warning.
786 assert(isNew && "Node emitted out of order - early");
787 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
788 .addReg(I->getReg());
789 }
790 break;
791 }
792}
Evan Chengbfcb3052010-03-25 01:38:16 +0000793
Andrew Trick84b454d2012-03-07 05:21:44 +0000794/// EmitSchedule - Emit the machine code in scheduled order. Return the new
795/// InsertPos and MachineBasicBlock that contains this insertion
796/// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
797/// not necessarily refer to returned BB. The emitter may split blocks.
Andrew Trick47c14452012-03-07 05:21:52 +0000798MachineBasicBlock *ScheduleDAGSDNodes::
799EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
Dan Gohmanbcea8592009-10-10 01:32:21 +0000800 InstrEmitter Emitter(BB, InsertPos);
801 DenseMap<SDValue, unsigned> VRBaseMap;
802 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
Evan Chengbfcb3052010-03-25 01:38:16 +0000803 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
804 SmallSet<unsigned, 8> Seen;
805 bool HasDbg = DAG->hasDebugValues();
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000806
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000807 // If this is the first BB, emit byval parameter dbg_value's.
808 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
809 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
810 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
811 for (; PDI != PDE; ++PDI) {
Dan Gohman891ff8f2010-04-30 19:35:33 +0000812 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000813 if (DbgMI)
Dan Gohman84023e02010-07-10 09:00:22 +0000814 BB->insert(InsertPos, DbgMI);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000815 }
816 }
817
Dan Gohmanbcea8592009-10-10 01:32:21 +0000818 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
819 SUnit *SU = Sequence[i];
820 if (!SU) {
821 // Null SUnit* is a noop.
Andrew Trick84b454d2012-03-07 05:21:44 +0000822 TII->insertNoop(*Emitter.getBlock(), InsertPos);
Dan Gohmanbcea8592009-10-10 01:32:21 +0000823 continue;
824 }
825
826 // For pre-regalloc scheduling, create instructions corresponding to the
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000827 // SDNode and any glued SDNodes and append them to the block.
Dan Gohmanbcea8592009-10-10 01:32:21 +0000828 if (!SU->getNode()) {
829 // Emit a copy.
Andrew Trick84b454d2012-03-07 05:21:44 +0000830 EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
Dan Gohmanbcea8592009-10-10 01:32:21 +0000831 continue;
832 }
833
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000834 SmallVector<SDNode *, 4> GluedNodes;
Evan Chengd4f75962012-10-17 19:39:36 +0000835 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000836 GluedNodes.push_back(N);
837 while (!GluedNodes.empty()) {
838 SDNode *N = GluedNodes.back();
839 Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000840 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000841 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000842 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000843 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
Chris Lattner29d8f0c2010-12-23 17:24:32 +0000844 GluedNodes.pop_back();
Dan Gohmanbcea8592009-10-10 01:32:21 +0000845 }
846 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
Dan Gohmanaf1d8ca2010-05-01 00:01:06 +0000847 VRBaseMap);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000848 // Remember the source order of the inserted instruction.
Evan Chengbfcb3052010-03-25 01:38:16 +0000849 if (HasDbg)
Dan Gohman891ff8f2010-04-30 19:35:33 +0000850 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
Evan Chengbfcb3052010-03-25 01:38:16 +0000851 Seen);
852 }
853
Dale Johannesenfdb42fa2010-04-26 20:06:49 +0000854 // Insert all the dbg_values which have not already been inserted in source
Evan Chengbfcb3052010-03-25 01:38:16 +0000855 // order sequence.
856 if (HasDbg) {
Dan Gohman84023e02010-07-10 09:00:22 +0000857 MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
Evan Chengbfcb3052010-03-25 01:38:16 +0000858
859 // Sort the source order instructions and use the order to insert debug
860 // values.
861 std::sort(Orders.begin(), Orders.end(), OrderSorter());
862
863 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
864 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
865 // Now emit the rest according to source order.
866 unsigned LastOrder = 0;
Evan Chengbfcb3052010-03-25 01:38:16 +0000867 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
868 unsigned Order = Orders[i].first;
869 MachineInstr *MI = Orders[i].second;
870 // Insert all SDDbgValue's whose order(s) are before "Order".
871 if (!MI)
872 continue;
Evan Chengbfcb3052010-03-25 01:38:16 +0000873 for (; DI != DE &&
874 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
875 if ((*DI)->isInvalidated())
876 continue;
Dan Gohman891ff8f2010-04-30 19:35:33 +0000877 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
Evan Cheng962021b2010-04-26 07:38:55 +0000878 if (DbgMI) {
879 if (!LastOrder)
880 // Insert to start of the BB (after PHIs).
881 BB->insert(BBBegin, DbgMI);
882 else {
Dan Gohmana8dab362010-07-10 22:42:31 +0000883 // Insert at the instruction, which may be in a different
884 // block, if the block was split by a custom inserter.
Evan Cheng962021b2010-04-26 07:38:55 +0000885 MachineBasicBlock::iterator Pos = MI;
Dan Gohmana8dab362010-07-10 22:42:31 +0000886 MI->getParent()->insert(llvm::next(Pos), DbgMI);
Evan Cheng962021b2010-04-26 07:38:55 +0000887 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000888 }
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000889 }
Evan Chengbfcb3052010-03-25 01:38:16 +0000890 LastOrder = Order;
Evan Chengbfcb3052010-03-25 01:38:16 +0000891 }
892 // Add trailing DbgValue's before the terminator. FIXME: May want to add
893 // some of them before one or more conditional branches?
Bill Wendling7bf116a2012-03-14 07:14:25 +0000894 SmallVector<MachineInstr*, 8> DbgMIs;
Evan Chengbfcb3052010-03-25 01:38:16 +0000895 while (DI != DE) {
Bill Wendling7bf116a2012-03-14 07:14:25 +0000896 if (!(*DI)->isInvalidated())
897 if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
898 DbgMIs.push_back(DbgMI);
Evan Chengbfcb3052010-03-25 01:38:16 +0000899 ++DI;
900 }
Bill Wendling7bf116a2012-03-14 07:14:25 +0000901
902 MachineBasicBlock *InsertBB = Emitter.getBlock();
903 MachineBasicBlock::iterator Pos = InsertBB->getFirstTerminator();
904 InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
Dan Gohmanbcea8592009-10-10 01:32:21 +0000905 }
906
Dan Gohmanbcea8592009-10-10 01:32:21 +0000907 InsertPos = Emitter.getInsertPos();
Andrew Trick47c14452012-03-07 05:21:52 +0000908 return Emitter.getBlock();
Dan Gohmanbcea8592009-10-10 01:32:21 +0000909}
Andrew Trick56b94c52012-03-07 00:18:22 +0000910
911/// Return the basic block label.
912std::string ScheduleDAGSDNodes::getDAGName() const {
913 return "sunit-dag." + BB->getFullName();
914}