1193323Sed//===--- ScheduleDAGSDNodes.cpp - Implement the ScheduleDAGSDNodes class --===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This implements the ScheduleDAG class, which is a base class used by
11193323Sed// scheduling implementation classes.
12193323Sed//
13193323Sed//===----------------------------------------------------------------------===//
14193323Sed
15193323Sed#include "ScheduleDAGSDNodes.h"
16198090Srdivacky#include "InstrEmitter.h"
17249423Sdim#include "SDNodeDbgValue.h"
18202878Srdivacky#include "llvm/ADT/DenseMap.h"
19202878Srdivacky#include "llvm/ADT/SmallPtrSet.h"
20206083Srdivacky#include "llvm/ADT/SmallSet.h"
21202878Srdivacky#include "llvm/ADT/SmallVector.h"
22202878Srdivacky#include "llvm/ADT/Statistic.h"
23249423Sdim#include "llvm/CodeGen/MachineInstrBuilder.h"
24249423Sdim#include "llvm/CodeGen/MachineRegisterInfo.h"
25249423Sdim#include "llvm/CodeGen/SelectionDAG.h"
26249423Sdim#include "llvm/MC/MCInstrItineraries.h"
27221345Sdim#include "llvm/Support/CommandLine.h"
28193323Sed#include "llvm/Support/Debug.h"
29193323Sed#include "llvm/Support/raw_ostream.h"
30249423Sdim#include "llvm/Target/TargetInstrInfo.h"
31249423Sdim#include "llvm/Target/TargetLowering.h"
32249423Sdim#include "llvm/Target/TargetRegisterInfo.h"
33249423Sdim#include "llvm/Target/TargetSubtargetInfo.h"
34193323Sedusing namespace llvm;
35193323Sed
36276479Sdim#define DEBUG_TYPE "pre-RA-sched"
37276479Sdim
38202878SrdivackySTATISTIC(LoadsClustered, "Number of loads clustered together");
39202878Srdivacky
40280031Sdim// This allows the latency-based scheduler to notice high latency instructions
41280031Sdim// without a target itinerary. The choice of number here has more to do with
42280031Sdim// balancing scheduler heuristics than with the actual machine latency.
43221345Sdimstatic cl::opt<int> HighLatencyCycles(
44221345Sdim  "sched-high-latency-cycles", cl::Hidden, cl::init(10),
45221345Sdim  cl::desc("Roughly estimate the number of cycles that 'long latency'"
46221345Sdim           "instructions take for targets with no itinerary"));
47221345Sdim
48193323SedScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
49280031Sdim    : ScheduleDAG(mf), BB(nullptr), DAG(nullptr),
50280031Sdim      InstrItins(mf.getSubtarget().getInstrItineraryData()) {}
51193323Sed
52193323Sed/// Run - perform scheduling.
53193323Sed///
54234353Sdimvoid ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
55234353Sdim  BB = bb;
56193323Sed  DAG = dag;
57234353Sdim
58234353Sdim  // Clear the scheduler's SUnit DAG.
59234353Sdim  ScheduleDAG::clearDAG();
60234353Sdim  Sequence.clear();
61234353Sdim
62234353Sdim  // Invoke the target's selection of scheduler.
63234353Sdim  Schedule();
64193323Sed}
65193323Sed
66208599Srdivacky/// NewSUnit - Creates a new SUnit and return a ptr to it.
67208599Srdivacky///
68234353SdimSUnit *ScheduleDAGSDNodes::newSUnit(SDNode *N) {
69208599Srdivacky#ifndef NDEBUG
70276479Sdim  const SUnit *Addr = nullptr;
71208599Srdivacky  if (!SUnits.empty())
72208599Srdivacky    Addr = &SUnits[0];
73208599Srdivacky#endif
74288943Sdim  SUnits.emplace_back(N, (unsigned)SUnits.size());
75276479Sdim  assert((Addr == nullptr || Addr == &SUnits[0]) &&
76208599Srdivacky         "SUnits std::vector reallocated on the fly!");
77208599Srdivacky  SUnits.back().OrigNode = &SUnits.back();
78208599Srdivacky  SUnit *SU = &SUnits.back();
79208599Srdivacky  const TargetLowering &TLI = DAG->getTargetLoweringInfo();
80212904Sdim  if (!N ||
81212904Sdim      (N->isMachineOpcode() &&
82212904Sdim       N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
83210299Sed    SU->SchedulingPref = Sched::None;
84210299Sed  else
85210299Sed    SU->SchedulingPref = TLI.getSchedulingPreference(N);
86208599Srdivacky  return SU;
87208599Srdivacky}
88208599Srdivacky
89193323SedSUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
90234353Sdim  SUnit *SU = newSUnit(Old->getNode());
91193323Sed  SU->OrigNode = Old->OrigNode;
92193323Sed  SU->Latency = Old->Latency;
93221345Sdim  SU->isVRegCycle = Old->isVRegCycle;
94218893Sdim  SU->isCall = Old->isCall;
95221345Sdim  SU->isCallOp = Old->isCallOp;
96193323Sed  SU->isTwoAddress = Old->isTwoAddress;
97193323Sed  SU->isCommutable = Old->isCommutable;
98193323Sed  SU->hasPhysRegDefs = Old->hasPhysRegDefs;
99193323Sed  SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
100221345Sdim  SU->isScheduleHigh = Old->isScheduleHigh;
101221345Sdim  SU->isScheduleLow = Old->isScheduleLow;
102208599Srdivacky  SU->SchedulingPref = Old->SchedulingPref;
103193323Sed  Old->isCloned = true;
104193323Sed  return SU;
105193323Sed}
106193323Sed
107193323Sed/// CheckForPhysRegDependency - Check if the dependency between def and use of
108193323Sed/// a specified operand is a physical register dependency. If so, returns the
109193323Sed/// register and the cost of copying the register.
110193323Sedstatic void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
111218893Sdim                                      const TargetRegisterInfo *TRI,
112193323Sed                                      const TargetInstrInfo *TII,
113193323Sed                                      unsigned &PhysReg, int &Cost) {
114193323Sed  if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
115193323Sed    return;
116193323Sed
117193323Sed  unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
118193323Sed  if (TargetRegisterInfo::isVirtualRegister(Reg))
119193323Sed    return;
120193323Sed
121193323Sed  unsigned ResNo = User->getOperand(2).getResNo();
122280031Sdim  if (Def->getOpcode() == ISD::CopyFromReg &&
123280031Sdim      cast<RegisterSDNode>(Def->getOperand(1))->getReg() == Reg) {
124280031Sdim    PhysReg = Reg;
125280031Sdim  } else if (Def->isMachineOpcode()) {
126224145Sdim    const MCInstrDesc &II = TII->get(Def->getMachineOpcode());
127193323Sed    if (ResNo >= II.getNumDefs() &&
128280031Sdim        II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg)
129193323Sed      PhysReg = Reg;
130193323Sed  }
131280031Sdim
132280031Sdim  if (PhysReg != 0) {
133280031Sdim    const TargetRegisterClass *RC =
134280031Sdim        TRI->getMinimalPhysRegClass(Reg, Def->getSimpleValueType(ResNo));
135280031Sdim    Cost = RC->getCopyCost();
136280031Sdim  }
137193323Sed}
138193323Sed
139235864Sdim// Helper for AddGlue to clone node operands.
140288943Sdimstatic void CloneNodeWithValues(SDNode *N, SelectionDAG *DAG, ArrayRef<EVT> VTs,
141235864Sdim                                SDValue ExtraOper = SDValue()) {
142288943Sdim  SmallVector<SDValue, 8> Ops(N->op_begin(), N->op_end());
143235864Sdim  if (ExtraOper.getNode())
144235864Sdim    Ops.push_back(ExtraOper);
145210299Sed
146276479Sdim  SDVTList VTList = DAG->getVTList(VTs);
147276479Sdim  MachineSDNode::mmo_iterator Begin = nullptr, End = nullptr;
148210299Sed  MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
149210299Sed
150210299Sed  // Store memory references.
151210299Sed  if (MN) {
152210299Sed    Begin = MN->memoperands_begin();
153210299Sed    End = MN->memoperands_end();
154210299Sed  }
155210299Sed
156276479Sdim  DAG->MorphNodeTo(N, N->getOpcode(), VTList, Ops);
157210299Sed
158210299Sed  // Reset the memory references
159210299Sed  if (MN)
160210299Sed    MN->setMemRefs(Begin, End);
161202878Srdivacky}
162202878Srdivacky
163235864Sdimstatic bool AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
164235864Sdim  SDNode *GlueDestNode = Glue.getNode();
165235864Sdim
166235864Sdim  // Don't add glue from a node to itself.
167235864Sdim  if (GlueDestNode == N) return false;
168235864Sdim
169235864Sdim  // Don't add a glue operand to something that already uses glue.
170235864Sdim  if (GlueDestNode &&
171235864Sdim      N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
172235864Sdim    return false;
173235864Sdim  }
174235864Sdim  // Don't add glue to something that already has a glue value.
175235864Sdim  if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return false;
176235864Sdim
177288943Sdim  SmallVector<EVT, 4> VTs(N->value_begin(), N->value_end());
178235864Sdim  if (AddGlue)
179235864Sdim    VTs.push_back(MVT::Glue);
180235864Sdim
181235864Sdim  CloneNodeWithValues(N, DAG, VTs, Glue);
182235864Sdim
183235864Sdim  return true;
184235864Sdim}
185235864Sdim
186235864Sdim// Cleanup after unsuccessful AddGlue. Use the standard method of morphing the
187235864Sdim// node even though simply shrinking the value list is sufficient.
188235864Sdimstatic void RemoveUnusedGlue(SDNode *N, SelectionDAG *DAG) {
189235864Sdim  assert((N->getValueType(N->getNumValues() - 1) == MVT::Glue &&
190235864Sdim          !N->hasAnyUseOfValue(N->getNumValues() - 1)) &&
191235864Sdim         "expected an unused glue value");
192235864Sdim
193288943Sdim  CloneNodeWithValues(N, DAG,
194288943Sdim                      makeArrayRef(N->value_begin(), N->getNumValues() - 1));
195235864Sdim}
196235864Sdim
197218893Sdim/// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
198202878Srdivacky/// This function finds loads of the same base and different offsets. If the
199218893Sdim/// offsets are not far apart (target specific), it add MVT::Glue inputs and
200202878Srdivacky/// outputs to ensure they are scheduled together and in order. This
201202878Srdivacky/// optimization may benefit some targets by improving cache locality.
202210299Sedvoid ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
203276479Sdim  SDNode *Chain = nullptr;
204210299Sed  unsigned NumOps = Node->getNumOperands();
205210299Sed  if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
206210299Sed    Chain = Node->getOperand(NumOps-1).getNode();
207210299Sed  if (!Chain)
208210299Sed    return;
209210299Sed
210210299Sed  // Look for other loads of the same chain. Find loads that are loading from
211210299Sed  // the same base pointer and different offsets.
212202878Srdivacky  SmallPtrSet<SDNode*, 16> Visited;
213202878Srdivacky  SmallVector<int64_t, 4> Offsets;
214202878Srdivacky  DenseMap<long long, SDNode*> O2SMap;  // Map from offset to SDNode.
215210299Sed  bool Cluster = false;
216210299Sed  SDNode *Base = Node;
217265925Sdim  // This algorithm requires a reasonably low use count before finding a match
218265925Sdim  // to avoid uselessly blowing up compile time in large blocks.
219265925Sdim  unsigned UseCount = 0;
220210299Sed  for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
221265925Sdim       I != E && UseCount < 100; ++I, ++UseCount) {
222210299Sed    SDNode *User = *I;
223280031Sdim    if (User == Node || !Visited.insert(User).second)
224202878Srdivacky      continue;
225210299Sed    int64_t Offset1, Offset2;
226210299Sed    if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
227210299Sed        Offset1 == Offset2)
228210299Sed      // FIXME: Should be ok if they addresses are identical. But earlier
229210299Sed      // optimizations really should have eliminated one of the loads.
230202878Srdivacky      continue;
231210299Sed    if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
232210299Sed      Offsets.push_back(Offset1);
233210299Sed    O2SMap.insert(std::make_pair(Offset2, User));
234210299Sed    Offsets.push_back(Offset2);
235210299Sed    if (Offset2 < Offset1)
236210299Sed      Base = User;
237210299Sed    Cluster = true;
238265925Sdim    // Reset UseCount to allow more matches.
239265925Sdim    UseCount = 0;
240210299Sed  }
241202878Srdivacky
242210299Sed  if (!Cluster)
243210299Sed    return;
244202878Srdivacky
245210299Sed  // Sort them in increasing order.
246210299Sed  std::sort(Offsets.begin(), Offsets.end());
247202878Srdivacky
248210299Sed  // Check if the loads are close enough.
249210299Sed  SmallVector<SDNode*, 4> Loads;
250210299Sed  unsigned NumLoads = 0;
251210299Sed  int64_t BaseOff = Offsets[0];
252210299Sed  SDNode *BaseLoad = O2SMap[BaseOff];
253210299Sed  Loads.push_back(BaseLoad);
254210299Sed  for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
255210299Sed    int64_t Offset = Offsets[i];
256210299Sed    SDNode *Load = O2SMap[Offset];
257210299Sed    if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
258210299Sed      break; // Stop right here. Ignore loads that are further away.
259210299Sed    Loads.push_back(Load);
260210299Sed    ++NumLoads;
261210299Sed  }
262202878Srdivacky
263210299Sed  if (NumLoads == 0)
264210299Sed    return;
265202878Srdivacky
266218893Sdim  // Cluster loads by adding MVT::Glue outputs and inputs. This also
267210299Sed  // ensure they are scheduled in order of increasing addresses.
268210299Sed  SDNode *Lead = Loads[0];
269276479Sdim  SDValue InGlue = SDValue(nullptr, 0);
270235864Sdim  if (AddGlue(Lead, InGlue, true, DAG))
271235864Sdim    InGlue = SDValue(Lead, Lead->getNumValues() - 1);
272210299Sed  for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
273218893Sdim    bool OutGlue = I < E - 1;
274210299Sed    SDNode *Load = Loads[I];
275210299Sed
276235864Sdim    // If AddGlue fails, we could leave an unsused glue value. This should not
277235864Sdim    // cause any
278235864Sdim    if (AddGlue(Load, InGlue, OutGlue, DAG)) {
279235864Sdim      if (OutGlue)
280235864Sdim        InGlue = SDValue(Load, Load->getNumValues() - 1);
281210299Sed
282235864Sdim      ++LoadsClustered;
283235864Sdim    }
284235864Sdim    else if (!OutGlue && InGlue.getNode())
285235864Sdim      RemoveUnusedGlue(InGlue.getNode(), DAG);
286210299Sed  }
287210299Sed}
288210299Sed
289210299Sed/// ClusterNodes - Cluster certain nodes which should be scheduled together.
290210299Sed///
291210299Sedvoid ScheduleDAGSDNodes::ClusterNodes() {
292288943Sdim  for (SDNode &NI : DAG->allnodes()) {
293288943Sdim    SDNode *Node = &NI;
294210299Sed    if (!Node || !Node->isMachineOpcode())
295202878Srdivacky      continue;
296202878Srdivacky
297210299Sed    unsigned Opc = Node->getMachineOpcode();
298224145Sdim    const MCInstrDesc &MCID = TII->get(Opc);
299224145Sdim    if (MCID.mayLoad())
300210299Sed      // Cluster loads from "near" addresses into combined SUnits.
301210299Sed      ClusterNeighboringLoads(Node);
302202878Srdivacky  }
303202878Srdivacky}
304202878Srdivacky
305193323Sedvoid ScheduleDAGSDNodes::BuildSchedUnits() {
306193323Sed  // During scheduling, the NodeId field of SDNode is used to map SDNodes
307193323Sed  // to their associated SUnits by holding SUnits table indices. A value
308193323Sed  // of -1 means the SDNode does not yet have an associated SUnit.
309193323Sed  unsigned NumNodes = 0;
310288943Sdim  for (SDNode &NI : DAG->allnodes()) {
311288943Sdim    NI.setNodeId(-1);
312193323Sed    ++NumNodes;
313193323Sed  }
314193323Sed
315193323Sed  // Reserve entries in the vector for each of the SUnits we are creating.  This
316193323Sed  // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
317193323Sed  // invalidated.
318193323Sed  // FIXME: Multiply by 2 because we may clone nodes during scheduling.
319193323Sed  // This is a temporary workaround.
320193323Sed  SUnits.reserve(NumNodes * 2);
321218893Sdim
322204642Srdivacky  // Add all nodes in depth first order.
323204642Srdivacky  SmallVector<SDNode*, 64> Worklist;
324204642Srdivacky  SmallPtrSet<SDNode*, 64> Visited;
325204642Srdivacky  Worklist.push_back(DAG->getRoot().getNode());
326204642Srdivacky  Visited.insert(DAG->getRoot().getNode());
327218893Sdim
328221345Sdim  SmallVector<SUnit*, 8> CallSUnits;
329204642Srdivacky  while (!Worklist.empty()) {
330204642Srdivacky    SDNode *NI = Worklist.pop_back_val();
331218893Sdim
332204642Srdivacky    // Add all operands to the worklist unless they've already been added.
333288943Sdim    for (const SDValue &Op : NI->op_values())
334288943Sdim      if (Visited.insert(Op.getNode()).second)
335288943Sdim        Worklist.push_back(Op.getNode());
336218893Sdim
337193323Sed    if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
338193323Sed      continue;
339218893Sdim
340193323Sed    // If this node has already been processed, stop now.
341193323Sed    if (NI->getNodeId() != -1) continue;
342218893Sdim
343234353Sdim    SUnit *NodeSUnit = newSUnit(NI);
344218893Sdim
345218893Sdim    // See if anything is glued to this node, if so, add them to glued
346218893Sdim    // nodes.  Nodes can have at most one glue input and one glue output.  Glue
347218893Sdim    // is required to be the last operand and result of a node.
348218893Sdim
349218893Sdim    // Scan up to find glued preds.
350193323Sed    SDNode *N = NI;
351193323Sed    while (N->getNumOperands() &&
352218893Sdim           N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
353193323Sed      N = N->getOperand(N->getNumOperands()-1).getNode();
354193323Sed      assert(N->getNodeId() == -1 && "Node already inserted!");
355193323Sed      N->setNodeId(NodeSUnit->NodeNum);
356218893Sdim      if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
357218893Sdim        NodeSUnit->isCall = true;
358193323Sed    }
359218893Sdim
360218893Sdim    // Scan down to find any glued succs.
361193323Sed    N = NI;
362218893Sdim    while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
363218893Sdim      SDValue GlueVal(N, N->getNumValues()-1);
364218893Sdim
365218893Sdim      // There are either zero or one users of the Glue result.
366218893Sdim      bool HasGlueUse = false;
367218893Sdim      for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
368193323Sed           UI != E; ++UI)
369218893Sdim        if (GlueVal.isOperandOf(*UI)) {
370218893Sdim          HasGlueUse = true;
371193323Sed          assert(N->getNodeId() == -1 && "Node already inserted!");
372193323Sed          N->setNodeId(NodeSUnit->NodeNum);
373193323Sed          N = *UI;
374218893Sdim          if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
375218893Sdim            NodeSUnit->isCall = true;
376193323Sed          break;
377193323Sed        }
378218893Sdim      if (!HasGlueUse) break;
379193323Sed    }
380218893Sdim
381221345Sdim    if (NodeSUnit->isCall)
382221345Sdim      CallSUnits.push_back(NodeSUnit);
383221345Sdim
384221345Sdim    // Schedule zero-latency TokenFactor below any nodes that may increase the
385221345Sdim    // schedule height. Otherwise, ancestors of the TokenFactor may appear to
386221345Sdim    // have false stalls.
387221345Sdim    if (NI->getOpcode() == ISD::TokenFactor)
388221345Sdim      NodeSUnit->isScheduleLow = true;
389221345Sdim
390218893Sdim    // If there are glue operands involved, N is now the bottom-most node
391218893Sdim    // of the sequence of nodes that are glued together.
392193323Sed    // Update the SUnit.
393193323Sed    NodeSUnit->setNode(N);
394193323Sed    assert(N->getNodeId() == -1 && "Node already inserted!");
395193323Sed    N->setNodeId(NodeSUnit->NodeNum);
396193323Sed
397218893Sdim    // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
398218893Sdim    InitNumRegDefsLeft(NodeSUnit);
399218893Sdim
400193323Sed    // Assign the Latency field of NodeSUnit using target-provided information.
401234353Sdim    computeLatency(NodeSUnit);
402193323Sed  }
403221345Sdim
404221345Sdim  // Find all call operands.
405221345Sdim  while (!CallSUnits.empty()) {
406221345Sdim    SUnit *SU = CallSUnits.pop_back_val();
407221345Sdim    for (const SDNode *SUNode = SU->getNode(); SUNode;
408221345Sdim         SUNode = SUNode->getGluedNode()) {
409221345Sdim      if (SUNode->getOpcode() != ISD::CopyToReg)
410221345Sdim        continue;
411221345Sdim      SDNode *SrcN = SUNode->getOperand(2).getNode();
412221345Sdim      if (isPassiveNode(SrcN)) continue;   // Not scheduled.
413221345Sdim      SUnit *SrcSU = &SUnits[SrcN->getNodeId()];
414221345Sdim      SrcSU->isCallOp = true;
415221345Sdim    }
416221345Sdim  }
417193323Sed}
418193323Sed
419193323Sedvoid ScheduleDAGSDNodes::AddSchedEdges() {
420280031Sdim  const TargetSubtargetInfo &ST = MF.getSubtarget();
421198090Srdivacky
422198090Srdivacky  // Check to see if the scheduler cares about latencies.
423234353Sdim  bool UnitLatencies = forceUnitLatencies();
424198090Srdivacky
425193323Sed  // Pass 2: add the preds, succs, etc.
426193323Sed  for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
427193323Sed    SUnit *SU = &SUnits[su];
428193323Sed    SDNode *MainNode = SU->getNode();
429218893Sdim
430193323Sed    if (MainNode->isMachineOpcode()) {
431193323Sed      unsigned Opc = MainNode->getMachineOpcode();
432224145Sdim      const MCInstrDesc &MCID = TII->get(Opc);
433224145Sdim      for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
434224145Sdim        if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
435193323Sed          SU->isTwoAddress = true;
436193323Sed          break;
437193323Sed        }
438193323Sed      }
439224145Sdim      if (MCID.isCommutable())
440193323Sed        SU->isCommutable = true;
441193323Sed    }
442218893Sdim
443193323Sed    // Find all predecessors and successors of the group.
444218893Sdim    for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
445193323Sed      if (N->isMachineOpcode() &&
446193323Sed          TII->get(N->getMachineOpcode()).getImplicitDefs()) {
447193323Sed        SU->hasPhysRegClobbers = true;
448198090Srdivacky        unsigned NumUsed = InstrEmitter::CountResults(N);
449193323Sed        while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
450193323Sed          --NumUsed;    // Skip over unused values at the end.
451193323Sed        if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
452193323Sed          SU->hasPhysRegDefs = true;
453193323Sed      }
454218893Sdim
455193323Sed      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
456193323Sed        SDNode *OpN = N->getOperand(i).getNode();
457193323Sed        if (isPassiveNode(OpN)) continue;   // Not scheduled.
458193323Sed        SUnit *OpSU = &SUnits[OpN->getNodeId()];
459193323Sed        assert(OpSU && "Node has no SUnit!");
460193323Sed        if (OpSU == SU) continue;           // In the same group.
461193323Sed
462198090Srdivacky        EVT OpVT = N->getOperand(i).getValueType();
463218893Sdim        assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
464193323Sed        bool isChain = OpVT == MVT::Other;
465193323Sed
466193323Sed        unsigned PhysReg = 0;
467193323Sed        int Cost = 1;
468193323Sed        // Determine if this is a physical register dependency.
469193323Sed        CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
470193323Sed        assert((PhysReg == 0 || !isChain) &&
471193323Sed               "Chain dependence via physreg data?");
472193323Sed        // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
473193323Sed        // emits a copy from the physical register to a virtual register unless
474193323Sed        // it requires a cross class copy (cost < 0). That means we are only
475193323Sed        // treating "expensive to copy" register dependency as physical register
476193323Sed        // dependency. This may change in the future though.
477224145Sdim        if (Cost >= 0 && !StressSched)
478193323Sed          PhysReg = 0;
479198090Srdivacky
480210299Sed        // If this is a ctrl dep, latency is 1.
481210299Sed        unsigned OpLatency = isChain ? 1 : OpSU->Latency;
482221345Sdim        // Special-case TokenFactor chains as zero-latency.
483221345Sdim        if(isChain && OpN->getOpcode() == ISD::TokenFactor)
484221345Sdim          OpLatency = 0;
485221345Sdim
486243830Sdim        SDep Dep = isChain ? SDep(OpSU, SDep::Barrier)
487243830Sdim          : SDep(OpSU, SDep::Data, PhysReg);
488243830Sdim        Dep.setLatency(OpLatency);
489198090Srdivacky        if (!isChain && !UnitLatencies) {
490243830Sdim          computeOperandLatency(OpN, N, i, Dep);
491243830Sdim          ST.adjustSchedDependency(OpSU, SU, Dep);
492198090Srdivacky        }
493198090Srdivacky
494243830Sdim        if (!SU->addPred(Dep) && !Dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
495218893Sdim          // Multiple register uses are combined in the same SUnit. For example,
496218893Sdim          // we could have a set of glued nodes with all their defs consumed by
497218893Sdim          // another set of glued nodes. Register pressure tracking sees this as
498218893Sdim          // a single use, so to keep pressure balanced we reduce the defs.
499221345Sdim          //
500221345Sdim          // We can't tell (without more book-keeping) if this results from
501221345Sdim          // glued nodes or duplicate operands. As long as we don't reduce
502221345Sdim          // NumRegDefsLeft to zero, we handle the common cases well.
503218893Sdim          --OpSU->NumRegDefsLeft;
504218893Sdim        }
505193323Sed      }
506193323Sed    }
507193323Sed  }
508193323Sed}
509193323Sed
510193323Sed/// BuildSchedGraph - Build the SUnit graph from the selection dag that we
511193323Sed/// are input.  This SUnit graph is similar to the SelectionDAG, but
512193323Sed/// excludes nodes that aren't interesting to scheduling, and represents
513218893Sdim/// glued together nodes with a single SUnit.
514198090Srdivackyvoid ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
515210299Sed  // Cluster certain nodes which should be scheduled together.
516210299Sed  ClusterNodes();
517193323Sed  // Populate the SUnits array.
518193323Sed  BuildSchedUnits();
519193323Sed  // Compute all the scheduling dependencies between nodes.
520193323Sed  AddSchedEdges();
521193323Sed}
522193323Sed
523218893Sdim// Initialize NumNodeDefs for the current Node's opcode.
524218893Sdimvoid ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
525221345Sdim  // Check for phys reg copy.
526221345Sdim  if (!Node)
527221345Sdim    return;
528221345Sdim
529218893Sdim  if (!Node->isMachineOpcode()) {
530218893Sdim    if (Node->getOpcode() == ISD::CopyFromReg)
531218893Sdim      NodeNumDefs = 1;
532218893Sdim    else
533218893Sdim      NodeNumDefs = 0;
534218893Sdim    return;
535218893Sdim  }
536218893Sdim  unsigned POpc = Node->getMachineOpcode();
537218893Sdim  if (POpc == TargetOpcode::IMPLICIT_DEF) {
538218893Sdim    // No register need be allocated for this.
539218893Sdim    NodeNumDefs = 0;
540218893Sdim    return;
541218893Sdim  }
542280031Sdim  if (POpc == TargetOpcode::PATCHPOINT &&
543280031Sdim      Node->getValueType(0) == MVT::Other) {
544280031Sdim    // PATCHPOINT is defined to have one result, but it might really have none
545280031Sdim    // if we're not using CallingConv::AnyReg. Don't mistake the chain for a
546280031Sdim    // real definition.
547280031Sdim    NodeNumDefs = 0;
548280031Sdim    return;
549280031Sdim  }
550218893Sdim  unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
551218893Sdim  // Some instructions define regs that are not represented in the selection DAG
552218893Sdim  // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
553218893Sdim  NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
554218893Sdim  DefIdx = 0;
555218893Sdim}
556218893Sdim
557218893Sdim// Construct a RegDefIter for this SUnit and find the first valid value.
558218893SdimScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
559218893Sdim                                           const ScheduleDAGSDNodes *SD)
560218893Sdim  : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
561218893Sdim  InitNodeNumDefs();
562218893Sdim  Advance();
563218893Sdim}
564218893Sdim
565218893Sdim// Advance to the next valid value defined by the SUnit.
566218893Sdimvoid ScheduleDAGSDNodes::RegDefIter::Advance() {
567218893Sdim  for (;Node;) { // Visit all glued nodes.
568218893Sdim    for (;DefIdx < NodeNumDefs; ++DefIdx) {
569218893Sdim      if (!Node->hasAnyUseOfValue(DefIdx))
570218893Sdim        continue;
571249423Sdim      ValueType = Node->getSimpleValueType(DefIdx);
572218893Sdim      ++DefIdx;
573218893Sdim      return; // Found a normal regdef.
574218893Sdim    }
575218893Sdim    Node = Node->getGluedNode();
576276479Sdim    if (!Node) {
577218893Sdim      return; // No values left to visit.
578218893Sdim    }
579218893Sdim    InitNodeNumDefs();
580218893Sdim  }
581218893Sdim}
582218893Sdim
583218893Sdimvoid ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
584218893Sdim  assert(SU->NumRegDefsLeft == 0 && "expect a new node");
585218893Sdim  for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
586218893Sdim    assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
587218893Sdim    ++SU->NumRegDefsLeft;
588218893Sdim  }
589218893Sdim}
590218893Sdim
591234353Sdimvoid ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
592221345Sdim  SDNode *N = SU->getNode();
593221345Sdim
594221345Sdim  // TokenFactor operands are considered zero latency, and some schedulers
595221345Sdim  // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
596221345Sdim  // whenever node latency is nonzero.
597221345Sdim  if (N && N->getOpcode() == ISD::TokenFactor) {
598221345Sdim    SU->Latency = 0;
599221345Sdim    return;
600221345Sdim  }
601221345Sdim
602208599Srdivacky  // Check to see if the scheduler cares about latencies.
603234353Sdim  if (forceUnitLatencies()) {
604208599Srdivacky    SU->Latency = 1;
605208599Srdivacky    return;
606208599Srdivacky  }
607208599Srdivacky
608218893Sdim  if (!InstrItins || InstrItins->isEmpty()) {
609221345Sdim    if (N && N->isMachineOpcode() &&
610221345Sdim        TII->isHighLatencyDef(N->getMachineOpcode()))
611221345Sdim      SU->Latency = HighLatencyCycles;
612221345Sdim    else
613221345Sdim      SU->Latency = 1;
614208599Srdivacky    return;
615208599Srdivacky  }
616218893Sdim
617193323Sed  // Compute the latency for the node.  We use the sum of the latencies for
618218893Sdim  // all nodes glued together into this SUnit.
619193323Sed  SU->Latency = 0;
620218893Sdim  for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
621218893Sdim    if (N->isMachineOpcode())
622218893Sdim      SU->Latency += TII->getInstrLatency(InstrItins, N);
623193323Sed}
624193323Sed
625234353Sdimvoid ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
626208599Srdivacky                                               unsigned OpIdx, SDep& dep) const{
627208599Srdivacky  // Check to see if the scheduler cares about latencies.
628234353Sdim  if (forceUnitLatencies())
629208599Srdivacky    return;
630208599Srdivacky
631208599Srdivacky  if (dep.getKind() != SDep::Data)
632208599Srdivacky    return;
633208599Srdivacky
634208599Srdivacky  unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
635218893Sdim  if (Use->isMachineOpcode())
636218893Sdim    // Adjust the use operand index by num of defs.
637218893Sdim    OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
638218893Sdim  int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
639218893Sdim  if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
640218893Sdim      !BB->succ_empty()) {
641218893Sdim    unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
642218893Sdim    if (TargetRegisterInfo::isVirtualRegister(Reg))
643218893Sdim      // This copy is a liveout value. It is likely coalesced, so reduce the
644218893Sdim      // latency so not to penalize the def.
645218893Sdim      // FIXME: need target specific adjustment here?
646218893Sdim      Latency = (Latency > 1) ? Latency - 1 : 1;
647208599Srdivacky  }
648218893Sdim  if (Latency >= 0)
649218893Sdim    dep.setLatency(Latency);
650208599Srdivacky}
651208599Srdivacky
652193323Sedvoid ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
653243830Sdim#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
654193323Sed  if (!SU->getNode()) {
655202375Srdivacky    dbgs() << "PHYS REG COPY\n";
656193323Sed    return;
657193323Sed  }
658193323Sed
659193323Sed  SU->getNode()->dump(DAG);
660202375Srdivacky  dbgs() << "\n";
661218893Sdim  SmallVector<SDNode *, 4> GluedNodes;
662218893Sdim  for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
663218893Sdim    GluedNodes.push_back(N);
664218893Sdim  while (!GluedNodes.empty()) {
665202375Srdivacky    dbgs() << "    ";
666218893Sdim    GluedNodes.back()->dump(DAG);
667202375Srdivacky    dbgs() << "\n";
668218893Sdim    GluedNodes.pop_back();
669193323Sed  }
670243830Sdim#endif
671193323Sed}
672198090Srdivacky
673243830Sdim#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
674234353Sdimvoid ScheduleDAGSDNodes::dumpSchedule() const {
675234353Sdim  for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
676234353Sdim    if (SUnit *SU = Sequence[i])
677234353Sdim      SU->dump(this);
678234353Sdim    else
679234353Sdim      dbgs() << "**** NOOP ****\n";
680234353Sdim  }
681234353Sdim}
682243830Sdim#endif
683234353Sdim
684234353Sdim#ifndef NDEBUG
685234353Sdim/// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
686234353Sdim/// their state is consistent with the nodes listed in Sequence.
687234353Sdim///
688234353Sdimvoid ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
689234353Sdim  unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
690234353Sdim  unsigned Noops = 0;
691234353Sdim  for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
692234353Sdim    if (!Sequence[i])
693234353Sdim      ++Noops;
694234353Sdim  assert(Sequence.size() - Noops == ScheduledNodes &&
695234353Sdim         "The number of nodes scheduled doesn't match the expected number!");
696234353Sdim}
697234353Sdim#endif // NDEBUG
698234353Sdim
699221345Sdim/// ProcessSDDbgValues - Process SDDbgValues associated with this node.
700261991Sdimstatic void
701261991SdimProcessSDDbgValues(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
702261991Sdim                   SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
703261991Sdim                   DenseMap<SDValue, unsigned> &VRBaseMap, unsigned Order) {
704218893Sdim  if (!N->getHasDebugValue())
705206083Srdivacky    return;
706206083Srdivacky
707206083Srdivacky  // Opportunistically insert immediate dbg_value uses, i.e. those with source
708206083Srdivacky  // order number right after the N.
709218893Sdim  MachineBasicBlock *BB = Emitter.getBlock();
710206083Srdivacky  MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
711224145Sdim  ArrayRef<SDDbgValue*> DVs = DAG->GetDbgValues(N);
712206083Srdivacky  for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
713206083Srdivacky    if (DVs[i]->isInvalidated())
714206083Srdivacky      continue;
715206083Srdivacky    unsigned DVOrder = DVs[i]->getOrder();
716218893Sdim    if (!Order || DVOrder == ++Order) {
717207618Srdivacky      MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
718207618Srdivacky      if (DbgMI) {
719207618Srdivacky        Orders.push_back(std::make_pair(DVOrder, DbgMI));
720207618Srdivacky        BB->insert(InsertPos, DbgMI);
721207618Srdivacky      }
722206083Srdivacky      DVs[i]->setIsInvalidated();
723206083Srdivacky    }
724206083Srdivacky  }
725206083Srdivacky}
726206083Srdivacky
727218893Sdim// ProcessSourceNode - Process nodes with source order numbers. These are added
728218893Sdim// to a vector which EmitSchedule uses to determine how to insert dbg_value
729218893Sdim// instructions in the right order.
730261991Sdimstatic void
731261991SdimProcessSourceNode(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
732261991Sdim                  DenseMap<SDValue, unsigned> &VRBaseMap,
733261991Sdim                  SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
734261991Sdim                  SmallSet<unsigned, 8> &Seen) {
735261991Sdim  unsigned Order = N->getIROrder();
736280031Sdim  if (!Order || !Seen.insert(Order).second) {
737218893Sdim    // Process any valid SDDbgValues even if node does not have any order
738218893Sdim    // assigned.
739218893Sdim    ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
740218893Sdim    return;
741218893Sdim  }
742206083Srdivacky
743218893Sdim  MachineBasicBlock *BB = Emitter.getBlock();
744261991Sdim  if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI() ||
745261991Sdim      // Fast-isel may have inserted some instructions, in which case the
746261991Sdim      // BB->back().isPHI() test will not fire when we want it to.
747276479Sdim      std::prev(Emitter.getInsertPos())->isPHI()) {
748218893Sdim    // Did not insert any instruction.
749276479Sdim    Orders.push_back(std::make_pair(Order, (MachineInstr*)nullptr));
750218893Sdim    return;
751218893Sdim  }
752218893Sdim
753276479Sdim  Orders.push_back(std::make_pair(Order, std::prev(Emitter.getInsertPos())));
754218893Sdim  ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
755218893Sdim}
756218893Sdim
757234353Sdimvoid ScheduleDAGSDNodes::
758234353SdimEmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
759234353Sdim                MachineBasicBlock::iterator InsertPos) {
760234353Sdim  for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
761234353Sdim       I != E; ++I) {
762234353Sdim    if (I->isCtrl()) continue;  // ignore chain preds
763234353Sdim    if (I->getSUnit()->CopyDstRC) {
764234353Sdim      // Copy to physical register.
765234353Sdim      DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->getSUnit());
766234353Sdim      assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
767234353Sdim      // Find the destination physical register.
768234353Sdim      unsigned Reg = 0;
769234353Sdim      for (SUnit::const_succ_iterator II = SU->Succs.begin(),
770234353Sdim             EE = SU->Succs.end(); II != EE; ++II) {
771234353Sdim        if (II->isCtrl()) continue;  // ignore chain preds
772234353Sdim        if (II->getReg()) {
773234353Sdim          Reg = II->getReg();
774234353Sdim          break;
775234353Sdim        }
776234353Sdim      }
777234353Sdim      BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
778234353Sdim        .addReg(VRI->second);
779234353Sdim    } else {
780234353Sdim      // Copy from physical register.
781234353Sdim      assert(I->getReg() && "Unknown physical register!");
782234353Sdim      unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
783234353Sdim      bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
784234353Sdim      (void)isNew; // Silence compiler warning.
785234353Sdim      assert(isNew && "Node emitted out of order - early");
786234353Sdim      BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
787234353Sdim        .addReg(I->getReg());
788234353Sdim    }
789234353Sdim    break;
790234353Sdim  }
791234353Sdim}
792218893Sdim
793234353Sdim/// EmitSchedule - Emit the machine code in scheduled order. Return the new
794234353Sdim/// InsertPos and MachineBasicBlock that contains this insertion
795234353Sdim/// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
796234353Sdim/// not necessarily refer to returned BB. The emitter may split blocks.
797234353SdimMachineBasicBlock *ScheduleDAGSDNodes::
798234353SdimEmitSchedule(MachineBasicBlock::iterator &InsertPos) {
799198090Srdivacky  InstrEmitter Emitter(BB, InsertPos);
800198090Srdivacky  DenseMap<SDValue, unsigned> VRBaseMap;
801198090Srdivacky  DenseMap<SUnit*, unsigned> CopyVRBaseMap;
802206083Srdivacky  SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
803206083Srdivacky  SmallSet<unsigned, 8> Seen;
804206083Srdivacky  bool HasDbg = DAG->hasDebugValues();
805205218Srdivacky
806207618Srdivacky  // If this is the first BB, emit byval parameter dbg_value's.
807207618Srdivacky  if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
808207618Srdivacky    SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
809207618Srdivacky    SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
810207618Srdivacky    for (; PDI != PDE; ++PDI) {
811207618Srdivacky      MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
812207618Srdivacky      if (DbgMI)
813210299Sed        BB->insert(InsertPos, DbgMI);
814207618Srdivacky    }
815207618Srdivacky  }
816207618Srdivacky
817198090Srdivacky  for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
818198090Srdivacky    SUnit *SU = Sequence[i];
819198090Srdivacky    if (!SU) {
820198090Srdivacky      // Null SUnit* is a noop.
821234353Sdim      TII->insertNoop(*Emitter.getBlock(), InsertPos);
822198090Srdivacky      continue;
823198090Srdivacky    }
824198090Srdivacky
825198090Srdivacky    // For pre-regalloc scheduling, create instructions corresponding to the
826218893Sdim    // SDNode and any glued SDNodes and append them to the block.
827198090Srdivacky    if (!SU->getNode()) {
828198090Srdivacky      // Emit a copy.
829234353Sdim      EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
830198090Srdivacky      continue;
831198090Srdivacky    }
832198090Srdivacky
833218893Sdim    SmallVector<SDNode *, 4> GluedNodes;
834243830Sdim    for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
835218893Sdim      GluedNodes.push_back(N);
836218893Sdim    while (!GluedNodes.empty()) {
837218893Sdim      SDNode *N = GluedNodes.back();
838218893Sdim      Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
839207618Srdivacky                       VRBaseMap);
840207618Srdivacky      // Remember the source order of the inserted instruction.
841206083Srdivacky      if (HasDbg)
842207618Srdivacky        ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
843218893Sdim      GluedNodes.pop_back();
844198090Srdivacky    }
845198090Srdivacky    Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
846207618Srdivacky                     VRBaseMap);
847207618Srdivacky    // Remember the source order of the inserted instruction.
848206083Srdivacky    if (HasDbg)
849207618Srdivacky      ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
850206083Srdivacky                        Seen);
851206083Srdivacky  }
852206083Srdivacky
853207618Srdivacky  // Insert all the dbg_values which have not already been inserted in source
854206083Srdivacky  // order sequence.
855206083Srdivacky  if (HasDbg) {
856210299Sed    MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
857206083Srdivacky
858206083Srdivacky    // Sort the source order instructions and use the order to insert debug
859206083Srdivacky    // values.
860261991Sdim    std::sort(Orders.begin(), Orders.end(), less_first());
861206083Srdivacky
862206083Srdivacky    SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
863206083Srdivacky    SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
864206083Srdivacky    // Now emit the rest according to source order.
865206083Srdivacky    unsigned LastOrder = 0;
866206083Srdivacky    for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
867206083Srdivacky      unsigned Order = Orders[i].first;
868206083Srdivacky      MachineInstr *MI = Orders[i].second;
869206083Srdivacky      // Insert all SDDbgValue's whose order(s) are before "Order".
870206083Srdivacky      if (!MI)
871206083Srdivacky        continue;
872206083Srdivacky      for (; DI != DE &&
873206083Srdivacky             (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
874206083Srdivacky        if ((*DI)->isInvalidated())
875206083Srdivacky          continue;
876207618Srdivacky        MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
877207618Srdivacky        if (DbgMI) {
878207618Srdivacky          if (!LastOrder)
879207618Srdivacky            // Insert to start of the BB (after PHIs).
880207618Srdivacky            BB->insert(BBBegin, DbgMI);
881207618Srdivacky          else {
882210299Sed            // Insert at the instruction, which may be in a different
883210299Sed            // block, if the block was split by a custom inserter.
884207618Srdivacky            MachineBasicBlock::iterator Pos = MI;
885261991Sdim            MI->getParent()->insert(Pos, DbgMI);
886207618Srdivacky          }
887206083Srdivacky        }
888205218Srdivacky      }
889206083Srdivacky      LastOrder = Order;
890206083Srdivacky    }
891206083Srdivacky    // Add trailing DbgValue's before the terminator. FIXME: May want to add
892206083Srdivacky    // some of them before one or more conditional branches?
893234353Sdim    SmallVector<MachineInstr*, 8> DbgMIs;
894206083Srdivacky    while (DI != DE) {
895234353Sdim      if (!(*DI)->isInvalidated())
896234353Sdim        if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
897234353Sdim          DbgMIs.push_back(DbgMI);
898206083Srdivacky      ++DI;
899206083Srdivacky    }
900234353Sdim
901234353Sdim    MachineBasicBlock *InsertBB = Emitter.getBlock();
902234353Sdim    MachineBasicBlock::iterator Pos = InsertBB->getFirstTerminator();
903234353Sdim    InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
904198090Srdivacky  }
905198090Srdivacky
906198090Srdivacky  InsertPos = Emitter.getInsertPos();
907234353Sdim  return Emitter.getBlock();
908198090Srdivacky}
909234353Sdim
910234353Sdim/// Return the basic block label.
911234353Sdimstd::string ScheduleDAGSDNodes::getDAGName() const {
912234353Sdim  return "sunit-dag." + BB->getFullName();
913234353Sdim}
914