LLVM 24.0.0git
ScheduleDAGSDNodes.cpp
Go to the documentation of this file.
1//===--- ScheduleDAGSDNodes.cpp - Implement the ScheduleDAGSDNodes class --===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements the ScheduleDAG class, which is a base class used by
10// scheduling implementation classes.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ScheduleDAGSDNodes.h"
15#include "InstrEmitter.h"
16#include "SDNodeDbgValue.h"
17#include "SelectionDAGOptions.h"
18#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/Statistic.h"
30#include "llvm/Config/llvm-config.h"
33#include "llvm/Support/Debug.h"
36using namespace llvm;
37
38#define DEBUG_TYPE "pre-RA-sched"
39
40STATISTIC(LoadsClustered, "Number of loads clustered together");
41
43 : ScheduleDAG(mf), InstrItins(mf.getSubtarget().getInstrItineraryData()) {}
44
45/// Run - perform scheduling.
46///
48 BB = bb;
49 DAG = dag;
50
51 // Clear the scheduler's SUnit DAG.
53 Sequence.clear();
54
55 // Invoke the target's selection of scheduler.
56 Schedule();
57}
58
59/// NewSUnit - Creates a new SUnit and return a ptr to it.
60///
62#ifndef NDEBUG
63 const SUnit *Addr = nullptr;
64 if (!SUnits.empty())
65 Addr = &SUnits[0];
66#endif
67 SUnits.emplace_back(N, (unsigned)SUnits.size());
68 assert((Addr == nullptr || Addr == &SUnits[0]) &&
69 "SUnits std::vector reallocated on the fly!");
70 SUnits.back().OrigNode = &SUnits.back();
71 SUnit *SU = &SUnits.back();
72 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
73 if (!N ||
74 (N->isMachineOpcode() &&
75 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF))
77 else
78 SU->SchedulingPref = TLI.getSchedulingPreference(N);
79 return SU;
80}
81
83 SUnit *SU = newSUnit(Old->getNode());
84 SU->OrigNode = Old->OrigNode;
85 SU->Latency = Old->Latency;
86 SU->isVRegCycle = Old->isVRegCycle;
87 SU->isCall = Old->isCall;
88 SU->isCallOp = Old->isCallOp;
89 SU->isTwoAddress = Old->isTwoAddress;
90 SU->isCommutable = Old->isCommutable;
96 Old->isCloned = true;
97 return SU;
98}
99
100/// CheckForPhysRegDependency - Check if the dependency between def and use of
101/// a specified operand is a physical register dependency. If so, returns the
102/// register and the cost of copying the register.
103static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op,
104 const TargetRegisterInfo *TRI,
105 const TargetInstrInfo *TII,
106 MCRegister &PhysReg, int &Cost) {
107 if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
108 return;
109
111 if (Reg.isVirtual())
112 return;
113
114 unsigned ResNo = User->getOperand(2).getResNo();
115 if (Def->getOpcode() == ISD::CopyFromReg &&
116 cast<RegisterSDNode>(Def->getOperand(1))->getReg() == Reg) {
117 PhysReg = Reg;
118 } else if (Def->isMachineOpcode()) {
119 const MCInstrDesc &II = TII->get(Def->getMachineOpcode());
120 if (ResNo >= II.getNumDefs() && II.hasImplicitDefOfPhysReg(Reg))
121 PhysReg = Reg;
122 }
123
124 if (PhysReg) {
125 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
126 Cost = RC->expensiveOrImpossibleToCopy() ? -1 : RC->getCopyCost();
127 }
128}
129
130// Helper for AddGlue to clone node operands.
132 SDValue ExtraOper = SDValue()) {
134 if (ExtraOper.getNode())
135 Ops.push_back(ExtraOper);
136
137 SDVTList VTList = DAG->getVTList(VTs);
139
140 // Store memory references.
142 if (MN)
143 MMOs.assign(MN->memoperands_begin(), MN->memoperands_end());
144
145 DAG->MorphNodeTo(N, N->getOpcode(), VTList, Ops);
146
147 // Reset the memory references
148 if (MN)
149 DAG->setNodeMemRefs(MN, MMOs);
150}
151
152static bool AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) {
153 SDNode *GlueDestNode = Glue.getNode();
154
155 // Don't add glue from a node to itself.
156 if (GlueDestNode == N) return false;
157
158 // Don't add a glue operand to something that already uses glue.
159 if (GlueDestNode &&
160 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
161 return false;
162 }
163 // Don't add glue to something that already has a glue value.
164 if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return false;
165
166 SmallVector<EVT, 4> VTs(N->values());
167 if (AddGlue)
168 VTs.push_back(MVT::Glue);
169
170 CloneNodeWithValues(N, DAG, VTs, Glue);
171
172 return true;
173}
174
175// Cleanup after unsuccessful AddGlue. Use the standard method of morphing the
176// node even though simply shrinking the value list is sufficient.
178 assert((N->getValueType(N->getNumValues() - 1) == MVT::Glue &&
179 !N->hasAnyUseOfValue(N->getNumValues() - 1)) &&
180 "expected an unused glue value");
181
183 ArrayRef(N->value_begin(), N->getNumValues() - 1));
184}
185
186/// ClusterNeighboringLoads - Force nearby loads together by "gluing" them.
187/// This function finds loads of the same base and different offsets. If the
188/// offsets are not far apart (target specific), it add MVT::Glue inputs and
189/// outputs to ensure they are scheduled together and in order. This
190/// optimization may benefit some targets by improving cache locality.
191void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) {
192 SDValue Chain;
193 unsigned NumOps = Node->getNumOperands();
194 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other)
195 Chain = Node->getOperand(NumOps-1);
196 if (!Chain)
197 return;
198
199 // Skip any load instruction that has a tied input. There may be an additional
200 // dependency requiring a different order than by increasing offsets, and the
201 // added glue may introduce a cycle.
202 auto hasTiedInput = [this](const SDNode *N) {
203 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
204 for (unsigned I = 0; I != MCID.getNumOperands(); ++I) {
205 if (MCID.getOperandConstraint(I, MCOI::TIED_TO) != -1)
206 return true;
207 }
208
209 return false;
210 };
211
212 // Look for other loads of the same chain. Find loads that are loading from
213 // the same base pointer and different offsets.
214 SmallPtrSet<SDNode*, 16> Visited;
216 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode.
217 bool Cluster = false;
218 SDNode *Base = Node;
219
220 if (hasTiedInput(Base))
221 return;
222
223 // This algorithm requires a reasonably low use count before finding a match
224 // to avoid uselessly blowing up compile time in large blocks.
225 unsigned UseCount = 0;
226 for (SDNode::user_iterator I = Chain->user_begin(), E = Chain->user_end();
227 I != E && UseCount < 100; ++I, ++UseCount) {
228 if (I.getUse().getResNo() != Chain.getResNo())
229 continue;
230
231 SDNode *User = *I;
232 if (User == Node || !Visited.insert(User).second)
233 continue;
234 int64_t Offset1, Offset2;
235 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) ||
236 Offset1 == Offset2 ||
237 hasTiedInput(User)) {
238 // FIXME: Should be ok if they addresses are identical. But earlier
239 // optimizations really should have eliminated one of the loads.
240 continue;
241 }
242 if (O2SMap.insert(std::make_pair(Offset1, Base)).second)
243 Offsets.push_back(Offset1);
244 O2SMap.insert(std::make_pair(Offset2, User));
245 Offsets.push_back(Offset2);
246 if (Offset2 < Offset1)
247 Base = User;
248 Cluster = true;
249 // Reset UseCount to allow more matches.
250 UseCount = 0;
251 }
252
253 if (!Cluster)
254 return;
255
256 // Sort them in increasing order.
257 llvm::sort(Offsets);
258
259 // Check if the loads are close enough.
261 unsigned NumLoads = 0;
262 int64_t BaseOff = Offsets[0];
263 SDNode *BaseLoad = O2SMap[BaseOff];
264 Loads.push_back(BaseLoad);
265 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) {
266 int64_t Offset = Offsets[i];
267 SDNode *Load = O2SMap[Offset];
268 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads))
269 break; // Stop right here. Ignore loads that are further away.
270 Loads.push_back(Load);
271 ++NumLoads;
272 }
273
274 if (NumLoads == 0)
275 return;
276
277 // Cluster loads by adding MVT::Glue outputs and inputs. This also
278 // ensure they are scheduled in order of increasing addresses.
279 SDNode *Lead = Loads[0];
280 SDValue InGlue;
281 if (AddGlue(Lead, InGlue, true, DAG))
282 InGlue = SDValue(Lead, Lead->getNumValues() - 1);
283 for (unsigned I = 1, E = Loads.size(); I != E; ++I) {
284 bool OutGlue = I < E - 1;
285 SDNode *Load = Loads[I];
286
287 // If AddGlue fails, we could leave an unsused glue value. This should not
288 // cause any
289 if (AddGlue(Load, InGlue, OutGlue, DAG)) {
290 if (OutGlue)
291 InGlue = SDValue(Load, Load->getNumValues() - 1);
292
293 ++LoadsClustered;
294 }
295 else if (!OutGlue && InGlue.getNode())
296 RemoveUnusedGlue(InGlue.getNode(), DAG);
297 }
298}
299
300/// ClusterNodes - Cluster certain nodes which should be scheduled together.
301///
302void ScheduleDAGSDNodes::ClusterNodes() {
303 for (SDNode &NI : DAG->allnodes()) {
304 SDNode *Node = &NI;
305 if (!Node || !Node->isMachineOpcode())
306 continue;
307
308 unsigned Opc = Node->getMachineOpcode();
309 const MCInstrDesc &MCID = TII->get(Opc);
310 if (MCID.mayLoad())
311 // Cluster loads from "near" addresses into combined SUnits.
312 ClusterNeighboringLoads(Node);
313 }
314}
315
316void 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 (SDNode &NI : DAG->allnodes()) {
322 NI.setNodeId(-1);
323 NI.setSchedulerWorklistVisited(false);
324 ++NumNodes;
325 }
326
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
329 // invalidated.
330 // FIXME: Multiply by 2 because we may clone nodes during scheduling.
331 // This is a temporary workaround.
332 SUnits.reserve(NumNodes * 2);
333
334 // Add all nodes in depth first order.
336 Worklist.push_back(DAG->getRoot().getNode());
337 DAG->getRoot().getNode()->setSchedulerWorklistVisited(true);
338
339 SmallVector<SUnit*, 8> CallSUnits;
340 while (!Worklist.empty()) {
341 SDNode *NI = Worklist.pop_back_val();
342
343 // Add all operands to the worklist unless they've already been added.
344 for (const SDValue &Op : NI->op_values()) {
345 if (Op.getNode()->getSchedulerWorklistVisited())
346 continue;
347 Op.getNode()->setSchedulerWorklistVisited(true);
348 Worklist.push_back(Op.getNode());
349 }
350
351 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
352 continue;
353
354 // If this node has already been processed, stop now.
355 if (NI->getNodeId() != -1) continue;
356
357 SUnit *NodeSUnit = newSUnit(NI);
358
359 // See if anything is glued to this node, if so, add them to glued
360 // nodes. Nodes can have at most one glue input and one glue output. Glue
361 // is required to be the last operand and result of a node.
362
363 // Scan up to find glued preds.
364 SDNode *N = NI;
365 while (N->getNumOperands() &&
366 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) {
367 N = N->getOperand(N->getNumOperands()-1).getNode();
368 assert(N->getNodeId() == -1 && "Node already inserted!");
369 N->setNodeId(NodeSUnit->NodeNum);
370 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
371 NodeSUnit->isCall = true;
372 }
373
374 // Scan down to find any glued succs.
375 N = NI;
376 while (N->getValueType(N->getNumValues()-1) == MVT::Glue) {
377 SDValue GlueVal(N, N->getNumValues()-1);
378
379 // There are either zero or one users of the Glue result.
380 bool HasGlueUse = false;
381 for (SDNode *U : N->users())
382 if (GlueVal.isOperandOf(U)) {
383 HasGlueUse = true;
384 assert(N->getNodeId() == -1 && "Node already inserted!");
385 N->setNodeId(NodeSUnit->NodeNum);
386 N = U;
387 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall())
388 NodeSUnit->isCall = true;
389 break;
390 }
391 if (!HasGlueUse) break;
392 }
393
394 if (NodeSUnit->isCall)
395 CallSUnits.push_back(NodeSUnit);
396
397 // Schedule zero-latency TokenFactor below any nodes that may increase the
398 // schedule height. Otherwise, ancestors of the TokenFactor may appear to
399 // have false stalls.
400 if (NI->getOpcode() == ISD::TokenFactor)
401 NodeSUnit->isScheduleLow = true;
402
403 // If there are glue operands involved, N is now the bottom-most node
404 // of the sequence of nodes that are glued together.
405 // Update the SUnit.
406 NodeSUnit->setNode(N);
407 assert(N->getNodeId() == -1 && "Node already inserted!");
408 N->setNodeId(NodeSUnit->NodeNum);
409
410 // Compute NumRegDefsLeft. This must be done before AddSchedEdges.
411 InitNumRegDefsLeft(NodeSUnit);
412
413 // Assign the Latency field of NodeSUnit using target-provided information.
414 computeLatency(NodeSUnit);
415 }
416
417 // Find all call operands.
418 while (!CallSUnits.empty()) {
419 SUnit *SU = CallSUnits.pop_back_val();
420 for (const SDNode *SUNode = SU->getNode(); SUNode;
421 SUNode = SUNode->getGluedNode()) {
422 if (SUNode->getOpcode() != ISD::CopyToReg)
423 continue;
424 SDNode *SrcN = SUNode->getOperand(2).getNode();
425 if (isPassiveNode(SrcN)) continue; // Not scheduled.
426 SUnit *SrcSU = &SUnits[SrcN->getNodeId()];
427 SrcSU->isCallOp = true;
428 }
429 }
430}
431
432void ScheduleDAGSDNodes::AddSchedEdges() {
433 const TargetSubtargetInfo &ST = MF.getSubtarget();
434
435 // Check to see if the scheduler cares about latencies.
436 bool UnitLatencies = forceUnitLatencies();
437
438 // Pass 2: add the preds, succs, etc.
439 for (SUnit &SU : SUnits) {
440 SDNode *MainNode = SU.getNode();
441
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;
448 break;
449 }
450 }
451 if (MCID.isCommutable())
452 SU.isCommutable = true;
453 }
454
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()).implicit_defs().empty()) {
459 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
460 SU.hasPhysRegClobbers = true;
461 // Results beyond the explicit defs are physical register defs, unless
462 // the target models variadic results as virtual registers. This must
463 // match InstrEmitter::EmitMachineNode.
464 bool HasVRegVariadicDefs = !MF.getTarget().usesPhysRegsForValues() &&
465 MCID.isVariadic() &&
466 MCID.variadicOpsAreDefs();
467 unsigned NumUsed = InstrEmitter::CountResults(N);
468 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1))
469 --NumUsed; // Skip over unused values at the end.
470 if (!HasVRegVariadicDefs && NumUsed > MCID.getNumDefs())
471 SU.hasPhysRegDefs = true;
472 }
473
474 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
475 SDNode *OpN = N->getOperand(i).getNode();
476 unsigned DefIdx = N->getOperand(i).getResNo();
477 if (isPassiveNode(OpN)) continue; // Not scheduled.
478 SUnit *OpSU = &SUnits[OpN->getNodeId()];
479 assert(OpSU && "Node has no SUnit!");
480 if (OpSU == &SU)
481 continue; // In the same group.
482
483 EVT OpVT = N->getOperand(i).getValueType();
484 assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!");
485 bool isChain = OpVT == MVT::Other;
486
487 MCRegister PhysReg;
488 int Cost = 1;
489 // Determine if this is a physical register dependency.
490 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
491 assert((!PhysReg || !isChain) && "Chain dependence via physreg data?");
492 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler
493 // emits a copy from the physical register to a virtual register unless
494 // it requires a cross class copy (cost < 0). That means we are only
495 // treating "expensive to copy" register dependency as physical register
496 // dependency. This may change in the future though.
497 if (Cost >= 0 && !StressSched)
498 PhysReg = MCRegister();
499
500 // If this is a ctrl dep, latency is 1.
501 unsigned OpLatency = isChain ? 1 : OpSU->Latency;
502 // Special-case TokenFactor chains as zero-latency.
503 if(isChain && OpN->getOpcode() == ISD::TokenFactor)
504 OpLatency = 0;
505
506 SDep Dep = isChain ? SDep(OpSU, SDep::Barrier)
507 : SDep(OpSU, SDep::Data, PhysReg);
508 Dep.setLatency(OpLatency);
509 if (!isChain && !UnitLatencies) {
510 computeOperandLatency(OpN, N, i, Dep);
511 ST.adjustSchedDependency(OpSU, DefIdx, &SU, i, Dep, nullptr);
512 }
513
514 if (!SU.addPred(Dep) && !Dep.isCtrl() && OpSU->NumRegDefsLeft > 1) {
515 // Multiple register uses are combined in the same SUnit. For example,
516 // we could have a set of glued nodes with all their defs consumed by
517 // another set of glued nodes. Register pressure tracking sees this as
518 // a single use, so to keep pressure balanced we reduce the defs.
519 //
520 // We can't tell (without more book-keeping) if this results from
521 // glued nodes or duplicate operands. As long as we don't reduce
522 // NumRegDefsLeft to zero, we handle the common cases well.
523 --OpSU->NumRegDefsLeft;
524 }
525 }
526 }
527 }
528}
529
530/// BuildSchedGraph - Build the SUnit graph from the selection dag that we
531/// are input. This SUnit graph is similar to the SelectionDAG, but
532/// excludes nodes that aren't interesting to scheduling, and represents
533/// glued together nodes with a single SUnit.
535 // Cluster certain nodes which should be scheduled together.
536 ClusterNodes();
537 // Populate the SUnits array.
538 BuildSchedUnits();
539 // Compute all the scheduling dependencies between nodes.
540 AddSchedEdges();
541}
542
543// Initialize NumNodeDefs for the current Node's opcode.
544void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() {
545 // Check for phys reg copy.
546 if (!Node)
547 return;
548
549 if (!Node->isMachineOpcode()) {
550 if (Node->getOpcode() == ISD::CopyFromReg)
551 NodeNumDefs = 1;
552 else
553 NodeNumDefs = 0;
554 return;
555 }
556 unsigned POpc = Node->getMachineOpcode();
557 if (POpc == TargetOpcode::IMPLICIT_DEF) {
558 // No register need be allocated for this.
559 NodeNumDefs = 0;
560 return;
561 }
562 if (POpc == TargetOpcode::PATCHPOINT &&
563 Node->getValueType(0) == MVT::Other) {
564 // PATCHPOINT is defined to have one result, but it might really have none
565 // if we're not using CallingConv::AnyReg. Don't mistake the chain for a
566 // real definition.
567 NodeNumDefs = 0;
568 return;
569 }
570 unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs();
571 // Some instructions define regs that are not represented in the selection DAG
572 // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues.
573 NodeNumDefs = std::min(Node->getNumValues(), NRegDefs);
574 DefIdx = 0;
575}
576
577// Construct a RegDefIter for this SUnit and find the first valid value.
579 const ScheduleDAGSDNodes *SD)
580 : SchedDAG(SD), Node(SU->getNode()) {
581 InitNodeNumDefs();
582 Advance();
583}
584
585// Advance to the next valid value defined by the SUnit.
587 for (;Node;) { // Visit all glued nodes.
588 for (;DefIdx < NodeNumDefs; ++DefIdx) {
589 if (!Node->hasAnyUseOfValue(DefIdx))
590 continue;
591 ValueType = Node->getSimpleValueType(DefIdx);
592 ++DefIdx;
593 return; // Found a normal regdef.
594 }
595 Node = Node->getGluedNode();
596 if (!Node) {
597 return; // No values left to visit.
598 }
599 InitNodeNumDefs();
600 }
601}
602
604 assert(SU->NumRegDefsLeft == 0 && "expect a new node");
605 for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) {
606 assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected");
607 ++SU->NumRegDefsLeft;
608 }
609}
610
612 SDNode *N = SU->getNode();
613
614 // TokenFactor operands are considered zero latency, and some schedulers
615 // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero
616 // whenever node latency is nonzero.
617 if (N && N->getOpcode() == ISD::TokenFactor) {
618 SU->Latency = 0;
619 return;
620 }
621
622 // Check to see if the scheduler cares about latencies.
623 if (forceUnitLatencies()) {
624 SU->Latency = 1;
625 return;
626 }
627
628 if (!InstrItins || InstrItins->isEmpty()) {
629 if (N && N->isMachineOpcode() &&
630 TII->isHighLatencyDef(N->getMachineOpcode()))
631 SU->Latency = DAG->getSelectionDAGOptions().sched_high_latency_cycles;
632 else
633 SU->Latency = 1;
634 return;
635 }
636
637 // Compute the latency for the node. We use the sum of the latencies for
638 // all nodes glued together into this SUnit.
639 SU->Latency = 0;
640 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode())
641 if (N->isMachineOpcode())
642 SU->Latency += TII->getInstrLatency(InstrItins, N);
643}
644
646 unsigned OpIdx, SDep& dep) const{
647 // Check to see if the scheduler cares about latencies.
648 if (forceUnitLatencies())
649 return;
650
651 if (dep.getKind() != SDep::Data)
652 return;
653
654 unsigned DefIdx = Use->getOperand(OpIdx).getResNo();
655 if (Use->isMachineOpcode())
656 // Adjust the use operand index by num of defs.
657 OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs();
658 std::optional<unsigned> Latency =
659 TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx);
660 if (Latency > 1U && Use->getOpcode() == ISD::CopyToReg &&
661 !BB->succ_empty()) {
662 Register Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
663 if (Reg.isVirtual())
664 // This copy is a liveout value. It is likely coalesced, so reduce the
665 // latency so not to penalize the def.
666 // FIXME: need target specific adjustment here?
667 Latency = *Latency - 1;
668 }
669 if (Latency)
670 dep.setLatency(*Latency);
671}
672
673void ScheduleDAGSDNodes::dumpNode(const SUnit &SU) const {
674#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
675 dumpNodeName(SU);
676 dbgs() << ": ";
677
678 if (!SU.getNode()) {
679 dbgs() << "PHYS REG COPY\n";
680 return;
681 }
682
683 SU.getNode()->dump(DAG);
684 dbgs() << "\n";
685 SmallVector<SDNode *, 4> GluedNodes;
686 for (SDNode *N = SU.getNode()->getGluedNode(); N; N = N->getGluedNode())
687 GluedNodes.push_back(N);
688 while (!GluedNodes.empty()) {
689 dbgs() << " ";
690 GluedNodes.back()->dump(DAG);
691 dbgs() << "\n";
692 GluedNodes.pop_back();
693 }
694#endif
695}
696
698#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
699 if (EntrySU.getNode() != nullptr)
701 for (const SUnit &SU : SUnits)
702 dumpNodeAll(SU);
703 if (ExitSU.getNode() != nullptr)
705#endif
706}
707
708#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
710 for (const SUnit *SU : Sequence) {
711 if (SU)
712 dumpNode(*SU);
713 else
714 dbgs() << "**** NOOP ****\n";
715 }
716}
717#endif
718
719#ifndef NDEBUG
720/// VerifyScheduledSequence - Verify that all SUnits were scheduled and that
721/// their state is consistent with the nodes listed in Sequence.
722///
724 unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp);
725 unsigned Noops = llvm::count(Sequence, nullptr);
726 assert(Sequence.size() - Noops == ScheduledNodes &&
727 "The number of nodes scheduled doesn't match the expected number!");
728}
729#endif // NDEBUG
730
731/// ProcessSDDbgValues - Process SDDbgValues associated with this node.
732static void
734 SmallVectorImpl<std::pair<unsigned, MachineInstr*> > &Orders,
735 InstrEmitter::VRBaseMapType &VRBaseMap, unsigned Order) {
736 if (!N->getHasDebugValue())
737 return;
738
739 /// Returns true if \p DV has any VReg operand locations which don't exist in
740 /// VRBaseMap.
741 auto HasUnknownVReg = [&VRBaseMap](SDDbgValue *DV) {
742 for (const SDDbgOperand &L : DV->getLocationOps()) {
743 if (L.getKind() == SDDbgOperand::SDNODE &&
744 VRBaseMap.count({L.getSDNode(), L.getResNo()}) == 0)
745 return true;
746 }
747 return false;
748 };
749
750 // Opportunistically insert immediate dbg_value uses, i.e. those with the same
751 // source order number as N.
752 MachineBasicBlock *BB = Emitter.getBlock();
753 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos();
754 for (auto *DV : DAG->GetDbgValues(N)) {
755 if (DV->isEmitted())
756 continue;
757 unsigned DVOrder = DV->getOrder();
758 if (Order != 0 && DVOrder != Order)
759 continue;
760 // If DV has any VReg location operands which haven't been mapped then
761 // either that node is no longer available or we just haven't visited the
762 // node yet. In the former case we should emit an undef dbg_value, but we
763 // can do it later. And for the latter we'll want to wait until all
764 // dependent nodes have been visited.
765 if (!DV->isInvalidated() && HasUnknownVReg(DV))
766 continue;
767 MachineInstr *DbgMI = Emitter.EmitDbgValue(DV, VRBaseMap);
768 if (!DbgMI)
769 continue;
770 Orders.push_back({DVOrder, DbgMI});
771 BB->insert(InsertPos, DbgMI);
772 }
773}
774
775// ProcessSourceNode - Process nodes with source order numbers. These are added
776// to a vector which EmitSchedule uses to determine how to insert dbg_value
777// instructions in the right order.
778static void
781 SmallVectorImpl<std::pair<unsigned, MachineInstr *>> &Orders,
782 SmallSet<Register, 8> &Seen, MachineInstr *NewInsn) {
783 unsigned Order = N->getIROrder();
784 if (!Order || Seen.count(Order)) {
785 // Process any valid SDDbgValues even if node does not have any order
786 // assigned.
787 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0);
788 return;
789 }
790
791 // If a new instruction was generated for this Order number, record it.
792 // Otherwise, leave this order number unseen: we will either find later
793 // instructions for it, or leave it unseen if there were no instructions at
794 // all.
795 if (NewInsn) {
796 Seen.insert(Order);
797 Orders.push_back({Order, NewInsn});
798 }
799
800 // Even if no instruction was generated, a Value may have become defined via
801 // earlier nodes. Try to process them now.
802 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
803}
804
805void ScheduleDAGSDNodes::
806EmitPhysRegCopy(SUnit *SU, SmallDenseMap<SUnit *, Register, 16> &VRBaseMap,
807 MachineBasicBlock::iterator InsertPos) {
808 for (const SDep &Pred : SU->Preds) {
809 if (Pred.isCtrl())
810 continue; // ignore chain preds
811 if (Pred.getSUnit()->CopyDstRC) {
812 // Copy to physical register.
813 auto VRI = VRBaseMap.find(Pred.getSUnit());
814 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
815 // Find the destination physical register.
817 for (const SDep &Succ : SU->Succs) {
818 if (Succ.isCtrl())
819 continue; // ignore chain preds
820 if (Succ.getReg()) {
821 Reg = Succ.getReg();
822 break;
823 }
824 }
825 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg)
826 .addReg(VRI->second);
827 } else {
828 // Copy from physical register.
829 assert(Pred.getReg() && "Unknown physical register!");
830 Register VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
831 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
832 (void)isNew; // Silence compiler warning.
833 assert(isNew && "Node emitted out of order - early");
834 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase)
835 .addReg(Pred.getReg());
836 }
837 break;
838 }
839}
840
841/// Mark physreg defs dead on \p MI, emitted for a cloned node \p SU. All copies
842/// share one SDNode, so InstrEmitter can't tell which copy lost its users. A
843/// live def of an expensive-to-copy physreg is carried on a scheduler edge by
844/// some copy, so it is dead if \p SU has no such edge.
846 const TargetRegisterInfo *TRI) {
847 for (MachineOperand &MO : MI.implicit_operands()) {
848 if (!MO.isReg() || !MO.isDef() || MO.isDead())
849 continue;
850 Register Reg = MO.getReg();
851 if (!TRI->getMinimalPhysRegClass(Reg)->expensiveOrImpossibleToCopy())
852 continue;
853 if (none_of(SU.Succs, [=](const SDep &Succ) {
854 return Succ.isAssignedRegDep() && Succ.getReg() == Reg;
855 }))
856 MO.setIsDead();
857 }
858}
859
860/// EmitSchedule - Emit the machine code in scheduled order. Return the new
861/// InsertPos and MachineBasicBlock that contains this insertion
862/// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does
863/// not necessarily refer to returned BB. The emitter may split blocks.
866 InstrEmitter Emitter(DAG->getTarget(), BB, InsertPos);
871 bool HasDbg = DAG->hasDebugValues();
872
873 // Emit a node, and determine where its first instruction is for debuginfo.
874 // Zero, one, or multiple instructions can be created when emitting a node.
875 auto EmitNode =
876 [&](SDNode *Node, bool IsClone, bool IsCloned,
878 // Fetch instruction prior to this, or end() if nonexistant.
879 auto GetPrevInsn = [&](MachineBasicBlock::iterator I) {
880 if (I == BB->begin())
881 return BB->end();
882 else
883 return std::prev(Emitter.getInsertPos());
884 };
885
886 MachineBasicBlock::iterator Before = GetPrevInsn(Emitter.getInsertPos());
887 Emitter.EmitNode(Node, IsClone, IsCloned, VRBaseMap);
888 MachineBasicBlock::iterator After = GetPrevInsn(Emitter.getInsertPos());
889
890 // If the iterator did not change, no instructions were inserted.
891 if (Before == After)
892 return nullptr;
893
895 if (Before == BB->end()) {
896 // There were no prior instructions; the new ones must start at the
897 // beginning of the block.
898 MI = &Emitter.getBlock()->instr_front();
899 } else {
900 // Return first instruction after the pre-existing instructions.
901 MI = &*std::next(Before);
902 }
903
904 if (MI->isCandidateForAdditionalCallInfo()) {
905 if (DAG->getTarget().Options.EmitCallSiteInfo ||
906 DAG->getTarget().Options.EmitCallGraphSection)
907 MF.addCallSiteInfo(MI, DAG->getCallSiteInfo(Node));
908
909 if (auto CalledGlobal = DAG->getCalledGlobal(Node))
910 if (CalledGlobal->Callee)
911 MF.addCalledGlobal(MI, *CalledGlobal);
912 }
913
914 if (DAG->getNoMergeSiteInfo(Node)) {
916 }
917
918 if (MDNode *MD = DAG->getPCSections(Node))
919 MI->setPCSections(MF, MD);
920
921 // Set MMRAs on _all_ added instructions.
922 if (MDNode *MMRA = DAG->getMMRAMetadata(Node)) {
923 for (MachineBasicBlock::iterator It = MI->getIterator(),
924 End = std::next(After);
925 It != End; ++It)
926 It->setMMRAMetadata(MF, MMRA);
927 }
928
929 return MI;
930 };
931
932 // If this is the first BB, emit byval parameter dbg_value's.
933 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) {
934 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin();
935 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd();
936 for (; PDI != PDE; ++PDI) {
937 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap);
938 if (DbgMI) {
939 BB->insert(InsertPos, DbgMI);
940 // We re-emit the dbg_value closer to its use, too, after instructions
941 // are emitted to the BB.
942 (*PDI)->clearIsEmitted();
943 }
944 }
945 }
946
947 for (SUnit *SU : Sequence) {
948 if (!SU) {
949 // Null SUnit* is a noop.
950 TII->insertNoop(*Emitter.getBlock(), InsertPos);
951 continue;
952 }
953
954 // For pre-regalloc scheduling, create instructions corresponding to the
955 // SDNode and any glued SDNodes and append them to the block.
956 if (!SU->getNode()) {
957 // Emit a copy.
958 EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
959 continue;
960 }
961
962 SmallVector<SDNode *, 4> GluedNodes;
963 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode())
964 GluedNodes.push_back(N);
965 while (!GluedNodes.empty()) {
966 SDNode *N = GluedNodes.back();
967 auto NewInsn = EmitNode(N, SU->OrigNode != SU, SU->isCloned, VRBaseMap);
968 // Remember the source order of the inserted instruction.
969 if (HasDbg)
970 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen, NewInsn);
971
972 if (MDNode *MD = DAG->getHeapAllocSite(N))
973 if (NewInsn && NewInsn->isCall())
974 NewInsn->setHeapAllocMarker(MF, MD);
975
976 GluedNodes.pop_back();
977 }
978 auto NewInsn =
979 EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned, VRBaseMap);
980 // Remember the source order of the inserted instruction.
981 if (HasDbg)
982 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders, Seen,
983 NewInsn);
984
985 if (MDNode *MD = DAG->getHeapAllocSite(SU->getNode())) {
986 if (NewInsn && NewInsn->isCall())
987 NewInsn->setHeapAllocMarker(MF, MD);
988 }
989
990 if (NewInsn && SU->OrigNode->isCloned)
991 markClonedNodeDeadDefs(*SU, *NewInsn, TRI);
992 }
993
994 // Insert all the dbg_values which have not already been inserted in source
995 // order sequence.
996 if (HasDbg) {
997 MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI();
998
999 // Sort the source order instructions and use the order to insert debug
1000 // values. Use stable_sort so that DBG_VALUEs are inserted in the same order
1001 // regardless of the host's implementation fo std::sort.
1002 llvm::stable_sort(Orders, less_first());
1003 std::stable_sort(DAG->DbgBegin(), DAG->DbgEnd(),
1004 [](const SDDbgValue *LHS, const SDDbgValue *RHS) {
1005 return LHS->getOrder() < RHS->getOrder();
1006 });
1007
1008 SDDbgInfo::DbgIterator DI = DAG->DbgBegin();
1009 SDDbgInfo::DbgIterator DE = DAG->DbgEnd();
1010 // Now emit the rest according to source order.
1011 unsigned LastOrder = 0;
1012 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) {
1013 unsigned Order = Orders[i].first;
1014 MachineInstr *MI = Orders[i].second;
1015 // Insert all SDDbgValue's whose order(s) are before "Order".
1016 assert(MI);
1017 for (; DI != DE; ++DI) {
1018 if ((*DI)->getOrder() < LastOrder || (*DI)->getOrder() >= Order)
1019 break;
1020 if ((*DI)->isEmitted())
1021 continue;
1022
1023 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap);
1024 if (DbgMI) {
1025 if (!LastOrder)
1026 // Insert to start of the BB (after PHIs).
1027 BB->insert(BBBegin, DbgMI);
1028 else {
1029 // Insert at the instruction, which may be in a different
1030 // block, if the block was split by a custom inserter.
1032 MI->getParent()->insert(Pos, DbgMI);
1033 }
1034 }
1035 }
1036 LastOrder = Order;
1037 }
1038 // Add trailing DbgValue's before the terminator. FIXME: May want to add
1039 // some of them before one or more conditional branches?
1041 for (; DI != DE; ++DI) {
1042 if ((*DI)->isEmitted())
1043 continue;
1044 assert((*DI)->getOrder() >= LastOrder &&
1045 "emitting DBG_VALUE out of order");
1046 if (MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap))
1047 DbgMIs.push_back(DbgMI);
1048 }
1049
1050 MachineBasicBlock *InsertBB = Emitter.getBlock();
1052 InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
1053
1054 SDDbgInfo::DbgLabelIterator DLI = DAG->DbgLabelBegin();
1055 SDDbgInfo::DbgLabelIterator DLE = DAG->DbgLabelEnd();
1056 // Now emit the rest according to source order.
1057 LastOrder = 0;
1058 for (const auto &InstrOrder : Orders) {
1059 unsigned Order = InstrOrder.first;
1060 MachineInstr *MI = InstrOrder.second;
1061 if (!MI)
1062 continue;
1063
1064 // Insert all SDDbgLabel's whose order(s) are before "Order".
1065 for (; DLI != DLE &&
1066 (*DLI)->getOrder() >= LastOrder && (*DLI)->getOrder() < Order;
1067 ++DLI) {
1068 MachineInstr *DbgMI = Emitter.EmitDbgLabel(*DLI);
1069 if (DbgMI) {
1070 if (!LastOrder)
1071 // Insert to start of the BB (after PHIs).
1072 BB->insert(BBBegin, DbgMI);
1073 else {
1074 // Insert at the instruction, which may be in a different
1075 // block, if the block was split by a custom inserter.
1077 MI->getParent()->insert(Pos, DbgMI);
1078 }
1079 }
1080 }
1081 if (DLI == DLE)
1082 break;
1083
1084 LastOrder = Order;
1085 }
1086 }
1087
1088 InsertPos = Emitter.getInsertPos();
1089 // In some cases, DBG_VALUEs might be inserted after the first terminator,
1090 // which results in an invalid MBB. If that happens, move the DBG_VALUEs
1091 // before the first terminator.
1092 MachineBasicBlock *InsertBB = Emitter.getBlock();
1093 auto FirstTerm = InsertBB->getFirstTerminator();
1094 if (FirstTerm != InsertBB->end()) {
1095 assert(!FirstTerm->isDebugValue() &&
1096 "first terminator cannot be a debug value");
1098 make_range(std::next(FirstTerm), InsertBB->end()))) {
1099 // Only scan up to insertion point.
1100 if (&MI == InsertPos)
1101 break;
1102
1103 if (!MI.isDebugValue())
1104 continue;
1105
1106 // The DBG_VALUE was referencing a value produced by a terminator. By
1107 // moving the DBG_VALUE, the referenced value also needs invalidating.
1108 MI.getOperand(0).ChangeToRegister(0, false);
1109 MI.moveBefore(&*FirstTerm);
1110 }
1111 }
1112 return InsertBB;
1113}
1114
1115/// Return the basic block label.
1117 return "sunit-dag." + BB->getFullName();
1118}
return SDValue()
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
dxil container DXContainer Global Emitter
This file defines the DenseMap class.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
unsigned Opc
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
uint64_t IntrinsicInst * II
static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter, InstrEmitter::VRBaseMapType &VRBaseMap, SmallVectorImpl< std::pair< unsigned, MachineInstr * > > &Orders, SmallSet< Register, 8 > &Seen, MachineInstr *NewInsn)
static bool AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG)
static void RemoveUnusedGlue(SDNode *N, SelectionDAG *DAG)
static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op, const TargetRegisterInfo *TRI, const TargetInstrInfo *TII, MCRegister &PhysReg, int &Cost)
CheckForPhysRegDependency - Check if the dependency between def and use of a specified operand is a p...
static void ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG, InstrEmitter &Emitter, SmallVectorImpl< std::pair< unsigned, MachineInstr * > > &Orders, InstrEmitter::VRBaseMapType &VRBaseMap, unsigned Order)
ProcessSDDbgValues - Process SDDbgValues associated with this node.
static void markClonedNodeDeadDefs(const SUnit &SU, MachineInstr &MI, const TargetRegisterInfo *TRI)
Mark physreg defs dead on MI, emitted for a cloned node SU.
static void CloneNodeWithValues(SDNode *N, SelectionDAG *DAG, ArrayRef< EVT > VTs, SDValue ExtraOper=SDValue())
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
This file describes how to lower LLVM code to machine code.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
SmallDenseMap< SDValue, Register, 16 > VRBaseMapType
static unsigned CountResults(SDNode *Node)
CountResults - The results of target nodes have register or immediate operands first,...
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
bool mayLoad() const
Return true if this instruction could possibly read memory.
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
bool variadicOpsAreDefs() const
Return true if variadic operands of this instruction are definitions.
int getOperandConstraint(unsigned OpNum, MCOI::OperandConstraint Constraint) const
Returns the value of the specified operand constraint if it is present.
bool isCommutable() const
Return true if this may be a 2- or 3-address instruction (of the form "X = op Y, Z,...
bool isVariadic() const
Return true if this instruction can have a variable number of operands.
bool expensiveOrImpossibleToCopy() const
uint8_t getCopyCost() const
getCopyCost - Return the cost of copying a value between two registers in this class.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
Metadata node.
Definition Metadata.h:1087
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
BasicBlockListType::iterator iterator
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
An SDNode that represents everything that will be needed to construct a MachineInstr.
mmo_iterator memoperands_begin() const
mmo_iterator memoperands_end() const
Wrapper class representing virtual and physical registers.
Definition Register.h:20
SmallVectorImpl< SDDbgLabel * >::iterator DbgLabelIterator
SmallVectorImpl< SDDbgValue * >::iterator DbgIterator
Holds the information for a single machine location through SDISel; either an SDNode,...
@ SDNODE
Value is the result of an expression.
Holds the information from a dbg_value node through SDISel.
Represents one node in the SelectionDAG.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
int getNodeId() const
Return the unique node id.
LLVM_ABI void dump() const
Dump this node, for debugging.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
iterator_range< value_op_iterator > op_values() const
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getMachineOpcode() const
This may only be called if isMachineOpcode returns true.
static user_iterator user_end()
user_iterator user_begin() const
Provide iteration support to walk over all users of an SDNode.
SDNode * getGluedNode() const
If this node has a glue operand, return the node to which the glue operand points.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
unsigned getResNo() const
get the index which selects a specific result in the SDNode
Scheduling dependency.
Definition ScheduleDAG.h:54
Kind getKind() const
Returns an enum value representing the kind of the dependence.
@ Data
Regular data dependence (aka true-dependence).
Definition ScheduleDAG.h:58
void setLatency(unsigned Lat)
Sets the latency for this edge.
@ Barrier
An unknown scheduling barrier.
Definition ScheduleDAG.h:74
bool isCtrl() const
Shorthand for getKind() != SDep::Data.
Register getReg() const
Returns the register associated with this edge.
Scheduling unit. This is a node in the scheduling DAG.
bool isCloned
True if this node has been cloned.
bool isCall
Is a function call.
void setNode(SDNode *N)
Assigns the representative SDNode for this SUnit.
unsigned NodeNum
Entry # of node in the node vector.
bool hasPhysRegClobbers
Has any physreg defs, used or not.
bool isCallOp
Is a function call operand.
const TargetRegisterClass * CopyDstRC
Is a special copy node if != nullptr.
unsigned short Latency
Node latency.
unsigned short NumRegDefsLeft
bool isScheduleHigh
True if preferable to schedule high.
bool isScheduleLow
True if preferable to schedule low.
bool hasPhysRegDefs
Has physreg defs that are being used.
SmallVector< SDep, 4 > Succs
All sunit successors.
Sched::Preference SchedulingPref
Scheduling preference.
SDNode * getNode() const
Returns the representative SDNode for this SUnit.
bool isTwoAddress
Is a two-address instruction.
bool isCommutable
Is a commutable instruction.
bool isVRegCycle
May use and def the same vreg.
SmallVector< SDep, 4 > Preds
All sunit predecessors.
SUnit * OrigNode
If not this, the node from which this node was cloned.
LLVM_ABI bool addPred(const SDep &D, bool Required=true)
Adds the specified edge as a pred of the current node if not already.
RegDefIter - In place iteration over the values defined by an SUnit.
RegDefIter(const SUnit *SU, const ScheduleDAGSDNodes *SD)
SUnit * newSUnit(SDNode *N)
NewSUnit - Creates a new SUnit and return a ptr to it.
void VerifyScheduledSequence(bool isBottomUp)
VerifyScheduledSequence - Verify that all SUnits are scheduled and consistent with the Sequence of sc...
virtual void Schedule()=0
Schedule - Order nodes according to selected style, filling in the Sequence member.
virtual void computeLatency(SUnit *SU)
computeLatency - Compute node latency.
std::string getDAGName() const override
Return the basic block label.
virtual MachineBasicBlock * EmitSchedule(MachineBasicBlock::iterator &InsertPos)
EmitSchedule - Insert MachineInstrs into the MachineBasicBlock according to the order specified in Se...
virtual bool forceUnitLatencies() const
ForceUnitLatencies - Return true if all scheduling edges should be given a latency value of one.
static bool isPassiveNode(SDNode *Node)
isPassiveNode - Return true if the node is a non-scheduled leaf.
const InstrItineraryData * InstrItins
void InitNumRegDefsLeft(SUnit *SU)
InitNumRegDefsLeft - Determine the # of regs defined by this node.
std::vector< SUnit * > Sequence
The schedule. Null SUnit*'s represent noop instructions.
void Run(SelectionDAG *dag, MachineBasicBlock *bb)
Run - perform scheduling.
void BuildSchedGraph()
BuildSchedGraph - Build the SUnit graph from the selection dag that we are input.
void dumpNode(const SUnit &SU) const override
SUnit * Clone(SUnit *Old)
Clone - Creates a clone of the specified SUnit.
ScheduleDAGSDNodes(MachineFunction &mf)
virtual void computeOperandLatency(SDNode *Def, SDNode *Use, unsigned OpIdx, SDep &dep) const
MachineRegisterInfo & MRI
Virtual/real register map.
void clearDAG()
Clears the DAG state (between regions).
const TargetInstrInfo * TII
Target instruction information.
std::vector< SUnit > SUnits
The scheduling units.
const TargetRegisterInfo * TRI
Target processor register info.
SUnit EntrySU
Special node for the region entry.
MachineFunction & MF
Machine function.
ScheduleDAG(const ScheduleDAG &)=delete
void dumpNodeAll(const SUnit &SU) const
unsigned VerifyScheduledDAG(bool isBottomUp)
Verifies that all SUnits were scheduled and that their state is consistent.
void dumpNodeName(const SUnit &SU) const
SUnit ExitSU
Special node for the region exit.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDNode * MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs, ArrayRef< SDValue > Ops)
This mutates the specified node to have the specified return type, opcode, and operands.
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
ArrayRef< SDDbgValue * > GetDbgValues(const SDNode *SD) const
Get the debug values which reference the given SDNode.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:226
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
Offsets
Offsets in bytes from the start of the input buffer.
@ User
could "use" a pointer
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
InstructionCost Cost
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
#define N
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1455