1 //===--- ScheduleDAGSDNodes.cpp - Implement the ScheduleDAGSDNodes class --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the ScheduleDAG class, which is a base class used by
11 // scheduling implementation classes.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "pre-RA-sched"
16 #include "SDNodeDbgValue.h"
17 #include "ScheduleDAGSDNodes.h"
18 #include "InstrEmitter.h"
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Target/TargetSubtarget.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
35 STATISTIC(LoadsClustered, "Number of loads clustered together");
37 // This allows latency based scheduler to notice high latency instructions
38 // without a target itinerary. The choise if number here has more to do with
39 // balancing scheduler heursitics than with the actual machine latency.
40 static cl::opt<int> HighLatencyCycles(
41 "sched-high-latency-cycles", cl::Hidden, cl::init(10),
42 cl::desc("Roughly estimate the number of cycles that 'long latency'"
43 "instructions take for targets with no itinerary"));
45 ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
47 InstrItins(mf.getTarget().getInstrItineraryData()) {}
49 /// Run - perform scheduling.
51 void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb,
52 MachineBasicBlock::iterator insertPos) {
54 ScheduleDAG::Run(bb, insertPos);
57 /// NewSUnit - Creates a new SUnit and return a ptr to it.
59 SUnit *ScheduleDAGSDNodes::NewSUnit(SDNode *N) {
61 const SUnit *Addr = 0;
65 SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
66 assert((Addr == 0 || Addr == &SUnits[0]) &&
67 "SUnits std::vector reallocated on the fly!");
68 SUnits.back().OrigNode = &SUnits.back();
69 SUnit *SU = &SUnits.back();
70 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
72 (N->isMachineOpcode() &&
73 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
74 SU->SchedulingPref = Sched::None;
76 SU->SchedulingPref = TLI.getSchedulingPreference(N);
80 SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
81 SUnit *SU = NewSUnit(Old->getNode());
82 SU->OrigNode = Old->OrigNode;
83 SU->Latency = Old->Latency;
84 SU->isVRegCycle = Old->isVRegCycle;
85 SU->isCall = Old->isCall;
86 SU->isTwoAddress = Old->isTwoAddress;
87 SU->isCommutable = Old->isCommutable;
88 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
89 SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
90 SU->SchedulingPref = Old->SchedulingPref;
95 /// CheckForPhysRegDependency - Check if the dependency between def and use of
96 /// a specified operand is a physical register dependency. If so, returns the
97 /// register and the cost of copying the register.
98 static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
99 const TargetRegisterInfo *TRI,
100 const TargetInstrInfo *TII,
101 unsigned &PhysReg, int &Cost) {
102 if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
105 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
106 if (TargetRegisterInfo::isVirtualRegister(Reg))
109 unsigned ResNo = User->getOperand(2).getResNo();
110 if (Def->isMachineOpcode()) {
111 const TargetInstrDesc &II = TII->get(Def->getMachineOpcode());
112 if (ResNo >= II.getNumDefs() &&
113 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
115 const TargetRegisterClass *RC =
116 TRI->getMinimalPhysRegClass(Reg, Def->getValueType(ResNo));
117 Cost = RC->getCopyCost();
122 static void AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
123 SmallVector<EVT, 4> VTs;
124 SDNode *GlueDestNode = Glue.getNode();
126 // Don't add glue from a node to itself.
127 if (GlueDestNode == N) return;
129 // Don't add glue to something which already has glue.
130 if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return;
132 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
133 VTs.push_back(N->getValueType(I));
136 VTs.push_back(MVT::Glue);
138 SmallVector<SDValue, 4> Ops;
139 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I)
140 Ops.push_back(N->getOperand(I));
145 SDVTList VTList = DAG->getVTList(&VTs[0], VTs.size());
146 MachineSDNode::mmo_iterator Begin = 0, End = 0;
147 MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
149 // Store memory references.
151 Begin = MN->memoperands_begin();
152 End = MN->memoperands_end();
155 DAG->MorphNodeTo(N, N->getOpcode(), VTList, &Ops[0], Ops.size());
157 // Reset the memory references
159 MN->setMemRefs(Begin, End);
162 /// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
163 /// This function finds loads of the same base and different offsets. If the
164 /// offsets are not far apart (target specific), it add MVT::Glue inputs and
165 /// outputs to ensure they are scheduled together and in order. This
166 /// optimization may benefit some targets by improving cache locality.
167 void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
169 unsigned NumOps = Node->getNumOperands();
170 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
171 Chain = Node->getOperand(NumOps-1).getNode();
175 // Look for other loads of the same chain. Find loads that are loading from
176 // the same base pointer and different offsets.
177 SmallPtrSet<SDNode*, 16> Visited;
178 SmallVector<int64_t, 4> Offsets;
179 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
180 bool Cluster = false;
182 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
185 if (User == Node || !Visited.insert(User))
187 int64_t Offset1, Offset2;
188 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
190 // FIXME: Should be ok if they addresses are identical. But earlier
191 // optimizations really should have eliminated one of the loads.
193 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
194 Offsets.push_back(Offset1);
195 O2SMap.insert(std::make_pair(Offset2, User));
196 Offsets.push_back(Offset2);
197 if (Offset2 < Offset1)
205 // Sort them in increasing order.
206 std::sort(Offsets.begin(), Offsets.end());
208 // Check if the loads are close enough.
209 SmallVector<SDNode*, 4> Loads;
210 unsigned NumLoads = 0;
211 int64_t BaseOff = Offsets[0];
212 SDNode *BaseLoad = O2SMap[BaseOff];
213 Loads.push_back(BaseLoad);
214 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
215 int64_t Offset = Offsets[i];
216 SDNode *Load = O2SMap[Offset];
217 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
218 break; // Stop right here. Ignore loads that are further away.
219 Loads.push_back(Load);
226 // Cluster loads by adding MVT::Glue outputs and inputs. This also
227 // ensure they are scheduled in order of increasing addresses.
228 SDNode *Lead = Loads[0];
229 AddGlue(Lead, SDValue(0, 0), true, DAG);
231 SDValue InGlue = SDValue(Lead, Lead->getNumValues() - 1);
232 for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
233 bool OutGlue = I < E - 1;
234 SDNode *Load = Loads[I];
236 AddGlue(Load, InGlue, OutGlue, DAG);
239 InGlue = SDValue(Load, Load->getNumValues() - 1);
245 /// ClusterNodes - Cluster certain nodes which should be scheduled together.
247 void ScheduleDAGSDNodes::ClusterNodes() {
248 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
249 E = DAG->allnodes_end(); NI != E; ++NI) {
251 if (!Node || !Node->isMachineOpcode())
254 unsigned Opc = Node->getMachineOpcode();
255 const TargetInstrDesc &TID = TII->get(Opc);
257 // Cluster loads from "near" addresses into combined SUnits.
258 ClusterNeighboringLoads(Node);
262 void ScheduleDAGSDNodes::BuildSchedUnits() {
263 // During scheduling, the NodeId field of SDNode is used to map SDNodes
264 // to their associated SUnits by holding SUnits table indices. A value
265 // of -1 means the SDNode does not yet have an associated SUnit.
266 unsigned NumNodes = 0;
267 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
268 E = DAG->allnodes_end(); NI != E; ++NI) {
273 // Reserve entries in the vector for each of the SUnits we are creating. This
274 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
276 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
277 // This is a temporary workaround.
278 SUnits.reserve(NumNodes * 2);
280 // Add all nodes in depth first order.
281 SmallVector<SDNode*, 64> Worklist;
282 SmallPtrSet<SDNode*, 64> Visited;
283 Worklist.push_back(DAG->getRoot().getNode());
284 Visited.insert(DAG->getRoot().getNode());
286 while (!Worklist.empty()) {
287 SDNode *NI = Worklist.pop_back_val();
289 // Add all operands to the worklist unless they've already been added.
290 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
291 if (Visited.insert(NI->getOperand(i).getNode()))
292 Worklist.push_back(NI->getOperand(i).getNode());
294 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
297 // If this node has already been processed, stop now.
298 if (NI->getNodeId() != -1) continue;
300 SUnit *NodeSUnit = NewSUnit(NI);
302 // See if anything is glued to this node, if so, add them to glued
303 // nodes. Nodes can have at most one glue input and one glue output. Glue
304 // is required to be the last operand and result of a node.
306 // Scan up to find glued preds.
308 while (N->getNumOperands() &&
309 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
310 N = N->getOperand(N->getNumOperands()-1).getNode();
311 assert(N->getNodeId() == -1 && "Node already inserted!");
312 N->setNodeId(NodeSUnit->NodeNum);
313 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
314 NodeSUnit->isCall = true;
317 // Scan down to find any glued succs.
319 while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
320 SDValue GlueVal(N, N->getNumValues()-1);
322 // There are either zero or one users of the Glue result.
323 bool HasGlueUse = false;
324 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
326 if (GlueVal.isOperandOf(*UI)) {
328 assert(N->getNodeId() == -1 && "Node already inserted!");
329 N->setNodeId(NodeSUnit->NodeNum);
331 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
332 NodeSUnit->isCall = true;
335 if (!HasGlueUse) break;
338 // If there are glue operands involved, N is now the bottom-most node
339 // of the sequence of nodes that are glued together.
341 NodeSUnit->setNode(N);
342 assert(N->getNodeId() == -1 && "Node already inserted!");
343 N->setNodeId(NodeSUnit->NodeNum);
345 // Set isVRegCycle if the node operands are live into and value is live out
346 // of a single block loop.
347 InitVRegCycleFlag(NodeSUnit);
349 // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
350 InitNumRegDefsLeft(NodeSUnit);
352 // Assign the Latency field of NodeSUnit using target-provided information.
353 ComputeLatency(NodeSUnit);
357 void ScheduleDAGSDNodes::AddSchedEdges() {
358 const TargetSubtarget &ST = TM.getSubtarget<TargetSubtarget>();
360 // Check to see if the scheduler cares about latencies.
361 bool UnitLatencies = ForceUnitLatencies();
363 // Pass 2: add the preds, succs, etc.
364 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
365 SUnit *SU = &SUnits[su];
366 SDNode *MainNode = SU->getNode();
368 if (MainNode->isMachineOpcode()) {
369 unsigned Opc = MainNode->getMachineOpcode();
370 const TargetInstrDesc &TID = TII->get(Opc);
371 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
372 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
373 SU->isTwoAddress = true;
377 if (TID.isCommutable())
378 SU->isCommutable = true;
381 // Find all predecessors and successors of the group.
382 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
383 if (N->isMachineOpcode() &&
384 TII->get(N->getMachineOpcode()).getImplicitDefs()) {
385 SU->hasPhysRegClobbers = true;
386 unsigned NumUsed = InstrEmitter::CountResults(N);
387 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
388 --NumUsed; // Skip over unused values at the end.
389 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
390 SU->hasPhysRegDefs = true;
393 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
394 SDNode *OpN = N->getOperand(i).getNode();
395 if (isPassiveNode(OpN)) continue; // Not scheduled.
396 SUnit *OpSU = &SUnits[OpN->getNodeId()];
397 assert(OpSU && "Node has no SUnit!");
398 if (OpSU == SU) continue; // In the same group.
400 EVT OpVT = N->getOperand(i).getValueType();
401 assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
402 bool isChain = OpVT == MVT::Other;
404 unsigned PhysReg = 0;
406 // Determine if this is a physical register dependency.
407 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
408 assert((PhysReg == 0 || !isChain) &&
409 "Chain dependence via physreg data?");
410 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
411 // emits a copy from the physical register to a virtual register unless
412 // it requires a cross class copy (cost < 0). That means we are only
413 // treating "expensive to copy" register dependency as physical register
414 // dependency. This may change in the future though.
418 // If this is a ctrl dep, latency is 1.
419 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
420 const SDep &dep = SDep(OpSU, isChain ? SDep::Order : SDep::Data,
422 if (!isChain && !UnitLatencies) {
423 ComputeOperandLatency(OpN, N, i, const_cast<SDep &>(dep));
424 ST.adjustSchedDependency(OpSU, SU, const_cast<SDep &>(dep));
427 if (!SU->addPred(dep) && !dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
428 // Multiple register uses are combined in the same SUnit. For example,
429 // we could have a set of glued nodes with all their defs consumed by
430 // another set of glued nodes. Register pressure tracking sees this as
431 // a single use, so to keep pressure balanced we reduce the defs.
433 // We can't tell (without more book-keeping) if this results from
434 // glued nodes or duplicate operands. As long as we don't reduce
435 // NumRegDefsLeft to zero, we handle the common cases well.
436 --OpSU->NumRegDefsLeft;
443 /// BuildSchedGraph - Build the SUnit graph from the selection dag that we
444 /// are input. This SUnit graph is similar to the SelectionDAG, but
445 /// excludes nodes that aren't interesting to scheduling, and represents
446 /// glued together nodes with a single SUnit.
447 void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
448 // Cluster certain nodes which should be scheduled together.
450 // Populate the SUnits array.
452 // Compute all the scheduling dependencies between nodes.
456 // Initialize NumNodeDefs for the current Node's opcode.
457 void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
458 // Check for phys reg copy.
462 if (!Node->isMachineOpcode()) {
463 if (Node->getOpcode() == ISD::CopyFromReg)
469 unsigned POpc = Node->getMachineOpcode();
470 if (POpc == TargetOpcode::IMPLICIT_DEF) {
471 // No register need be allocated for this.
475 unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
476 // Some instructions define regs that are not represented in the selection DAG
477 // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
478 NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
482 // Construct a RegDefIter for this SUnit and find the first valid value.
483 ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
484 const ScheduleDAGSDNodes *SD)
485 : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
490 // Advance to the next valid value defined by the SUnit.
491 void ScheduleDAGSDNodes::RegDefIter::Advance() {
492 for (;Node;) { // Visit all glued nodes.
493 for (;DefIdx < NodeNumDefs; ++DefIdx) {
494 if (!Node->hasAnyUseOfValue(DefIdx))
496 if (Node->isMachineOpcode() &&
497 Node->getMachineOpcode() == TargetOpcode::EXTRACT_SUBREG) {
498 // Propagate the incoming (full-register) type. I doubt it's needed.
499 ValueType = Node->getOperand(0).getValueType();
502 ValueType = Node->getValueType(DefIdx);
505 return; // Found a normal regdef.
507 Node = Node->getGluedNode();
509 return; // No values left to visit.
515 // Set isVRegCycle if this node's single use is CopyToReg and its only active
516 // data operands are CopyFromReg.
518 // This is only relevant for single-block loops, in which case the VRegCycle
519 // node is likely an induction variable in which the operand and target virtual
520 // registers should be coalesced (e.g. pre/post increment values). Setting the
521 // isVRegCycle flag helps the scheduler prioritize other uses of the same
522 // CopyFromReg so that this node becomes the virtual register "kill". This
523 // avoids interference between the values live in and out of the block and
524 // eliminates a copy inside the loop.
525 void ScheduleDAGSDNodes::InitVRegCycleFlag(SUnit *SU) {
526 if (!BB->isSuccessor(BB))
529 SDNode *N = SU->getNode();
530 if (N->getGluedNode())
533 if (!N->hasOneUse() || N->use_begin()->getOpcode() != ISD::CopyToReg)
536 bool FoundLiveIn = false;
537 for (SDNode::op_iterator OI = N->op_begin(), E = N->op_end(); OI != E; ++OI) {
538 EVT OpVT = OI->getValueType();
539 assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
541 if (OpVT == MVT::Other)
542 continue; // ignore chain operands
544 if (isPassiveNode(OI->getNode()))
545 continue; // ignore constants and such
547 if (OI->getNode()->getOpcode() != ISD::CopyFromReg)
553 SU->isVRegCycle = true;
556 void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
557 assert(SU->NumRegDefsLeft == 0 && "expect a new node");
558 for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
559 assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
560 ++SU->NumRegDefsLeft;
564 void ScheduleDAGSDNodes::ComputeLatency(SUnit *SU) {
565 // Check to see if the scheduler cares about latencies.
566 if (ForceUnitLatencies()) {
571 if (!InstrItins || InstrItins->isEmpty()) {
572 SDNode *N = SU->getNode();
573 if (N && N->isMachineOpcode() &&
574 TII->isHighLatencyDef(N->getMachineOpcode()))
575 SU->Latency = HighLatencyCycles;
581 // Compute the latency for the node. We use the sum of the latencies for
582 // all nodes glued together into this SUnit.
584 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
585 if (N->isMachineOpcode())
586 SU->Latency += TII->getInstrLatency(InstrItins, N);
589 void ScheduleDAGSDNodes::ComputeOperandLatency(SDNode *Def, SDNode *Use,
590 unsigned OpIdx, SDep& dep) const{
591 // Check to see if the scheduler cares about latencies.
592 if (ForceUnitLatencies())
595 if (dep.getKind() != SDep::Data)
598 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
599 if (Use->isMachineOpcode())
600 // Adjust the use operand index by num of defs.
601 OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
602 int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
603 if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
605 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
606 if (TargetRegisterInfo::isVirtualRegister(Reg))
607 // This copy is a liveout value. It is likely coalesced, so reduce the
608 // latency so not to penalize the def.
609 // FIXME: need target specific adjustment here?
610 Latency = (Latency > 1) ? Latency - 1 : 1;
613 dep.setLatency(Latency);
616 void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
617 if (!SU->getNode()) {
618 dbgs() << "PHYS REG COPY\n";
622 SU->getNode()->dump(DAG);
624 SmallVector<SDNode *, 4> GluedNodes;
625 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
626 GluedNodes.push_back(N);
627 while (!GluedNodes.empty()) {
629 GluedNodes.back()->dump(DAG);
631 GluedNodes.pop_back();
637 bool operator()(const std::pair<unsigned, MachineInstr*> &A,
638 const std::pair<unsigned, MachineInstr*> &B) {
639 return A.first < B.first;
644 /// ProcessSDDbgValues - Process SDDbgValues assoicated with this node.
645 static void ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG,
646 InstrEmitter &Emitter,
647 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
648 DenseMap<SDValue, unsigned> &VRBaseMap,
650 if (!N->getHasDebugValue())
653 // Opportunistically insert immediate dbg_value uses, i.e. those with source
654 // order number right after the N.
655 MachineBasicBlock *BB = Emitter.getBlock();
656 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
657 SmallVector<SDDbgValue*,2> &DVs = DAG->GetDbgValues(N);
658 for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
659 if (DVs[i]->isInvalidated())
661 unsigned DVOrder = DVs[i]->getOrder();
662 if (!Order || DVOrder == ++Order) {
663 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
665 Orders.push_back(std::make_pair(DVOrder, DbgMI));
666 BB->insert(InsertPos, DbgMI);
668 DVs[i]->setIsInvalidated();
673 // ProcessSourceNode - Process nodes with source order numbers. These are added
674 // to a vector which EmitSchedule uses to determine how to insert dbg_value
675 // instructions in the right order.
676 static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG,
677 InstrEmitter &Emitter,
678 DenseMap<SDValue, unsigned> &VRBaseMap,
679 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
680 SmallSet<unsigned, 8> &Seen) {
681 unsigned Order = DAG->GetOrdering(N);
682 if (!Order || !Seen.insert(Order)) {
683 // Process any valid SDDbgValues even if node does not have any order
685 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
689 MachineBasicBlock *BB = Emitter.getBlock();
690 if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI()) {
691 // Did not insert any instruction.
692 Orders.push_back(std::make_pair(Order, (MachineInstr*)0));
696 Orders.push_back(std::make_pair(Order, prior(Emitter.getInsertPos())));
697 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
701 /// EmitSchedule - Emit the machine code in scheduled order.
702 MachineBasicBlock *ScheduleDAGSDNodes::EmitSchedule() {
703 InstrEmitter Emitter(BB, InsertPos);
704 DenseMap<SDValue, unsigned> VRBaseMap;
705 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
706 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
707 SmallSet<unsigned, 8> Seen;
708 bool HasDbg = DAG->hasDebugValues();
710 // If this is the first BB, emit byval parameter dbg_value's.
711 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
712 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
713 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
714 for (; PDI != PDE; ++PDI) {
715 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
717 BB->insert(InsertPos, DbgMI);
721 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
722 SUnit *SU = Sequence[i];
724 // Null SUnit* is a noop.
729 // For pre-regalloc scheduling, create instructions corresponding to the
730 // SDNode and any glued SDNodes and append them to the block.
731 if (!SU->getNode()) {
733 EmitPhysRegCopy(SU, CopyVRBaseMap);
737 SmallVector<SDNode *, 4> GluedNodes;
738 for (SDNode *N = SU->getNode()->getGluedNode(); N;
739 N = N->getGluedNode())
740 GluedNodes.push_back(N);
741 while (!GluedNodes.empty()) {
742 SDNode *N = GluedNodes.back();
743 Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
745 // Remember the source order of the inserted instruction.
747 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
748 GluedNodes.pop_back();
750 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
752 // Remember the source order of the inserted instruction.
754 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
758 // Insert all the dbg_values which have not already been inserted in source
761 MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
763 // Sort the source order instructions and use the order to insert debug
765 std::sort(Orders.begin(), Orders.end(), OrderSorter());
767 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
768 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
769 // Now emit the rest according to source order.
770 unsigned LastOrder = 0;
771 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
772 unsigned Order = Orders[i].first;
773 MachineInstr *MI = Orders[i].second;
774 // Insert all SDDbgValue's whose order(s) are before "Order".
778 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
779 if ((*DI)->isInvalidated())
781 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
784 // Insert to start of the BB (after PHIs).
785 BB->insert(BBBegin, DbgMI);
787 // Insert at the instruction, which may be in a different
788 // block, if the block was split by a custom inserter.
789 MachineBasicBlock::iterator Pos = MI;
790 MI->getParent()->insert(llvm::next(Pos), DbgMI);
796 // Add trailing DbgValue's before the terminator. FIXME: May want to add
797 // some of them before one or more conditional branches?
799 MachineBasicBlock *InsertBB = Emitter.getBlock();
800 MachineBasicBlock::iterator Pos= Emitter.getBlock()->getFirstTerminator();
801 if (!(*DI)->isInvalidated()) {
802 MachineInstr *DbgMI= Emitter.EmitDbgValue(*DI, VRBaseMap);
804 InsertBB->insert(Pos, DbgMI);
810 BB = Emitter.getBlock();
811 InsertPos = Emitter.getInsertPos();