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 #include "ScheduleDAGSDNodes.h"
16 #include "InstrEmitter.h"
17 #include "SDNodeDbgValue.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/MC/MCInstrItineraries.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetLowering.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetSubtargetInfo.h"
36 #define DEBUG_TYPE "pre-RA-sched"
38 STATISTIC(LoadsClustered, "Number of loads clustered together");
40 // This allows the latency-based scheduler to notice high latency instructions
41 // without a target itinerary. The choice of number here has more to do with
42 // balancing scheduler heuristics than with the actual machine latency.
43 static cl::opt<int> HighLatencyCycles(
44 "sched-high-latency-cycles", cl::Hidden, cl::init(10),
45 cl::desc("Roughly estimate the number of cycles that 'long latency'"
46 "instructions take for targets with no itinerary"));
48 ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
49 : ScheduleDAG(mf), BB(nullptr), DAG(nullptr),
50 InstrItins(mf.getSubtarget().getInstrItineraryData()) {}
52 /// Run - perform scheduling.
54 void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
58 // Clear the scheduler's SUnit DAG.
59 ScheduleDAG::clearDAG();
62 // Invoke the target's selection of scheduler.
66 /// NewSUnit - Creates a new SUnit and return a ptr to it.
68 SUnit *ScheduleDAGSDNodes::newSUnit(SDNode *N) {
70 const SUnit *Addr = nullptr;
74 SUnits.push_back(SUnit(N, (unsigned)SUnits.size()));
75 assert((Addr == nullptr || Addr == &SUnits[0]) &&
76 "SUnits std::vector reallocated on the fly!");
77 SUnits.back().OrigNode = &SUnits.back();
78 SUnit *SU = &SUnits.back();
79 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
81 (N->isMachineOpcode() &&
82 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
83 SU->SchedulingPref = Sched::None;
85 SU->SchedulingPref = TLI.getSchedulingPreference(N);
89 SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
90 SUnit *SU = newSUnit(Old->getNode());
91 SU->OrigNode = Old->OrigNode;
92 SU->Latency = Old->Latency;
93 SU->isVRegCycle = Old->isVRegCycle;
94 SU->isCall = Old->isCall;
95 SU->isCallOp = Old->isCallOp;
96 SU->isTwoAddress = Old->isTwoAddress;
97 SU->isCommutable = Old->isCommutable;
98 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
99 SU->hasPhysRegClobbers = Old->hasPhysRegClobbers;
100 SU->isScheduleHigh = Old->isScheduleHigh;
101 SU->isScheduleLow = Old->isScheduleLow;
102 SU->SchedulingPref = Old->SchedulingPref;
103 Old->isCloned = true;
107 /// CheckForPhysRegDependency - Check if the dependency between def and use of
108 /// a specified operand is a physical register dependency. If so, returns the
109 /// register and the cost of copying the register.
110 static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
111 const TargetRegisterInfo *TRI,
112 const TargetInstrInfo *TII,
113 unsigned &PhysReg, int &Cost) {
114 if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
117 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
118 if (TargetRegisterInfo::isVirtualRegister(Reg))
121 unsigned ResNo = User->getOperand(2).getResNo();
122 if (Def->getOpcode() == ISD::CopyFromReg &&
123 cast<RegisterSDNode>(Def->getOperand(1))->getReg() == Reg) {
125 } else if (Def->isMachineOpcode()) {
126 const MCInstrDesc &II = TII->get(Def->getMachineOpcode());
127 if (ResNo >= II.getNumDefs() &&
128 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg)
133 const TargetRegisterClass *RC =
134 TRI->getMinimalPhysRegClass(Reg, Def->getSimpleValueType(ResNo));
135 Cost = RC->getCopyCost();
139 // Helper for AddGlue to clone node operands.
140 static void CloneNodeWithValues(SDNode *N, SelectionDAG *DAG,
141 SmallVectorImpl<EVT> &VTs,
142 SDValue ExtraOper = SDValue()) {
143 SmallVector<SDValue, 8> Ops;
144 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I)
145 Ops.push_back(N->getOperand(I));
147 if (ExtraOper.getNode())
148 Ops.push_back(ExtraOper);
150 SDVTList VTList = DAG->getVTList(VTs);
151 MachineSDNode::mmo_iterator Begin = nullptr, End = nullptr;
152 MachineSDNode *MN = dyn_cast<MachineSDNode>(N);
154 // Store memory references.
156 Begin = MN->memoperands_begin();
157 End = MN->memoperands_end();
160 DAG->MorphNodeTo(N, N->getOpcode(), VTList, Ops);
162 // Reset the memory references
164 MN->setMemRefs(Begin, End);
167 static bool AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
168 SmallVector<EVT, 4> VTs;
169 SDNode *GlueDestNode = Glue.getNode();
171 // Don't add glue from a node to itself.
172 if (GlueDestNode == N) return false;
174 // Don't add a glue operand to something that already uses glue.
176 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
179 // Don't add glue to something that already has a glue value.
180 if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return false;
182 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
183 VTs.push_back(N->getValueType(I));
186 VTs.push_back(MVT::Glue);
188 CloneNodeWithValues(N, DAG, VTs, Glue);
193 // Cleanup after unsuccessful AddGlue. Use the standard method of morphing the
194 // node even though simply shrinking the value list is sufficient.
195 static void RemoveUnusedGlue(SDNode *N, SelectionDAG *DAG) {
196 assert((N->getValueType(N->getNumValues() - 1) == MVT::Glue &&
197 !N->hasAnyUseOfValue(N->getNumValues() - 1)) &&
198 "expected an unused glue value");
200 SmallVector<EVT, 4> VTs;
201 for (unsigned I = 0, E = N->getNumValues()-1; I != E; ++I)
202 VTs.push_back(N->getValueType(I));
204 CloneNodeWithValues(N, DAG, VTs);
207 /// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
208 /// This function finds loads of the same base and different offsets. If the
209 /// offsets are not far apart (target specific), it add MVT::Glue inputs and
210 /// outputs to ensure they are scheduled together and in order. This
211 /// optimization may benefit some targets by improving cache locality.
212 void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
213 SDNode *Chain = nullptr;
214 unsigned NumOps = Node->getNumOperands();
215 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
216 Chain = Node->getOperand(NumOps-1).getNode();
220 // Look for other loads of the same chain. Find loads that are loading from
221 // the same base pointer and different offsets.
222 SmallPtrSet<SDNode*, 16> Visited;
223 SmallVector<int64_t, 4> Offsets;
224 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
225 bool Cluster = false;
227 // This algorithm requires a reasonably low use count before finding a match
228 // to avoid uselessly blowing up compile time in large blocks.
229 unsigned UseCount = 0;
230 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end();
231 I != E && UseCount < 100; ++I, ++UseCount) {
233 if (User == Node || !Visited.insert(User).second)
235 int64_t Offset1, Offset2;
236 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
238 // FIXME: Should be ok if they addresses are identical. But earlier
239 // optimizations really should have eliminated one of the loads.
241 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
242 Offsets.push_back(Offset1);
243 O2SMap.insert(std::make_pair(Offset2, User));
244 Offsets.push_back(Offset2);
245 if (Offset2 < Offset1)
248 // Reset UseCount to allow more matches.
255 // Sort them in increasing order.
256 std::sort(Offsets.begin(), Offsets.end());
258 // Check if the loads are close enough.
259 SmallVector<SDNode*, 4> Loads;
260 unsigned NumLoads = 0;
261 int64_t BaseOff = Offsets[0];
262 SDNode *BaseLoad = O2SMap[BaseOff];
263 Loads.push_back(BaseLoad);
264 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
265 int64_t Offset = Offsets[i];
266 SDNode *Load = O2SMap[Offset];
267 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
268 break; // Stop right here. Ignore loads that are further away.
269 Loads.push_back(Load);
276 // Cluster loads by adding MVT::Glue outputs and inputs. This also
277 // ensure they are scheduled in order of increasing addresses.
278 SDNode *Lead = Loads[0];
279 SDValue InGlue = SDValue(nullptr, 0);
280 if (AddGlue(Lead, InGlue, true, DAG))
281 InGlue = SDValue(Lead, Lead->getNumValues() - 1);
282 for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
283 bool OutGlue = I < E - 1;
284 SDNode *Load = Loads[I];
286 // If AddGlue fails, we could leave an unsused glue value. This should not
288 if (AddGlue(Load, InGlue, OutGlue, DAG)) {
290 InGlue = SDValue(Load, Load->getNumValues() - 1);
294 else if (!OutGlue && InGlue.getNode())
295 RemoveUnusedGlue(InGlue.getNode(), DAG);
299 /// ClusterNodes - Cluster certain nodes which should be scheduled together.
301 void ScheduleDAGSDNodes::ClusterNodes() {
302 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
303 E = DAG->allnodes_end(); NI != E; ++NI) {
305 if (!Node || !Node->isMachineOpcode())
308 unsigned Opc = Node->getMachineOpcode();
309 const MCInstrDesc &MCID = TII->get(Opc);
311 // Cluster loads from "near" addresses into combined SUnits.
312 ClusterNeighboringLoads(Node);
316 void ScheduleDAGSDNodes::BuildSchedUnits() {
317 // During scheduling, the NodeId field of SDNode is used to map SDNodes
318 // to their associated SUnits by holding SUnits table indices. A value
319 // of -1 means the SDNode does not yet have an associated SUnit.
320 unsigned NumNodes = 0;
321 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(),
322 E = DAG->allnodes_end(); NI != E; ++NI) {
327 // Reserve entries in the vector for each of the SUnits we are creating. This
328 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
330 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
331 // This is a temporary workaround.
332 SUnits.reserve(NumNodes * 2);
334 // Add all nodes in depth first order.
335 SmallVector<SDNode*, 64> Worklist;
336 SmallPtrSet<SDNode*, 64> Visited;
337 Worklist.push_back(DAG->getRoot().getNode());
338 Visited.insert(DAG->getRoot().getNode());
340 SmallVector<SUnit*, 8> CallSUnits;
341 while (!Worklist.empty()) {
342 SDNode *NI = Worklist.pop_back_val();
344 // Add all operands to the worklist unless they've already been added.
345 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i)
346 if (Visited.insert(NI->getOperand(i).getNode()).second)
347 Worklist.push_back(NI->getOperand(i).getNode());
349 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
352 // If this node has already been processed, stop now.
353 if (NI->getNodeId() != -1) continue;
355 SUnit *NodeSUnit = newSUnit(NI);
357 // See if anything is glued to this node, if so, add them to glued
358 // nodes. Nodes can have at most one glue input and one glue output. Glue
359 // is required to be the last operand and result of a node.
361 // Scan up to find glued preds.
363 while (N->getNumOperands() &&
364 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
365 N = N->getOperand(N->getNumOperands()-1).getNode();
366 assert(N->getNodeId() == -1 && "Node already inserted!");
367 N->setNodeId(NodeSUnit->NodeNum);
368 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
369 NodeSUnit->isCall = true;
372 // Scan down to find any glued succs.
374 while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
375 SDValue GlueVal(N, N->getNumValues()-1);
377 // There are either zero or one users of the Glue result.
378 bool HasGlueUse = false;
379 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
381 if (GlueVal.isOperandOf(*UI)) {
383 assert(N->getNodeId() == -1 && "Node already inserted!");
384 N->setNodeId(NodeSUnit->NodeNum);
386 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
387 NodeSUnit->isCall = true;
390 if (!HasGlueUse) break;
393 if (NodeSUnit->isCall)
394 CallSUnits.push_back(NodeSUnit);
396 // Schedule zero-latency TokenFactor below any nodes that may increase the
397 // schedule height. Otherwise, ancestors of the TokenFactor may appear to
398 // have false stalls.
399 if (NI->getOpcode() == ISD::TokenFactor)
400 NodeSUnit->isScheduleLow = true;
402 // If there are glue operands involved, N is now the bottom-most node
403 // of the sequence of nodes that are glued together.
405 NodeSUnit->setNode(N);
406 assert(N->getNodeId() == -1 && "Node already inserted!");
407 N->setNodeId(NodeSUnit->NodeNum);
409 // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
410 InitNumRegDefsLeft(NodeSUnit);
412 // Assign the Latency field of NodeSUnit using target-provided information.
413 computeLatency(NodeSUnit);
416 // Find all call operands.
417 while (!CallSUnits.empty()) {
418 SUnit *SU = CallSUnits.pop_back_val();
419 for (const SDNode *SUNode = SU->getNode(); SUNode;
420 SUNode = SUNode->getGluedNode()) {
421 if (SUNode->getOpcode() != ISD::CopyToReg)
423 SDNode *SrcN = SUNode->getOperand(2).getNode();
424 if (isPassiveNode(SrcN)) continue; // Not scheduled.
425 SUnit *SrcSU = &SUnits[SrcN->getNodeId()];
426 SrcSU->isCallOp = true;
431 void ScheduleDAGSDNodes::AddSchedEdges() {
432 const TargetSubtargetInfo &ST = MF.getSubtarget();
434 // Check to see if the scheduler cares about latencies.
435 bool UnitLatencies = forceUnitLatencies();
437 // Pass 2: add the preds, succs, etc.
438 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
439 SUnit *SU = &SUnits[su];
440 SDNode *MainNode = SU->getNode();
442 if (MainNode->isMachineOpcode()) {
443 unsigned Opc = MainNode->getMachineOpcode();
444 const MCInstrDesc &MCID = TII->get(Opc);
445 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
446 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
447 SU->isTwoAddress = true;
451 if (MCID.isCommutable())
452 SU->isCommutable = true;
455 // Find all predecessors and successors of the group.
456 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) {
457 if (N->isMachineOpcode() &&
458 TII->get(N->getMachineOpcode()).getImplicitDefs()) {
459 SU->hasPhysRegClobbers = true;
460 unsigned NumUsed = InstrEmitter::CountResults(N);
461 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
462 --NumUsed; // Skip over unused values at the end.
463 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs())
464 SU->hasPhysRegDefs = true;
467 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
468 SDNode *OpN = N->getOperand(i).getNode();
469 if (isPassiveNode(OpN)) continue; // Not scheduled.
470 SUnit *OpSU = &SUnits[OpN->getNodeId()];
471 assert(OpSU && "Node has no SUnit!");
472 if (OpSU == SU) continue; // In the same group.
474 EVT OpVT = N->getOperand(i).getValueType();
475 assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
476 bool isChain = OpVT == MVT::Other;
478 unsigned PhysReg = 0;
480 // Determine if this is a physical register dependency.
481 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
482 assert((PhysReg == 0 || !isChain) &&
483 "Chain dependence via physreg data?");
484 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
485 // emits a copy from the physical register to a virtual register unless
486 // it requires a cross class copy (cost < 0). That means we are only
487 // treating "expensive to copy" register dependency as physical register
488 // dependency. This may change in the future though.
489 if (Cost >= 0 && !StressSched)
492 // If this is a ctrl dep, latency is 1.
493 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
494 // Special-case TokenFactor chains as zero-latency.
495 if(isChain && OpN->getOpcode() == ISD::TokenFactor)
498 SDep Dep = isChain ? SDep(OpSU, SDep::Barrier)
499 : SDep(OpSU, SDep::Data, PhysReg);
500 Dep.setLatency(OpLatency);
501 if (!isChain && !UnitLatencies) {
502 computeOperandLatency(OpN, N, i, Dep);
503 ST.adjustSchedDependency(OpSU, SU, Dep);
506 if (!SU->addPred(Dep) && !Dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
507 // Multiple register uses are combined in the same SUnit. For example,
508 // we could have a set of glued nodes with all their defs consumed by
509 // another set of glued nodes. Register pressure tracking sees this as
510 // a single use, so to keep pressure balanced we reduce the defs.
512 // We can't tell (without more book-keeping) if this results from
513 // glued nodes or duplicate operands. As long as we don't reduce
514 // NumRegDefsLeft to zero, we handle the common cases well.
515 --OpSU->NumRegDefsLeft;
522 /// BuildSchedGraph - Build the SUnit graph from the selection dag that we
523 /// are input. This SUnit graph is similar to the SelectionDAG, but
524 /// excludes nodes that aren't interesting to scheduling, and represents
525 /// glued together nodes with a single SUnit.
526 void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) {
527 // Cluster certain nodes which should be scheduled together.
529 // Populate the SUnits array.
531 // Compute all the scheduling dependencies between nodes.
535 // Initialize NumNodeDefs for the current Node's opcode.
536 void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
537 // Check for phys reg copy.
541 if (!Node->isMachineOpcode()) {
542 if (Node->getOpcode() == ISD::CopyFromReg)
548 unsigned POpc = Node->getMachineOpcode();
549 if (POpc == TargetOpcode::IMPLICIT_DEF) {
550 // No register need be allocated for this.
554 unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
555 // Some instructions define regs that are not represented in the selection DAG
556 // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
557 NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
561 // Construct a RegDefIter for this SUnit and find the first valid value.
562 ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU,
563 const ScheduleDAGSDNodes *SD)
564 : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) {
569 // Advance to the next valid value defined by the SUnit.
570 void ScheduleDAGSDNodes::RegDefIter::Advance() {
571 for (;Node;) { // Visit all glued nodes.
572 for (;DefIdx < NodeNumDefs; ++DefIdx) {
573 if (!Node->hasAnyUseOfValue(DefIdx))
575 ValueType = Node->getSimpleValueType(DefIdx);
577 return; // Found a normal regdef.
579 Node = Node->getGluedNode();
581 return; // No values left to visit.
587 void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) {
588 assert(SU->NumRegDefsLeft == 0 && "expect a new node");
589 for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
590 assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
591 ++SU->NumRegDefsLeft;
595 void ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
596 SDNode *N = SU->getNode();
598 // TokenFactor operands are considered zero latency, and some schedulers
599 // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
600 // whenever node latency is nonzero.
601 if (N && N->getOpcode() == ISD::TokenFactor) {
606 // Check to see if the scheduler cares about latencies.
607 if (forceUnitLatencies()) {
612 if (!InstrItins || InstrItins->isEmpty()) {
613 if (N && N->isMachineOpcode() &&
614 TII->isHighLatencyDef(N->getMachineOpcode()))
615 SU->Latency = HighLatencyCycles;
621 // Compute the latency for the node. We use the sum of the latencies for
622 // all nodes glued together into this SUnit.
624 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
625 if (N->isMachineOpcode())
626 SU->Latency += TII->getInstrLatency(InstrItins, N);
629 void ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
630 unsigned OpIdx, SDep& dep) const{
631 // Check to see if the scheduler cares about latencies.
632 if (forceUnitLatencies())
635 if (dep.getKind() != SDep::Data)
638 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
639 if (Use->isMachineOpcode())
640 // Adjust the use operand index by num of defs.
641 OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
642 int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
643 if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg &&
645 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
646 if (TargetRegisterInfo::isVirtualRegister(Reg))
647 // This copy is a liveout value. It is likely coalesced, so reduce the
648 // latency so not to penalize the def.
649 // FIXME: need target specific adjustment here?
650 Latency = (Latency > 1) ? Latency - 1 : 1;
653 dep.setLatency(Latency);
656 void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const {
657 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
658 if (!SU->getNode()) {
659 dbgs() << "PHYS REG COPY\n";
663 SU->getNode()->dump(DAG);
665 SmallVector<SDNode *, 4> GluedNodes;
666 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
667 GluedNodes.push_back(N);
668 while (!GluedNodes.empty()) {
670 GluedNodes.back()->dump(DAG);
672 GluedNodes.pop_back();
677 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
678 void ScheduleDAGSDNodes::dumpSchedule() const {
679 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
680 if (SUnit *SU = Sequence[i])
683 dbgs() << "**** NOOP ****\n";
689 /// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
690 /// their state is consistent with the nodes listed in Sequence.
692 void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
693 unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
695 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
698 assert(Sequence.size() - Noops == ScheduledNodes &&
699 "The number of nodes scheduled doesn't match the expected number!");
703 /// ProcessSDDbgValues - Process SDDbgValues associated with this node.
705 ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
706 SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
707 DenseMap<SDValue, unsigned> &VRBaseMap, unsigned Order) {
708 if (!N->getHasDebugValue())
711 // Opportunistically insert immediate dbg_value uses, i.e. those with source
712 // order number right after the N.
713 MachineBasicBlock *BB = Emitter.getBlock();
714 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
715 ArrayRef<SDDbgValue*> DVs = DAG->GetDbgValues(N);
716 for (unsigned i = 0, e = DVs.size(); i != e; ++i) {
717 if (DVs[i]->isInvalidated())
719 unsigned DVOrder = DVs[i]->getOrder();
720 if (!Order || DVOrder == ++Order) {
721 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap);
723 Orders.push_back(std::make_pair(DVOrder, DbgMI));
724 BB->insert(InsertPos, DbgMI);
726 DVs[i]->setIsInvalidated();
731 // ProcessSourceNode - Process nodes with source order numbers. These are added
732 // to a vector which EmitSchedule uses to determine how to insert dbg_value
733 // instructions in the right order.
735 ProcessSourceNode(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter,
736 DenseMap<SDValue, unsigned> &VRBaseMap,
737 SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
738 SmallSet<unsigned, 8> &Seen) {
739 unsigned Order = N->getIROrder();
740 if (!Order || !Seen.insert(Order).second) {
741 // Process any valid SDDbgValues even if node does not have any order
743 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
747 MachineBasicBlock *BB = Emitter.getBlock();
748 if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI() ||
749 // Fast-isel may have inserted some instructions, in which case the
750 // BB->back().isPHI() test will not fire when we want it to.
751 std::prev(Emitter.getInsertPos())->isPHI()) {
752 // Did not insert any instruction.
753 Orders.push_back(std::make_pair(Order, (MachineInstr*)nullptr));
757 Orders.push_back(std::make_pair(Order, std::prev(Emitter.getInsertPos())));
758 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
761 void ScheduleDAGSDNodes::
762 EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
763 MachineBasicBlock::iterator InsertPos) {
764 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
766 if (I->isCtrl()) continue; // ignore chain preds
767 if (I->getSUnit()->CopyDstRC) {
768 // Copy to physical register.
769 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->getSUnit());
770 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
771 // Find the destination physical register.
773 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
774 EE = SU->Succs.end(); II != EE; ++II) {
775 if (II->isCtrl()) continue; // ignore chain preds
781 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
782 .addReg(VRI->second);
784 // Copy from physical register.
785 assert(I->getReg() && "Unknown physical register!");
786 unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
787 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
788 (void)isNew; // Silence compiler warning.
789 assert(isNew && "Node emitted out of order - early");
790 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
791 .addReg(I->getReg());
797 /// EmitSchedule - Emit the machine code in scheduled order. Return the new
798 /// InsertPos and MachineBasicBlock that contains this insertion
799 /// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
800 /// not necessarily refer to returned BB. The emitter may split blocks.
801 MachineBasicBlock *ScheduleDAGSDNodes::
802 EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
803 InstrEmitter Emitter(BB, InsertPos);
804 DenseMap<SDValue, unsigned> VRBaseMap;
805 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
806 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders;
807 SmallSet<unsigned, 8> Seen;
808 bool HasDbg = DAG->hasDebugValues();
810 // If this is the first BB, emit byval parameter dbg_value's.
811 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
812 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
813 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
814 for (; PDI != PDE; ++PDI) {
815 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
817 BB->insert(InsertPos, DbgMI);
821 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
822 SUnit *SU = Sequence[i];
824 // Null SUnit* is a noop.
825 TII->insertNoop(*Emitter.getBlock(), InsertPos);
829 // For pre-regalloc scheduling, create instructions corresponding to the
830 // SDNode and any glued SDNodes and append them to the block.
831 if (!SU->getNode()) {
833 EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
837 SmallVector<SDNode *, 4> GluedNodes;
838 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
839 GluedNodes.push_back(N);
840 while (!GluedNodes.empty()) {
841 SDNode *N = GluedNodes.back();
842 Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned,
844 // Remember the source order of the inserted instruction.
846 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen);
847 GluedNodes.pop_back();
849 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned,
851 // Remember the source order of the inserted instruction.
853 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders,
857 // Insert all the dbg_values which have not already been inserted in source
860 MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
862 // Sort the source order instructions and use the order to insert debug
864 std::sort(Orders.begin(), Orders.end(), less_first());
866 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
867 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
868 // Now emit the rest according to source order.
869 unsigned LastOrder = 0;
870 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
871 unsigned Order = Orders[i].first;
872 MachineInstr *MI = Orders[i].second;
873 // Insert all SDDbgValue's whose order(s) are before "Order".
877 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) {
878 if ((*DI)->isInvalidated())
880 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
883 // Insert to start of the BB (after PHIs).
884 BB->insert(BBBegin, DbgMI);
886 // Insert at the instruction, which may be in a different
887 // block, if the block was split by a custom inserter.
888 MachineBasicBlock::iterator Pos = MI;
889 MI->getParent()->insert(Pos, DbgMI);
895 // Add trailing DbgValue's before the terminator. FIXME: May want to add
896 // some of them before one or more conditional branches?
897 SmallVector<MachineInstr*, 8> DbgMIs;
899 if (!(*DI)->isInvalidated())
900 if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
901 DbgMIs.push_back(DbgMI);
905 MachineBasicBlock *InsertBB = Emitter.getBlock();
906 MachineBasicBlock::iterator Pos = InsertBB->getFirstTerminator();
907 InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
910 InsertPos = Emitter.getInsertPos();
911 return Emitter.getBlock();
914 /// Return the basic block label.
915 std::string ScheduleDAGSDNodes::getDAGName() const {
916 return "sunit-dag." + BB->getFullName();