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/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
34 STATISTIC(LoadsClustered, "Number of loads clustered together");
36 ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
38 InstrItins(mf.getTarget().getInstrItineraryData()) {}
40 /// Run - perform scheduling.
42 void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb,
43 MachineBasicBlock::iterator insertPos) {
45 ScheduleDAG::Run(bb, insertPos);
48 /// NewSUnit - Creates a new SUnit and return a ptr to it.
50 SUnit *ScheduleDAGSDNodes::NewSUnit(SDNode *N) {
52 const SUnit *Addr = 0;
56 SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
57 assert((Addr == 0 || Addr == &SUnits[0]) &&
58 "SUnits std::vector reallocated on the fly!");
59 SUnits.back().OrigNode = &SUnits.back();
60 SUnit *SU = &SUnits.back();
61 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
63 (N->isMachineOpcode() &&
64 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
65 SU->SchedulingPref = Sched::None;
67 SU->SchedulingPref = TLI.getSchedulingPreference(N);
71 SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
72 SUnit *SU = NewSUnit(Old->getNode());
73 SU->OrigNode = Old->OrigNode;
74 SU->Latency = Old->Latency;
75 SU->isCall = Old->isCall;
76 SU->isTwoAddress = Old->isTwoAddress;
77 SU->isCommutable = Old->isCommutable;
78 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
79 SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
80 SU->SchedulingPref = Old->SchedulingPref;
85 /// CheckForPhysRegDependency - Check if the dependency between def and use of
86 /// a specified operand is a physical register dependency. If so, returns the
87 /// register and the cost of copying the register.
88 static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
89 const TargetRegisterInfo *TRI,
90 const TargetInstrInfo *TII,
91 unsigned &PhysReg, int &Cost) {
92 if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
95 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
96 if (TargetRegisterInfo::isVirtualRegister(Reg))
99 unsigned ResNo = User->getOperand(2).getResNo();
100 if (Def->isMachineOpcode()) {
101 const TargetInstrDesc &II = TII->get(Def->getMachineOpcode());
102 if (ResNo >= II.getNumDefs() &&
103 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
105 const TargetRegisterClass *RC =
106 TRI->getMinimalPhysRegClass(Reg, Def->getValueType(ResNo));
107 Cost = RC->getCopyCost();
112 static void AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
113 SmallVector<EVT, 4> VTs;
114 SDNode *GlueDestNode = Glue.getNode();
116 // Don't add glue from a node to itself.
117 if (GlueDestNode == N) return;
119 // Don't add glue to something which already has glue.
120 if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return;
122 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
123 VTs.push_back(N->getValueType(I));
126 VTs.push_back(MVT::Glue);
128 SmallVector<SDValue, 4> Ops;
129 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I)
130 Ops.push_back(N->getOperand(I));
135 SDVTList VTList = DAG->getVTList(&VTs[0], VTs.size());
136 MachineSDNode::mmo_iterator Begin = 0, End = 0;
137 MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
139 // Store memory references.
141 Begin = MN->memoperands_begin();
142 End = MN->memoperands_end();
145 DAG->MorphNodeTo(N, N->getOpcode(), VTList, &Ops[0], Ops.size());
147 // Reset the memory references
149 MN->setMemRefs(Begin, End);
152 /// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
153 /// This function finds loads of the same base and different offsets. If the
154 /// offsets are not far apart (target specific), it add MVT::Glue inputs and
155 /// outputs to ensure they are scheduled together and in order. This
156 /// optimization may benefit some targets by improving cache locality.
157 void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
159 unsigned NumOps = Node->getNumOperands();
160 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
161 Chain = Node->getOperand(NumOps-1).getNode();
165 // Look for other loads of the same chain. Find loads that are loading from
166 // the same base pointer and different offsets.
167 SmallPtrSet<SDNode*, 16> Visited;
168 SmallVector<int64_t, 4> Offsets;
169 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
170 bool Cluster = false;
172 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
175 if (User == Node || !Visited.insert(User))
177 int64_t Offset1, Offset2;
178 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
180 // FIXME: Should be ok if they addresses are identical. But earlier
181 // optimizations really should have eliminated one of the loads.
183 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
184 Offsets.push_back(Offset1);
185 O2SMap.insert(std::make_pair(Offset2, User));
186 Offsets.push_back(Offset2);
187 if (Offset2 < Offset1)
195 // Sort them in increasing order.
196 std::sort(Offsets.begin(), Offsets.end());
198 // Check if the loads are close enough.
199 SmallVector<SDNode*, 4> Loads;
200 unsigned NumLoads = 0;
201 int64_t BaseOff = Offsets[0];
202 SDNode *BaseLoad = O2SMap[BaseOff];
203 Loads.push_back(BaseLoad);
204 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
205 int64_t Offset = Offsets[i];
206 SDNode *Load = O2SMap[Offset];
207 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
208 break; // Stop right here. Ignore loads that are further away.
209 Loads.push_back(Load);
216 // Cluster loads by adding MVT::Glue outputs and inputs. This also
217 // ensure they are scheduled in order of increasing addresses.
218 SDNode *Lead = Loads[0];
219 AddGlue(Lead, SDValue(0, 0), true, DAG);
221 SDValue InGlue = SDValue(Lead, Lead->getNumValues() - 1);
222 for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
223 bool OutGlue = I < E - 1;
224 SDNode *Load = Loads[I];
226 AddGlue(Load, InGlue, OutGlue, DAG);
229 InGlue = SDValue(Load, Load->getNumValues() - 1);
235 /// ClusterNodes - Cluster certain nodes which should be scheduled together.
237 void ScheduleDAGSDNodes::ClusterNodes() {
238 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
239 E = DAG->allnodes_end(); NI != E; ++NI) {
241 if (!Node || !Node->isMachineOpcode())
244 unsigned Opc = Node->getMachineOpcode();
245 const TargetInstrDesc &TID = TII->get(Opc);
247 // Cluster loads from "near" addresses into combined SUnits.
248 ClusterNeighboringLoads(Node);
252 void ScheduleDAGSDNodes::BuildSchedUnits() {
253 // During scheduling, the NodeId field of SDNode is used to map SDNodes
254 // to their associated SUnits by holding SUnits table indices. A value
255 // of -1 means the SDNode does not yet have an associated SUnit.
256 unsigned NumNodes = 0;
257 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
258 E = DAG->allnodes_end(); NI != E; ++NI) {
263 // Reserve entries in the vector for each of the SUnits we are creating. This
264 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
266 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
267 // This is a temporary workaround.
268 SUnits.reserve(NumNodes * 2);
270 // Add all nodes in depth first order.
271 SmallVector<SDNode*, 64> Worklist;
272 SmallPtrSet<SDNode*, 64> Visited;
273 Worklist.push_back(DAG->getRoot().getNode());
274 Visited.insert(DAG->getRoot().getNode());
276 while (!Worklist.empty()) {
277 SDNode *NI = Worklist.pop_back_val();
279 // Add all operands to the worklist unless they've already been added.
280 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
281 if (Visited.insert(NI->getOperand(i).getNode()))
282 Worklist.push_back(NI->getOperand(i).getNode());
284 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
287 // If this node has already been processed, stop now.
288 if (NI->getNodeId() != -1) continue;
290 SUnit *NodeSUnit = NewSUnit(NI);
292 // See if anything is glued to this node, if so, add them to glued
293 // nodes. Nodes can have at most one glue input and one glue output. Glue
294 // is required to be the last operand and result of a node.
296 // Scan up to find glued preds.
298 while (N->getNumOperands() &&
299 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
300 N = N->getOperand(N->getNumOperands()-1).getNode();
301 assert(N->getNodeId() == -1 && "Node already inserted!");
302 N->setNodeId(NodeSUnit->NodeNum);
303 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
304 NodeSUnit->isCall = true;
307 // Scan down to find any glued succs.
309 while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
310 SDValue GlueVal(N, N->getNumValues()-1);
312 // There are either zero or one users of the Glue result.
313 bool HasGlueUse = false;
314 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
316 if (GlueVal.isOperandOf(*UI)) {
318 assert(N->getNodeId() == -1 && "Node already inserted!");
319 N->setNodeId(NodeSUnit->NodeNum);
321 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
322 NodeSUnit->isCall = true;
325 if (!HasGlueUse) break;
328 // If there are glue operands involved, N is now the bottom-most node
329 // of the sequence of nodes that are glued together.
331 NodeSUnit->setNode(N);
332 assert(N->getNodeId() == -1 && "Node already inserted!");
333 N->setNodeId(NodeSUnit->NodeNum);
335 // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
336 InitNumRegDefsLeft(NodeSUnit);
338 // Assign the Latency field of NodeSUnit using target-provided information.
339 ComputeLatency(NodeSUnit);
343 void ScheduleDAGSDNodes::AddSchedEdges() {
344 const TargetSubtarget &ST = TM.getSubtarget<TargetSubtarget>();
346 // Check to see if the scheduler cares about latencies.
347 bool UnitLatencies = ForceUnitLatencies();
349 // Pass 2: add the preds, succs, etc.
350 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
351 SUnit *SU = &SUnits[su];
352 SDNode *MainNode = SU->getNode();
354 if (MainNode->isMachineOpcode()) {
355 unsigned Opc = MainNode->getMachineOpcode();
356 const TargetInstrDesc &TID = TII->get(Opc);
357 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
358 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
359 SU->isTwoAddress = true;
363 if (TID.isCommutable())
364 SU->isCommutable = true;
367 // Find all predecessors and successors of the group.
368 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
369 if (N->isMachineOpcode() &&
370 TII->get(N->getMachineOpcode()).getImplicitDefs()) {
371 SU->hasPhysRegClobbers = true;
372 unsigned NumUsed = InstrEmitter::CountResults(N);
373 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
374 --NumUsed; // Skip over unused values at the end.
375 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
376 SU->hasPhysRegDefs = true;
379 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
380 SDNode *OpN = N->getOperand(i).getNode();
381 if (isPassiveNode(OpN)) continue; // Not scheduled.
382 SUnit *OpSU = &SUnits[OpN->getNodeId()];
383 assert(OpSU && "Node has no SUnit!");
384 if (OpSU == SU) continue; // In the same group.
386 EVT OpVT = N->getOperand(i).getValueType();
387 assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
388 bool isChain = OpVT == MVT::Other;
390 unsigned PhysReg = 0;
392 // Determine if this is a physical register dependency.
393 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
394 assert((PhysReg == 0 || !isChain) &&
395 "Chain dependence via physreg data?");
396 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
397 // emits a copy from the physical register to a virtual register unless
398 // it requires a cross class copy (cost < 0). That means we are only
399 // treating "expensive to copy" register dependency as physical register
400 // dependency. This may change in the future though.
404 // If this is a ctrl dep, latency is 1.
405 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
406 const SDep &dep = SDep(OpSU, isChain ? SDep::Order : SDep::Data,
408 if (!isChain && !UnitLatencies) {
409 ComputeOperandLatency(OpN, N, i, const_cast<SDep &>(dep));
410 ST.adjustSchedDependency(OpSU, SU, const_cast<SDep &>(dep));
413 if (!SU->addPred(dep) && !dep.isCtrl() && OpSU->NumRegDefsLeft > 0) {
414 // Multiple register uses are combined in the same SUnit. For example,
415 // we could have a set of glued nodes with all their defs consumed by
416 // another set of glued nodes. Register pressure tracking sees this as
417 // a single use, so to keep pressure balanced we reduce the defs.
418 --OpSU->NumRegDefsLeft;
425 /// BuildSchedGraph - Build the SUnit graph from the selection dag that we
426 /// are input. This SUnit graph is similar to the SelectionDAG, but
427 /// excludes nodes that aren't interesting to scheduling, and represents
428 /// glued together nodes with a single SUnit.
429 void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
430 // Cluster certain nodes which should be scheduled together.
432 // Populate the SUnits array.
434 // Compute all the scheduling dependencies between nodes.
438 // Initialize NumNodeDefs for the current Node's opcode.
439 void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
440 if (!Node->isMachineOpcode()) {
441 if (Node->getOpcode() == ISD::CopyFromReg)
447 unsigned POpc = Node->getMachineOpcode();
448 if (POpc == TargetOpcode::IMPLICIT_DEF) {
449 // No register need be allocated for this.
453 unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
454 // Some instructions define regs that are not represented in the selection DAG
455 // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
456 NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
460 // Construct a RegDefIter for this SUnit and find the first valid value.
461 ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
462 const ScheduleDAGSDNodes *SD)
463 : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
468 // Advance to the next valid value defined by the SUnit.
469 void ScheduleDAGSDNodes::RegDefIter::Advance() {
470 for (;Node;) { // Visit all glued nodes.
471 for (;DefIdx < NodeNumDefs; ++DefIdx) {
472 if (!Node->hasAnyUseOfValue(DefIdx))
474 if (Node->isMachineOpcode() &&
475 Node->getMachineOpcode() == TargetOpcode::EXTRACT_SUBREG) {
476 // Propagate the incoming (full-register) type. I doubt it's needed.
477 ValueType = Node->getOperand(0).getValueType();
480 ValueType = Node->getValueType(DefIdx);
483 return; // Found a normal regdef.
485 Node = Node->getGluedNode();
487 return; // No values left to visit.
493 void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
494 assert(SU->NumRegDefsLeft == 0 && "expect a new node");
495 for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
496 assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
497 ++SU->NumRegDefsLeft;
501 void ScheduleDAGSDNodes::ComputeLatency(SUnit *SU) {
502 // Check to see if the scheduler cares about latencies.
503 if (ForceUnitLatencies()) {
508 if (!InstrItins || InstrItins->isEmpty()) {
513 // Compute the latency for the node. We use the sum of the latencies for
514 // all nodes glued together into this SUnit.
516 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
517 if (N->isMachineOpcode())
518 SU->Latency += TII->getInstrLatency(InstrItins, N);
521 void ScheduleDAGSDNodes::ComputeOperandLatency(SDNode *Def, SDNode *Use,
522 unsigned OpIdx, SDep& dep) const{
523 // Check to see if the scheduler cares about latencies.
524 if (ForceUnitLatencies())
527 if (dep.getKind() != SDep::Data)
530 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
531 if (Use->isMachineOpcode())
532 // Adjust the use operand index by num of defs.
533 OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
534 int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
535 if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
537 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
538 if (TargetRegisterInfo::isVirtualRegister(Reg))
539 // This copy is a liveout value. It is likely coalesced, so reduce the
540 // latency so not to penalize the def.
541 // FIXME: need target specific adjustment here?
542 Latency = (Latency > 1) ? Latency - 1 : 1;
545 dep.setLatency(Latency);
548 void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
549 if (!SU->getNode()) {
550 dbgs() << "PHYS REG COPY\n";
554 SU->getNode()->dump(DAG);
556 SmallVector<SDNode *, 4> GluedNodes;
557 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
558 GluedNodes.push_back(N);
559 while (!GluedNodes.empty()) {
561 GluedNodes.back()->dump(DAG);
563 GluedNodes.pop_back();
569 bool operator()(const std::pair<unsigned, MachineInstr*> &A,
570 const std::pair<unsigned, MachineInstr*> &B) {
571 return A.first < B.first;
576 /// ProcessSDDbgValues - Process SDDbgValues assoicated with this node.
577 static void ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG,
578 InstrEmitter &Emitter,
579 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
580 DenseMap<SDValue, unsigned> &VRBaseMap,
582 if (!N->getHasDebugValue())
585 // Opportunistically insert immediate dbg_value uses, i.e. those with source
586 // order number right after the N.
587 MachineBasicBlock *BB = Emitter.getBlock();
588 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
589 SmallVector<SDDbgValue*,2> &DVs = DAG->GetDbgValues(N);
590 for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
591 if (DVs[i]->isInvalidated())
593 unsigned DVOrder = DVs[i]->getOrder();
594 if (!Order || DVOrder == ++Order) {
595 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
597 Orders.push_back(std::make_pair(DVOrder, DbgMI));
598 BB->insert(InsertPos, DbgMI);
600 DVs[i]->setIsInvalidated();
605 // ProcessSourceNode - Process nodes with source order numbers. These are added
606 // to a vector which EmitSchedule uses to determine how to insert dbg_value
607 // instructions in the right order.
608 static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG,
609 InstrEmitter &Emitter,
610 DenseMap<SDValue, unsigned> &VRBaseMap,
611 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders,
612 SmallSet<unsigned, 8> &Seen) {
613 unsigned Order = DAG->GetOrdering(N);
614 if (!Order || !Seen.insert(Order)) {
615 // Process any valid SDDbgValues even if node does not have any order
617 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
621 MachineBasicBlock *BB = Emitter.getBlock();
622 if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI()) {
623 // Did not insert any instruction.
624 Orders.push_back(std::make_pair(Order, (MachineInstr*)0));
628 Orders.push_back(std::make_pair(Order, prior(Emitter.getInsertPos())));
629 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
633 /// EmitSchedule - Emit the machine code in scheduled order.
634 MachineBasicBlock *ScheduleDAGSDNodes::EmitSchedule() {
635 InstrEmitter Emitter(BB, InsertPos);
636 DenseMap<SDValue, unsigned> VRBaseMap;
637 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
638 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
639 SmallSet<unsigned, 8> Seen;
640 bool HasDbg = DAG->hasDebugValues();
642 // If this is the first BB, emit byval parameter dbg_value's.
643 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
644 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
645 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
646 for (; PDI != PDE; ++PDI) {
647 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
649 BB->insert(InsertPos, DbgMI);
653 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
654 SUnit *SU = Sequence[i];
656 // Null SUnit* is a noop.
661 // For pre-regalloc scheduling, create instructions corresponding to the
662 // SDNode and any glued SDNodes and append them to the block.
663 if (!SU->getNode()) {
665 EmitPhysRegCopy(SU, CopyVRBaseMap);
669 SmallVector<SDNode *, 4> GluedNodes;
670 for (SDNode *N = SU->getNode()->getGluedNode(); N;
671 N = N->getGluedNode())
672 GluedNodes.push_back(N);
673 while (!GluedNodes.empty()) {
674 SDNode *N = GluedNodes.back();
675 Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
677 // Remember the source order of the inserted instruction.
679 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
680 GluedNodes.pop_back();
682 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
684 // Remember the source order of the inserted instruction.
686 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
690 // Insert all the dbg_values which have not already been inserted in source
693 MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
695 // Sort the source order instructions and use the order to insert debug
697 std::sort(Orders.begin(), Orders.end(), OrderSorter());
699 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
700 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
701 // Now emit the rest according to source order.
702 unsigned LastOrder = 0;
703 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
704 unsigned Order = Orders[i].first;
705 MachineInstr *MI = Orders[i].second;
706 // Insert all SDDbgValue's whose order(s) are before "Order".
710 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
711 if ((*DI)->isInvalidated())
713 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
716 // Insert to start of the BB (after PHIs).
717 BB->insert(BBBegin, DbgMI);
719 // Insert at the instruction, which may be in a different
720 // block, if the block was split by a custom inserter.
721 MachineBasicBlock::iterator Pos = MI;
722 MI->getParent()->insert(llvm::next(Pos), DbgMI);
728 // Add trailing DbgValue's before the terminator. FIXME: May want to add
729 // some of them before one or more conditional branches?
731 MachineBasicBlock *InsertBB = Emitter.getBlock();
732 MachineBasicBlock::iterator Pos= Emitter.getBlock()->getFirstTerminator();
733 if (!(*DI)->isInvalidated()) {
734 MachineInstr *DbgMI= Emitter.EmitDbgValue(*DI, VRBaseMap);
736 InsertBB->insert(Pos, DbgMI);
742 BB = Emitter.getBlock();
743 InsertPos = Emitter.getInsertPos();