Prefer SmallVector::append/insert over push_back loops.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAGSDNodes.cpp
1 //===--- 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 #include "ScheduleDAGSDNodes.h"
16 #include "InstrEmitter.h"
17 #include "SDNodeDbgValue.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/MC/MCInstrItineraries.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetLowering.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetSubtargetInfo.h"
34 using namespace llvm;
35
36 #define DEBUG_TYPE "pre-RA-sched"
37
38 STATISTIC(LoadsClustered, "Number of loads clustered together");
39
40 // This allows the latency-based scheduler to notice high latency instructions
41 // without a target itinerary. The choice of number here has more to do with
42 // balancing scheduler heuristics than with the actual machine latency.
43 static 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
48 ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
49     : ScheduleDAG(mf), BB(nullptr), DAG(nullptr),
50       InstrItins(mf.getSubtarget().getInstrItineraryData()) {}
51
52 /// Run - perform scheduling.
53 ///
54 void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
55   BB = bb;
56   DAG = dag;
57
58   // Clear the scheduler's SUnit DAG.
59   ScheduleDAG::clearDAG();
60   Sequence.clear();
61
62   // Invoke the target's selection of scheduler.
63   Schedule();
64 }
65
66 /// NewSUnit - Creates a new SUnit and return a ptr to it.
67 ///
68 SUnit *ScheduleDAGSDNodes::newSUnit(SDNode *N) {
69 #ifndef NDEBUG
70   const SUnit *Addr = nullptr;
71   if (!SUnits.empty())
72     Addr = &SUnits[0];
73 #endif
74   SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
75   assert((Addr == nullptr || 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();
80   if (!N ||
81       (N->isMachineOpcode() &&
82        N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
83     SU->SchedulingPref = Sched::None;
84   else
85     SU->SchedulingPref = TLI.getSchedulingPreference(N);
86   return SU;
87 }
88
89 SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
90   SUnit *SU = newSUnit(Old->getNode());
91   SU->OrigNode = Old->OrigNode;
92   SU->Latency = Old->Latency;
93   SU->isVRegCycle = Old->isVRegCycle;
94   SU->isCall = Old->isCall;
95   SU->isCallOp = Old->isCallOp;
96   SU->isTwoAddress = Old->isTwoAddress;
97   SU->isCommutable = Old->isCommutable;
98   SU->hasPhysRegDefs = Old->hasPhysRegDefs;
99   SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
100   SU->isScheduleHigh = Old->isScheduleHigh;
101   SU->isScheduleLow = Old->isScheduleLow;
102   SU->SchedulingPref = Old->SchedulingPref;
103   Old->isCloned = true;
104   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
109 /// register and the cost of copying the register.
110 static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
111                                       const TargetRegisterInfo *TRI,
112                                       const TargetInstrInfo *TII,
113                                       unsigned &PhysReg, int &Cost) {
114   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->getOpcode() == ISD::CopyFromReg &&
123       cast<RegisterSDNode>(Def->getOperand(1))->getReg() == Reg) {
124     PhysReg = Reg;
125   } else if (Def->isMachineOpcode()) {
126     const MCInstrDesc &II = TII->get(Def->getMachineOpcode());
127     if (ResNo >= II.getNumDefs() &&
128         II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg)
129       PhysReg = Reg;
130   }
131
132   if (PhysReg != 0) {
133     const TargetRegisterClass *RC =
134         TRI->getMinimalPhysRegClass(Reg, Def->getSimpleValueType(ResNo));
135     Cost = RC->getCopyCost();
136   }
137 }
138
139 // Helper for AddGlue to clone node operands.
140 static void CloneNodeWithValues(SDNode *N, SelectionDAG *DAG, ArrayRef<EVT> VTs,
141                                 SDValue ExtraOper = SDValue()) {
142   SmallVector<SDValue, 8> Ops(N->op_begin(), N->op_end());
143   if (ExtraOper.getNode())
144     Ops.push_back(ExtraOper);
145
146   SDVTList VTList = DAG->getVTList(VTs);
147   MachineSDNode::mmo_iterator Begin = nullptr, End = nullptr;
148   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
156   DAG->MorphNodeTo(N, N->getOpcode(), VTList, Ops);
157
158   // Reset the memory references
159   if (MN)
160     MN->setMemRefs(Begin, End);
161 }
162
163 static bool AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
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   SmallVector<EVT, 4> VTs(N->value_begin(), N->value_end());
178   if (AddGlue)
179     VTs.push_back(MVT::Glue);
180
181   CloneNodeWithValues(N, DAG, VTs, Glue);
182
183   return true;
184 }
185
186 // Cleanup after unsuccessful AddGlue. Use the standard method of morphing the
187 // node even though simply shrinking the value list is sufficient.
188 static void RemoveUnusedGlue(SDNode *N, SelectionDAG *DAG) {
189   assert((N->getValueType(N->getNumValues() - 1) == MVT::Glue &&
190           !N->hasAnyUseOfValue(N->getNumValues() - 1)) &&
191          "expected an unused glue value");
192
193   CloneNodeWithValues(N, DAG,
194                       makeArrayRef(N->value_begin(), N->getNumValues() - 1));
195 }
196
197 /// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
198 /// This function finds loads of the same base and different offsets. If the
199 /// offsets are not far apart (target specific), it add MVT::Glue inputs and
200 /// outputs to ensure they are scheduled together and in order. This
201 /// optimization may benefit some targets by improving cache locality.
202 void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
203   SDNode *Chain = nullptr;
204   unsigned NumOps = Node->getNumOperands();
205   if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
206     Chain = Node->getOperand(NumOps-1).getNode();
207   if (!Chain)
208     return;
209
210   // Look for other loads of the same chain. Find loads that are loading from
211   // the same base pointer and different offsets.
212   SmallPtrSet<SDNode*, 16> Visited;
213   SmallVector<int64_t, 4> Offsets;
214   DenseMap<long long, SDNode*> O2SMap;  // Map from offset to SDNode.
215   bool Cluster = false;
216   SDNode *Base = Node;
217   // This algorithm requires a reasonably low use count before finding a match
218   // to avoid uselessly blowing up compile time in large blocks.
219   unsigned UseCount = 0;
220   for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
221        I != E && UseCount < 100; ++I, ++UseCount) {
222     SDNode *User = *I;
223     if (User == Node || !Visited.insert(User).second)
224       continue;
225     int64_t Offset1, Offset2;
226     if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
227         Offset1 == Offset2)
228       // FIXME: Should be ok if they addresses are identical. But earlier
229       // optimizations really should have eliminated one of the loads.
230       continue;
231     if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
232       Offsets.push_back(Offset1);
233     O2SMap.insert(std::make_pair(Offset2, User));
234     Offsets.push_back(Offset2);
235     if (Offset2 < Offset1)
236       Base = User;
237     Cluster = true;
238     // Reset UseCount to allow more matches.
239     UseCount = 0;
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
266   // Cluster loads by adding MVT::Glue outputs and inputs. This also
267   // ensure they are scheduled in order of increasing addresses.
268   SDNode *Lead = Loads[0];
269   SDValue InGlue = SDValue(nullptr, 0);
270   if (AddGlue(Lead, InGlue, true, DAG))
271     InGlue = SDValue(Lead, Lead->getNumValues() - 1);
272   for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
273     bool OutGlue = I < E - 1;
274     SDNode *Load = Loads[I];
275
276     // 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);
281
282       ++LoadsClustered;
283     }
284     else if (!OutGlue && InGlue.getNode())
285       RemoveUnusedGlue(InGlue.getNode(), DAG);
286   }
287 }
288
289 /// ClusterNodes - Cluster certain nodes which should be scheduled together.
290 ///
291 void ScheduleDAGSDNodes::ClusterNodes() {
292   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();
299     const MCInstrDesc &MCID = TII->get(Opc);
300     if (MCID.mayLoad())
301       // Cluster loads from "near" addresses into combined SUnits.
302       ClusterNeighboringLoads(Node);
303   }
304 }
305
306 void ScheduleDAGSDNodes::BuildSchedUnits() {
307   // 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
317   // 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.
320   // FIXME: Multiply by 2 because we may clone nodes during scheduling.
321   // This is a temporary workaround.
322   SUnits.reserve(NumNodes * 2);
323
324   // 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());
329
330   SmallVector<SUnit*, 8> CallSUnits;
331   while (!Worklist.empty()) {
332     SDNode *NI = Worklist.pop_back_val();
333
334     // 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()).second)
337         Worklist.push_back(NI->getOperand(i).getNode());
338
339     if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
340       continue;
341
342     // If this node has already been processed, stop now.
343     if (NI->getNodeId() != -1) continue;
344
345     SUnit *NodeSUnit = newSUnit(NI);
346
347     // 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.
350
351     // Scan up to find glued preds.
352     SDNode *N = NI;
353     while (N->getNumOperands() &&
354            N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
355       N = N->getOperand(N->getNumOperands()-1).getNode();
356       assert(N->getNodeId() == -1 && "Node already inserted!");
357       N->setNodeId(NodeSUnit->NodeNum);
358       if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
359         NodeSUnit->isCall = true;
360     }
361
362     // Scan down to find any glued succs.
363     N = NI;
364     while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
365       SDValue GlueVal(N, N->getNumValues()-1);
366
367       // There are either zero or one users of the Glue result.
368       bool HasGlueUse = false;
369       for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
370            UI != E; ++UI)
371         if (GlueVal.isOperandOf(*UI)) {
372           HasGlueUse = true;
373           assert(N->getNodeId() == -1 && "Node already inserted!");
374           N->setNodeId(NodeSUnit->NodeNum);
375           N = *UI;
376           if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
377             NodeSUnit->isCall = true;
378           break;
379         }
380       if (!HasGlueUse) break;
381     }
382
383     if (NodeSUnit->isCall)
384       CallSUnits.push_back(NodeSUnit);
385
386     // 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
392     // If there are glue operands involved, N is now the bottom-most node
393     // of the sequence of nodes that are glued together.
394     // Update the SUnit.
395     NodeSUnit->setNode(N);
396     assert(N->getNodeId() == -1 && "Node already inserted!");
397     N->setNodeId(NodeSUnit->NodeNum);
398
399     // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
400     InitNumRegDefsLeft(NodeSUnit);
401
402     // Assign the Latency field of NodeSUnit using target-provided information.
403     computeLatency(NodeSUnit);
404   }
405
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   }
419 }
420
421 void ScheduleDAGSDNodes::AddSchedEdges() {
422   const TargetSubtargetInfo &ST = MF.getSubtarget();
423
424   // Check to see if the scheduler cares about latencies.
425   bool UnitLatencies = forceUnitLatencies();
426
427   // 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();
431
432     if (MainNode->isMachineOpcode()) {
433       unsigned Opc = MainNode->getMachineOpcode();
434       const MCInstrDesc &MCID = TII->get(Opc);
435       for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
436         if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
437           SU->isTwoAddress = true;
438           break;
439         }
440       }
441       if (MCID.isCommutable())
442         SU->isCommutable = true;
443     }
444
445     // Find all predecessors and successors of the group.
446     for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
447       if (N->isMachineOpcode() &&
448           TII->get(N->getMachineOpcode()).getImplicitDefs()) {
449         SU->hasPhysRegClobbers = true;
450         unsigned NumUsed = InstrEmitter::CountResults(N);
451         while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
452           --NumUsed;    // Skip over unused values at the end.
453         if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
454           SU->hasPhysRegDefs = true;
455       }
456
457       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
464         EVT OpVT = N->getOperand(i).getValueType();
465         assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
466         bool isChain = OpVT == MVT::Other;
467
468         unsigned PhysReg = 0;
469         int Cost = 1;
470         // Determine if this is a physical register dependency.
471         CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
472         assert((PhysReg == 0 || !isChain) &&
473                "Chain dependence via physreg data?");
474         // 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.
479         if (Cost >= 0 && !StressSched)
480           PhysReg = 0;
481
482         // If this is a ctrl dep, latency is 1.
483         unsigned OpLatency = isChain ? 1 : OpSU->Latency;
484         // Special-case TokenFactor chains as zero-latency.
485         if(isChain && OpN->getOpcode() == ISD::TokenFactor)
486           OpLatency = 0;
487
488         SDep Dep = isChain ? SDep(OpSU, SDep::Barrier)
489           : SDep(OpSU, SDep::Data, PhysReg);
490         Dep.setLatency(OpLatency);
491         if (!isChain && !UnitLatencies) {
492           computeOperandLatency(OpN, N, i, Dep);
493           ST.adjustSchedDependency(OpSU, SU, Dep);
494         }
495
496         if (!SU->addPred(Dep) && !Dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
497           // 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.
501           //
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.
505           --OpSU->NumRegDefsLeft;
506         }
507       }
508     }
509   }
510 }
511
512 /// 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
515 /// glued together nodes with a single SUnit.
516 void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
517   // Cluster certain nodes which should be scheduled together.
518   ClusterNodes();
519   // Populate the SUnits array.
520   BuildSchedUnits();
521   // Compute all the scheduling dependencies between nodes.
522   AddSchedEdges();
523 }
524
525 // Initialize NumNodeDefs for the current Node's opcode.
526 void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
527   // Check for phys reg copy.
528   if (!Node)
529     return;
530
531   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   if (POpc == TargetOpcode::PATCHPOINT &&
545       Node->getValueType(0) == MVT::Other) {
546     // PATCHPOINT is defined to have one result, but it might really have none
547     // if we're not using CallingConv::AnyReg. Don't mistake the chain for a
548     // real definition.
549     NodeNumDefs = 0;
550     return;
551   }
552   unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
553   // Some instructions define regs that are not represented in the selection DAG
554   // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
555   NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
556   DefIdx = 0;
557 }
558
559 // Construct a RegDefIter for this SUnit and find the first valid value.
560 ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
561                                            const ScheduleDAGSDNodes *SD)
562   : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
563   InitNodeNumDefs();
564   Advance();
565 }
566
567 // Advance to the next valid value defined by the SUnit.
568 void ScheduleDAGSDNodes::RegDefIter::Advance() {
569   for (;Node;) { // Visit all glued nodes.
570     for (;DefIdx < NodeNumDefs; ++DefIdx) {
571       if (!Node->hasAnyUseOfValue(DefIdx))
572         continue;
573       ValueType = Node->getSimpleValueType(DefIdx);
574       ++DefIdx;
575       return; // Found a normal regdef.
576     }
577     Node = Node->getGluedNode();
578     if (!Node) {
579       return; // No values left to visit.
580     }
581     InitNodeNumDefs();
582   }
583 }
584
585 void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
586   assert(SU->NumRegDefsLeft == 0 && "expect a new node");
587   for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
588     assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
589     ++SU->NumRegDefsLeft;
590   }
591 }
592
593 void ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
594   SDNode *N = SU->getNode();
595
596   // TokenFactor operands are considered zero latency, and some schedulers
597   // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
598   // whenever node latency is nonzero.
599   if (N && N->getOpcode() == ISD::TokenFactor) {
600     SU->Latency = 0;
601     return;
602   }
603
604   // Check to see if the scheduler cares about latencies.
605   if (forceUnitLatencies()) {
606     SU->Latency = 1;
607     return;
608   }
609
610   if (!InstrItins || InstrItins->isEmpty()) {
611     if (N && N->isMachineOpcode() &&
612         TII->isHighLatencyDef(N->getMachineOpcode()))
613       SU->Latency = HighLatencyCycles;
614     else
615       SU->Latency = 1;
616     return;
617   }
618
619   // Compute the latency for the node.  We use the sum of the latencies for
620   // all nodes glued together into this SUnit.
621   SU->Latency = 0;
622   for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
623     if (N->isMachineOpcode())
624       SU->Latency += TII->getInstrLatency(InstrItins, N);
625 }
626
627 void ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
628                                                unsigned OpIdx, SDep& dep) const{
629   // Check to see if the scheduler cares about latencies.
630   if (forceUnitLatencies())
631     return;
632
633   if (dep.getKind() != SDep::Data)
634     return;
635
636   unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
637   if (Use->isMachineOpcode())
638     // Adjust the use operand index by num of defs.
639     OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
640   int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
641   if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
642       !BB->succ_empty()) {
643     unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
644     if (TargetRegisterInfo::isVirtualRegister(Reg))
645       // This copy is a liveout value. It is likely coalesced, so reduce the
646       // latency so not to penalize the def.
647       // FIXME: need target specific adjustment here?
648       Latency = (Latency > 1) ? Latency - 1 : 1;
649   }
650   if (Latency >= 0)
651     dep.setLatency(Latency);
652 }
653
654 void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
655 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
656   if (!SU->getNode()) {
657     dbgs() << "PHYS REG COPY\n";
658     return;
659   }
660
661   SU->getNode()->dump(DAG);
662   dbgs() << "\n";
663   SmallVector<SDNode *, 4> GluedNodes;
664   for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
665     GluedNodes.push_back(N);
666   while (!GluedNodes.empty()) {
667     dbgs() << "    ";
668     GluedNodes.back()->dump(DAG);
669     dbgs() << "\n";
670     GluedNodes.pop_back();
671   }
672 #endif
673 }
674
675 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
676 void ScheduleDAGSDNodes::dumpSchedule() const {
677   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
678     if (SUnit *SU = Sequence[i])
679       SU->dump(this);
680     else
681       dbgs() << "**** NOOP ****\n";
682   }
683 }
684 #endif
685
686 #ifndef NDEBUG
687 /// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
688 /// their state is consistent with the nodes listed in Sequence.
689 ///
690 void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
691   unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
692   unsigned Noops = 0;
693   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
694     if (!Sequence[i])
695       ++Noops;
696   assert(Sequence.size() - Noops == ScheduledNodes &&
697          "The number of nodes scheduled doesn't match the expected number!");
698 }
699 #endif // NDEBUG
700
701 /// ProcessSDDbgValues - Process SDDbgValues associated with this node.
702 static void
703 ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
704                    SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
705                    DenseMap<SDValue, unsigned> &VRBaseMap, unsigned Order) {
706   if (!N->getHasDebugValue())
707     return;
708
709   // Opportunistically insert immediate dbg_value uses, i.e. those with source
710   // order number right after the N.
711   MachineBasicBlock *BB = Emitter.getBlock();
712   MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
713   ArrayRef<SDDbgValue*> DVs = DAG->GetDbgValues(N);
714   for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
715     if (DVs[i]->isInvalidated())
716       continue;
717     unsigned DVOrder = DVs[i]->getOrder();
718     if (!Order || DVOrder == ++Order) {
719       MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
720       if (DbgMI) {
721         Orders.push_back(std::make_pair(DVOrder, DbgMI));
722         BB->insert(InsertPos, DbgMI);
723       }
724       DVs[i]->setIsInvalidated();
725     }
726   }
727 }
728
729 // ProcessSourceNode - Process nodes with source order numbers. These are added
730 // to a vector which EmitSchedule uses to determine how to insert dbg_value
731 // instructions in the right order.
732 static void
733 ProcessSourceNode(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
734                   DenseMap<SDValue, unsigned> &VRBaseMap,
735                   SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
736                   SmallSet<unsigned, 8> &Seen) {
737   unsigned Order = N->getIROrder();
738   if (!Order || !Seen.insert(Order).second) {
739     // Process any valid SDDbgValues even if node does not have any order
740     // assigned.
741     ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
742     return;
743   }
744
745   MachineBasicBlock *BB = Emitter.getBlock();
746   if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI() ||
747       // Fast-isel may have inserted some instructions, in which case the
748       // BB->back().isPHI() test will not fire when we want it to.
749       std::prev(Emitter.getInsertPos())->isPHI()) {
750     // Did not insert any instruction.
751     Orders.push_back(std::make_pair(Order, (MachineInstr*)nullptr));
752     return;
753   }
754
755   Orders.push_back(std::make_pair(Order, std::prev(Emitter.getInsertPos())));
756   ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
757 }
758
759 void ScheduleDAGSDNodes::
760 EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
761                 MachineBasicBlock::iterator InsertPos) {
762   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
763        I != E; ++I) {
764     if (I->isCtrl()) continue;  // ignore chain preds
765     if (I->getSUnit()->CopyDstRC) {
766       // Copy to physical register.
767       DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->getSUnit());
768       assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
769       // Find the destination physical register.
770       unsigned Reg = 0;
771       for (SUnit::const_succ_iterator II = SU->Succs.begin(),
772              EE = SU->Succs.end(); II != EE; ++II) {
773         if (II->isCtrl()) continue;  // ignore chain preds
774         if (II->getReg()) {
775           Reg = II->getReg();
776           break;
777         }
778       }
779       BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
780         .addReg(VRI->second);
781     } else {
782       // Copy from physical register.
783       assert(I->getReg() && "Unknown physical register!");
784       unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
785       bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
786       (void)isNew; // Silence compiler warning.
787       assert(isNew && "Node emitted out of order - early");
788       BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
789         .addReg(I->getReg());
790     }
791     break;
792   }
793 }
794
795 /// EmitSchedule - Emit the machine code in scheduled order. Return the new
796 /// InsertPos and MachineBasicBlock that contains this insertion
797 /// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
798 /// not necessarily refer to returned BB. The emitter may split blocks.
799 MachineBasicBlock *ScheduleDAGSDNodes::
800 EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
801   InstrEmitter Emitter(BB, InsertPos);
802   DenseMap<SDValue, unsigned> VRBaseMap;
803   DenseMap<SUnit*, unsigned> CopyVRBaseMap;
804   SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
805   SmallSet<unsigned, 8> Seen;
806   bool HasDbg = DAG->hasDebugValues();
807
808   // If this is the first BB, emit byval parameter dbg_value's.
809   if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
810     SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
811     SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
812     for (; PDI != PDE; ++PDI) {
813       MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
814       if (DbgMI)
815         BB->insert(InsertPos, DbgMI);
816     }
817   }
818
819   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
820     SUnit *SU = Sequence[i];
821     if (!SU) {
822       // Null SUnit* is a noop.
823       TII->insertNoop(*Emitter.getBlock(), InsertPos);
824       continue;
825     }
826
827     // For pre-regalloc scheduling, create instructions corresponding to the
828     // SDNode and any glued SDNodes and append them to the block.
829     if (!SU->getNode()) {
830       // Emit a copy.
831       EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
832       continue;
833     }
834
835     SmallVector<SDNode *, 4> GluedNodes;
836     for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
837       GluedNodes.push_back(N);
838     while (!GluedNodes.empty()) {
839       SDNode *N = GluedNodes.back();
840       Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
841                        VRBaseMap);
842       // Remember the source order of the inserted instruction.
843       if (HasDbg)
844         ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
845       GluedNodes.pop_back();
846     }
847     Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
848                      VRBaseMap);
849     // Remember the source order of the inserted instruction.
850     if (HasDbg)
851       ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
852                         Seen);
853   }
854
855   // Insert all the dbg_values which have not already been inserted in source
856   // order sequence.
857   if (HasDbg) {
858     MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
859
860     // Sort the source order instructions and use the order to insert debug
861     // values.
862     std::sort(Orders.begin(), Orders.end(), less_first());
863
864     SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
865     SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
866     // Now emit the rest according to source order.
867     unsigned LastOrder = 0;
868     for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
869       unsigned Order = Orders[i].first;
870       MachineInstr *MI = Orders[i].second;
871       // Insert all SDDbgValue's whose order(s) are before "Order".
872       if (!MI)
873         continue;
874       for (; DI != DE &&
875              (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
876         if ((*DI)->isInvalidated())
877           continue;
878         MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
879         if (DbgMI) {
880           if (!LastOrder)
881             // Insert to start of the BB (after PHIs).
882             BB->insert(BBBegin, DbgMI);
883           else {
884             // Insert at the instruction, which may be in a different
885             // block, if the block was split by a custom inserter.
886             MachineBasicBlock::iterator Pos = MI;
887             MI->getParent()->insert(Pos, DbgMI);
888           }
889         }
890       }
891       LastOrder = Order;
892     }
893     // Add trailing DbgValue's before the terminator. FIXME: May want to add
894     // some of them before one or more conditional branches?
895     SmallVector<MachineInstr*, 8> DbgMIs;
896     while (DI != DE) {
897       if (!(*DI)->isInvalidated())
898         if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
899           DbgMIs.push_back(DbgMI);
900       ++DI;
901     }
902
903     MachineBasicBlock *InsertBB = Emitter.getBlock();
904     MachineBasicBlock::iterator Pos = InsertBB->getFirstTerminator();
905     InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
906   }
907
908   InsertPos = Emitter.getInsertPos();
909   return Emitter.getBlock();
910 }
911
912 /// Return the basic block label.
913 std::string ScheduleDAGSDNodes::getDAGName() const {
914   return "sunit-dag." + BB->getFullName();
915 }