LLVM 24.0.0git
ScheduleDAGRRList.cpp
Go to the documentation of this file.
1//===- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler ------===//
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 bottom-up and top-down register pressure reduction list
10// schedulers, using standard algorithms. The basic approach uses a priority
11// queue of available nodes to schedule. One at a time, nodes are taken from
12// the priority queue (thus in priority order), checked for legality to
13// schedule, and emitted if legal.
14//
15//===----------------------------------------------------------------------===//
16
17#include "ScheduleDAGSDNodes.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/SparseSet.h"
24#include "llvm/ADT/Statistic.h"
40#include "llvm/Config/llvm-config.h"
41#include "llvm/IR/InlineAsm.h"
42#include "llvm/MC/MCInstrDesc.h"
48#include "llvm/Support/Debug.h"
51#include <algorithm>
52#include <cassert>
53#include <cstdint>
54#include <cstdlib>
55#include <iterator>
56#include <limits>
57#include <memory>
58#include <utility>
59#include <vector>
60
61using namespace llvm;
62
63#define DEBUG_TYPE "pre-RA-sched"
64
65STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
66STATISTIC(NumUnfolds, "Number of nodes unfolded");
67STATISTIC(NumDups, "Number of duplicated nodes");
68STATISTIC(NumPRCopies, "Number of physical register copies");
69
72 "Bottom-up register reduction list scheduling",
74
77 "Similar to list-burr but schedules in source "
78 "order when possible",
80
83 "Bottom-up register pressure aware list scheduling "
84 "which tries to balance latency and register pressure",
86
89 "Bottom-up register pressure aware list scheduling "
90 "which tries to balance ILP and register pressure",
92
94 "disable-sched-cycles", cl::Hidden, cl::init(false),
95 cl::desc("Disable cycle-level precision during preRA scheduling"));
96
97// Temporary sched=list-ilp flags until the heuristics are robust.
98// Some options are also available under sched=list-hybrid.
100 "disable-sched-reg-pressure", cl::Hidden, cl::init(false),
101 cl::desc("Disable regpressure priority in sched=list-ilp"));
103 "disable-sched-live-uses", cl::Hidden, cl::init(true),
104 cl::desc("Disable live use priority in sched=list-ilp"));
106 "disable-sched-vrcycle", cl::Hidden, cl::init(false),
107 cl::desc("Disable virtual register cycle interference checks"));
109 "disable-sched-physreg-join", cl::Hidden, cl::init(false),
110 cl::desc("Disable physreg def-use affinity"));
112 "disable-sched-stalls", cl::Hidden, cl::init(true),
113 cl::desc("Disable no-stall priority in sched=list-ilp"));
115 "disable-sched-critical-path", cl::Hidden, cl::init(false),
116 cl::desc("Disable critical path priority in sched=list-ilp"));
118 "disable-sched-height", cl::Hidden, cl::init(false),
119 cl::desc("Disable scheduled-height priority in sched=list-ilp"));
121 "disable-2addr-hack", cl::Hidden, cl::init(true),
122 cl::desc("Disable scheduler's two-address hack"));
123
125 "max-sched-reorder", cl::Hidden, cl::init(6),
126 cl::desc("Number of instructions to allow ahead of the critical path "
127 "in sched=list-ilp"));
128
130 AvgIPC("sched-avg-ipc", cl::Hidden, cl::init(1),
131 cl::desc("Average inst/cycle when no target itinerary exists."));
132
133namespace {
134
135//===----------------------------------------------------------------------===//
136/// ScheduleDAGRRList - The actual register reduction list scheduler
137/// implementation. This supports both top-down and bottom-up scheduling.
138///
139class ScheduleDAGRRList : public ScheduleDAGSDNodes {
140private:
141 /// NeedLatency - True if the scheduler will make use of latency information.
142 bool NeedLatency;
143
144 /// AvailableQueue - The priority queue to use for the available SUnits.
145 SchedulingPriorityQueue *AvailableQueue;
146
147 /// PendingQueue - This contains all of the instructions whose operands have
148 /// been issued, but their results are not ready yet (due to the latency of
149 /// the operation). Once the operands becomes available, the instruction is
150 /// added to the AvailableQueue.
151 std::vector<SUnit *> PendingQueue;
152
153 /// HazardRec - The hazard recognizer to use.
154 ScheduleHazardRecognizer *HazardRec;
155
156 /// CurCycle - The current scheduler state corresponds to this cycle.
157 unsigned CurCycle = 0;
158
159 /// MinAvailableCycle - Cycle of the soonest available instruction.
160 unsigned MinAvailableCycle = ~0u;
161
162 /// IssueCount - Count instructions issued in this cycle
163 /// Currently valid only for bottom-up scheduling.
164 unsigned IssueCount = 0u;
165
166 /// A physical register, or the special call resource, that is "live": Def
167 /// must be scheduled before any other node that modifies the register.
168 struct LiveReg {
169 unsigned Reg;
170 /// The nearest definition of the register.
171 SUnit *Def = nullptr;
172 /// The use that made the register live.
173 SUnit *Gen = nullptr;
174
175 explicit LiveReg(unsigned Reg) : Reg(Reg) {}
176 unsigned getSparseSetIndex() const { return Reg; }
177 };
178
179 /// The live registers, indexed by register number. TRI->getNumRegs() is a
180 /// special register that tracks the virtual resource of a calling sequence.
181 /// Few registers are live at once, and most blocks have none, so this avoids
182 /// allocating and clearing an array of all registers for every block.
183 SparseSet<LiveReg> LiveRegs;
184
185 // Collect interferences between physical register use/defs.
186 // Each interference is an SUnit and set of physical registers.
187 SmallVector<SUnit*, 4> Interferences;
188
189 using LRegsMapT = DenseMap<SUnit *, SmallVector<unsigned, 4>>;
190
191 LRegsMapT LRegsMap;
192
193 /// Topo - A topological ordering for SUnits which permits fast IsReachable
194 /// and similar queries.
195 ScheduleDAGTopologicalSort Topo;
196
197 // Hack to keep track of the inverse of FindCallSeqStart without more crazy
198 // DAG crawling.
199 SmallDenseMap<SUnit *, SUnit *, 16> CallSeqEndForStart;
200
201public:
202 ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
203 SchedulingPriorityQueue *availqueue,
204 CodeGenOptLevel OptLevel)
205 : ScheduleDAGSDNodes(mf), NeedLatency(needlatency),
206 AvailableQueue(availqueue), Topo(SUnits, nullptr) {
207 const TargetSubtargetInfo &STI = mf.getSubtarget();
208 if (DisableSchedCycles || !NeedLatency)
209 HazardRec = new ScheduleHazardRecognizer();
210 else
211 HazardRec = STI.getInstrInfo()->CreateTargetHazardRecognizer(&STI, this);
212 }
213
214 ~ScheduleDAGRRList() override {
215 delete HazardRec;
216 delete AvailableQueue;
217 }
218
219 void Schedule() override;
220
221 LiveReg *findLiveReg(unsigned Reg) {
222 // The universe is only set once a register becomes live.
223 if (LiveRegs.empty())
224 return nullptr;
225 auto I = LiveRegs.find(Reg);
226 return I == LiveRegs.end() ? nullptr : &*I;
227 }
228
229 SUnit *getLiveRegDef(unsigned Reg) {
230 LiveReg *LR = findLiveReg(Reg);
231 return LR ? LR->Def : nullptr;
232 }
233
234 SUnit *getLiveRegGen(unsigned Reg) {
235 LiveReg *LR = findLiveReg(Reg);
236 return LR ? LR->Gen : nullptr;
237 }
238
239 /// Return the entry for Reg, adding one with a null Def and Gen if it isn't
240 /// live. The reference is invalidated by adding another register.
241 LiveReg &addLiveReg(unsigned Reg) {
242 // setUniverse requires an empty set.
243 if (LiveRegs.empty())
244 LiveRegs.setUniverse(TRI->getNumRegs() + 1);
245 return *LiveRegs.insert(LiveReg(Reg)).first;
246 }
247
248 void removeLiveReg(unsigned Reg) {
249 if (!LiveRegs.erase(Reg))
250 llvm_unreachable("Register is not live!");
251 }
252
253 ScheduleHazardRecognizer *getHazardRec() { return HazardRec; }
254
255 /// IsReachable - Checks if SU is reachable from TargetSU.
256 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
257 return Topo.IsReachable(SU, TargetSU);
258 }
259
260 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
261 /// create a cycle.
262 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
263 return Topo.WillCreateCycle(SU, TargetSU);
264 }
265
266 /// AddPredQueued - Queues and update to add a predecessor edge to SUnit SU.
267 /// This returns true if this is a new predecessor.
268 /// Does *NOT* update the topological ordering! It just queues an update.
269 void AddPredQueued(SUnit *SU, const SDep &D) {
270 Topo.AddPredQueued(SU, D.getSUnit());
271 SU->addPred(D);
272 }
273
274 /// RemovePred - removes a predecessor edge from SUnit SU.
275 /// This returns true if an edge was removed.
276 /// Updates the topological ordering if required.
277 void RemovePred(SUnit *SU, const SDep &D) {
278 Topo.RemovePred(SU, D.getSUnit());
279 SU->removePred(D);
280 }
281
282private:
283 bool isReady(SUnit *SU) {
284 return DisableSchedCycles || !AvailableQueue->hasReadyFilter() ||
285 AvailableQueue->isReady(SU);
286 }
287
288 void ReleasePred(SUnit *SU, const SDep *PredEdge);
289 void ReleasePredecessors(SUnit *SU);
290 void ReleasePending();
291 void AdvanceToCycle(unsigned NextCycle);
292 void AdvancePastStalls(SUnit *SU);
293 void EmitNode(SUnit *SU);
294 void ScheduleNodeBottomUp(SUnit*);
295 void CapturePred(SDep *PredEdge);
296 void UnscheduleNodeBottomUp(SUnit*);
297 void RestoreHazardCheckerBottomUp();
298 void BacktrackBottomUp(SUnit*, SUnit*);
299 SUnit *TryUnfoldSU(SUnit *);
300 SUnit *CopyAndMoveSuccessors(SUnit*);
301 void InsertCopiesAndMoveSuccs(SUnit*, unsigned,
302 const TargetRegisterClass*,
303 const TargetRegisterClass*,
304 SmallVectorImpl<SUnit*>&);
305 bool DelayForLiveRegsBottomUp(SUnit*, SmallVectorImpl<unsigned>&);
306 void CheckForLiveRegDef(SUnit *SU, MCRegister Reg,
307 SmallSet<unsigned, 4> &RegAdded,
308 SmallVectorImpl<unsigned> &LRegs,
309 const SDNode *Node = nullptr);
310 void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
311 SmallSet<unsigned, 4> &RegAdded,
312 SmallVectorImpl<unsigned> &LRegs);
313
314 void releaseInterferences(unsigned Reg = 0);
315
316 SUnit *PickNodeToScheduleBottomUp();
317 void ListScheduleBottomUp();
318
319 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
320 SUnit *CreateNewSUnit(SDNode *N) {
321 unsigned NumSUnits = SUnits.size();
322 SUnit *NewNode = newSUnit(N);
323 // Update the topological ordering.
324 if (NewNode->NodeNum >= NumSUnits)
325 Topo.AddSUnitWithoutPredecessors(NewNode);
326 return NewNode;
327 }
328
329 /// CreateClone - Creates a new SUnit from an existing one.
330 SUnit *CreateClone(SUnit *N) {
331 unsigned NumSUnits = SUnits.size();
332 SUnit *NewNode = Clone(N);
333 // Update the topological ordering.
334 if (NewNode->NodeNum >= NumSUnits)
335 Topo.AddSUnitWithoutPredecessors(NewNode);
336 return NewNode;
337 }
338
339 /// forceUnitLatencies - Register-pressure-reducing scheduling doesn't
340 /// need actual latency information but the hybrid scheduler does.
341 bool forceUnitLatencies() const override {
342 return !NeedLatency;
343 }
344};
345
346} // end anonymous namespace
347
348static constexpr unsigned RegSequenceCost = 1;
349
350/// GetCostForDef - Looks up the register class and cost for a given definition.
351/// Typically this just means looking up the representative register class,
352/// but for untyped values (MVT::Untyped) it means inspecting the node's
353/// opcode to determine what register class is being generated.
355 const TargetLowering *TLI,
356 const TargetInstrInfo *TII,
357 const TargetRegisterInfo *TRI,
358 unsigned &RegClass, unsigned &Cost,
359 const MachineFunction &MF) {
360 MVT VT = RegDefPos.GetValue();
361
362 // Special handling for untyped values. These values can only come from
363 // the expansion of custom DAG-to-DAG patterns.
364 if (VT == MVT::Untyped) {
365 const SDNode *Node = RegDefPos.GetNode();
366
367 // Special handling for CopyFromReg of untyped values.
368 if (!Node->isMachineOpcode() && Node->getOpcode() == ISD::CopyFromReg) {
369 Register Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
371 RegClass = RC->getID();
372 Cost = 1;
373 return;
374 }
375
376 unsigned Opcode = Node->getMachineOpcode();
377 if (Opcode == TargetOpcode::REG_SEQUENCE) {
378 unsigned DstRCIdx = Node->getConstantOperandVal(0);
379 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
380 RegClass = RC->getID();
381 Cost = RegSequenceCost;
382 return;
383 }
384
385 unsigned Idx = RegDefPos.GetIdx();
386 const MCInstrDesc &Desc = TII->get(Opcode);
387 const TargetRegisterClass *RC = TII->getRegClass(Desc, Idx);
388 assert(RC && "Not a valid register class");
389 RegClass = RC->getID();
390 // FIXME: Cost arbitrarily set to 1 because there doesn't seem to be a
391 // better way to determine it.
392 Cost = 1;
393 } else {
394 RegClass = TLI->getRepRegClassFor(VT)->getID();
395 Cost = TLI->getRepRegClassCostFor(VT);
396 }
397}
398
399/// Schedule - Schedule the DAG using list scheduling.
400void ScheduleDAGRRList::Schedule() {
401 LLVM_DEBUG(dbgs() << "********** List Scheduling " << printMBBReference(*BB)
402 << " '" << BB->getName() << "' **********\n");
403
404 CurCycle = 0;
405 IssueCount = 0;
406 MinAvailableCycle =
407 DisableSchedCycles ? 0 : std::numeric_limits<unsigned>::max();
408 LiveRegs.clear();
409 CallSeqEndForStart.clear();
410 assert(Interferences.empty() && LRegsMap.empty() && "stale Interferences");
411 assert(PendingQueue.empty() && "stale PendingQueue");
412
413 // Build the scheduling graph.
414 BuildSchedGraph();
415
416 LLVM_DEBUG(dump());
417 Topo.MarkDirty();
418
419 AvailableQueue->initNodes(SUnits);
420
421 HazardRec->Reset();
422
423 // Execute the actual scheduling loop.
424 ListScheduleBottomUp();
425
426 AvailableQueue->releaseState();
427
428 LLVM_DEBUG({
429 dbgs() << "*** Final schedule ***\n";
430 dumpSchedule();
431 dbgs() << '\n';
432 });
433}
434
435//===----------------------------------------------------------------------===//
436// Bottom-Up Scheduling
437//===----------------------------------------------------------------------===//
438
439/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
440/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
441void ScheduleDAGRRList::ReleasePred(SUnit *SU, const SDep *PredEdge) {
442 SUnit *PredSU = PredEdge->getSUnit();
443
444#ifndef NDEBUG
445 if (PredSU->NumSuccsLeft == 0) {
446 dbgs() << "*** Scheduling failed! ***\n";
447 dumpNode(*PredSU);
448 dbgs() << " has been released too many times!\n";
449 llvm_unreachable(nullptr);
450 }
451#endif
452 --PredSU->NumSuccsLeft;
453
454 if (!forceUnitLatencies()) {
455 // Updating predecessor's height. This is now the cycle when the
456 // predecessor can be scheduled without causing a pipeline stall.
457 PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
458 }
459
460 // If all the node's successors are scheduled, this node is ready
461 // to be scheduled. Ignore the special EntrySU node.
462 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU) {
463 PredSU->isAvailable = true;
464
465 unsigned Height = PredSU->getHeight();
466 if (Height < MinAvailableCycle)
467 MinAvailableCycle = Height;
468
469 if (isReady(PredSU)) {
470 AvailableQueue->push(PredSU);
471 }
472 // CapturePred and others may have left the node in the pending queue, avoid
473 // adding it twice.
474 else if (!PredSU->isPending) {
475 PredSU->isPending = true;
476 PendingQueue.push_back(PredSU);
477 }
478 }
479}
480
481/// IsChainDependent - Test if Outer is reachable from Inner through
482/// chain dependencies.
483static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
484 unsigned NestLevel,
485 const TargetInstrInfo *TII) {
486 SDNode *N = Outer;
487 while (true) {
488 if (N == Inner)
489 return true;
490 // For a TokenFactor, examine each operand. There may be multiple ways
491 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
492 // most nesting in order to ensure that we find the corresponding match.
493 if (N->getOpcode() == ISD::TokenFactor) {
494 for (const SDValue &Op : N->op_values())
495 if (IsChainDependent(Op.getNode(), Inner, NestLevel, TII))
496 return true;
497 return false;
498 }
499 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
500 if (N->isMachineOpcode()) {
501 if (N->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
502 ++NestLevel;
503 } else if (N->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
504 if (NestLevel == 0)
505 return false;
506 --NestLevel;
507 }
508 }
509 // Otherwise, find the chain and continue climbing.
510 for (const SDValue &Op : N->op_values())
511 if (Op.getValueType() == MVT::Other) {
512 N = Op.getNode();
513 goto found_chain_operand;
514 }
515 return false;
516 found_chain_operand:;
517 if (N->getOpcode() == ISD::EntryToken)
518 return false;
519 }
520}
521
522/// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
523/// the corresponding (lowered) CALLSEQ_BEGIN node.
524///
525/// NestLevel and MaxNested are used in recursion to indcate the current level
526/// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maximum
527/// level seen so far.
528///
529/// TODO: It would be better to give CALLSEQ_END an explicit operand to point
530/// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
531static SDNode *
532FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
533 const TargetInstrInfo *TII) {
534 while (true) {
535 // For a TokenFactor, examine each operand. There may be multiple ways
536 // to get to the CALLSEQ_BEGIN, but we need to find the path with the
537 // most nesting in order to ensure that we find the corresponding match.
538 if (N->getOpcode() == ISD::TokenFactor) {
539 SDNode *Best = nullptr;
540 unsigned BestMaxNest = MaxNest;
541 for (const SDValue &Op : N->op_values()) {
542 unsigned MyNestLevel = NestLevel;
543 unsigned MyMaxNest = MaxNest;
544 if (SDNode *New = FindCallSeqStart(Op.getNode(),
545 MyNestLevel, MyMaxNest, TII))
546 if (!Best || (MyMaxNest > BestMaxNest)) {
547 Best = New;
548 BestMaxNest = MyMaxNest;
549 }
550 }
551 assert(Best);
552 MaxNest = BestMaxNest;
553 return Best;
554 }
555 // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
556 if (N->isMachineOpcode()) {
557 if (N->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
558 ++NestLevel;
559 MaxNest = std::max(MaxNest, NestLevel);
560 } else if (N->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
561 assert(NestLevel != 0);
562 --NestLevel;
563 if (NestLevel == 0)
564 return N;
565 }
566 }
567 // Otherwise, find the chain and continue climbing.
568 for (const SDValue &Op : N->op_values())
569 if (Op.getValueType() == MVT::Other) {
570 N = Op.getNode();
571 goto found_chain_operand;
572 }
573 return nullptr;
574 found_chain_operand:;
575 if (N->getOpcode() == ISD::EntryToken)
576 return nullptr;
577 }
578}
579
580/// Call ReleasePred for each predecessor, then update register live def/gen.
581/// Always update the live Def for a register dependence even if the current SU
582/// also defines the register. This effectively create one large live range
583/// across a sequence of two-address node. This is important because the
584/// entire chain must be scheduled together. Example:
585///
586/// flags = (3) add
587/// flags = (2) addc flags
588/// flags = (1) addc flags
589///
590/// results in
591///
592/// Def of live register flags = 3
593/// Gen of live register flags = 1
594///
595/// If (2) addc is unscheduled, then (1) addc must also be unscheduled to avoid
596/// interference on flags.
597void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
598 // Bottom up: release predecessors
599 for (SDep &Pred : SU->Preds) {
600 ReleasePred(SU, &Pred);
601 if (Pred.isAssignedRegDep()) {
602 // This is a physical register dependency and it's impossible or
603 // expensive to copy the register. Make sure nothing that can
604 // clobber the register is scheduled between the predecessor and
605 // this node.
606 LiveReg &LR = addLiveReg(Pred.getReg());
607 assert((!LR.Def || LR.Def == SU || LR.Def == Pred.getSUnit()) &&
608 "interference on register dependence");
609 LR.Def = Pred.getSUnit();
610 if (!LR.Gen)
611 LR.Gen = SU;
612 }
613 }
614
615 // If we're scheduling a lowered CALLSEQ_END, find the corresponding
616 // CALLSEQ_BEGIN. Inject an artificial physical register dependence between
617 // these nodes, to prevent other calls from being interscheduled with them.
618 unsigned CallResource = TRI->getNumRegs();
619 if (!getLiveRegDef(CallResource))
620 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode())
621 if (Node->isMachineOpcode() &&
622 Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
623 unsigned NestLevel = 0;
624 unsigned MaxNest = 0;
625 SDNode *N = FindCallSeqStart(Node, NestLevel, MaxNest, TII);
626 assert(N && "Must find call sequence start");
627
628 SUnit *Def = &SUnits[N->getNodeId()];
629 CallSeqEndForStart[Def] = SU;
630
631 LiveReg &LR = addLiveReg(CallResource);
632 LR.Def = Def;
633 LR.Gen = SU;
634 break;
635 }
636}
637
638/// Check to see if any of the pending instructions are ready to issue. If
639/// so, add them to the available queue.
640void ScheduleDAGRRList::ReleasePending() {
641 if (DisableSchedCycles) {
642 assert(PendingQueue.empty() && "pending instrs not allowed in this mode");
643 return;
644 }
645
646 // If the available queue is empty, it is safe to reset MinAvailableCycle.
647 if (AvailableQueue->empty())
648 MinAvailableCycle = std::numeric_limits<unsigned>::max();
649
650 // Check to see if any of the pending instructions are ready to issue. If
651 // so, add them to the available queue.
652 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
653 unsigned ReadyCycle = PendingQueue[i]->getHeight();
654 if (ReadyCycle < MinAvailableCycle)
655 MinAvailableCycle = ReadyCycle;
656
657 if (PendingQueue[i]->isAvailable) {
658 if (!isReady(PendingQueue[i]))
659 continue;
660 AvailableQueue->push(PendingQueue[i]);
661 }
662 PendingQueue[i]->isPending = false;
663 PendingQueue[i] = PendingQueue.back();
664 PendingQueue.pop_back();
665 --i; --e;
666 }
667}
668
669/// Move the scheduler state forward by the specified number of Cycles.
670void ScheduleDAGRRList::AdvanceToCycle(unsigned NextCycle) {
671 if (NextCycle <= CurCycle)
672 return;
673
674 IssueCount = 0;
675 AvailableQueue->setCurCycle(NextCycle);
676 if (!HazardRec->isEnabled()) {
677 // Bypass lots of virtual calls in case of long latency.
678 CurCycle = NextCycle;
679 }
680 else {
681 for (; CurCycle != NextCycle; ++CurCycle) {
682 HazardRec->RecedeCycle();
683 }
684 }
685 // FIXME: Instead of visiting the pending Q each time, set a dirty flag on the
686 // available Q to release pending nodes at least once before popping.
687 ReleasePending();
688}
689
690/// Move the scheduler state forward until the specified node's dependents are
691/// ready and can be scheduled with no resource conflicts.
692void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
694 return;
695
696 // FIXME: Nodes such as CopyFromReg probably should not advance the current
697 // cycle. Otherwise, we can wrongly mask real stalls. If the non-machine node
698 // has predecessors the cycle will be advanced when they are scheduled.
699 // But given the crude nature of modeling latency though such nodes, we
700 // currently need to treat these nodes like real instructions.
701 // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
702
703 unsigned ReadyCycle = SU->getHeight();
704
705 // Bump CurCycle to account for latency. We assume the latency of other
706 // available instructions may be hidden by the stall (not a full pipe stall).
707 // This updates the hazard recognizer's cycle before reserving resources for
708 // this instruction.
709 AdvanceToCycle(ReadyCycle);
710
711 // Calls are scheduled in their preceding cycle, so don't conflict with
712 // hazards from instructions after the call. EmitNode will reset the
713 // scoreboard state before emitting the call.
714 if (SU->isCall)
715 return;
716
717 // FIXME: For resource conflicts in very long non-pipelined stages, we
718 // should probably skip ahead here to avoid useless scoreboard checks.
719 int Stalls = 0;
720 while (true) {
722 HazardRec->getHazardType(SU, -Stalls);
723
725 break;
726
727 ++Stalls;
728 }
729 AdvanceToCycle(CurCycle + Stalls);
730}
731
732/// Record this SUnit in the HazardRecognizer.
733/// Does not update CurCycle.
734void ScheduleDAGRRList::EmitNode(SUnit *SU) {
735 if (!HazardRec->isEnabled())
736 return;
737
738 // Check for phys reg copy.
739 if (!SU->getNode())
740 return;
741
742 switch (SU->getNode()->getOpcode()) {
743 default:
744 assert(SU->getNode()->isMachineOpcode() &&
745 "This target-independent node should not be scheduled.");
746 break;
748 case ISD::TokenFactor:
751 case ISD::CopyToReg:
752 case ISD::CopyFromReg:
753 case ISD::EH_LABEL:
755 // Noops don't affect the scoreboard state. Copies are likely to be
756 // removed.
757 return;
758 case ISD::INLINEASM:
760 // For inline asm, clear the pipeline state.
761 HazardRec->Reset();
762 return;
763 }
764 if (SU->isCall) {
765 // Calls are scheduled with their preceding instructions. For bottom-up
766 // scheduling, clear the pipeline state before emitting.
767 HazardRec->Reset();
768 }
769
770 HazardRec->EmitInstruction(SU);
771}
772
773static void resetVRegCycle(SUnit *SU);
774
775/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
776/// count of its predecessors. If a predecessor pending count is zero, add it to
777/// the Available queue.
778void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
779 LLVM_DEBUG(dbgs() << "\n*** Scheduling [" << CurCycle << "]: ");
780 LLVM_DEBUG(dumpNode(*SU));
781
782#ifndef NDEBUG
783 if (CurCycle < SU->getHeight())
784 LLVM_DEBUG(dbgs() << " Height [" << SU->getHeight()
785 << "] pipeline stall!\n");
786#endif
787
788 // FIXME: Do not modify node height. It may interfere with
789 // backtracking. Instead add a "ready cycle" to SUnit. Before scheduling the
790 // node its ready cycle can aid heuristics, and after scheduling it can
791 // indicate the scheduled cycle.
792 SU->setHeightToAtLeast(CurCycle);
793
794 // Reserve resources for the scheduled instruction.
795 EmitNode(SU);
796
797 Sequence.push_back(SU);
798
799 AvailableQueue->scheduledNode(SU);
800
801 // If HazardRec is disabled, and each inst counts as one cycle, then
802 // advance CurCycle before ReleasePredecessors to avoid useless pushes to
803 // PendingQueue for schedulers that implement HasReadyFilter.
804 if (!HazardRec->isEnabled() && AvgIPC < 2)
805 AdvanceToCycle(CurCycle + 1);
806
807 // Update liveness of predecessors before successors to avoid treating a
808 // two-address node as a live range def.
809 ReleasePredecessors(SU);
810
811 // Release all the implicit physical register defs that are live.
812 for (SDep &Succ : SU->Succs) {
813 // The live Def is not SU when SU is a two-address node.
814 if (Succ.isAssignedRegDep() && getLiveRegDef(Succ.getReg()) == SU) {
815 removeLiveReg(Succ.getReg());
816 releaseInterferences(Succ.getReg());
817 }
818 }
819 // Release the special call resource dependence, if this is the beginning
820 // of a call.
821 unsigned CallResource = TRI->getNumRegs();
822 if (getLiveRegDef(CallResource) == SU)
823 for (const SDNode *SUNode = SU->getNode(); SUNode;
824 SUNode = SUNode->getGluedNode()) {
825 if (SUNode->isMachineOpcode() &&
826 SUNode->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
827 removeLiveReg(CallResource);
828 releaseInterferences(CallResource);
829 }
830 }
831
832 resetVRegCycle(SU);
833
834 SU->isScheduled = true;
835
836 // Conditions under which the scheduler should eagerly advance the cycle:
837 // (1) No available instructions
838 // (2) All pipelines full, so available instructions must have hazards.
839 //
840 // If HazardRec is disabled, the cycle was pre-advanced before calling
841 // ReleasePredecessors. In that case, IssueCount should remain 0.
842 //
843 // Check AvailableQueue after ReleasePredecessors in case of zero latency.
844 if (HazardRec->isEnabled() || AvgIPC > 1) {
845 if (SU->getNode() && SU->getNode()->isMachineOpcode())
846 ++IssueCount;
847 if ((HazardRec->isEnabled() && HazardRec->atIssueLimit())
848 || (!HazardRec->isEnabled() && IssueCount == AvgIPC))
849 AdvanceToCycle(CurCycle + 1);
850 }
851}
852
853/// CapturePred - This does the opposite of ReleasePred. Since SU is being
854/// unscheduled, increase the succ left count of its predecessors. Remove
855/// them from AvailableQueue if necessary.
856void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
857 SUnit *PredSU = PredEdge->getSUnit();
858 if (PredSU->isAvailable) {
859 PredSU->isAvailable = false;
860 if (!PredSU->isPending)
861 AvailableQueue->remove(PredSU);
862 }
863
864 assert(PredSU->NumSuccsLeft < std::numeric_limits<unsigned>::max() &&
865 "NumSuccsLeft will overflow!");
866 ++PredSU->NumSuccsLeft;
867}
868
869/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
870/// its predecessor states to reflect the change.
871void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
872 LLVM_DEBUG(dbgs() << "*** Unscheduling [" << SU->getHeight() << "]: ");
873 LLVM_DEBUG(dumpNode(*SU));
874
875 for (SDep &Pred : SU->Preds) {
876 CapturePred(&Pred);
877 if (Pred.isAssignedRegDep() && SU == getLiveRegGen(Pred.getReg())) {
878 assert(getLiveRegDef(Pred.getReg()) == Pred.getSUnit() &&
879 "Physical register dependency violated?");
880 removeLiveReg(Pred.getReg());
881 releaseInterferences(Pred.getReg());
882 }
883 }
884
885 // Reclaim the special call resource dependence, if this is the beginning
886 // of a call.
887 unsigned CallResource = TRI->getNumRegs();
888 for (const SDNode *SUNode = SU->getNode(); SUNode;
889 SUNode = SUNode->getGluedNode()) {
890 if (SUNode->isMachineOpcode() &&
891 SUNode->getMachineOpcode() == TII->getCallFrameSetupOpcode()) {
892 SUnit *SeqEnd = CallSeqEndForStart[SU];
893 assert(SeqEnd && "Call sequence start/end must be known");
894 assert(!findLiveReg(CallResource));
895 LiveReg &LR = addLiveReg(CallResource);
896 LR.Def = SU;
897 LR.Gen = SeqEnd;
898 }
899 }
900
901 // Release the special call resource dependence, if this is the end
902 // of a call.
903 if (getLiveRegGen(CallResource) == SU)
904 for (const SDNode *SUNode = SU->getNode(); SUNode;
905 SUNode = SUNode->getGluedNode()) {
906 if (SUNode->isMachineOpcode() &&
907 SUNode->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
908 assert(getLiveRegDef(CallResource));
909 removeLiveReg(CallResource);
910 releaseInterferences(CallResource);
911 }
912 }
913
914 for (auto &Succ : SU->Succs) {
915 if (Succ.isAssignedRegDep()) {
916 auto Reg = Succ.getReg();
917 LiveReg &LR = addLiveReg(Reg);
918 // This becomes the nearest def. Note that an earlier def may still be
919 // pending if this is a two-address node.
920 LR.Def = SU;
921
922 // Update Gen only if it was empty before this unscheduling.
923 // This is to avoid incorrect updating Gen set in previous run.
924 if (!LR.Gen) {
925 // Find the successor with the lowest height.
926 LR.Gen = Succ.getSUnit();
927 for (auto &Succ2 : SU->Succs) {
928 if (Succ2.isAssignedRegDep() && Succ2.getReg() == Reg &&
929 Succ2.getSUnit()->getHeight() < LR.Gen->getHeight())
930 LR.Gen = Succ2.getSUnit();
931 }
932 }
933 }
934 }
935 if (SU->getHeight() < MinAvailableCycle)
936 MinAvailableCycle = SU->getHeight();
937
938 SU->setHeightDirty();
939 SU->isScheduled = false;
940 SU->isAvailable = true;
941 if (!DisableSchedCycles && AvailableQueue->hasReadyFilter()) {
942 // Don't make available until backtracking is complete.
943 SU->isPending = true;
944 PendingQueue.push_back(SU);
945 }
946 else {
947 AvailableQueue->push(SU);
948 }
949 AvailableQueue->unscheduledNode(SU);
950}
951
952/// After backtracking, the hazard checker needs to be restored to a state
953/// corresponding the current cycle.
954void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
955 HazardRec->Reset();
956
957 unsigned LookAhead = std::min((unsigned)Sequence.size(),
958 HazardRec->getMaxLookAhead());
959 if (LookAhead == 0)
960 return;
961
962 std::vector<SUnit *>::const_iterator I = (Sequence.end() - LookAhead);
963 unsigned HazardCycle = (*I)->getHeight();
964 for (auto E = Sequence.end(); I != E; ++I) {
965 SUnit *SU = *I;
966 for (; SU->getHeight() > HazardCycle; ++HazardCycle) {
967 HazardRec->RecedeCycle();
968 }
969 EmitNode(SU);
970 }
971}
972
973/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
974/// BTCycle in order to schedule a specific node.
975void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
976 SUnit *OldSU = Sequence.back();
977 while (true) {
978 Sequence.pop_back();
979 // FIXME: use ready cycle instead of height
980 CurCycle = OldSU->getHeight();
981 UnscheduleNodeBottomUp(OldSU);
982 AvailableQueue->setCurCycle(CurCycle);
983 if (OldSU == BtSU)
984 break;
985 OldSU = Sequence.back();
986 }
987
988 assert(!SU->isSucc(OldSU) && "Something is wrong!");
989
990 RestoreHazardCheckerBottomUp();
991
992 ReleasePending();
993
994 ++NumBacktracks;
995}
996
997static bool isOperandOf(const SUnit *SU, SDNode *N) {
998 for (const SDNode *SUNode = SU->getNode(); SUNode;
999 SUNode = SUNode->getGluedNode()) {
1000 if (SUNode->isOperandOf(N))
1001 return true;
1002 }
1003 return false;
1004}
1005
1006/// TryUnfold - Attempt to unfold
1007SUnit *ScheduleDAGRRList::TryUnfoldSU(SUnit *SU) {
1008 SDNode *N = SU->getNode();
1009 // Use while over if to ease fall through.
1010 SmallVector<SDNode *, 2> NewNodes;
1011 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
1012 return nullptr;
1013
1014 assert(NewNodes.size() == 2 && "Expected a load folding node!");
1015
1016 N = NewNodes[1];
1017 SDNode *LoadNode = NewNodes[0];
1018 unsigned NumVals = N->getNumValues();
1019 unsigned OldNumVals = SU->getNode()->getNumValues();
1020
1021 // LoadNode may already exist (e.g. a load from the same location that was
1022 // not folded). Its chain result then already has users, and redirecting the
1023 // chain uses of SU's node to it below can CSE one of them into an existing
1024 // node and delete it while an SUnit still refers to it. Cloning SU is not
1025 // safe for a memory access either, so give up and let the caller insert
1026 // physical register copies instead.
1027 if (LoadNode->getNodeId() != -1)
1028 return nullptr;
1029 assert(N->getNodeId() == -1 && "Node using a new load can't exist yet!");
1030
1031 SUnit *LoadSU = CreateNewSUnit(LoadNode);
1032 LoadNode->setNodeId(LoadSU->NodeNum);
1033 InitNumRegDefsLeft(LoadSU);
1034 computeLatency(LoadSU);
1035
1036 SUnit *NewSU = CreateNewSUnit(N);
1037 N->setNodeId(NewSU->NodeNum);
1038
1039 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1040 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) {
1041 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) {
1042 NewSU->isTwoAddress = true;
1043 break;
1044 }
1045 }
1046 if (MCID.isCommutable())
1047 NewSU->isCommutable = true;
1048
1049 InitNumRegDefsLeft(NewSU);
1050 computeLatency(NewSU);
1051
1052 LLVM_DEBUG(dbgs() << "Unfolding " << *SU << "\n");
1053
1054 // Now that we are committed to unfolding replace DAG Uses.
1055 for (unsigned i = 0; i != NumVals; ++i)
1056 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
1057 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals - 1),
1058 SDValue(LoadNode, 1));
1059
1060 // Record all the edges to and from the old SU, by category.
1061 SmallVector<SDep, 4> ChainPreds;
1062 SmallVector<SDep, 4> ChainSuccs;
1063 SmallVector<SDep, 4> LoadPreds;
1064 SmallVector<SDep, 4> NodePreds;
1065 SmallVector<SDep, 4> NodeSuccs;
1066 for (SDep &Pred : SU->Preds) {
1067 if (Pred.isCtrl())
1068 ChainPreds.push_back(Pred);
1069 else if (isOperandOf(Pred.getSUnit(), LoadNode))
1070 LoadPreds.push_back(Pred);
1071 else
1072 NodePreds.push_back(Pred);
1073 }
1074 for (SDep &Succ : SU->Succs) {
1075 if (Succ.isCtrl())
1076 ChainSuccs.push_back(Succ);
1077 else
1078 NodeSuccs.push_back(Succ);
1079 }
1080
1081 // Now assign edges to the newly-created nodes.
1082 for (const SDep &Pred : ChainPreds) {
1083 RemovePred(SU, Pred);
1084 AddPredQueued(LoadSU, Pred);
1085 }
1086 for (const SDep &Pred : LoadPreds) {
1087 RemovePred(SU, Pred);
1088 AddPredQueued(LoadSU, Pred);
1089 }
1090 for (const SDep &Pred : NodePreds) {
1091 RemovePred(SU, Pred);
1092 AddPredQueued(NewSU, Pred);
1093 }
1094 for (SDep &D : NodeSuccs) {
1095 SUnit *SuccDep = D.getSUnit();
1096 D.setSUnit(SU);
1097 RemovePred(SuccDep, D);
1098 D.setSUnit(NewSU);
1099 AddPredQueued(SuccDep, D);
1100 // Balance register pressure.
1101 if (AvailableQueue->tracksRegPressure() && SuccDep->isScheduled &&
1102 !D.isCtrl() && NewSU->NumRegDefsLeft > 0)
1103 --NewSU->NumRegDefsLeft;
1104 }
1105 for (SDep &D : ChainSuccs) {
1106 SUnit *SuccDep = D.getSUnit();
1107 D.setSUnit(SU);
1108 RemovePred(SuccDep, D);
1109 D.setSUnit(LoadSU);
1110 AddPredQueued(SuccDep, D);
1111 }
1112
1113 // Add a data dependency to reflect that NewSU reads the value defined
1114 // by LoadSU.
1115 SDep D(LoadSU, SDep::Data, 0);
1116 D.setLatency(LoadSU->Latency);
1117 AddPredQueued(NewSU, D);
1118
1119 AvailableQueue->addNode(LoadSU);
1120 AvailableQueue->addNode(NewSU);
1121
1122 ++NumUnfolds;
1123
1124 if (NewSU->NumSuccsLeft == 0)
1125 NewSU->isAvailable = true;
1126
1127 return NewSU;
1128}
1129
1130/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
1131/// successors to the newly created node.
1132SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
1133 SDNode *N = SU->getNode();
1134 if (!N)
1135 return nullptr;
1136
1137 LLVM_DEBUG(dbgs() << "Considering duplicating the SU\n");
1138 LLVM_DEBUG(dumpNode(*SU));
1139
1140 if (N->getGluedNode() &&
1141 !TII->canCopyGluedNodeDuringSchedule(N)) {
1142 LLVM_DEBUG(
1143 dbgs()
1144 << "Giving up because it has incoming glue and the target does not "
1145 "want to copy it\n");
1146 return nullptr;
1147 }
1148
1149 SUnit *NewSU;
1150 bool TryUnfold = false;
1151 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
1152 MVT VT = N->getSimpleValueType(i);
1153 if (VT == MVT::Glue) {
1154 LLVM_DEBUG(dbgs() << "Giving up because it has outgoing glue\n");
1155 return nullptr;
1156 } else if (VT == MVT::Other)
1157 TryUnfold = true;
1158 }
1159 for (const SDValue &Op : N->op_values()) {
1160 MVT VT = Op.getNode()->getSimpleValueType(Op.getResNo());
1161 if (VT == MVT::Glue && !TII->canCopyGluedNodeDuringSchedule(N)) {
1162 LLVM_DEBUG(
1163 dbgs() << "Giving up because it one of the operands is glue and "
1164 "the target does not want to copy it\n");
1165 return nullptr;
1166 }
1167 }
1168
1169 // If possible unfold instruction.
1170 if (TryUnfold) {
1171 SUnit *UnfoldSU = TryUnfoldSU(SU);
1172 if (!UnfoldSU)
1173 return nullptr;
1174 SU = UnfoldSU;
1175 N = SU->getNode();
1176 // If this can be scheduled don't bother duplicating and just return
1177 if (SU->NumSuccsLeft == 0)
1178 return SU;
1179 }
1180
1181 LLVM_DEBUG(dbgs() << " Duplicating " << *SU << "\n");
1182 NewSU = CreateClone(SU);
1183
1184 // New SUnit has the exact same predecessors.
1185 for (SDep &Pred : SU->Preds)
1186 if (!Pred.isArtificial())
1187 AddPredQueued(NewSU, Pred);
1188
1189 // Make sure the clone comes after the original. (InstrEmitter assumes
1190 // this ordering.)
1191 AddPredQueued(NewSU, SDep(SU, SDep::Artificial));
1192
1193 // Only copy scheduled successors. Cut them from old node's successor
1194 // list and move them over.
1196 for (SDep &Succ : SU->Succs) {
1197 if (Succ.isArtificial())
1198 continue;
1199 SUnit *SuccSU = Succ.getSUnit();
1200 if (SuccSU->isScheduled) {
1201 SDep D = Succ;
1202 D.setSUnit(NewSU);
1203 AddPredQueued(SuccSU, D);
1204 D.setSUnit(SU);
1205 DelDeps.emplace_back(SuccSU, D);
1206 }
1207 }
1208 for (const auto &[DelSU, DelD] : DelDeps)
1209 RemovePred(DelSU, DelD);
1210
1211 AvailableQueue->updateNode(SU);
1212 AvailableQueue->addNode(NewSU);
1213
1214 ++NumDups;
1215 return NewSU;
1216}
1217
1218/// InsertCopiesAndMoveSuccs - Insert register copies and move all
1219/// scheduled successors of the given SUnit to the last copy.
1220void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
1221 const TargetRegisterClass *DestRC,
1222 const TargetRegisterClass *SrcRC,
1223 SmallVectorImpl<SUnit*> &Copies) {
1224 SUnit *CopyFromSU = CreateNewSUnit(nullptr);
1225 CopyFromSU->CopySrcRC = SrcRC;
1226 CopyFromSU->CopyDstRC = DestRC;
1227
1228 SUnit *CopyToSU = CreateNewSUnit(nullptr);
1229 CopyToSU->CopySrcRC = DestRC;
1230 CopyToSU->CopyDstRC = SrcRC;
1231
1232 // Only copy scheduled successors. Cut them from old node's successor
1233 // list and move them over.
1235 for (SDep &Succ : SU->Succs) {
1236 if (Succ.isArtificial())
1237 continue;
1238 SUnit *SuccSU = Succ.getSUnit();
1239 if (SuccSU->isScheduled) {
1240 SDep D = Succ;
1241 D.setSUnit(CopyToSU);
1242 AddPredQueued(SuccSU, D);
1243 DelDeps.emplace_back(SuccSU, Succ);
1244 }
1245 else {
1246 // Avoid scheduling the def-side copy before other successors. Otherwise,
1247 // we could introduce another physreg interference on the copy and
1248 // continue inserting copies indefinitely.
1249 AddPredQueued(SuccSU, SDep(CopyFromSU, SDep::Artificial));
1250 }
1251 }
1252 for (const auto &[DelSU, DelD] : DelDeps)
1253 RemovePred(DelSU, DelD);
1254
1255 SDep FromDep(SU, SDep::Data, Reg);
1256 FromDep.setLatency(SU->Latency);
1257 AddPredQueued(CopyFromSU, FromDep);
1258 SDep ToDep(CopyFromSU, SDep::Data, 0);
1259 ToDep.setLatency(CopyFromSU->Latency);
1260 AddPredQueued(CopyToSU, ToDep);
1261
1262 AvailableQueue->updateNode(SU);
1263 AvailableQueue->addNode(CopyFromSU);
1264 AvailableQueue->addNode(CopyToSU);
1265 Copies.push_back(CopyFromSU);
1266 Copies.push_back(CopyToSU);
1267
1268 ++NumPRCopies;
1269}
1270
1271/// CheckForLiveRegDef - Return true and update live register vector if the
1272/// specified register def of the specified SUnit clobbers any "live" registers.
1273void ScheduleDAGRRList::CheckForLiveRegDef(SUnit *SU, MCRegister Reg,
1274 SmallSet<unsigned, 4> &RegAdded,
1275 SmallVectorImpl<unsigned> &LRegs,
1276 const SDNode *Node) {
1277 for (MCRegAliasIterator AliasI(Reg, TRI, true); AliasI.isValid(); ++AliasI) {
1278 SUnit *Def = getLiveRegDef(*AliasI);
1279
1280 // Check if Ref is live.
1281 if (!Def)
1282 continue;
1283
1284 // Allow multiple uses of the same def.
1285 if (Def == SU)
1286 continue;
1287
1288 // Allow multiple uses of same def
1289 if (Node && Def->getNode() == Node)
1290 continue;
1291
1292 // Add Reg to the set of interfering live regs.
1293 if (RegAdded.insert(*AliasI).second) {
1294 LRegs.push_back(*AliasI);
1295 }
1296 }
1297}
1298
1299/// CheckForLiveRegDefMasked - Check for any live physregs that are clobbered
1300/// by RegMask, and add them to LRegs.
1301void ScheduleDAGRRList::CheckForLiveRegDefMasked(
1302 SUnit *SU, const uint32_t *RegMask, SmallSet<unsigned, 4> &RegAdded,
1303 SmallVectorImpl<unsigned> &LRegs) {
1304 // Look at all live registers, except the special CallResource. Add them in
1305 // register order, independent of the order they became live in.
1306 unsigned CallResource = TRI->getNumRegs();
1307 SmallVector<unsigned, 8> Clobbered;
1308 for (const LiveReg &LR : LiveRegs) {
1309 if (LR.Reg == CallResource || LR.Def == SU)
1310 continue;
1311 if (MachineOperand::clobbersPhysReg(RegMask, LR.Reg))
1312 Clobbered.push_back(LR.Reg);
1313 }
1314 llvm::sort(Clobbered);
1315 for (unsigned Reg : Clobbered)
1316 if (RegAdded.insert(Reg).second)
1317 LRegs.push_back(Reg);
1318}
1319
1320/// getNodeRegMask - Returns the register mask attached to an SDNode, if any.
1321static const uint32_t *getNodeRegMask(const SDNode *N) {
1322 for (const SDValue &Op : N->op_values())
1323 if (const auto *RegOp = dyn_cast<RegisterMaskSDNode>(Op.getNode()))
1324 return RegOp->getRegMask();
1325 return nullptr;
1326}
1327
1328/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
1329/// scheduling of the given node to satisfy live physical register dependencies.
1330/// If the specific node is the last one that's available to schedule, do
1331/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
1332bool ScheduleDAGRRList::
1333DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) {
1334 if (LiveRegs.empty())
1335 return false;
1336
1337 SmallSet<unsigned, 4> RegAdded;
1338 // If this node would clobber any "live" register, then it's not ready.
1339 //
1340 // If SU is the currently live definition of the same register that it uses,
1341 // then we are free to schedule it.
1342 for (SDep &Pred : SU->Preds) {
1343 if (Pred.isAssignedRegDep() && getLiveRegDef(Pred.getReg()) != SU)
1344 CheckForLiveRegDef(Pred.getSUnit(), Pred.getReg(), RegAdded, LRegs);
1345 }
1346
1347 for (SDNode *Node = SU->getNode(); Node; Node = Node->getGluedNode()) {
1348 if (Node->getOpcode() == ISD::INLINEASM ||
1349 Node->getOpcode() == ISD::INLINEASM_BR) {
1350 // Inline asm can clobber physical defs.
1351 unsigned NumOps = Node->getNumOperands();
1352 if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
1353 --NumOps; // Ignore the glue operand.
1354
1355 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
1356 unsigned Flags = Node->getConstantOperandVal(i);
1357 const InlineAsm::Flag F(Flags);
1358 unsigned NumVals = F.getNumOperandRegisters();
1359
1360 ++i; // Skip the ID value.
1361 if (F.isRegDefKind() || F.isRegDefEarlyClobberKind() ||
1362 F.isClobberKind()) {
1363 // Check for def of register or earlyclobber register.
1364 for (; NumVals; --NumVals, ++i) {
1365 Register Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1366 if (Reg.isPhysical())
1367 CheckForLiveRegDef(SU, Reg, RegAdded, LRegs);
1368 }
1369 } else
1370 i += NumVals;
1371 }
1372 continue;
1373 }
1374
1375 if (Node->getOpcode() == ISD::CopyToReg) {
1376 Register Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
1377 if (Reg.isPhysical()) {
1378 SDNode *SrcNode = Node->getOperand(2).getNode();
1379 CheckForLiveRegDef(SU, Reg, RegAdded, LRegs, SrcNode);
1380 }
1381 }
1382
1383 if (!Node->isMachineOpcode())
1384 continue;
1385 // If we're in the middle of scheduling a call, don't begin scheduling
1386 // another call. Also, don't allow any physical registers to be live across
1387 // the call.
1388 if (Node->getMachineOpcode() == TII->getCallFrameDestroyOpcode()) {
1389 // Check the special calling-sequence resource.
1390 unsigned CallResource = TRI->getNumRegs();
1391 if (LiveReg *LR = findLiveReg(CallResource)) {
1392 SDNode *Gen = LR->Gen->getNode();
1393 while (SDNode *Glued = Gen->getGluedNode())
1394 Gen = Glued;
1395 if (!IsChainDependent(Gen, Node, 0, TII) &&
1396 RegAdded.insert(CallResource).second)
1397 LRegs.push_back(CallResource);
1398 }
1399 }
1400 if (const uint32_t *RegMask = getNodeRegMask(Node))
1401 CheckForLiveRegDefMasked(SU, RegMask, RegAdded, LRegs);
1402
1403 const MCInstrDesc &MCID = TII->get(Node->getMachineOpcode());
1404 if (MCID.hasOptionalDef()) {
1405 // Most ARM instructions have an OptionalDef for CPSR, to model the S-bit.
1406 // This operand can be either a def of CPSR, if the S bit is set; or a use
1407 // of %noreg. When the OptionalDef is set to a valid register, we need to
1408 // handle it in the same way as an ImplicitDef.
1409 for (unsigned i = 0; i < MCID.getNumDefs(); ++i)
1410 if (MCID.operands()[i].isOptionalDef()) {
1411 const SDValue &OptionalDef = Node->getOperand(i - Node->getNumValues());
1412 Register Reg = cast<RegisterSDNode>(OptionalDef)->getReg();
1413 CheckForLiveRegDef(SU, Reg, RegAdded, LRegs);
1414 }
1415 }
1416 for (MCPhysReg Reg : MCID.implicit_defs())
1417 CheckForLiveRegDef(SU, Reg, RegAdded, LRegs);
1418 }
1419
1420 return !LRegs.empty();
1421}
1422
1423void ScheduleDAGRRList::releaseInterferences(unsigned Reg) {
1424 // Add the nodes that aren't ready back onto the available list.
1425 for (unsigned i = Interferences.size(); i > 0; --i) {
1426 SUnit *SU = Interferences[i-1];
1427 LRegsMapT::iterator LRegsPos = LRegsMap.find(SU);
1428 if (Reg) {
1429 SmallVectorImpl<unsigned> &LRegs = LRegsPos->second;
1430 if (!is_contained(LRegs, Reg))
1431 continue;
1432 }
1433 SU->isPending = false;
1434 // The interfering node may no longer be available due to backtracking.
1435 // Furthermore, it may have been made available again, in which case it is
1436 // now already in the AvailableQueue.
1437 if (SU->isAvailable && !SU->NodeQueueId) {
1438 LLVM_DEBUG(dbgs() << " Repushing " << *SU << '\n');
1439 AvailableQueue->push(SU);
1440 }
1441 if (i < Interferences.size())
1442 Interferences[i-1] = Interferences.back();
1443 Interferences.pop_back();
1444 LRegsMap.erase(LRegsPos);
1445 }
1446}
1447
1448/// Return a node that can be scheduled in this cycle. Requirements:
1449/// (1) Ready: latency has been satisfied
1450/// (2) No Hazards: resources are available
1451/// (3) No Interferences: may unschedule to break register interferences.
1452SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1453 SUnit *CurSU = AvailableQueue->empty() ? nullptr : AvailableQueue->pop();
1454 auto FindAvailableNode = [&]() {
1455 while (CurSU) {
1456 SmallVector<unsigned, 4> LRegs;
1457 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1458 break;
1459 LLVM_DEBUG(dbgs() << " Interfering reg ";
1460 if (LRegs[0] == TRI->getNumRegs()) dbgs() << "CallResource";
1461 else dbgs() << printReg(LRegs[0], TRI);
1462 dbgs() << " " << *CurSU << '\n');
1463 auto [LRegsIter, LRegsInserted] = LRegsMap.try_emplace(CurSU, LRegs);
1464 if (LRegsInserted) {
1465 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
1466 Interferences.push_back(CurSU);
1467 }
1468 else {
1469 assert(CurSU->isPending && "Interferences are pending");
1470 // Update the interference with current live regs.
1471 LRegsIter->second = LRegs;
1472 }
1473 CurSU = AvailableQueue->pop();
1474 }
1475 };
1476 FindAvailableNode();
1477 if (CurSU)
1478 return CurSU;
1479
1480 // We query the topological order in the loop body, so make sure outstanding
1481 // updates are applied before entering it (we only enter the loop if there
1482 // are some interferences). If we make changes to the ordering, we exit
1483 // the loop.
1484
1485 // All candidates are delayed due to live physical reg dependencies.
1486 // Try backtracking, code duplication, or inserting cross class copies
1487 // to resolve it.
1488 for (SUnit *TrySU : Interferences) {
1489 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
1490
1491 // Try unscheduling up to the point where it's safe to schedule
1492 // this node.
1493 SUnit *BtSU = nullptr;
1494 unsigned LiveCycle = std::numeric_limits<unsigned>::max();
1495 for (unsigned Reg : LRegs) {
1496 SUnit *Gen = getLiveRegGen(Reg);
1497 if (Gen->getHeight() < LiveCycle) {
1498 BtSU = Gen;
1499 LiveCycle = BtSU->getHeight();
1500 }
1501 }
1502 if (!WillCreateCycle(TrySU, BtSU)) {
1503 // BacktrackBottomUp mutates Interferences!
1504 BacktrackBottomUp(TrySU, BtSU);
1505
1506 // Force the current node to be scheduled before the node that
1507 // requires the physical reg dep.
1508 if (BtSU->isAvailable) {
1509 BtSU->isAvailable = false;
1510 if (!BtSU->isPending)
1511 AvailableQueue->remove(BtSU);
1512 }
1513 LLVM_DEBUG(dbgs() << "ARTIFICIAL edge from " << *BtSU << " to " << *TrySU
1514 << "\n");
1515 AddPredQueued(TrySU, SDep(BtSU, SDep::Artificial));
1516
1517 // If one or more successors has been unscheduled, then the current
1518 // node is no longer available.
1519 if (!TrySU->isAvailable || !TrySU->NodeQueueId) {
1520 LLVM_DEBUG(dbgs() << "TrySU not available; choosing node from queue\n");
1521 CurSU = AvailableQueue->pop();
1522 } else {
1523 LLVM_DEBUG(dbgs() << "TrySU available\n");
1524 // Available and in AvailableQueue
1525 AvailableQueue->remove(TrySU);
1526 CurSU = TrySU;
1527 }
1528 FindAvailableNode();
1529 // Interferences has been mutated. We must break.
1530 break;
1531 }
1532 }
1533
1534 if (!CurSU) {
1535 // Can't backtrack. If it's too expensive to copy the value, then try
1536 // duplicate the nodes that produces these "too expensive to copy"
1537 // values to break the dependency. In case even that doesn't work,
1538 // insert cross class copies.
1539 // If it's not too expensive, i.e. cost != -1, issue copies.
1540 SUnit *TrySU = Interferences[0];
1541 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
1542 assert(LRegs.size() == 1 && "Can't handle this yet!");
1543 unsigned Reg = LRegs[0];
1544 SUnit *LRDef = getLiveRegDef(Reg);
1545 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1546 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1547
1548 // If cross copy register class is the same as RC, then it must be possible
1549 // copy the value directly. Do not try duplicate the def.
1550 // If cross copy register class is not the same as RC, then it's possible to
1551 // copy the value but it require cross register class copies and it is
1552 // expensive.
1553 // If cross copy register class is null, then it's not possible to copy
1554 // the value at all.
1555 SUnit *NewDef = nullptr;
1556 if (DestRC != RC) {
1557 NewDef = CopyAndMoveSuccessors(LRDef);
1558 if (!DestRC && !NewDef)
1559 report_fatal_error("Can't handle live physical register dependency!");
1560 }
1561 if (!NewDef) {
1562 // Issue copies, these can be expensive cross register class copies.
1564 InsertCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1565 LLVM_DEBUG(dbgs() << " Adding an edge from " << *TrySU << " to "
1566 << *Copies.front() << "\n");
1567 AddPredQueued(TrySU, SDep(Copies.front(), SDep::Artificial));
1568 NewDef = Copies.back();
1569 }
1570
1571 LLVM_DEBUG(dbgs() << " Adding an edge from " << *NewDef << " to "
1572 << *TrySU << "\n");
1573 findLiveReg(Reg)->Def = NewDef;
1574 AddPredQueued(NewDef, SDep(TrySU, SDep::Artificial));
1575 TrySU->isAvailable = false;
1576 CurSU = NewDef;
1577 }
1578 assert(CurSU && "Unable to resolve live physical register dependencies!");
1579 return CurSU;
1580}
1581
1582/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
1583/// schedulers.
1584void ScheduleDAGRRList::ListScheduleBottomUp() {
1585 // Release any predecessors of the special Exit node.
1586 ReleasePredecessors(&ExitSU);
1587
1588 // Add root to Available queue.
1589 if (!SUnits.empty()) {
1590 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
1591 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
1592 RootSU->isAvailable = true;
1593 AvailableQueue->push(RootSU);
1594 }
1595
1596 // While Available queue is not empty, grab the node with the highest
1597 // priority. If it is not ready put it back. Schedule the node.
1598 Sequence.reserve(SUnits.size());
1599 while (!AvailableQueue->empty() || !Interferences.empty()) {
1600 LLVM_DEBUG(dbgs() << "\nExamining Available:\n";
1601 AvailableQueue->dump(this));
1602
1603 // Pick the best node to schedule taking all constraints into
1604 // consideration.
1605 SUnit *SU = PickNodeToScheduleBottomUp();
1606
1607 AdvancePastStalls(SU);
1608
1609 ScheduleNodeBottomUp(SU);
1610
1611 while (AvailableQueue->empty() && !PendingQueue.empty()) {
1612 // Advance the cycle to free resources. Skip ahead to the next ready SU.
1613 assert(MinAvailableCycle < std::numeric_limits<unsigned>::max() &&
1614 "MinAvailableCycle uninitialized");
1615 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1616 }
1617 }
1618
1619 // Reverse the order if it is bottom up.
1620 std::reverse(Sequence.begin(), Sequence.end());
1621
1622#ifndef NDEBUG
1623 VerifyScheduledSequence(/*isBottomUp=*/true);
1624#endif
1625}
1626
1627namespace {
1628
1629class RegReductionPQBase;
1630
1631struct queue_sort {
1632 bool isReady(SUnit* SU, unsigned CurCycle) const { return true; }
1633};
1634
1635#ifndef NDEBUG
1636template<class SF>
1637struct reverse_sort : public queue_sort {
1638 SF &SortFunc;
1639
1640 reverse_sort(SF &sf) : SortFunc(sf) {}
1641
1642 bool operator()(SUnit* left, SUnit* right) const {
1643 // reverse left/right rather than simply !SortFunc(left, right)
1644 // to expose different paths in the comparison logic.
1645 return SortFunc(right, left);
1646 }
1647};
1648#endif // NDEBUG
1649
1650/// bu_ls_rr_sort - Priority function for bottom up register pressure
1651// reduction scheduler.
1652struct bu_ls_rr_sort : public queue_sort {
1653 enum {
1654 IsBottomUp = true,
1655 HasReadyFilter = false
1656 };
1657
1658 RegReductionPQBase *SPQ;
1659
1660 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1661
1662 bool operator()(SUnit* left, SUnit* right) const;
1663};
1664
1665// src_ls_rr_sort - Priority function for source order scheduler.
1666struct src_ls_rr_sort : public queue_sort {
1667 enum {
1668 IsBottomUp = true,
1669 HasReadyFilter = false
1670 };
1671
1672 RegReductionPQBase *SPQ;
1673
1674 src_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1675
1676 bool operator()(SUnit* left, SUnit* right) const;
1677};
1678
1679// hybrid_ls_rr_sort - Priority function for hybrid scheduler.
1680struct hybrid_ls_rr_sort : public queue_sort {
1681 enum {
1682 IsBottomUp = true,
1683 HasReadyFilter = false
1684 };
1685
1686 RegReductionPQBase *SPQ;
1687
1688 hybrid_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1689
1690 bool isReady(SUnit *SU, unsigned CurCycle) const;
1691
1692 bool operator()(SUnit* left, SUnit* right) const;
1693};
1694
1695// ilp_ls_rr_sort - Priority function for ILP (instruction level parallelism)
1696// scheduler.
1697struct ilp_ls_rr_sort : public queue_sort {
1698 enum {
1699 IsBottomUp = true,
1700 HasReadyFilter = false
1701 };
1702
1703 RegReductionPQBase *SPQ;
1704
1705 ilp_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1706
1707 bool isReady(SUnit *SU, unsigned CurCycle) const;
1708
1709 bool operator()(SUnit* left, SUnit* right) const;
1710};
1711
1712class RegReductionPQBase : public SchedulingPriorityQueue {
1713protected:
1714 std::vector<SUnit *> Queue;
1715 unsigned CurQueueId = 0;
1716 bool TracksRegPressure;
1717 bool SrcOrder;
1718
1719 // SUnits - The SUnits for the current graph.
1720 std::vector<SUnit> *SUnits = nullptr;
1721
1722 MachineFunction &MF;
1723 const TargetInstrInfo *TII = nullptr;
1724 const TargetRegisterInfo *TRI = nullptr;
1725 const TargetLowering *TLI = nullptr;
1726 ScheduleDAGRRList *scheduleDAG = nullptr;
1727
1728 // SethiUllmanNumbers - The SethiUllman number for each node.
1729 std::vector<unsigned> SethiUllmanNumbers;
1730
1731 /// RegPressure - Tracking current reg pressure per register class.
1732 std::vector<unsigned> RegPressure;
1733
1734 /// RegLimit - Tracking the number of allocatable registers per register
1735 /// class.
1736 std::vector<unsigned> RegLimit;
1737
1738public:
1739 RegReductionPQBase(MachineFunction &mf,
1740 bool hasReadyFilter,
1741 bool tracksrp,
1742 bool srcorder,
1743 const TargetInstrInfo *tii,
1744 const TargetRegisterInfo *tri,
1745 const TargetLowering *tli)
1746 : SchedulingPriorityQueue(hasReadyFilter), TracksRegPressure(tracksrp),
1747 SrcOrder(srcorder), MF(mf), TII(tii), TRI(tri), TLI(tli) {
1748 if (TracksRegPressure) {
1749 unsigned NumRC = TRI->getNumRegClasses();
1750 RegLimit.resize(NumRC);
1751 RegPressure.resize(NumRC);
1752 llvm::fill(RegLimit, 0);
1753 llvm::fill(RegPressure, 0);
1754 }
1755 }
1756
1757 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1758 scheduleDAG = scheduleDag;
1759 }
1760
1761 ScheduleHazardRecognizer* getHazardRec() {
1762 return scheduleDAG->getHazardRec();
1763 }
1764
1765 void initNodes(std::vector<SUnit> &sunits) override;
1766
1767 void addNode(const SUnit *SU) override;
1768
1769 void updateNode(const SUnit *SU) override;
1770
1771 void releaseState() override {
1772 SUnits = nullptr;
1773 SethiUllmanNumbers.clear();
1774 llvm::fill(RegPressure, 0);
1775 }
1776
1777 unsigned getNodePriority(const SUnit *SU) const;
1778
1779 unsigned getNodeOrdering(const SUnit *SU) const {
1780 if (!SU->getNode()) return 0;
1781
1782 return SU->getNode()->getIROrder();
1783 }
1784
1785 bool empty() const override { return Queue.empty(); }
1786
1787 void push(SUnit *U) override {
1788 assert(!U->NodeQueueId && "Node in the queue already");
1789 U->NodeQueueId = ++CurQueueId;
1790 Queue.push_back(U);
1791 }
1792
1793 void remove(SUnit *SU) override {
1794 assert(!Queue.empty() && "Queue is empty!");
1795 assert(SU->NodeQueueId != 0 && "Not in queue!");
1796 std::vector<SUnit *>::iterator I = llvm::find(Queue, SU);
1797 if (I != std::prev(Queue.end()))
1798 std::swap(*I, Queue.back());
1799 Queue.pop_back();
1800 SU->NodeQueueId = 0;
1801 }
1802
1803 bool tracksRegPressure() const override { return TracksRegPressure; }
1804
1805 void dumpRegPressure() const;
1806
1807 bool HighRegPressure(const SUnit *SU) const;
1808
1809 bool MayReduceRegPressure(SUnit *SU) const;
1810
1811 int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
1812
1813 void scheduledNode(SUnit *SU) override;
1814
1815 void unscheduledNode(SUnit *SU) override;
1816
1817protected:
1818 bool canClobber(const SUnit *SU, const SUnit *Op);
1819 void AddPseudoTwoAddrDeps();
1820 void PrescheduleNodesWithMultipleUses();
1821 void CalculateSethiUllmanNumbers();
1822};
1823
1824template<class SF>
1825static SUnit *popFromQueueImpl(std::vector<SUnit *> &Q, SF &Picker) {
1826 unsigned BestIdx = 0;
1827 // Only compute the cost for the first 1000 items in the queue, to avoid
1828 // excessive compile-times for very large queues.
1829 for (unsigned I = 1, E = std::min(Q.size(), (decltype(Q.size()))1000); I != E;
1830 I++)
1831 if (Picker(Q[BestIdx], Q[I]))
1832 BestIdx = I;
1833 SUnit *V = Q[BestIdx];
1834 if (BestIdx + 1 != Q.size())
1835 std::swap(Q[BestIdx], Q.back());
1836 Q.pop_back();
1837 return V;
1838}
1839
1840template<class SF>
1841SUnit *popFromQueue(std::vector<SUnit *> &Q, SF &Picker, ScheduleDAG *DAG) {
1842#ifndef NDEBUG
1843 if (DAG->StressSched) {
1844 reverse_sort<SF> RPicker(Picker);
1845 return popFromQueueImpl(Q, RPicker);
1846 }
1847#endif
1848 (void)DAG;
1849 return popFromQueueImpl(Q, Picker);
1850}
1851
1852//===----------------------------------------------------------------------===//
1853// RegReductionPriorityQueue Definition
1854//===----------------------------------------------------------------------===//
1855//
1856// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1857// to reduce register pressure.
1858//
1859template<class SF>
1860class RegReductionPriorityQueue : public RegReductionPQBase {
1861 SF Picker;
1862
1863public:
1864 RegReductionPriorityQueue(MachineFunction &mf,
1865 bool tracksrp,
1866 bool srcorder,
1867 const TargetInstrInfo *tii,
1868 const TargetRegisterInfo *tri,
1869 const TargetLowering *tli)
1870 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
1871 tii, tri, tli),
1872 Picker(this) {}
1873
1874 bool isBottomUp() const override { return SF::IsBottomUp; }
1875
1876 bool isReady(SUnit *U) const override {
1877 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1878 }
1879
1880 SUnit *pop() override {
1881 if (Queue.empty()) return nullptr;
1882
1883 SUnit *V = popFromQueue(Queue, Picker, scheduleDAG);
1884 V->NodeQueueId = 0;
1885 return V;
1886 }
1887
1888#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1889 LLVM_DUMP_METHOD void dump(ScheduleDAG *DAG) const override {
1890 // Emulate pop() without clobbering NodeQueueIds.
1891 std::vector<SUnit *> DumpQueue = Queue;
1892 SF DumpPicker = Picker;
1893 while (!DumpQueue.empty()) {
1894 SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
1895 dbgs() << "Height " << SU->getHeight() << ": ";
1896 DAG->dumpNode(*SU);
1897 }
1898 }
1899#endif
1900};
1901
1902using BURegReductionPriorityQueue = RegReductionPriorityQueue<bu_ls_rr_sort>;
1903using SrcRegReductionPriorityQueue = RegReductionPriorityQueue<src_ls_rr_sort>;
1904using HybridBURRPriorityQueue = RegReductionPriorityQueue<hybrid_ls_rr_sort>;
1905using ILPBURRPriorityQueue = RegReductionPriorityQueue<ilp_ls_rr_sort>;
1906
1907} // end anonymous namespace
1908
1909//===----------------------------------------------------------------------===//
1910// Static Node Priority for Register Pressure Reduction
1911//===----------------------------------------------------------------------===//
1912
1913// Check for special nodes that bypass scheduling heuristics.
1914// Currently this pushes TokenFactor nodes down, but may be used for other
1915// pseudo-ops as well.
1916//
1917// Return -1 to schedule right above left, 1 for left above right.
1918// Return 0 if no bias exists.
1919static int checkSpecialNodes(const SUnit *left, const SUnit *right) {
1920 bool LSchedLow = left->isScheduleLow;
1921 bool RSchedLow = right->isScheduleLow;
1922 if (LSchedLow != RSchedLow)
1923 return LSchedLow < RSchedLow ? 1 : -1;
1924 return 0;
1925}
1926
1927/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1928/// Smaller number is the higher priority.
1929static unsigned
1930CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1931 if (SUNumbers[SU->NodeNum] != 0)
1932 return SUNumbers[SU->NodeNum];
1933
1934 // Use WorkList to avoid stack overflow on excessively large IRs.
1935 struct WorkState {
1936 WorkState(const SUnit *SU) : SU(SU) {}
1937 const SUnit *SU;
1938 unsigned PredsProcessed = 0;
1939 };
1940
1942 WorkList.push_back(SU);
1943 while (!WorkList.empty()) {
1944 auto &Temp = WorkList.back();
1945 auto *TempSU = Temp.SU;
1946 bool AllPredsKnown = true;
1947 // Try to find a non-evaluated pred and push it into the processing stack.
1948 for (unsigned P = Temp.PredsProcessed; P < TempSU->Preds.size(); ++P) {
1949 auto &Pred = TempSU->Preds[P];
1950 if (Pred.isCtrl()) continue; // ignore chain preds
1951 SUnit *PredSU = Pred.getSUnit();
1952 if (SUNumbers[PredSU->NodeNum] == 0) {
1953#ifndef NDEBUG
1954 // In debug mode, check that we don't have such element in the stack.
1955 for (auto It : WorkList)
1956 assert(It.SU != PredSU && "Trying to push an element twice?");
1957#endif
1958 // Next time start processing this one starting from the next pred.
1959 Temp.PredsProcessed = P + 1;
1960 WorkList.push_back(PredSU);
1961 AllPredsKnown = false;
1962 break;
1963 }
1964 }
1965
1966 if (!AllPredsKnown)
1967 continue;
1968
1969 // Once all preds are known, we can calculate the answer for this one.
1970 unsigned SethiUllmanNumber = 0;
1971 unsigned Extra = 0;
1972 for (const SDep &Pred : TempSU->Preds) {
1973 if (Pred.isCtrl()) continue; // ignore chain preds
1974 SUnit *PredSU = Pred.getSUnit();
1975 unsigned PredSethiUllman = SUNumbers[PredSU->NodeNum];
1976 assert(PredSethiUllman > 0 && "We should have evaluated this pred!");
1977 if (PredSethiUllman > SethiUllmanNumber) {
1978 SethiUllmanNumber = PredSethiUllman;
1979 Extra = 0;
1980 } else if (PredSethiUllman == SethiUllmanNumber)
1981 ++Extra;
1982 }
1983
1984 SethiUllmanNumber += Extra;
1985 if (SethiUllmanNumber == 0)
1986 SethiUllmanNumber = 1;
1987 SUNumbers[TempSU->NodeNum] = SethiUllmanNumber;
1988 WorkList.pop_back();
1989 }
1990
1991 assert(SUNumbers[SU->NodeNum] > 0 && "SethiUllman should never be zero!");
1992 return SUNumbers[SU->NodeNum];
1993}
1994
1995/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1996/// scheduling units.
1997void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1998 SethiUllmanNumbers.assign(SUnits->size(), 0);
1999
2000 for (const SUnit &SU : *SUnits)
2001 CalcNodeSethiUllmanNumber(&SU, SethiUllmanNumbers);
2002}
2003
2004void RegReductionPQBase::addNode(const SUnit *SU) {
2005 unsigned SUSize = SethiUllmanNumbers.size();
2006 if (SUnits->size() > SUSize)
2007 SethiUllmanNumbers.resize(SUSize*2, 0);
2008 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
2009}
2010
2011void RegReductionPQBase::updateNode(const SUnit *SU) {
2012 SethiUllmanNumbers[SU->NodeNum] = 0;
2013 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
2014}
2015
2016// Lower priority means schedule further down. For bottom-up scheduling, lower
2017// priority SUs are scheduled before higher priority SUs.
2018unsigned RegReductionPQBase::getNodePriority(const SUnit *SU) const {
2019 assert(SU->NodeNum < SethiUllmanNumbers.size());
2020 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2022 // CopyToReg should be close to its uses to facilitate coalescing and
2023 // avoid spilling.
2024 return 0;
2025 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2026 Opc == TargetOpcode::SUBREG_TO_REG ||
2027 Opc == TargetOpcode::INSERT_SUBREG)
2028 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2029 // close to their uses to facilitate coalescing.
2030 return 0;
2031 if (SU->NumSuccs == 0 && SU->NumPreds != 0)
2032 // If SU does not have a register use, i.e. it doesn't produce a value
2033 // that would be consumed (e.g. store), then it terminates a chain of
2034 // computation. Give it a large SethiUllman number so it will be
2035 // scheduled right before its predecessors that it doesn't lengthen
2036 // their live ranges.
2037 return 0xffff;
2038 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2039 // If SU does not have a register def, schedule it close to its uses
2040 // because it does not lengthen any live ranges.
2041 return 0;
2042#if 1
2043 return SethiUllmanNumbers[SU->NodeNum];
2044#else
2045 unsigned Priority = SethiUllmanNumbers[SU->NodeNum];
2046 if (SU->isCallOp) {
2047 // FIXME: This assumes all of the defs are used as call operands.
2048 int NP = (int)Priority - SU->getNode()->getNumValues();
2049 return (NP > 0) ? NP : 0;
2050 }
2051 return Priority;
2052#endif
2053}
2054
2055//===----------------------------------------------------------------------===//
2056// Register Pressure Tracking
2057//===----------------------------------------------------------------------===//
2058
2059#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2060LLVM_DUMP_METHOD void RegReductionPQBase::dumpRegPressure() const {
2061 for (const TargetRegisterClass &RC : TRI->regclasses()) {
2062 unsigned Id = RC.getID();
2063 unsigned RP = RegPressure[Id];
2064 if (!RP) continue;
2065 LLVM_DEBUG(dbgs() << TRI->getRegClassName(&RC) << ": " << RP << " / "
2066 << RegLimit[Id] << '\n');
2067 }
2068}
2069#endif
2070
2071bool RegReductionPQBase::HighRegPressure(const SUnit *SU) const {
2072 if (!TLI)
2073 return false;
2074
2075 for (const SDep &Pred : SU->Preds) {
2076 if (Pred.isCtrl())
2077 continue;
2078 SUnit *PredSU = Pred.getSUnit();
2079 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2080 // to cover the number of registers defined (they are all live).
2081 if (PredSU->NumRegDefsLeft == 0) {
2082 continue;
2083 }
2084 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2085 RegDefPos.IsValid(); RegDefPos.Advance()) {
2086 unsigned RCId, Cost;
2087 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
2088
2089 if ((RegPressure[RCId] + Cost) >= RegLimit[RCId])
2090 return true;
2091 }
2092 }
2093 return false;
2094}
2095
2096bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU) const {
2097 const SDNode *N = SU->getNode();
2098
2099 if (!N->isMachineOpcode() || !SU->NumSuccs)
2100 return false;
2101
2102 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2103 for (unsigned i = 0; i != NumDefs; ++i) {
2104 MVT VT = N->getSimpleValueType(i);
2105 if (!N->hasAnyUseOfValue(i))
2106 continue;
2107 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2108 if (RegPressure[RCId] >= RegLimit[RCId])
2109 return true;
2110 }
2111 return false;
2112}
2113
2114// Compute the register pressure contribution by this instruction by count up
2115// for uses that are not live and down for defs. Only count register classes
2116// that are already under high pressure. As a side effect, compute the number of
2117// uses of registers that are already live.
2118//
2119// FIXME: This encompasses the logic in HighRegPressure and MayReduceRegPressure
2120// so could probably be factored.
2121int RegReductionPQBase::RegPressureDiff(SUnit *SU, unsigned &LiveUses) const {
2122 LiveUses = 0;
2123 int PDiff = 0;
2124 for (const SDep &Pred : SU->Preds) {
2125 if (Pred.isCtrl())
2126 continue;
2127 SUnit *PredSU = Pred.getSUnit();
2128 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2129 // to cover the number of registers defined (they are all live).
2130 if (PredSU->NumRegDefsLeft == 0) {
2131 if (PredSU->getNode()->isMachineOpcode())
2132 ++LiveUses;
2133 continue;
2134 }
2135 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2136 RegDefPos.IsValid(); RegDefPos.Advance()) {
2137 MVT VT = RegDefPos.GetValue();
2138 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2139 if (RegPressure[RCId] >= RegLimit[RCId])
2140 ++PDiff;
2141 }
2142 }
2143 const SDNode *N = SU->getNode();
2144
2145 if (!N || !N->isMachineOpcode() || !SU->NumSuccs)
2146 return PDiff;
2147
2148 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2149 for (unsigned i = 0; i != NumDefs; ++i) {
2150 MVT VT = N->getSimpleValueType(i);
2151 if (!N->hasAnyUseOfValue(i))
2152 continue;
2153 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2154 if (RegPressure[RCId] >= RegLimit[RCId])
2155 --PDiff;
2156 }
2157 return PDiff;
2158}
2159
2160void RegReductionPQBase::scheduledNode(SUnit *SU) {
2161 if (!TracksRegPressure)
2162 return;
2163
2164 if (!SU->getNode())
2165 return;
2166
2167 for (const SDep &Pred : SU->Preds) {
2168 if (Pred.isCtrl())
2169 continue;
2170 SUnit *PredSU = Pred.getSUnit();
2171 // NumRegDefsLeft is zero when enough uses of this node have been scheduled
2172 // to cover the number of registers defined (they are all live).
2173 if (PredSU->NumRegDefsLeft == 0) {
2174 continue;
2175 }
2176 // FIXME: The ScheduleDAG currently loses information about which of a
2177 // node's values is consumed by each dependence. Consequently, if the node
2178 // defines multiple register classes, we don't know which to pressurize
2179 // here. Instead the following loop consumes the register defs in an
2180 // arbitrary order. At least it handles the common case of clustered loads
2181 // to the same class. For precise liveness, each SDep needs to indicate the
2182 // result number. But that tightly couples the ScheduleDAG with the
2183 // SelectionDAG making updates tricky. A simpler hack would be to attach a
2184 // value type or register class to SDep.
2185 //
2186 // The most important aspect of register tracking is balancing the increase
2187 // here with the reduction further below. Note that this SU may use multiple
2188 // defs in PredSU. The can't be determined here, but we've already
2189 // compensated by reducing NumRegDefsLeft in PredSU during
2190 // ScheduleDAGSDNodes::AddSchedEdges.
2191 --PredSU->NumRegDefsLeft;
2192 unsigned SkipRegDefs = PredSU->NumRegDefsLeft;
2193 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2194 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2195 if (SkipRegDefs)
2196 continue;
2197
2198 unsigned RCId, Cost;
2199 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
2200 RegPressure[RCId] += Cost;
2201 break;
2202 }
2203 }
2204
2205 // We should have this assert, but there may be dead SDNodes that never
2206 // materialize as SUnits, so they don't appear to generate liveness.
2207 //assert(SU->NumRegDefsLeft == 0 && "not all regdefs have scheduled uses");
2208 int SkipRegDefs = (int)SU->NumRegDefsLeft;
2209 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
2210 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2211 if (SkipRegDefs > 0)
2212 continue;
2213 unsigned RCId, Cost;
2214 GetCostForDef(RegDefPos, TLI, TII, TRI, RCId, Cost, MF);
2215 if (RegPressure[RCId] < Cost) {
2216 // Register pressure tracking is imprecise. This can happen. But we try
2217 // hard not to let it happen because it likely results in poor scheduling.
2218 LLVM_DEBUG(dbgs() << " " << *SU << " has too many regdefs\n");
2219 RegPressure[RCId] = 0;
2220 }
2221 else {
2222 RegPressure[RCId] -= Cost;
2223 }
2224 }
2225 LLVM_DEBUG(dumpRegPressure());
2226}
2227
2228void RegReductionPQBase::unscheduledNode(SUnit *SU) {
2229 if (!TracksRegPressure)
2230 return;
2231
2232 const SDNode *N = SU->getNode();
2233 if (!N) return;
2234
2235 if (!N->isMachineOpcode()) {
2236 if (N->getOpcode() != ISD::CopyToReg)
2237 return;
2238 } else {
2239 unsigned Opc = N->getMachineOpcode();
2240 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2241 Opc == TargetOpcode::INSERT_SUBREG ||
2242 Opc == TargetOpcode::SUBREG_TO_REG ||
2243 Opc == TargetOpcode::REG_SEQUENCE ||
2244 Opc == TargetOpcode::IMPLICIT_DEF)
2245 return;
2246 }
2247
2248 for (const SDep &Pred : SU->Preds) {
2249 if (Pred.isCtrl())
2250 continue;
2251 SUnit *PredSU = Pred.getSUnit();
2252 // NumSuccsLeft counts all deps. Don't compare it with NumSuccs which only
2253 // counts data deps.
2254 if (PredSU->NumSuccsLeft != PredSU->Succs.size())
2255 continue;
2256 const SDNode *PN = PredSU->getNode();
2257 if (!PN->isMachineOpcode()) {
2258 if (PN->getOpcode() == ISD::CopyFromReg) {
2259 MVT VT = PN->getSimpleValueType(0);
2260 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2262 }
2263 continue;
2264 }
2265 unsigned POpc = PN->getMachineOpcode();
2266 if (POpc == TargetOpcode::IMPLICIT_DEF)
2267 continue;
2268 if (POpc == TargetOpcode::EXTRACT_SUBREG ||
2269 POpc == TargetOpcode::INSERT_SUBREG ||
2270 POpc == TargetOpcode::SUBREG_TO_REG) {
2271 MVT VT = PN->getSimpleValueType(0);
2272 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2274 continue;
2275 }
2276 if (POpc == TargetOpcode::REG_SEQUENCE) {
2277 unsigned DstRCIdx = PN->getConstantOperandVal(0);
2278 const TargetRegisterClass *RC = TRI->getRegClass(DstRCIdx);
2279 unsigned RCId = RC->getID();
2280 // REG_SEQUENCE is untyped, so getRepRegClassCostFor could not be used
2281 // here. Instead use the same constant as in GetCostForDef.
2283 continue;
2284 }
2285 unsigned NumDefs = TII->get(PN->getMachineOpcode()).getNumDefs();
2286 for (unsigned i = 0; i != NumDefs; ++i) {
2287 MVT VT = PN->getSimpleValueType(i);
2288 if (!PN->hasAnyUseOfValue(i))
2289 continue;
2290 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2291 if (RegPressure[RCId] < TLI->getRepRegClassCostFor(VT))
2292 // Register pressure tracking is imprecise. This can happen.
2293 RegPressure[RCId] = 0;
2294 else
2296 }
2297 }
2298
2299 // Check for isMachineOpcode() as PrescheduleNodesWithMultipleUses()
2300 // may transfer data dependencies to CopyToReg.
2301 if (SU->NumSuccs && N->isMachineOpcode()) {
2302 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2303 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2304 MVT VT = N->getSimpleValueType(i);
2305 if (VT == MVT::Glue || VT == MVT::Other)
2306 continue;
2307 if (!N->hasAnyUseOfValue(i))
2308 continue;
2309 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
2311 }
2312 }
2313
2314 LLVM_DEBUG(dumpRegPressure());
2315}
2316
2317//===----------------------------------------------------------------------===//
2318// Dynamic Node Priority for Register Pressure Reduction
2319//===----------------------------------------------------------------------===//
2320
2321/// closestSucc - Returns the scheduled cycle of the successor which is
2322/// closest to the current cycle.
2323static unsigned closestSucc(const SUnit *SU) {
2324 unsigned MaxHeight = 0;
2325 for (const SDep &Succ : SU->Succs) {
2326 if (Succ.isCtrl()) continue; // ignore chain succs
2327 unsigned Height = Succ.getSUnit()->getHeight();
2328 // If there are bunch of CopyToRegs stacked up, they should be considered
2329 // to be at the same position.
2330 if (Succ.getSUnit()->getNode() &&
2331 Succ.getSUnit()->getNode()->getOpcode() == ISD::CopyToReg)
2332 Height = closestSucc(Succ.getSUnit())+1;
2333 if (Height > MaxHeight)
2334 MaxHeight = Height;
2335 }
2336 return MaxHeight;
2337}
2338
2339/// calcMaxScratches - Returns an cost estimate of the worse case requirement
2340/// for scratch registers, i.e. number of data dependencies.
2341static unsigned calcMaxScratches(const SUnit *SU) {
2342 unsigned Scratches = 0;
2343 for (const SDep &Pred : SU->Preds) {
2344 if (Pred.isCtrl()) continue; // ignore chain preds
2345 Scratches++;
2346 }
2347 return Scratches;
2348}
2349
2350/// hasOnlyLiveInOpers - Return true if SU has only value predecessors that are
2351/// CopyFromReg from a virtual register.
2352static bool hasOnlyLiveInOpers(const SUnit *SU) {
2353 bool RetVal = false;
2354 for (const SDep &Pred : SU->Preds) {
2355 if (Pred.isCtrl()) continue;
2356 const SUnit *PredSU = Pred.getSUnit();
2357 if (PredSU->getNode() &&
2358 PredSU->getNode()->getOpcode() == ISD::CopyFromReg) {
2359 Register Reg =
2360 cast<RegisterSDNode>(PredSU->getNode()->getOperand(1))->getReg();
2361 if (Reg.isVirtual()) {
2362 RetVal = true;
2363 continue;
2364 }
2365 }
2366 return false;
2367 }
2368 return RetVal;
2369}
2370
2371/// hasOnlyLiveOutUses - Return true if SU has only value successors that are
2372/// CopyToReg to a virtual register. This SU def is probably a liveout and
2373/// it has no other use. It should be scheduled closer to the terminator.
2374static bool hasOnlyLiveOutUses(const SUnit *SU) {
2375 bool RetVal = false;
2376 for (const SDep &Succ : SU->Succs) {
2377 if (Succ.isCtrl()) continue;
2378 const SUnit *SuccSU = Succ.getSUnit();
2379 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg) {
2380 Register Reg =
2381 cast<RegisterSDNode>(SuccSU->getNode()->getOperand(1))->getReg();
2382 if (Reg.isVirtual()) {
2383 RetVal = true;
2384 continue;
2385 }
2386 }
2387 return false;
2388 }
2389 return RetVal;
2390}
2391
2392// Set isVRegCycle for a node with only live in opers and live out uses. Also
2393// set isVRegCycle for its CopyFromReg operands.
2394//
2395// This is only relevant for single-block loops, in which case the VRegCycle
2396// node is likely an induction variable in which the operand and target virtual
2397// registers should be coalesced (e.g. pre/post increment values). Setting the
2398// isVRegCycle flag helps the scheduler prioritize other uses of the same
2399// CopyFromReg so that this node becomes the virtual register "kill". This
2400// avoids interference between the values live in and out of the block and
2401// eliminates a copy inside the loop.
2402static void initVRegCycle(SUnit *SU) {
2404 return;
2405
2406 if (!hasOnlyLiveInOpers(SU) || !hasOnlyLiveOutUses(SU))
2407 return;
2408
2409 LLVM_DEBUG(dbgs() << "VRegCycle: " << *SU << "\n");
2410
2411 SU->isVRegCycle = true;
2412
2413 for (const SDep &Pred : SU->Preds) {
2414 if (Pred.isCtrl()) continue;
2415 Pred.getSUnit()->isVRegCycle = true;
2416 }
2417}
2418
2419// After scheduling the definition of a VRegCycle, clear the isVRegCycle flag of
2420// CopyFromReg operands. We should no longer penalize other uses of this VReg.
2421static void resetVRegCycle(SUnit *SU) {
2422 if (!SU->isVRegCycle)
2423 return;
2424
2425 for (const SDep &Pred : SU->Preds) {
2426 if (Pred.isCtrl()) continue; // ignore chain preds
2427 SUnit *PredSU = Pred.getSUnit();
2428 if (PredSU->isVRegCycle) {
2429 assert(PredSU->getNode()->getOpcode() == ISD::CopyFromReg &&
2430 "VRegCycle def must be CopyFromReg");
2431 Pred.getSUnit()->isVRegCycle = false;
2432 }
2433 }
2434}
2435
2436// Return true if this SUnit uses a CopyFromReg node marked as a VRegCycle. This
2437// means a node that defines the VRegCycle has not been scheduled yet.
2438static bool hasVRegCycleUse(const SUnit *SU) {
2439 // If this SU also defines the VReg, don't hoist it as a "use".
2440 if (SU->isVRegCycle)
2441 return false;
2442
2443 for (const SDep &Pred : SU->Preds) {
2444 if (Pred.isCtrl()) continue; // ignore chain preds
2445 if (Pred.getSUnit()->isVRegCycle &&
2446 Pred.getSUnit()->getNode()->getOpcode() == ISD::CopyFromReg) {
2447 LLVM_DEBUG(dbgs() << " VReg cycle use: " << *SU << "\n");
2448 return true;
2449 }
2450 }
2451 return false;
2452}
2453
2454// Check for either a dependence (latency) or resource (hazard) stall.
2455//
2456// Note: The ScheduleHazardRecognizer interface requires a non-const SU.
2457static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ) {
2458 if ((int)SPQ->getCurCycle() < Height) return true;
2459 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2461 return true;
2462 return false;
2463}
2464
2465// Return -1 if left has higher priority, 1 if right has higher priority.
2466// Return 0 if latency-based priority is equivalent.
2467static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref,
2468 RegReductionPQBase *SPQ) {
2469 // Scheduling an instruction that uses a VReg whose postincrement has not yet
2470 // been scheduled will induce a copy. Model this as an extra cycle of latency.
2471 int LPenalty = hasVRegCycleUse(left) ? 1 : 0;
2472 int RPenalty = hasVRegCycleUse(right) ? 1 : 0;
2473 int LHeight = (int)left->getHeight() + LPenalty;
2474 int RHeight = (int)right->getHeight() + RPenalty;
2475
2476 bool LStall = (!checkPref || left->SchedulingPref == Sched::ILP) &&
2477 BUHasStall(left, LHeight, SPQ);
2478 bool RStall = (!checkPref || right->SchedulingPref == Sched::ILP) &&
2479 BUHasStall(right, RHeight, SPQ);
2480
2481 // If scheduling one of the node will cause a pipeline stall, delay it.
2482 // If scheduling either one of the node will cause a pipeline stall, sort
2483 // them according to their height.
2484 if (LStall) {
2485 if (!RStall)
2486 return 1;
2487 if (LHeight != RHeight)
2488 return LHeight > RHeight ? 1 : -1;
2489 } else if (RStall)
2490 return -1;
2491
2492 // If either node is scheduling for latency, sort them by height/depth
2493 // and latency.
2494 if (!checkPref || (left->SchedulingPref == Sched::ILP ||
2495 right->SchedulingPref == Sched::ILP)) {
2496 // If neither instruction stalls (!LStall && !RStall) and HazardRecognizer
2497 // is enabled, grouping instructions by cycle, then its height is already
2498 // covered so only its depth matters. We also reach this point if both stall
2499 // but have the same height.
2500 if (!SPQ->getHazardRec()->isEnabled()) {
2501 if (LHeight != RHeight)
2502 return LHeight > RHeight ? 1 : -1;
2503 }
2504 int LDepth = left->getDepth() - LPenalty;
2505 int RDepth = right->getDepth() - RPenalty;
2506 if (LDepth != RDepth) {
2507 LLVM_DEBUG(dbgs() << " Comparing latency of " << *left << " depth "
2508 << LDepth << " vs " << *right << " depth " << RDepth
2509 << "\n");
2510 return LDepth < RDepth ? 1 : -1;
2511 }
2512 if (left->Latency != right->Latency)
2513 return left->Latency > right->Latency ? 1 : -1;
2514 }
2515 return 0;
2516}
2517
2518static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ) {
2519 // Schedule physical register definitions close to their use. This is
2520 // motivated by microarchitectures that can fuse cmp+jump macro-ops. But as
2521 // long as shortening physreg live ranges is generally good, we can defer
2522 // creating a subtarget hook.
2524 bool LHasPhysReg = left->hasPhysRegDefs;
2525 bool RHasPhysReg = right->hasPhysRegDefs;
2526 if (LHasPhysReg != RHasPhysReg) {
2527 #ifndef NDEBUG
2528 static const char *const PhysRegMsg[] = { " has no physreg",
2529 " defines a physreg" };
2530 #endif
2531 LLVM_DEBUG(dbgs() << " " << *left << " " << PhysRegMsg[LHasPhysReg]
2532 << " " << *right << " " << PhysRegMsg[RHasPhysReg]
2533 << "\n");
2534 return LHasPhysReg < RHasPhysReg;
2535 }
2536 }
2537
2538 // Prioritize by Sethi-Ulmann number and push CopyToReg nodes down.
2539 unsigned LPriority = SPQ->getNodePriority(left);
2540 unsigned RPriority = SPQ->getNodePriority(right);
2541
2542 // Be really careful about hoisting call operands above previous calls.
2543 // Only allows it if it would reduce register pressure.
2544 if (left->isCall && right->isCallOp) {
2545 unsigned RNumVals = right->getNode()->getNumValues();
2546 RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2547 }
2548 if (right->isCall && left->isCallOp) {
2549 unsigned LNumVals = left->getNode()->getNumValues();
2550 LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2551 }
2552
2553 if (LPriority != RPriority)
2554 return LPriority > RPriority;
2555
2556 // One or both of the nodes are calls and their sethi-ullman numbers are the
2557 // same, then keep source order.
2558 if (left->isCall || right->isCall) {
2559 unsigned LOrder = SPQ->getNodeOrdering(left);
2560 unsigned ROrder = SPQ->getNodeOrdering(right);
2561
2562 // Prefer an ordering where the lower the non-zero order number, the higher
2563 // the preference.
2564 if ((LOrder || ROrder) && LOrder != ROrder)
2565 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2566 }
2567
2568 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
2569 // e.g.
2570 // t1 = op t2, c1
2571 // t3 = op t4, c2
2572 //
2573 // and the following instructions are both ready.
2574 // t2 = op c3
2575 // t4 = op c4
2576 //
2577 // Then schedule t2 = op first.
2578 // i.e.
2579 // t4 = op c4
2580 // t2 = op c3
2581 // t1 = op t2, c1
2582 // t3 = op t4, c2
2583 //
2584 // This creates more short live intervals.
2585 unsigned LDist = closestSucc(left);
2586 unsigned RDist = closestSucc(right);
2587 if (LDist != RDist)
2588 return LDist < RDist;
2589
2590 // How many registers becomes live when the node is scheduled.
2591 unsigned LScratch = calcMaxScratches(left);
2592 unsigned RScratch = calcMaxScratches(right);
2593 if (LScratch != RScratch)
2594 return LScratch > RScratch;
2595
2596 // Comparing latency against a call makes little sense unless the node
2597 // is register pressure-neutral.
2598 if ((left->isCall && RPriority > 0) || (right->isCall && LPriority > 0))
2599 return (left->NodeQueueId > right->NodeQueueId);
2600
2601 // Do not compare latencies when one or both of the nodes are calls.
2602 if (!DisableSchedCycles &&
2603 !(left->isCall || right->isCall)) {
2604 int result = BUCompareLatency(left, right, false /*checkPref*/, SPQ);
2605 if (result != 0)
2606 return result > 0;
2607 }
2608 else {
2609 if (left->getHeight() != right->getHeight())
2610 return left->getHeight() > right->getHeight();
2611
2612 if (left->getDepth() != right->getDepth())
2613 return left->getDepth() < right->getDepth();
2614 }
2615
2616 assert(left->NodeQueueId && right->NodeQueueId &&
2617 "NodeQueueId cannot be zero");
2618 return (left->NodeQueueId > right->NodeQueueId);
2619}
2620
2621// Bottom up
2622bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2623 if (int res = checkSpecialNodes(left, right))
2624 return res > 0;
2625
2626 return BURRSort(left, right, SPQ);
2627}
2628
2629// Source order, otherwise bottom up.
2630bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2631 if (int res = checkSpecialNodes(left, right))
2632 return res > 0;
2633
2634 unsigned LOrder = SPQ->getNodeOrdering(left);
2635 unsigned ROrder = SPQ->getNodeOrdering(right);
2636
2637 // Prefer an ordering where the lower the non-zero order number, the higher
2638 // the preference.
2639 if ((LOrder || ROrder) && LOrder != ROrder)
2640 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2641
2642 return BURRSort(left, right, SPQ);
2643}
2644
2645// If the time between now and when the instruction will be ready can cover
2646// the spill code, then avoid adding it to the ready queue. This gives long
2647// stalls highest priority and allows hoisting across calls. It should also
2648// speed up processing the available queue.
2649bool hybrid_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2650 static const unsigned ReadyDelay = 3;
2651
2652 if (SPQ->MayReduceRegPressure(SU)) return true;
2653
2654 if (SU->getHeight() > (CurCycle + ReadyDelay)) return false;
2655
2656 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2658 return false;
2659
2660 return true;
2661}
2662
2663// Return true if right should be scheduled with higher priority than left.
2664bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2665 if (int res = checkSpecialNodes(left, right))
2666 return res > 0;
2667
2668 if (left->isCall || right->isCall)
2669 // No way to compute latency of calls.
2670 return BURRSort(left, right, SPQ);
2671
2672 bool LHigh = SPQ->HighRegPressure(left);
2673 bool RHigh = SPQ->HighRegPressure(right);
2674 // Avoid causing spills. If register pressure is high, schedule for
2675 // register pressure reduction.
2676 if (LHigh && !RHigh) {
2677 LLVM_DEBUG(dbgs() << " pressure " << *left << " > " << *right << "\n");
2678 return true;
2679 }
2680 else if (!LHigh && RHigh) {
2681 LLVM_DEBUG(dbgs() << " pressure " << *right << " > " << *left << "\n");
2682 return false;
2683 }
2684 if (!LHigh && !RHigh) {
2685 int result = BUCompareLatency(left, right, true /*checkPref*/, SPQ);
2686 if (result != 0)
2687 return result > 0;
2688 }
2689 return BURRSort(left, right, SPQ);
2690}
2691
2692// Schedule as many instructions in each cycle as possible. So don't make an
2693// instruction available unless it is ready in the current cycle.
2694bool ilp_ls_rr_sort::isReady(SUnit *SU, unsigned CurCycle) const {
2695 if (SU->getHeight() > CurCycle) return false;
2696
2697 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2699 return false;
2700
2701 return true;
2702}
2703
2704static bool canEnableCoalescing(SUnit *SU) {
2705 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
2707 // CopyToReg should be close to its uses to facilitate coalescing and
2708 // avoid spilling.
2709 return true;
2710
2711 if (Opc == TargetOpcode::EXTRACT_SUBREG ||
2712 Opc == TargetOpcode::SUBREG_TO_REG ||
2713 Opc == TargetOpcode::INSERT_SUBREG)
2714 // EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG nodes should be
2715 // close to their uses to facilitate coalescing.
2716 return true;
2717
2718 if (SU->NumPreds == 0 && SU->NumSuccs != 0)
2719 // If SU does not have a register def, schedule it close to its uses
2720 // because it does not lengthen any live ranges.
2721 return true;
2722
2723 return false;
2724}
2725
2726// list-ilp is currently an experimental scheduler that allows various
2727// heuristics to be enabled prior to the normal register reduction logic.
2728bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right) const {
2729 if (int res = checkSpecialNodes(left, right))
2730 return res > 0;
2731
2732 if (left->isCall || right->isCall)
2733 // No way to compute latency of calls.
2734 return BURRSort(left, right, SPQ);
2735
2736 unsigned LLiveUses = 0, RLiveUses = 0;
2737 int LPDiff = 0, RPDiff = 0;
2739 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2740 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2741 }
2742 if (!DisableSchedRegPressure && LPDiff != RPDiff) {
2743 LLVM_DEBUG(dbgs() << "RegPressureDiff " << *left << ": " << LPDiff
2744 << " != " << *right << ": " << RPDiff << "\n");
2745 return LPDiff > RPDiff;
2746 }
2747
2748 if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
2749 bool LReduce = canEnableCoalescing(left);
2750 bool RReduce = canEnableCoalescing(right);
2751 if (LReduce && !RReduce) return false;
2752 if (RReduce && !LReduce) return true;
2753 }
2754
2755 if (!DisableSchedLiveUses && (LLiveUses != RLiveUses)) {
2756 LLVM_DEBUG(dbgs() << "Live uses " << *left << ": " << LLiveUses
2757 << " != " << *right << ": " << RLiveUses << "\n");
2758 return LLiveUses < RLiveUses;
2759 }
2760
2761 if (!DisableSchedStalls) {
2762 bool LStall = BUHasStall(left, left->getHeight(), SPQ);
2763 bool RStall = BUHasStall(right, right->getHeight(), SPQ);
2764 if (LStall != RStall)
2765 return left->getHeight() > right->getHeight();
2766 }
2767
2769 int spread = (int)left->getDepth() - (int)right->getDepth();
2770 if (std::abs(spread) > MaxReorderWindow) {
2771 LLVM_DEBUG(dbgs() << "Depth of " << *left << ": " << left->getDepth()
2772 << " != " << *right << ": " << right->getDepth()
2773 << "\n");
2774 return left->getDepth() < right->getDepth();
2775 }
2776 }
2777
2778 if (!DisableSchedHeight && left->getHeight() != right->getHeight()) {
2779 int spread = (int)left->getHeight() - (int)right->getHeight();
2780 if (std::abs(spread) > MaxReorderWindow)
2781 return left->getHeight() > right->getHeight();
2782 }
2783
2784 return BURRSort(left, right, SPQ);
2785}
2786
2787void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2788 SUnits = &sunits;
2789 CurQueueId = 0;
2790 setCurCycle(0);
2791 // The limits depend on function state that can change between blocks, e.g.
2792 // whether a frame pointer is needed.
2793 if (TracksRegPressure)
2794 for (const TargetRegisterClass &RC : TRI->regclasses())
2795 RegLimit[RC.getID()] = TRI->getRegPressureLimit(&RC, MF);
2796 // Add pseudo dependency edges for two-address nodes.
2797 if (!Disable2AddrHack)
2798 AddPseudoTwoAddrDeps();
2799 // Reroute edges to nodes with multiple uses.
2800 if (!TracksRegPressure && !SrcOrder)
2801 PrescheduleNodesWithMultipleUses();
2802 // Calculate node priorities.
2803 CalculateSethiUllmanNumbers();
2804
2805 // For single block loops, mark nodes that look like canonical IV increments.
2806 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB))
2807 for (SUnit &SU : sunits)
2808 initVRegCycle(&SU);
2809}
2810
2811//===----------------------------------------------------------------------===//
2812// Preschedule for Register Pressure
2813//===----------------------------------------------------------------------===//
2814
2815bool RegReductionPQBase::canClobber(const SUnit *SU, const SUnit *Op) {
2816 if (SU->isTwoAddress) {
2817 unsigned Opc = SU->getNode()->getMachineOpcode();
2818 const MCInstrDesc &MCID = TII->get(Opc);
2819 unsigned NumRes = MCID.getNumDefs();
2820 unsigned NumOps = MCID.getNumOperands() - NumRes;
2821 for (unsigned i = 0; i != NumOps; ++i) {
2822 if (MCID.getOperandConstraint(i+NumRes, MCOI::TIED_TO) != -1) {
2823 SDNode *DU = SU->getNode()->getOperand(i).getNode();
2824 if (DU->getNodeId() != -1 &&
2825 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
2826 return true;
2827 }
2828 }
2829 }
2830 return false;
2831}
2832
2833/// canClobberReachingPhysRegUse - True if SU would clobber one of it's
2834/// successor's explicit physregs whose definition can reach DepSU.
2835/// i.e. DepSU should not be scheduled above SU.
2836static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU,
2837 ScheduleDAGRRList *scheduleDAG,
2838 const TargetInstrInfo *TII,
2839 const TargetRegisterInfo *TRI) {
2840 ArrayRef<MCPhysReg> ImpDefs =
2841 TII->get(SU->getNode()->getMachineOpcode()).implicit_defs();
2842 const uint32_t *RegMask = getNodeRegMask(SU->getNode());
2843 if (ImpDefs.empty() && !RegMask)
2844 return false;
2845
2846 for (const SDep &Succ : SU->Succs) {
2847 SUnit *SuccSU = Succ.getSUnit();
2848 for (const SDep &SuccPred : SuccSU->Preds) {
2849 if (!SuccPred.isAssignedRegDep())
2850 continue;
2851
2852 if (RegMask &&
2853 MachineOperand::clobbersPhysReg(RegMask, SuccPred.getReg()) &&
2854 scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
2855 return true;
2856
2857 for (MCPhysReg ImpDef : ImpDefs) {
2858 // Return true if SU clobbers this physical register use and the
2859 // definition of the register reaches from DepSU. IsReachable queries
2860 // a topological forward sort of the DAG (following the successors).
2861 if (TRI->regsOverlap(ImpDef, SuccPred.getReg()) &&
2862 scheduleDAG->IsReachable(DepSU, SuccPred.getSUnit()))
2863 return true;
2864 }
2865 }
2866 }
2867 return false;
2868}
2869
2870/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
2871/// physical register defs.
2872static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
2873 const TargetInstrInfo *TII,
2874 const TargetRegisterInfo *TRI) {
2875 SDNode *N = SuccSU->getNode();
2876 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
2877 ArrayRef<MCPhysReg> ImpDefs = TII->get(N->getMachineOpcode()).implicit_defs();
2878 assert(!ImpDefs.empty() && "Caller should check hasPhysRegDefs");
2879 for (const SDNode *SUNode = SU->getNode(); SUNode;
2880 SUNode = SUNode->getGluedNode()) {
2881 if (!SUNode->isMachineOpcode())
2882 continue;
2883 ArrayRef<MCPhysReg> SUImpDefs =
2884 TII->get(SUNode->getMachineOpcode()).implicit_defs();
2885 const uint32_t *SURegMask = getNodeRegMask(SUNode);
2886 if (SUImpDefs.empty() && !SURegMask)
2887 continue;
2888 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
2889 MVT VT = N->getSimpleValueType(i);
2890 if (VT == MVT::Glue || VT == MVT::Other)
2891 continue;
2892 if (!N->hasAnyUseOfValue(i))
2893 continue;
2894 MCPhysReg Reg = ImpDefs[i - NumDefs];
2895 if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
2896 return true;
2897 for (MCPhysReg SUReg : SUImpDefs) {
2898 if (TRI->regsOverlap(Reg, SUReg))
2899 return true;
2900 }
2901 }
2902 }
2903 return false;
2904}
2905
2906/// PrescheduleNodesWithMultipleUses - Nodes with multiple uses
2907/// are not handled well by the general register pressure reduction
2908/// heuristics. When presented with code like this:
2909///
2910/// N
2911/// / |
2912/// / |
2913/// U store
2914/// |
2915/// ...
2916///
2917/// the heuristics tend to push the store up, but since the
2918/// operand of the store has another use (U), this would increase
2919/// the length of that other use (the U->N edge).
2920///
2921/// This function transforms code like the above to route U's
2922/// dependence through the store when possible, like this:
2923///
2924/// N
2925/// ||
2926/// ||
2927/// store
2928/// |
2929/// U
2930/// |
2931/// ...
2932///
2933/// This results in the store being scheduled immediately
2934/// after N, which shortens the U->N live range, reducing
2935/// register pressure.
2936void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
2937 // Visit all the nodes in topological order, working top-down.
2938 for (SUnit &SU : *SUnits) {
2939 // For now, only look at nodes with no data successors, such as stores.
2940 // These are especially important, due to the heuristics in
2941 // getNodePriority for nodes with no data successors.
2942 if (SU.NumSuccs != 0)
2943 continue;
2944 // For now, only look at nodes with exactly one data predecessor.
2945 if (SU.NumPreds != 1)
2946 continue;
2947 // Avoid prescheduling copies to virtual registers, which don't behave
2948 // like other nodes from the perspective of scheduling heuristics.
2949 if (SDNode *N = SU.getNode())
2950 if (N->getOpcode() == ISD::CopyToReg &&
2951 cast<RegisterSDNode>(N->getOperand(1))->getReg().isVirtual())
2952 continue;
2953
2954 SDNode *PredFrameSetup = nullptr;
2955 for (const SDep &Pred : SU.Preds)
2956 if (Pred.isCtrl() && Pred.getSUnit()) {
2957 // Find the predecessor which is not data dependence.
2958 SDNode *PredND = Pred.getSUnit()->getNode();
2959
2960 // If PredND is FrameSetup, we should not pre-scheduled the node,
2961 // or else, when bottom up scheduling, ADJCALLSTACKDOWN and
2962 // ADJCALLSTACKUP may hold CallResource too long and make other
2963 // calls can't be scheduled. If there's no other available node
2964 // to schedule, the schedular will try to rename the register by
2965 // creating copy to avoid the conflict which will fail because
2966 // CallResource is not a real physical register.
2967 if (PredND && PredND->isMachineOpcode() &&
2968 (PredND->getMachineOpcode() == TII->getCallFrameSetupOpcode())) {
2969 PredFrameSetup = PredND;
2970 break;
2971 }
2972 }
2973 // Skip the node has FrameSetup parent.
2974 if (PredFrameSetup != nullptr)
2975 continue;
2976
2977 // Locate the single data predecessor.
2978 SUnit *PredSU = nullptr;
2979 for (const SDep &Pred : SU.Preds)
2980 if (!Pred.isCtrl()) {
2981 PredSU = Pred.getSUnit();
2982 break;
2983 }
2984 assert(PredSU);
2985
2986 // Don't rewrite edges that carry physregs, because that requires additional
2987 // support infrastructure.
2988 if (PredSU->hasPhysRegDefs)
2989 continue;
2990 // Short-circuit the case where SU is PredSU's only data successor.
2991 if (PredSU->NumSuccs == 1)
2992 continue;
2993 // Avoid prescheduling to copies from virtual registers, which don't behave
2994 // like other nodes from the perspective of scheduling heuristics.
2995 if (SDNode *N = SU.getNode())
2996 if (N->getOpcode() == ISD::CopyFromReg &&
2997 cast<RegisterSDNode>(N->getOperand(1))->getReg().isVirtual())
2998 continue;
2999
3000 // Perform checks on the successors of PredSU.
3001 for (const SDep &PredSucc : PredSU->Succs) {
3002 SUnit *PredSuccSU = PredSucc.getSUnit();
3003 if (PredSuccSU == &SU) continue;
3004 // If PredSU has another successor with no data successors, for
3005 // now don't attempt to choose either over the other.
3006 if (PredSuccSU->NumSuccs == 0)
3007 goto outer_loop_continue;
3008 // Don't break physical register dependencies.
3009 if (SU.hasPhysRegClobbers && PredSuccSU->hasPhysRegDefs)
3010 if (canClobberPhysRegDefs(PredSuccSU, &SU, TII, TRI))
3011 goto outer_loop_continue;
3012 // Don't introduce graph cycles.
3013 if (scheduleDAG->IsReachable(&SU, PredSuccSU))
3014 goto outer_loop_continue;
3015 }
3016
3017 // Ok, the transformation is safe and the heuristics suggest it is
3018 // profitable. Update the graph.
3019 LLVM_DEBUG(
3020 dbgs() << " Prescheduling " << SU << " next to PredSU " << *PredSU
3021 << " to guide scheduling in the presence of multiple uses\n");
3022 for (unsigned i = 0; i != PredSU->Succs.size(); ++i) {
3023 SDep Edge = PredSU->Succs[i];
3024 assert(!Edge.isAssignedRegDep());
3025 SUnit *SuccSU = Edge.getSUnit();
3026 if (SuccSU != &SU) {
3027 Edge.setSUnit(PredSU);
3028 scheduleDAG->RemovePred(SuccSU, Edge);
3029 scheduleDAG->AddPredQueued(&SU, Edge);
3030 Edge.setSUnit(&SU);
3031 scheduleDAG->AddPredQueued(SuccSU, Edge);
3032 --i;
3033 }
3034 }
3035 outer_loop_continue:;
3036 }
3037}
3038
3039/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
3040/// it as a def&use operand. Add a pseudo control edge from it to the other
3041/// node (if it won't create a cycle) so the two-address one will be scheduled
3042/// first (lower in the schedule). If both nodes are two-address, favor the
3043/// one that has a CopyToReg use (more likely to be a loop induction update).
3044/// If both are two-address, but one is commutable while the other is not
3045/// commutable, favor the one that's not commutable.
3046void RegReductionPQBase::AddPseudoTwoAddrDeps() {
3047 for (SUnit &SU : *SUnits) {
3048 if (!SU.isTwoAddress)
3049 continue;
3050
3051 SDNode *Node = SU.getNode();
3052 if (!Node || !Node->isMachineOpcode() || SU.getNode()->getGluedNode())
3053 continue;
3054
3055 bool isLiveOut = hasOnlyLiveOutUses(&SU);
3056 unsigned Opc = Node->getMachineOpcode();
3057 const MCInstrDesc &MCID = TII->get(Opc);
3058 unsigned NumRes = MCID.getNumDefs();
3059 unsigned NumOps = MCID.getNumOperands() - NumRes;
3060 for (unsigned j = 0; j != NumOps; ++j) {
3061 if (MCID.getOperandConstraint(j+NumRes, MCOI::TIED_TO) == -1)
3062 continue;
3063 SDNode *DU = SU.getNode()->getOperand(j).getNode();
3064 if (DU->getNodeId() == -1)
3065 continue;
3066 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
3067 if (!DUSU)
3068 continue;
3069 for (const SDep &Succ : DUSU->Succs) {
3070 if (Succ.isCtrl())
3071 continue;
3072 SUnit *SuccSU = Succ.getSUnit();
3073 if (SuccSU == &SU)
3074 continue;
3075 // Be conservative. Ignore if nodes aren't at roughly the same
3076 // depth and height.
3077 if (SuccSU->getHeight() < SU.getHeight() &&
3078 (SU.getHeight() - SuccSU->getHeight()) > 1)
3079 continue;
3080 // Skip past COPY_TO_REGCLASS nodes, so that the pseudo edge
3081 // constrains whatever is using the copy, instead of the copy
3082 // itself. In the case that the copy is coalesced, this
3083 // preserves the intent of the pseudo two-address heurietics.
3084 while (SuccSU->Succs.size() == 1 &&
3085 SuccSU->getNode()->isMachineOpcode() &&
3086 SuccSU->getNode()->getMachineOpcode() ==
3087 TargetOpcode::COPY_TO_REGCLASS)
3088 SuccSU = SuccSU->Succs.front().getSUnit();
3089 // Don't constrain non-instruction nodes.
3090 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
3091 continue;
3092 // Don't constrain nodes with physical register defs if the
3093 // predecessor can clobber them.
3094 if (SuccSU->hasPhysRegDefs && SU.hasPhysRegClobbers) {
3095 if (canClobberPhysRegDefs(SuccSU, &SU, TII, TRI))
3096 continue;
3097 }
3098 // Don't constrain EXTRACT_SUBREG, INSERT_SUBREG, and SUBREG_TO_REG;
3099 // these may be coalesced away. We want them close to their uses.
3100 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
3101 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
3102 SuccOpc == TargetOpcode::INSERT_SUBREG ||
3103 SuccOpc == TargetOpcode::SUBREG_TO_REG)
3104 continue;
3105 if (!canClobberReachingPhysRegUse(SuccSU, &SU, scheduleDAG, TII, TRI) &&
3106 (!canClobber(SuccSU, DUSU) ||
3107 (isLiveOut && !hasOnlyLiveOutUses(SuccSU)) ||
3108 (!SU.isCommutable && SuccSU->isCommutable)) &&
3109 !scheduleDAG->IsReachable(SuccSU, &SU)) {
3110 LLVM_DEBUG(dbgs() << " Adding a pseudo-two-addr edge from " << SU
3111 << " to " << *SuccSU << "\n");
3112 scheduleDAG->AddPredQueued(&SU, SDep(SuccSU, SDep::Artificial));
3113 }
3114 }
3115 }
3116 }
3117}
3118
3119//===----------------------------------------------------------------------===//
3120// Public Constructor Functions
3121//===----------------------------------------------------------------------===//
3122
3124 CodeGenOptLevel OptLevel) {
3125 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
3126 const TargetInstrInfo *TII = STI.getInstrInfo();
3127 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
3128
3129 BURegReductionPriorityQueue *PQ =
3130 new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, nullptr);
3131 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
3132 PQ->setScheduleDAG(SD);
3133 return SD;
3134}
3135
3138 CodeGenOptLevel OptLevel) {
3139 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
3140 const TargetInstrInfo *TII = STI.getInstrInfo();
3141 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
3142
3143 SrcRegReductionPriorityQueue *PQ =
3144 new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, nullptr);
3145 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, false, PQ, OptLevel);
3146 PQ->setScheduleDAG(SD);
3147 return SD;
3148}
3149
3152 CodeGenOptLevel OptLevel) {
3153 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
3154 const TargetInstrInfo *TII = STI.getInstrInfo();
3155 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
3156 const TargetLowering *TLI = IS->TLI;
3157
3158 HybridBURRPriorityQueue *PQ =
3159 new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
3160
3161 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
3162 PQ->setScheduleDAG(SD);
3163 return SD;
3164}
3165
3167 CodeGenOptLevel OptLevel) {
3168 const TargetSubtargetInfo &STI = IS->MF->getSubtarget();
3169 const TargetInstrInfo *TII = STI.getInstrInfo();
3170 const TargetRegisterInfo *TRI = STI.getRegisterInfo();
3171 const TargetLowering *TLI = IS->TLI;
3172
3173 ILPBURRPriorityQueue *PQ =
3174 new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
3175 ScheduleDAGRRList *SD = new ScheduleDAGRRList(*IS->MF, true, PQ, OptLevel);
3176 PQ->setScheduleDAG(SD);
3177 return SD;
3178}
return SDValue()
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
This file defines the DenseMap class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
SI Lower i1 Copies
static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg)
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
static bool CheckForLiveRegDef(SUnit *SU, MCRegister Reg, std::vector< SUnit * > &LiveRegDefs, SmallSet< unsigned, 4 > &RegAdded, SmallVectorImpl< unsigned > &LRegs, const TargetRegisterInfo *TRI, const SDNode *Node=nullptr)
CheckForLiveRegDef - Return true and update live register vector if the specified register def of the...
static bool canEnableCoalescing(SUnit *SU)
static RegisterScheduler sourceListDAGScheduler("source", "Similar to list-burr but schedules in source " "order when possible", createSourceListDAGScheduler)
static cl::opt< bool > DisableSchedCycles("disable-sched-cycles", cl::Hidden, cl::init(false), cl::desc("Disable cycle-level precision during preRA scheduling"))
static cl::opt< bool > DisableSchedStalls("disable-sched-stalls", cl::Hidden, cl::init(true), cl::desc("Disable no-stall priority in sched=list-ilp"))
static bool hasOnlyLiveInOpers(const SUnit *SU)
hasOnlyLiveInOpers - Return true if SU has only value predecessors that are CopyFromReg from a virtua...
static bool IsChainDependent(SDNode *Outer, SDNode *Inner, unsigned NestLevel, const TargetInstrInfo *TII)
IsChainDependent - Test if Outer is reachable from Inner through chain dependencies.
static bool hasOnlyLiveOutUses(const SUnit *SU)
hasOnlyLiveOutUses - Return true if SU has only value successors that are CopyToReg to a virtual regi...
static cl::opt< bool > DisableSchedCriticalPath("disable-sched-critical-path", cl::Hidden, cl::init(false), cl::desc("Disable critical path priority in sched=list-ilp"))
static cl::opt< bool > Disable2AddrHack("disable-2addr-hack", cl::Hidden, cl::init(true), cl::desc("Disable scheduler's two-address hack"))
static RegisterScheduler ILPListDAGScheduler("list-ilp", "Bottom-up register pressure aware list scheduling " "which tries to balance ILP and register pressure", createILPListDAGScheduler)
static void resetVRegCycle(SUnit *SU)
static RegisterScheduler hybridListDAGScheduler("list-hybrid", "Bottom-up register pressure aware list scheduling " "which tries to balance latency and register pressure", createHybridListDAGScheduler)
static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU, ScheduleDAGRRList *scheduleDAG, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
canClobberReachingPhysRegUse - True if SU would clobber one of it's successor's explicit physregs who...
static cl::opt< bool > DisableSchedPhysRegJoin("disable-sched-physreg-join", cl::Hidden, cl::init(false), cl::desc("Disable physreg def-use affinity"))
static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
canClobberPhysRegDefs - True if SU would clobber one of SuccSU's physical register defs.
static cl::opt< unsigned > AvgIPC("sched-avg-ipc", cl::Hidden, cl::init(1), cl::desc("Average inst/cycle when no target itinerary exists."))
static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos, const TargetLowering *TLI, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, unsigned &RegClass, unsigned &Cost, const MachineFunction &MF)
GetCostForDef - Looks up the register class and cost for a given definition.
static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ)
static cl::opt< bool > DisableSchedRegPressure("disable-sched-reg-pressure", cl::Hidden, cl::init(false), cl::desc("Disable regpressure priority in sched=list-ilp"))
static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ)
static void initVRegCycle(SUnit *SU)
static constexpr unsigned RegSequenceCost
static cl::opt< int > MaxReorderWindow("max-sched-reorder", cl::Hidden, cl::init(6), cl::desc("Number of instructions to allow ahead of the critical path " "in sched=list-ilp"))
static SDNode * FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest, const TargetInstrInfo *TII)
FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate the corresponding (lowered) C...
static bool isOperandOf(const SUnit *SU, SDNode *N)
static cl::opt< bool > DisableSchedVRegCycle("disable-sched-vrcycle", cl::Hidden, cl::init(false), cl::desc("Disable virtual register cycle interference checks"))
static int checkSpecialNodes(const SUnit *left, const SUnit *right)
static cl::opt< bool > DisableSchedLiveUses("disable-sched-live-uses", cl::Hidden, cl::init(true), cl::desc("Disable live use priority in sched=list-ilp"))
static const uint32_t * getNodeRegMask(const SDNode *N)
getNodeRegMask - Returns the register mask attached to an SDNode, if any.
static unsigned closestSucc(const SUnit *SU)
closestSucc - Returns the scheduled cycle of the successor which is closest to the current cycle.
static bool hasVRegCycleUse(const SUnit *SU)
static cl::opt< bool > DisableSchedHeight("disable-sched-height", cl::Hidden, cl::init(false), cl::desc("Disable scheduled-height priority in sched=list-ilp"))
static RegisterScheduler burrListDAGScheduler("list-burr", "Bottom-up register reduction list scheduling", createBURRListDAGScheduler)
static unsigned calcMaxScratches(const SUnit *SU)
calcMaxScratches - Returns an cost estimate of the worse case requirement for scratch registers,...
static unsigned CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector< unsigned > &SUNumbers)
CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref, RegReductionPQBase *SPQ)
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the SparseSet class derived from the version described in Briggs,...
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
#define LLVM_DEBUG(...)
Definition Debug.h:119
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
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
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.
ArrayRef< MCOperandInfo > operands() const
bool hasOptionalDef() const
Set if this instruction has an optional definition, e.g.
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
int getOperandConstraint(unsigned OpNum, MCOI::OperandConstraint Constraint) const
Returns the value of the specified operand constraint if it is present.
ArrayRef< MCPhysReg > implicit_defs() const
Return a list of registers that are potentially written by any instance of this machine instruction.
bool isCommutable() const
Return true if this may be a 2- or 3-address instruction (of the form "X = op Y, Z,...
unsigned getID() const
getID() - Return the register class ID number.
Machine Value Type.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
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.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
unsigned getIROrder() const
Return the node ordering.
void setNodeId(int Id)
Set unique node id.
MVT getSimpleValueType(unsigned ResNo) const
Return the type of a specified result as a simple type.
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.
const SDValue & getOperand(unsigned Num) const
uint64_t getConstantOperandVal(unsigned Num) const
Helper method returns the integer value of a ConstantSDNode operand.
LLVM_ABI bool hasAnyUseOfValue(unsigned Value) const
Return true if there are any use of the indicated value.
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
Scheduling dependency.
Definition ScheduleDAG.h:54
SUnit * getSUnit() const
@ Data
Regular data dependence (aka true-dependence).
Definition ScheduleDAG.h:58
@ Artificial
Arbitrary strong DAG edge (no real dependence).
Definition ScheduleDAG.h:77
unsigned getLatency() const
Returns the latency value for this edge, which roughly means the minimum number of cycles that must e...
bool isAssignedRegDep() const
Tests if this is a Data dependence that is associated with a register.
bool isArtificial() const
Tests if this is an Order dependence that is marked as "artificial", meaning it isn't necessary for c...
bool isCtrl() const
Shorthand for getKind() != SDep::Data.
void setSUnit(SUnit *SU)
Register getReg() const
Returns the register associated with this edge.
Scheduling unit. This is a node in the scheduling DAG.
bool isCall
Is a function call.
LLVM_ABI void setHeightToAtLeast(unsigned NewHeight)
If NewHeight is greater than this node's height value, set it to be the new height value.
unsigned NumSuccs
unsigned NumPreds
unsigned NodeQueueId
Queue id of node.
unsigned NodeNum
Entry # of node in the node vector.
unsigned NumSuccsLeft
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 getHeight() const
Returns the height of this node, which is the length of the maximum path down to any node which has n...
LLVM_ABI void setHeightDirty()
Sets a flag in this node to indicate that its stored Height value will require recomputation the next...
bool isSucc(const SUnit *N) const
Tests if node N is a successor of this node.
LLVM_ABI void removePred(const SDep &D)
Removes the specified edge as a pred of the current node if it exists.
unsigned short Latency
Node latency.
unsigned short NumRegDefsLeft
bool isPending
True once pending.
unsigned getDepth() const
Returns the depth of this node, which is the length of the maximum path up to any node which has no p...
bool isScheduled
True once scheduled.
bool isAvailable
True once available.
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.
const TargetRegisterClass * CopySrcRC
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.
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.
ScheduleDAGSDNodes - A ScheduleDAG for scheduling SDNode-based DAGs.
void MarkDirty()
Mark the ordering as temporarily broken, after a new node has been added.
virtual void dumpNode(const SUnit &SU) const =0
HazardRecognizer - This determines whether or not an instruction can be issued this cycle,...
virtual void RecedeCycle()
RecedeCycle - This callback is invoked whenever the next bottom-up instruction to be scheduled cannot...
virtual void Reset()
Reset - This callback is invoked when a new block of instructions is about to be schedule.
virtual void EmitInstruction(SUnit *)
EmitInstruction - This callback is invoked when an instruction is emitted, to advance the hazard stat...
virtual bool atIssueLimit() const
atIssueLimit - Return true if no more instructions may be issued in this cycle.
virtual HazardType getHazardType(SUnit *, int Stalls=0)
getHazardType - Return the hazard type of emitting this node.
This interface is used to plug different priorities computation algorithms into the list scheduler.
void setCurCycle(unsigned Cycle)
virtual void remove(SUnit *SU)=0
virtual void releaseState()=0
virtual SUnit * pop()=0
virtual void scheduledNode(SUnit *)
As each node is scheduled, this method is invoked.
virtual bool tracksRegPressure() const
virtual void dump(ScheduleDAG *) const
virtual void initNodes(std::vector< SUnit > &SUnits)=0
virtual bool empty() const =0
virtual void unscheduledNode(SUnit *)
virtual void addNode(const SUnit *SU)=0
virtual void updateNode(const SUnit *SU)=0
virtual void push(SUnit *U)=0
SelectionDAGISel - This is the common base class used for SelectionDAG-based pattern-matching instruc...
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
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
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.
virtual uint8_t getRepRegClassCostFor(MVT VT) const
Return the cost of the 'representative' register class for the specified value type.
virtual const TargetRegisterClass * getRepRegClassFor(MVT VT) const
Return the 'representative' register class for the specified value type.
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...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition ISDOpcodes.h:50
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:226
@ LIFETIME_START
This corresponds to the llvm.lifetime.
@ INLINEASM_BR
INLINEASM_BR - Branching version of inline asm. Used by asm-goto.
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ INLINEASM
INLINEASM - Represents an inline asm block.
initializer< Ty > init(const Ty &Val)
constexpr double e
Sequence
A sequence of states that a pointer may go through in which an objc_retain and objc_release are actua...
Definition PtrState.h:41
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
bool empty() const
Definition BasicBlock.h:101
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1775
LLVM_ABI ScheduleDAGSDNodes * createBURRListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createBURRListDAGScheduler - This creates a bottom up register usage reduction list scheduler.
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
LLVM_ABI ScheduleDAGSDNodes * createHybridListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel)
createHybridListDAGScheduler - This creates a bottom up register pressure aware list scheduler that m...
Op::Description Desc
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
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI ScheduleDAGSDNodes * createSourceListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createSourceListDAGScheduler - This creates a bottom up list scheduler that schedules nodes in source...
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
LLVM_ABI ScheduleDAGSDNodes * createILPListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel)
createILPListDAGScheduler - This creates a bottom up register pressure aware list scheduler that trie...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N