LLVM 24.0.0git
MachinePipeliner.h
Go to the documentation of this file.
1//===- MachinePipeliner.h - Machine Software Pipeliner Pass -------------===//
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// An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
10//
11// Software pipelining (SWP) is an instruction scheduling technique for loops
12// that overlap loop iterations and exploits ILP via a compiler transformation.
13//
14// Swing Modulo Scheduling is an implementation of software pipelining
15// that generates schedules that are near optimal in terms of initiation
16// interval, register requirements, and stage count. See the papers:
17//
18// "Swing Modulo Scheduling: A Lifetime-Sensitive Approach", by J. Llosa,
19// A. Gonzalez, E. Ayguade, and M. Valero. In PACT '96 Proceedings of the 1996
20// Conference on Parallel Architectures and Compilation Techiniques.
21//
22// "Lifetime-Sensitive Modulo Scheduling in a Production Environment", by J.
23// Llosa, E. Ayguade, A. Gonzalez, M. Valero, and J. Eckhardt. In IEEE
24// Transactions on Computers, Vol. 50, No. 3, 2001.
25//
26// "An Implementation of Swing Modulo Scheduling With Extensions for
27// Superblocks", by T. Lattner, Master's Thesis, University of Illinois at
28// Urbana-Champaign, 2005.
29//
30//
31// The SMS algorithm consists of three main steps after computing the minimal
32// initiation interval (MII).
33// 1) Analyze the dependence graph and compute information about each
34// instruction in the graph.
35// 2) Order the nodes (instructions) by priority based upon the heuristics
36// described in the algorithm.
37// 3) Attempt to schedule the nodes in the specified order using the MII.
38//
39//===----------------------------------------------------------------------===//
40#ifndef LLVM_CODEGEN_MACHINEPIPELINER_H
41#define LLVM_CODEGEN_MACHINEPIPELINER_H
42
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/SetVector.h"
55
56#include <deque>
57
58namespace llvm {
59
60class LiveIntervals;
61class NodeSet;
62class SMSchedule;
63
64/// Return true if BaseMI and OtherMI may access overlapping memory in a later
65/// iteration of the loop LoopBB. Returns true conservatively whenever overlap
66/// cannot be ruled out.
68 const MachineInstr *OtherMI,
69 const MachineBasicBlock *LoopBB,
71 const TargetInstrInfo &TII);
72
73/// Software pipelining policy for a loop, which a target can customize by
74/// implementing TargetSubtargetInfo::overridePipelinerPolicy.
76 /// Limit the register pressure of the scheduled loop, retrying at a higher
77 /// II when a schedule needs too many registers.
79};
80
82public:
83 static char ID;
84
86
87 bool runOnMachineFunction(MachineFunction &MF) override;
88
89 void getAnalysisUsage(AnalysisUsage &AU) const override;
90};
91
93 : public OptionalPassInfoMixin<MachinePipelinerPass> {
94public:
97};
98
99/// Represents a dependence between two instruction.
101 SUnit *Dst = nullptr;
102 SDep Pred;
103 unsigned Distance = 0;
104 bool IsValidationOnly = false;
105
106public:
107 /// Creates an edge corresponding to an edge represented by \p PredOrSucc and
108 /// \p Dep in the original DAG. This pair has no information about the
109 /// direction of the edge, so we need to pass an additional argument \p
110 /// IsSucc.
111 SwingSchedulerDDGEdge(SUnit *PredOrSucc, const SDep &Dep, bool IsSucc,
112 bool IsValidationOnly)
113 : Dst(PredOrSucc), Pred(Dep), Distance(0u),
114 IsValidationOnly(IsValidationOnly) {
115 SUnit *Src = Dep.getSUnit();
116
117 if (IsSucc) {
118 std::swap(Src, Dst);
119 Pred.setSUnit(Src);
120 }
121
122 // An anti-dependence to PHI means loop-carried dependence.
123 if (Pred.getKind() == SDep::Anti && Src->getInstr()->isPHI()) {
124 Distance = 1;
125 std::swap(Src, Dst);
126 auto Reg = Pred.getReg();
127 Pred = SDep(Src, SDep::Kind::Data, Reg);
128 }
129 }
130
131 /// Returns the SUnit from which the edge comes (source node).
132 SUnit *getSrc() const { return Pred.getSUnit(); }
133
134 /// Returns the SUnit to which the edge points (destination node).
135 SUnit *getDst() const { return Dst; }
136
137 /// Returns the latency value for the edge.
138 unsigned getLatency() const { return Pred.getLatency(); }
139
140 /// Sets the latency for the edge.
141 void setLatency(unsigned Latency) { Pred.setLatency(Latency); }
142
143 /// Returns the distance value for the edge.
144 unsigned getDistance() const { return Distance; }
145
146 /// Sets the distance value for the edge.
147 void setDistance(unsigned D) { Distance = D; }
148
149 /// Returns the register associated with the edge.
150 Register getReg() const { return Pred.getReg(); }
151
152 /// Returns true if the edge represents anti dependence.
153 bool isAntiDep() const { return Pred.getKind() == SDep::Kind::Anti; }
154
155 /// Returns true if the edge represents output dependence.
156 bool isOutputDep() const { return Pred.getKind() == SDep::Kind::Output; }
157
158 /// Returns true if the edge represents a dependence that is not data, anti or
159 /// output dependence.
160 bool isOrderDep() const { return Pred.getKind() == SDep::Kind::Order; }
161
162 /// Returns true if the edge represents unknown scheduling barrier.
163 bool isBarrier() const { return Pred.isBarrier(); }
164
165 /// Returns true if the edge represents an artificial dependence.
166 bool isArtificial() const { return Pred.isArtificial(); }
167
168 /// Tests if this is a Data dependence that is associated with a register.
169 bool isAssignedRegDep() const { return Pred.isAssignedRegDep(); }
170
171 /// Returns true for DDG nodes that we ignore when computing the cost
172 /// functions. We ignore the back-edge recurrence in order to avoid unbounded
173 /// recursion in the calculation of the ASAP, ALAP, etc functions.
174 LLVM_ABI bool ignoreDependence(bool IgnoreAnti) const;
175
176 /// Returns true if this edge is intended to be used only for validating the
177 /// schedule.
178 bool isValidationOnly() const { return IsValidationOnly; }
179};
180
181/// Represents loop-carried dependencies. Because SwingSchedulerDAG doesn't
182/// assume cycle dependencies as the name suggests, such dependencies must be
183/// handled separately. After DAG construction is finished, these dependencies
184/// are added to SwingSchedulerDDG.
185/// TODO: Also handle output-dependencies introduced by physical registers.
189
191
193 auto Ite = OrderDeps.find(Key);
194 if (Ite == OrderDeps.end())
195 return nullptr;
196 return &Ite->second;
197 }
198
199 /// Adds some edges to the original DAG that correspond to loop-carried
200 /// dependencies. Historically, loop-carried edges are represented by using
201 /// non-loop-carried edges in the original DAG. This function appends such
202 /// edges to preserve the previous behavior.
203 LLVM_ABI void modifySUnits(std::vector<SUnit> &SUnits,
204 const TargetInstrInfo *TII);
205
206#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
207 LLVM_ABI void dump(SUnit *SU, const TargetRegisterInfo *TRI,
208 const MachineRegisterInfo *MRI) const;
209#endif
210};
211
212/// This class provides APIs to retrieve edges from/to an SUnit node, with a
213/// particular focus on loop-carried dependencies. Since SUnit is not designed
214/// to represent such edges, handling them directly using its APIs has required
215/// non-trivial logic in the past. This class serves as a wrapper around SUnit,
216/// offering a simpler interface for managing these dependencies.
219
220 struct SwingSchedulerDDGEdges {
221 EdgesType Preds;
222 EdgesType Succs;
223
224 /// This field is a subset of ValidationOnlyEdges. These edges are used only
225 /// by specific heuristics, mainly for cycle detection. Although they are
226 /// unnecessary in theory (i.e., ignoring them should still yield a valid
227 /// schedule), they are retained to preserve the existing behavior. Since we
228 /// only need which extra edges exist from a given SUnit, we only store the
229 /// destination SUnits.
230 SmallVector<SUnit *, 4> ExtraSuccs;
231 };
232
233 void initEdges(SUnit *SU);
234
235 SUnit *EntrySU;
236 SUnit *ExitSU;
237
238 std::vector<SwingSchedulerDDGEdges> EdgesVec;
239 SwingSchedulerDDGEdges EntrySUEdges;
240 SwingSchedulerDDGEdges ExitSUEdges;
241
242 /// Edges that are used only when validating the schedule. These edges are
243 /// not considered to drive the optimization heuristics.
244 SmallVector<SwingSchedulerDDGEdge, 8> ValidationOnlyEdges;
245
246 /// Adds a NON-validation-only edge to the DDG. Assumes to be called only by
247 /// the ctor.
248 void addEdge(const SUnit *SU, const SwingSchedulerDDGEdge &Edge);
249
250 SwingSchedulerDDGEdges &getEdges(const SUnit *SU);
251 const SwingSchedulerDDGEdges &getEdges(const SUnit *SU) const;
252
253public:
254 LLVM_ABI SwingSchedulerDDG(std::vector<SUnit> &SUnits, SUnit *EntrySU,
255 SUnit *ExitSU, const LoopCarriedEdges &LCE);
256
257 LLVM_ABI const EdgesType &getInEdges(const SUnit *SU) const;
258
259 LLVM_ABI const EdgesType &getOutEdges(const SUnit *SU) const;
260
262
263 LLVM_ABI bool isValidSchedule(const SMSchedule &Schedule) const;
264};
265
266/// This class builds the dependence graph for the instructions in a loop,
267/// and attempts to schedule the instructions using the SMS algorithm.
270
271 std::unique_ptr<SwingSchedulerDDG> DDG;
272
273 /// The minimum initiation interval between iterations for this schedule.
274 unsigned MII = 0;
275 /// The maximum initiation interval between iterations for this schedule.
276 unsigned MAX_II = 0;
277 /// Set to true if a valid pipelined schedule is found for the loop.
278 bool Scheduled = false;
279 MachineLoop &Loop;
280 LiveIntervals &LIS;
281 const RegisterClassInfo &RegClassInfo;
282 unsigned II_setByPragma = 0;
283 TargetInstrInfo::PipelinerLoopInfo *LoopPipelinerInfo = nullptr;
284
285 /// Policy for this loop, after target and command line overrides.
287
288 /// A topological ordering of the SUnits, which is needed for changing
289 /// dependences and iterating over the SUnits.
291
292 struct NodeInfo {
293 int ASAP = 0;
294 int ALAP = 0;
295 int ZeroLatencyDepth = 0;
296 int ZeroLatencyHeight = 0;
297
298 NodeInfo() = default;
299 };
300 /// Computed properties for each node in the graph.
301 std::vector<NodeInfo> ScheduleInfo;
302
303 enum OrderKind { BottomUp = 0, TopDown = 1 };
304 /// Computed node ordering for scheduling.
305 SetVector<SUnit *> NodeOrder;
306
307 using NodeSetType = SmallVector<NodeSet, 8>;
308 using ValueMapTy = DenseMap<unsigned, unsigned>;
309 using MBBVectorTy = SmallVectorImpl<MachineBasicBlock *>;
311
312 /// Instructions to change when emitting the final schedule.
314
315 /// We may create a new instruction, so remember it because it
316 /// must be deleted when the pass is finished.
318
319 /// Ordered list of DAG postprocessing steps.
320 std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
321
322 /// Used to compute single-iteration dependencies (i.e., buildSchedGraph).
323 AliasAnalysis *AA;
324
325 /// Used to compute loop-carried dependencies (i.e.,
326 /// addLoopCarriedDependences).
327 BatchAAResults BAA;
328
329 MachineDominatorTree *MDT = nullptr;
330
331 /// Helper class to implement Johnson's circuit finding algorithm.
332 class Circuits {
333 std::vector<SUnit> &SUnits;
334 SetVector<SUnit *> Stack;
335 BitVector Blocked;
338 // Node to Index from ScheduleDAGTopologicalSort
339 std::vector<int> *Node2Idx;
340 unsigned NumPaths = 0u;
341 static unsigned MaxPaths;
342
343 public:
344 Circuits(std::vector<SUnit> &SUs, ScheduleDAGTopologicalSort &Topo)
345 : SUnits(SUs), Blocked(SUs.size()), B(SUs.size()), AdjK(SUs.size()) {
346 Node2Idx = new std::vector<int>(SUs.size());
347 unsigned Idx = 0;
348 for (const auto &NodeNum : Topo)
349 Node2Idx->at(NodeNum) = Idx++;
350 }
351 Circuits &operator=(const Circuits &other) = delete;
352 Circuits(const Circuits &other) = delete;
353 ~Circuits() { delete Node2Idx; }
354
355 /// Reset the data structures used in the circuit algorithm.
356 void reset() {
357 Stack.clear();
358 Blocked.reset();
359 B.assign(SUnits.size(), SmallPtrSet<SUnit *, 4>());
360 NumPaths = 0;
361 }
362
363 LLVM_ABI void createAdjacencyStructure(SwingSchedulerDDG *DDG);
364 LLVM_ABI bool circuit(int V, int S, NodeSetType &NodeSets,
365 const SwingSchedulerDAG *DAG,
366 bool HasBackedge = false);
367 LLVM_ABI void unblock(int U);
368 };
369
370 struct LLVM_ABI CopyToPhiMutation : public ScheduleDAGMutation {
371 void apply(ScheduleDAGInstrs *DAG) override;
372 };
373
374public:
377 LiveIntervals &lis, const RegisterClassInfo &rci,
379 AliasAnalysis *AA, MachineDominatorTree *MDT = nullptr);
380
381 void schedule() override;
382 void finishBlock() override;
383
384 /// Return true if the loop kernel has been scheduled.
385 bool hasNewSchedule() { return Scheduled; }
386
387 /// Return the earliest time an instruction may be scheduled.
388 int getASAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ASAP; }
389
390 /// Return the latest time an instruction my be scheduled.
391 int getALAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ALAP; }
392
393 /// The mobility function, which the number of slots in which
394 /// an instruction may be scheduled.
395 int getMOV(SUnit *Node) { return getALAP(Node) - getASAP(Node); }
396
397 /// The depth, in the dependence graph, for a node.
398 unsigned getDepth(SUnit *Node) { return Node->getDepth(); }
399
400 /// The maximum unweighted length of a path from an arbitrary node to the
401 /// given node in which each edge has latency 0
403 return ScheduleInfo[Node->NodeNum].ZeroLatencyDepth;
404 }
405
406 /// The height, in the dependence graph, for a node.
407 unsigned getHeight(SUnit *Node) { return Node->getHeight(); }
408
409 /// The maximum unweighted length of a path from the given node to an
410 /// arbitrary node in which each edge has latency 0
412 return ScheduleInfo[Node->NodeNum].ZeroLatencyHeight;
413 }
414
415 void applyInstrChange(MachineInstr *MI, SMSchedule &Schedule);
416
417 void fixupRegisterOverlaps(std::deque<SUnit *> &Instrs);
418
419 /// Return the new base register that was stored away for the changed
420 /// instruction.
423 InstrChanges.find(SU);
424 if (It != InstrChanges.end())
425 return It->second.first;
426 return Register();
427 }
428
429 void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {
430 Mutations.push_back(std::move(Mutation));
431 }
432
433 static bool classof(const ScheduleDAGInstrs *DAG) { return true; }
434
435 const SwingSchedulerDDG *getDDG() const { return DDG.get(); }
436
437private:
438 /// Set the policy for this loop, allowing the target to override it.
439 void initPolicy();
440 LoopCarriedEdges addLoopCarriedDependences();
441 void updatePhiDependences();
442 void changeDependences();
443 unsigned calculateResMII();
444 unsigned calculateRecMII(NodeSetType &RecNodeSets);
445 void findCircuits(NodeSetType &NodeSets);
446 void fuseRecs(NodeSetType &NodeSets);
447 void removeDuplicateNodes(NodeSetType &NodeSets);
448 void computeNodeFunctions(NodeSetType &NodeSets);
449 void registerPressureFilter(NodeSetType &NodeSets);
450 void colocateNodeSets(NodeSetType &NodeSets);
451 void checkNodeSets(NodeSetType &NodeSets);
452 void groupRemainingNodes(NodeSetType &NodeSets);
453 void addConnectedNodes(SUnit *SU, NodeSet &NewSet,
454 SetVector<SUnit *> &NodesAdded);
455 void computeNodeOrder(NodeSetType &NodeSets);
456 void checkValidNodeOrder(const NodeSetType &Circuits) const;
457 bool schedulePipeline(SMSchedule &Schedule);
458 MachineInstr *findDefInLoop(Register Reg);
459 bool canUseLastOffsetValue(MachineInstr *MI, unsigned &BasePos,
460 unsigned &OffsetPos, Register &NewBase,
461 int64_t &NewOffset);
462 void postProcessDAG();
463 /// Set the Minimum Initiation Interval for this schedule attempt.
464 void setMII(unsigned ResMII, unsigned RecMII);
465 /// Set the Maximum Initiation Interval for this schedule attempt.
466 void setMAX_II();
467};
468
469/// A NodeSet contains a set of SUnit DAG nodes with additional information
470/// that assigns a priority to the set.
471class NodeSet {
472 SetVector<SUnit *> Nodes;
473 bool HasRecurrence = false;
474 unsigned RecMII = 0;
475 int MaxMOV = 0;
476 unsigned MaxDepth = 0;
477 unsigned Colocate = 0;
478 SUnit *ExceedPressure = nullptr;
479 unsigned Latency = 0;
480
481public:
483
484 NodeSet() = default;
486 : Nodes(S, E), HasRecurrence(true) {
487 // Calculate the latency of this node set.
488 // Example to demonstrate the calculation:
489 // Given: N0 -> N1 -> N2 -> N0
490 // Edges:
491 // (N0 -> N1, 3)
492 // (N0 -> N1, 5)
493 // (N1 -> N2, 2)
494 // (N2 -> N0, 1)
495 // The total latency which is a lower bound of the recurrence MII is the
496 // longest path from N0 back to N0 given only the edges of this node set.
497 // In this example, the latency is: 5 + 2 + 1 = 8.
498 //
499 // Hold a map from each SUnit in the circle to the maximum distance from the
500 // source node by only considering the nodes.
501 const SwingSchedulerDDG *DDG = DAG->getDDG();
502 DenseMap<SUnit *, unsigned> SUnitToDistance;
503 for (auto *Node : Nodes)
504 SUnitToDistance[Node] = 0;
505
506 for (unsigned I = 1, E = Nodes.size(); I <= E; ++I) {
507 SUnit *U = Nodes[I - 1];
508 SUnit *V = Nodes[I % Nodes.size()];
509 for (const SwingSchedulerDDGEdge &Succ : DDG->getOutEdges(U)) {
510 SUnit *SuccSUnit = Succ.getDst();
511 if (V != SuccSUnit)
512 continue;
513 unsigned &DU = SUnitToDistance[U];
514 unsigned &DV = SUnitToDistance[V];
515 if (DU + Succ.getLatency() > DV)
516 DV = DU + Succ.getLatency();
517 }
518 }
519 // Handle a back-edge in loop carried dependencies
520 SUnit *FirstNode = Nodes[0];
521 SUnit *LastNode = Nodes[Nodes.size() - 1];
522
523 for (SUnit *SU : DDG->getExtraOutEdges(LastNode)) {
524 // If we have an order dep that is potentially loop carried then a
525 // back-edge exists between the last node and the first node in extra
526 // edges. Handle it manually by adding 1 to the distance of the last node.
527 if (SU != FirstNode)
528 continue;
529 unsigned &First = SUnitToDistance[FirstNode];
530 unsigned Last = SUnitToDistance[LastNode];
531 First = std::max(First, Last + 1);
532 }
533
534 // The latency is the distance from the source node to itself.
535 Latency = SUnitToDistance[Nodes.front()];
536 }
537
538 bool insert(SUnit *SU) { return Nodes.insert(SU); }
539
540 void insert(iterator S, iterator E) { Nodes.insert(S, E); }
541
542 template <typename UnaryPredicate> bool remove_if(UnaryPredicate P) {
543 return Nodes.remove_if(P);
544 }
545
546 unsigned count(SUnit *SU) const { return Nodes.count(SU); }
547
548 bool hasRecurrence() { return HasRecurrence; };
549
550 unsigned size() const { return Nodes.size(); }
551
552 bool empty() const { return Nodes.empty(); }
553
554 SUnit *getNode(unsigned i) const { return Nodes[i]; };
555
556 void setRecMII(unsigned mii) { RecMII = mii; };
557
558 void setColocate(unsigned c) { Colocate = c; };
559
560 void setExceedPressure(SUnit *SU) { ExceedPressure = SU; }
561
562 bool isExceedSU(SUnit *SU) { return ExceedPressure == SU; }
563
564 int compareRecMII(NodeSet &RHS) { return RecMII - RHS.RecMII; }
565
566 int getRecMII() { return RecMII; }
567
568 /// Summarize node functions for the entire node set.
570 for (SUnit *SU : *this) {
571 MaxMOV = std::max(MaxMOV, SSD->getMOV(SU));
572 MaxDepth = std::max(MaxDepth, SSD->getDepth(SU));
573 }
574 }
575
576 unsigned getLatency() { return Latency; }
577
578 unsigned getMaxDepth() { return MaxDepth; }
579
580 void clear() {
581 Nodes.clear();
582 RecMII = 0;
583 HasRecurrence = false;
584 MaxMOV = 0;
585 MaxDepth = 0;
586 Colocate = 0;
587 ExceedPressure = nullptr;
588 }
589
590 operator SetVector<SUnit *> &() { return Nodes; }
591
592 /// Sort the node sets by importance. First, rank them by recurrence MII,
593 /// then by mobility (least mobile done first), and finally by depth.
594 /// Each node set may contain a colocate value which is used as the first
595 /// tie breaker, if it's set.
596 bool operator>(const NodeSet &RHS) const {
597 if (RecMII == RHS.RecMII) {
598 if (Colocate != 0 && RHS.Colocate != 0 && Colocate != RHS.Colocate)
599 return Colocate < RHS.Colocate;
600 if (MaxMOV == RHS.MaxMOV)
601 return MaxDepth > RHS.MaxDepth;
602 return MaxMOV < RHS.MaxMOV;
603 }
604 return RecMII > RHS.RecMII;
605 }
606
607 bool operator==(const NodeSet &RHS) const {
608 return RecMII == RHS.RecMII && MaxMOV == RHS.MaxMOV &&
609 MaxDepth == RHS.MaxDepth;
610 }
611
612 bool operator!=(const NodeSet &RHS) const { return !operator==(RHS); }
613
614 iterator begin() { return Nodes.begin(); }
615 iterator end() { return Nodes.end(); }
616
617#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
618 LLVM_ABI void print(raw_ostream &os) const;
619 LLVM_DUMP_METHOD void dump() const;
620#endif
621};
622
623// 16 was selected based on the number of ProcResource kinds for all
624// existing Subtargets, so that SmallVector don't need to resize too often.
625static const int DefaultProcResSize = 16;
626
628private:
629 const MCSubtargetInfo *STI;
630 const MCSchedModel &SM;
631 const TargetSubtargetInfo *ST;
632 const TargetInstrInfo *TII;
634 const bool UseDFA;
635 /// DFA resources for each slot
637 /// Modulo Reservation Table. When a resource with ID R is consumed in cycle
638 /// C, it is counted in MRT[C mod II][R]. (Used when UseDFA == F)
640 /// The number of scheduled micro operations for each slot. Micro operations
641 /// are assumed to be scheduled one per cycle, starting with the cycle in
642 /// which the instruction is scheduled.
643 llvm::SmallVector<int> NumScheduledMops;
644 /// Each processor resource is associated with a so-called processor resource
645 /// mask. This vector allows to correlate processor resource IDs with
646 /// processor resource masks. There is exactly one element per each processor
647 /// resource declared by the scheduling model.
649 int InitiationInterval = 0;
650 /// The number of micro operations that can be scheduled at a cycle.
651 int IssueWidth;
652
653 int calculateResMIIDFA() const;
654 /// Check if MRT is overbooked
655 bool isOverbooked() const;
656 /// Reserve resources on MRT
657 void reserveResources(const MCSchedClassDesc *SCDesc, int Cycle);
658 /// Unreserve resources on MRT
659 void unreserveResources(const MCSchedClassDesc *SCDesc, int Cycle);
660
661 /// Return M satisfying Dividend = Divisor * X + M, 0 < M < Divisor.
662 /// The slot on MRT to reserve a resource for the cycle C is positiveModulo(C,
663 /// II).
664 int positiveModulo(int Dividend, int Divisor) const {
665 assert(Divisor > 0);
666 int R = Dividend % Divisor;
667 if (R < 0)
668 R += Divisor;
669 return R;
670 }
671
672#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
673 LLVM_DUMP_METHOD void dumpMRT() const;
674#endif
675
676public:
678 ScheduleDAGInstrs *DAG);
679
682
683 /// Check if the resources occupied by a machine instruction are available
684 /// in the current state.
685 LLVM_ABI bool canReserveResources(SUnit &SU, int Cycle);
686
687 /// Reserve the resources occupied by a machine instruction and change the
688 /// current state to reflect that change.
689 LLVM_ABI void reserveResources(SUnit &SU, int Cycle);
690
691 LLVM_ABI int calculateResMII() const;
692
693 /// Initialize resources with the initiation interval II.
694 LLVM_ABI void init(int II);
695};
696
697/// This class represents the scheduled code. The main data structure is a
698/// map from scheduled cycle to instructions. During scheduling, the
699/// data structure explicitly represents all stages/iterations. When
700/// the algorithm finshes, the schedule is collapsed into a single stage,
701/// which represents instructions from different loop iterations.
702///
703/// The SMS algorithm allows negative values for cycles, so the first cycle
704/// in the schedule is the smallest cycle value.
706private:
707 /// Map from execution cycle to instructions.
708 DenseMap<int, std::deque<SUnit *>> ScheduledInstrs;
709
710 /// Map from instruction to execution cycle.
711 std::map<SUnit *, int> InstrToCycle;
712
713 /// Keep track of the first cycle value in the schedule. It starts
714 /// as zero, but the algorithm allows negative values.
715 int FirstCycle = 0;
716
717 /// Keep track of the last cycle value in the schedule.
718 int LastCycle = 0;
719
720 /// The initiation interval (II) for the schedule.
721 int InitiationInterval = 0;
722
723 /// Target machine information.
724 const TargetSubtargetInfo &ST;
725
726 /// Virtual register information.
728
729 ResourceManager ProcItinResources;
730
731public:
733 : ST(mf->getSubtarget()), MRI(mf->getRegInfo()),
734 ProcItinResources(&ST, DAG) {}
735
736 void reset() {
737 ScheduledInstrs.clear();
738 InstrToCycle.clear();
739 FirstCycle = 0;
740 LastCycle = 0;
741 InitiationInterval = 0;
742 }
743
744 /// Set the initiation interval for this schedule.
746 InitiationInterval = ii;
747 ProcItinResources.init(ii);
748 }
749
750 /// Return the initiation interval for this schedule.
751 int getInitiationInterval() const { return InitiationInterval; }
752
753 /// Return the first cycle in the completed schedule. This
754 /// can be a negative value.
755 int getFirstCycle() const { return FirstCycle; }
756
757 /// Return the last cycle in the finalized schedule.
758 int getFinalCycle() const { return FirstCycle + InitiationInterval - 1; }
759
760 LLVM_ABI void computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
761 int II, SwingSchedulerDAG *DAG);
762 LLVM_ABI bool insert(SUnit *SU, int StartCycle, int EndCycle, int II);
763
764 /// Iterators for the cycle to instruction map.
768
769 /// Return true if the instruction is scheduled at the specified stage.
770 bool isScheduledAtStage(SUnit *SU, unsigned StageNum) {
771 return (stageScheduled(SU) == (int)StageNum);
772 }
773
774 /// Return the stage for a scheduled instruction. Return -1 if
775 /// the instruction has not been scheduled.
776 int stageScheduled(SUnit *SU) const {
777 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
778 if (it == InstrToCycle.end())
779 return -1;
780 return (it->second - FirstCycle) / InitiationInterval;
781 }
782
783 /// Return the cycle for a scheduled instruction. This function normalizes
784 /// the first cycle to be 0.
785 unsigned cycleScheduled(SUnit *SU) const {
786 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
787 assert(it != InstrToCycle.end() && "Instruction hasn't been scheduled.");
788 return (it->second - FirstCycle) % InitiationInterval;
789 }
790
791 /// Return the maximum stage count needed for this schedule.
792 unsigned getMaxStageCount() {
793 return (LastCycle - FirstCycle) / InitiationInterval;
794 }
795
796 /// Return the instructions that are scheduled at the specified cycle.
797 std::deque<SUnit *> &getInstructions(int cycle) {
798 return ScheduledInstrs[cycle];
799 }
800
802 computeUnpipelineableNodes(SwingSchedulerDAG *SSD,
804
805 LLVM_ABI std::deque<SUnit *>
806 reorderInstructions(const SwingSchedulerDAG *SSD,
807 const std::deque<SUnit *> &Instrs) const;
808
809 LLVM_ABI bool
810 normalizeNonPipelinedInstructions(SwingSchedulerDAG *SSD,
812 LLVM_ABI bool isValidSchedule(SwingSchedulerDAG *SSD);
813 LLVM_ABI void finalizeSchedule(SwingSchedulerDAG *SSD);
814 LLVM_ABI void orderDependence(const SwingSchedulerDAG *SSD, SUnit *SU,
815 std::deque<SUnit *> &Insts) const;
816 LLVM_ABI bool isLoopCarried(const SwingSchedulerDAG *SSD,
817 MachineInstr &Phi) const;
818 LLVM_ABI bool isLoopCarriedDefOfUse(const SwingSchedulerDAG *SSD,
819 MachineInstr *Def,
820 MachineOperand &MO) const;
821
822 LLVM_ABI bool
823 onlyHasLoopCarriedOutputOrOrderPreds(SUnit *SU,
824 const SwingSchedulerDDG *DDG) const;
825 LLVM_ABI void print(raw_ostream &os) const;
826 LLVM_ABI void dump() const;
827};
828
829} // end namespace llvm
830
831#endif // LLVM_CODEGEN_MACHINEPIPELINER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
#define P(N)
PowerPC VSX FMA Mutation
MachineRegisterInfo & MRI
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
Value * RHS
Represent the analysis usage information of a pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:410
iterator end()
Definition DenseMap.h:686
Generic base class for all target subtargets.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
A NodeSet contains a set of SUnit DAG nodes with additional information that assigns a priority to th...
SUnit * getNode(unsigned i) const
SetVector< SUnit * >::const_iterator iterator
bool isExceedSU(SUnit *SU)
void insert(iterator S, iterator E)
void setRecMII(unsigned mii)
void computeNodeSetInfo(SwingSchedulerDAG *SSD)
Summarize node functions for the entire node set.
unsigned getMaxDepth()
unsigned count(SUnit *SU) const
NodeSet()=default
void setColocate(unsigned c)
unsigned getLatency()
NodeSet(iterator S, iterator E, const SwingSchedulerDAG *DAG)
bool operator>(const NodeSet &RHS) const
Sort the node sets by importance.
int compareRecMII(NodeSet &RHS)
unsigned size() const
bool operator!=(const NodeSet &RHS) const
bool insert(SUnit *SU)
bool operator==(const NodeSet &RHS) const
bool remove_if(UnaryPredicate P)
bool empty() const
void setExceedPressure(SUnit *SU)
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
Wrapper class representing virtual and physical registers.
Definition Register.h:20
LLVM_ABI int calculateResMII() const
LLVM_ABI void initProcResourceVectors(const MCSchedModel &SM, SmallVectorImpl< uint64_t > &Masks)
LLVM_ABI ResourceManager(const TargetSubtargetInfo *ST, ScheduleDAGInstrs *DAG)
LLVM_ABI void init(int II)
Initialize resources with the initiation interval II.
LLVM_ABI bool canReserveResources(SUnit &SU, int Cycle)
Check if the resources occupied by a machine instruction are available in the current state.
Scheduling dependency.
Definition ScheduleDAG.h:54
SUnit * getSUnit() const
@ Output
A register output-dependence (aka WAW).
Definition ScheduleDAG.h:60
@ Order
Any other ordering dependency.
Definition ScheduleDAG.h:61
@ Anti
A register anti-dependence (aka WAR).
Definition ScheduleDAG.h:59
This class represents the scheduled code.
void setInitiationInterval(int ii)
Set the initiation interval for this schedule.
unsigned getMaxStageCount()
Return the maximum stage count needed for this schedule.
int stageScheduled(SUnit *SU) const
Return the stage for a scheduled instruction.
bool isScheduledAtStage(SUnit *SU, unsigned StageNum)
Return true if the instruction is scheduled at the specified stage.
int getInitiationInterval() const
Return the initiation interval for this schedule.
std::deque< SUnit * > & getInstructions(int cycle)
Return the instructions that are scheduled at the specified cycle.
int getFirstCycle() const
Return the first cycle in the completed schedule.
DenseMap< int, std::deque< SUnit * > >::const_iterator const_sched_iterator
DenseMap< int, std::deque< SUnit * > >::iterator sched_iterator
Iterators for the cycle to instruction map.
unsigned cycleScheduled(SUnit *SU) const
Return the cycle for a scheduled instruction.
SMSchedule(MachineFunction *mf, SwingSchedulerDAG *DAG)
int getFinalCycle() const
Return the last cycle in the finalized schedule.
Scheduling unit. This is a node in the scheduling DAG.
A ScheduleDAG for scheduling lists of MachineInstr.
ScheduleDAGInstrs(MachineFunction &mf, const MachineLoopInfo *mli, bool RemoveKillFlags=false)
const MachineLoopInfo * MLI
Mutate the DAG as a postpass after normal DAG building.
This class can compute a topological ordering for SUnits and provides methods for dynamically updatin...
std::vector< SUnit > SUnits
The scheduling units.
MachineFunction & MF
Machine function.
ScheduleDAG & operator=(const ScheduleDAG &)=delete
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
const value_type & front() const
Return the first element of the SetVector.
Definition SetVector.h:138
typename vector_type::const_iterator const_iterator
Definition SetVector.h:73
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class builds the dependence graph for the instructions in a loop, and attempts to schedule the i...
unsigned getDepth(SUnit *Node)
The depth, in the dependence graph, for a node.
SwingSchedulerDAG(MachineFunction &MF, const MachineLoopInfo *MLI, MachineOptimizationRemarkEmitter *ORE, MachineLoop &L, LiveIntervals &lis, const RegisterClassInfo &rci, unsigned II, TargetInstrInfo::PipelinerLoopInfo *PLI, AliasAnalysis *AA, MachineDominatorTree *MDT=nullptr)
int getASAP(SUnit *Node)
Return the earliest time an instruction may be scheduled.
const SwingSchedulerDDG * getDDG() const
void finishBlock() override
Clean up after the software pipeliner runs.
bool hasNewSchedule()
Return true if the loop kernel has been scheduled.
void addMutation(std::unique_ptr< ScheduleDAGMutation > Mutation)
int getZeroLatencyDepth(SUnit *Node)
The maximum unweighted length of a path from an arbitrary node to the given node in which each edge h...
void schedule() override
We override the schedule function in ScheduleDAGInstrs to implement the scheduling part of the Swing ...
int getMOV(SUnit *Node)
The mobility function, which the number of slots in which an instruction may be scheduled.
int getZeroLatencyHeight(SUnit *Node)
The maximum unweighted length of a path from the given node to an arbitrary node in which each edge h...
Register getInstrBaseReg(SUnit *SU) const
Return the new base register that was stored away for the changed instruction.
static bool classof(const ScheduleDAGInstrs *DAG)
unsigned getHeight(SUnit *Node)
The height, in the dependence graph, for a node.
int getALAP(SUnit *Node)
Return the latest time an instruction my be scheduled.
Represents a dependence between two instruction.
SUnit * getDst() const
Returns the SUnit to which the edge points (destination node).
Register getReg() const
Returns the register associated with the edge.
void setDistance(unsigned D)
Sets the distance value for the edge.
bool isBarrier() const
Returns true if the edge represents unknown scheduling barrier.
void setLatency(unsigned Latency)
Sets the latency for the edge.
SwingSchedulerDDGEdge(SUnit *PredOrSucc, const SDep &Dep, bool IsSucc, bool IsValidationOnly)
Creates an edge corresponding to an edge represented by PredOrSucc and Dep in the original DAG.
bool isAntiDep() const
Returns true if the edge represents anti dependence.
bool isAssignedRegDep() const
Tests if this is a Data dependence that is associated with a register.
bool isArtificial() const
Returns true if the edge represents an artificial dependence.
LLVM_ABI bool ignoreDependence(bool IgnoreAnti) const
Returns true for DDG nodes that we ignore when computing the cost functions.
bool isOrderDep() const
Returns true if the edge represents a dependence that is not data, anti or output dependence.
unsigned getLatency() const
Returns the latency value for the edge.
SUnit * getSrc() const
Returns the SUnit from which the edge comes (source node).
bool isValidationOnly() const
Returns true if this edge is intended to be used only for validating the schedule.
unsigned getDistance() const
Returns the distance value for the edge.
bool isOutputDep() const
Returns true if the edge represents output dependence.
This class provides APIs to retrieve edges from/to an SUnit node, with a particular focus on loop-car...
LLVM_ABI SwingSchedulerDDG(std::vector< SUnit > &SUnits, SUnit *EntrySU, SUnit *ExitSU, const LoopCarriedEdges &LCE)
LLVM_ABI ArrayRef< SUnit * > getExtraOutEdges(const SUnit *SU) const
LLVM_ABI const EdgesType & getInEdges(const SUnit *SU) const
LLVM_ABI bool isValidSchedule(const SMSchedule &Schedule) const
Check if Schedule doesn't violate the validation-only dependencies.
LLVM_ABI const EdgesType & getOutEdges(const SUnit *SU) const
Object returned by analyzeLoopForPipelining.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool mayOverlapInLaterIter(const MachineInstr *BaseMI, const MachineInstr *OtherMI, const MachineBasicBlock *LoopBB, const MachineRegisterInfo &MRI, const TargetInstrInfo &TII)
Return true if BaseMI and OtherMI may access overlapping memory in a later iteration of the loop Loop...
static const int DefaultProcResSize
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
Represents loop-carried dependencies.
SmallSetVector< SUnit *, 8 > OrderDep
LLVM_ABI void dump(SUnit *SU, const TargetRegisterInfo *TRI, const MachineRegisterInfo *MRI) const
const OrderDep * getOrderDepOrNull(SUnit *Key) const
LLVM_ABI void modifySUnits(std::vector< SUnit > &SUnits, const TargetInstrInfo *TII)
Adds some edges to the original DAG that correspond to loop-carried dependencies.
DenseMap< SUnit *, OrderDep > OrderDepsType
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Definition MCSchedule.h:124
Machine model for scheduling, bundling, and heuristics.
Definition MCSchedule.h:268
Software pipelining policy for a loop, which a target can customize by implementing TargetSubtargetIn...
bool ShouldLimitRegPressure
Limit the register pressure of the scheduled loop, retrying at a higher II when a schedule needs too ...
A CRTP mix-in for passes that can be skipped.