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 AAResults;
61class LiveIntervals;
62class NodeSet;
63class SMSchedule;
64
65/// Return true if BaseMI and OtherMI may access overlapping memory in a later
66/// iteration of the loop LoopBB. Returns true conservatively whenever overlap
67/// cannot be ruled out.
69 const MachineInstr *OtherMI,
70 const MachineBasicBlock *LoopBB,
72 const TargetInstrInfo &TII);
73
74/// Software pipelining policy for a loop, which a target can customize by
75/// implementing TargetSubtargetInfo::overridePipelinerPolicy.
77 /// Limit the register pressure of the scheduled loop, retrying at a higher
78 /// II when a schedule needs too many registers.
80};
81
83public:
84 static char ID;
85
87
88 bool runOnMachineFunction(MachineFunction &MF) override;
89
90 void getAnalysisUsage(AnalysisUsage &AU) const override;
91};
92
94 : public OptionalPassInfoMixin<MachinePipelinerPass> {
95public:
98};
99
100/// Represents a dependence between two instruction.
102 SUnit *Dst = nullptr;
103 SDep Pred;
104 unsigned Distance = 0;
105 bool IsValidationOnly = false;
106
107public:
108 /// Creates an edge corresponding to an edge represented by \p PredOrSucc and
109 /// \p Dep in the original DAG. This pair has no information about the
110 /// direction of the edge, so we need to pass an additional argument \p
111 /// IsSucc.
112 SwingSchedulerDDGEdge(SUnit *PredOrSucc, const SDep &Dep, bool IsSucc,
113 bool IsValidationOnly)
114 : Dst(PredOrSucc), Pred(Dep), Distance(0u),
115 IsValidationOnly(IsValidationOnly) {
116 SUnit *Src = Dep.getSUnit();
117
118 if (IsSucc) {
119 std::swap(Src, Dst);
120 Pred.setSUnit(Src);
121 }
122
123 // An anti-dependence to PHI means loop-carried dependence.
124 if (Pred.getKind() == SDep::Anti && Src->getInstr()->isPHI()) {
125 Distance = 1;
126 std::swap(Src, Dst);
127 auto Reg = Pred.getReg();
128 Pred = SDep(Src, SDep::Kind::Data, Reg);
129 }
130 }
131
132 /// Returns the SUnit from which the edge comes (source node).
133 SUnit *getSrc() const { return Pred.getSUnit(); }
134
135 /// Returns the SUnit to which the edge points (destination node).
136 SUnit *getDst() const { return Dst; }
137
138 /// Returns the latency value for the edge.
139 unsigned getLatency() const { return Pred.getLatency(); }
140
141 /// Sets the latency for the edge.
142 void setLatency(unsigned Latency) { Pred.setLatency(Latency); }
143
144 /// Returns the distance value for the edge.
145 unsigned getDistance() const { return Distance; }
146
147 /// Sets the distance value for the edge.
148 void setDistance(unsigned D) { Distance = D; }
149
150 /// Returns the register associated with the edge.
151 Register getReg() const { return Pred.getReg(); }
152
153 /// Returns true if the edge represents anti dependence.
154 bool isAntiDep() const { return Pred.getKind() == SDep::Kind::Anti; }
155
156 /// Returns true if the edge represents output dependence.
157 bool isOutputDep() const { return Pred.getKind() == SDep::Kind::Output; }
158
159 /// Returns true if the edge represents a dependence that is not data, anti or
160 /// output dependence.
161 bool isOrderDep() const { return Pred.getKind() == SDep::Kind::Order; }
162
163 /// Returns true if the edge represents unknown scheduling barrier.
164 bool isBarrier() const { return Pred.isBarrier(); }
165
166 /// Returns true if the edge represents an artificial dependence.
167 bool isArtificial() const { return Pred.isArtificial(); }
168
169 /// Tests if this is a Data dependence that is associated with a register.
170 bool isAssignedRegDep() const { return Pred.isAssignedRegDep(); }
171
172 /// Returns true for DDG nodes that we ignore when computing the cost
173 /// functions. We ignore the back-edge recurrence in order to avoid unbounded
174 /// recursion in the calculation of the ASAP, ALAP, etc functions.
175 LLVM_ABI bool ignoreDependence(bool IgnoreAnti) const;
176
177 /// Returns true if this edge is intended to be used only for validating the
178 /// schedule.
179 bool isValidationOnly() const { return IsValidationOnly; }
180};
181
182/// Represents loop-carried dependencies. Because SwingSchedulerDAG doesn't
183/// assume cycle dependencies as the name suggests, such dependencies must be
184/// handled separately. After DAG construction is finished, these dependencies
185/// are added to SwingSchedulerDDG.
186/// TODO: Also handle output-dependencies introduced by physical registers.
190
192
194 auto Ite = OrderDeps.find(Key);
195 if (Ite == OrderDeps.end())
196 return nullptr;
197 return &Ite->second;
198 }
199
200 /// Adds some edges to the original DAG that correspond to loop-carried
201 /// dependencies. Historically, loop-carried edges are represented by using
202 /// non-loop-carried edges in the original DAG. This function appends such
203 /// edges to preserve the previous behavior.
204 LLVM_ABI void modifySUnits(std::vector<SUnit> &SUnits,
205 const TargetInstrInfo *TII);
206
207#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
208 LLVM_ABI void dump(SUnit *SU, const TargetRegisterInfo *TRI,
209 const MachineRegisterInfo *MRI) const;
210#endif
211};
212
213/// This class provides APIs to retrieve edges from/to an SUnit node, with a
214/// particular focus on loop-carried dependencies. Since SUnit is not designed
215/// to represent such edges, handling them directly using its APIs has required
216/// non-trivial logic in the past. This class serves as a wrapper around SUnit,
217/// offering a simpler interface for managing these dependencies.
220
221 struct SwingSchedulerDDGEdges {
222 EdgesType Preds;
223 EdgesType Succs;
224
225 /// This field is a subset of ValidationOnlyEdges. These edges are used only
226 /// by specific heuristics, mainly for cycle detection. Although they are
227 /// unnecessary in theory (i.e., ignoring them should still yield a valid
228 /// schedule), they are retained to preserve the existing behavior. Since we
229 /// only need which extra edges exist from a given SUnit, we only store the
230 /// destination SUnits.
231 SmallVector<SUnit *, 4> ExtraSuccs;
232 };
233
234 void initEdges(SUnit *SU);
235
236 SUnit *EntrySU;
237 SUnit *ExitSU;
238
239 std::vector<SwingSchedulerDDGEdges> EdgesVec;
240 SwingSchedulerDDGEdges EntrySUEdges;
241 SwingSchedulerDDGEdges ExitSUEdges;
242
243 /// Edges that are used only when validating the schedule. These edges are
244 /// not considered to drive the optimization heuristics.
245 SmallVector<SwingSchedulerDDGEdge, 8> ValidationOnlyEdges;
246
247 /// Adds a NON-validation-only edge to the DDG. Assumes to be called only by
248 /// the ctor.
249 void addEdge(const SUnit *SU, const SwingSchedulerDDGEdge &Edge);
250
251 SwingSchedulerDDGEdges &getEdges(const SUnit *SU);
252 const SwingSchedulerDDGEdges &getEdges(const SUnit *SU) const;
253
254public:
255 LLVM_ABI SwingSchedulerDDG(std::vector<SUnit> &SUnits, SUnit *EntrySU,
256 SUnit *ExitSU, const LoopCarriedEdges &LCE);
257
258 LLVM_ABI const EdgesType &getInEdges(const SUnit *SU) const;
259
260 LLVM_ABI const EdgesType &getOutEdges(const SUnit *SU) const;
261
263
264 LLVM_ABI bool isValidSchedule(const SMSchedule &Schedule) const;
265};
266
267/// This class builds the dependence graph for the instructions in a loop,
268/// and attempts to schedule the instructions using the SMS algorithm.
271
272 std::unique_ptr<SwingSchedulerDDG> DDG;
273
274 /// The minimum initiation interval between iterations for this schedule.
275 unsigned MII = 0;
276 /// The maximum initiation interval between iterations for this schedule.
277 unsigned MAX_II = 0;
278 /// Set to true if a valid pipelined schedule is found for the loop.
279 bool Scheduled = false;
280 MachineLoop &Loop;
281 LiveIntervals &LIS;
282 const RegisterClassInfo &RegClassInfo;
283 unsigned II_setByPragma = 0;
284 TargetInstrInfo::PipelinerLoopInfo *LoopPipelinerInfo = nullptr;
285
286 /// Policy for this loop, after target and command line overrides.
288
289 /// A topological ordering of the SUnits, which is needed for changing
290 /// dependences and iterating over the SUnits.
292
293 struct NodeInfo {
294 int ASAP = 0;
295 int ALAP = 0;
296 int ZeroLatencyDepth = 0;
297 int ZeroLatencyHeight = 0;
298
299 NodeInfo() = default;
300 };
301 /// Computed properties for each node in the graph.
302 std::vector<NodeInfo> ScheduleInfo;
303
304 enum OrderKind { BottomUp = 0, TopDown = 1 };
305 /// Computed node ordering for scheduling.
306 SetVector<SUnit *> NodeOrder;
307
308 using NodeSetType = SmallVector<NodeSet, 8>;
309 using ValueMapTy = DenseMap<unsigned, unsigned>;
310 using MBBVectorTy = SmallVectorImpl<MachineBasicBlock *>;
312
313 /// Instructions to change when emitting the final schedule.
315
316 /// We may create a new instruction, so remember it because it
317 /// must be deleted when the pass is finished.
319
320 /// Ordered list of DAG postprocessing steps.
321 std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
322
323 /// Used to compute single-iteration dependencies (i.e., buildSchedGraph).
324 AliasAnalysis *AA;
325
326 /// Used to compute loop-carried dependencies (i.e.,
327 /// addLoopCarriedDependences).
328 BatchAAResults BAA;
329
330 /// Helper class to implement Johnson's circuit finding algorithm.
331 class Circuits {
332 std::vector<SUnit> &SUnits;
333 SetVector<SUnit *> Stack;
334 BitVector Blocked;
337 // Node to Index from ScheduleDAGTopologicalSort
338 std::vector<int> *Node2Idx;
339 unsigned NumPaths = 0u;
340 static unsigned MaxPaths;
341
342 public:
343 Circuits(std::vector<SUnit> &SUs, ScheduleDAGTopologicalSort &Topo)
344 : SUnits(SUs), Blocked(SUs.size()), B(SUs.size()), AdjK(SUs.size()) {
345 Node2Idx = new std::vector<int>(SUs.size());
346 unsigned Idx = 0;
347 for (const auto &NodeNum : Topo)
348 Node2Idx->at(NodeNum) = Idx++;
349 }
350 Circuits &operator=(const Circuits &other) = delete;
351 Circuits(const Circuits &other) = delete;
352 ~Circuits() { delete Node2Idx; }
353
354 /// Reset the data structures used in the circuit algorithm.
355 void reset() {
356 Stack.clear();
357 Blocked.reset();
358 B.assign(SUnits.size(), SmallPtrSet<SUnit *, 4>());
359 NumPaths = 0;
360 }
361
362 LLVM_ABI void createAdjacencyStructure(SwingSchedulerDDG *DDG);
363 LLVM_ABI bool circuit(int V, int S, NodeSetType &NodeSets,
364 const SwingSchedulerDAG *DAG,
365 bool HasBackedge = false);
366 LLVM_ABI void unblock(int U);
367 };
368
369 struct LLVM_ABI CopyToPhiMutation : public ScheduleDAGMutation {
370 void apply(ScheduleDAGInstrs *DAG) override;
371 };
372
373public:
376 LiveIntervals &lis, const RegisterClassInfo &rci,
378 AliasAnalysis *AA);
379
380 void schedule() override;
381 void finishBlock() override;
382
383 /// Return true if the loop kernel has been scheduled.
384 bool hasNewSchedule() { return Scheduled; }
385
386 /// Return the earliest time an instruction may be scheduled.
387 int getASAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ASAP; }
388
389 /// Return the latest time an instruction my be scheduled.
390 int getALAP(SUnit *Node) { return ScheduleInfo[Node->NodeNum].ALAP; }
391
392 /// The mobility function, which the number of slots in which
393 /// an instruction may be scheduled.
394 int getMOV(SUnit *Node) { return getALAP(Node) - getASAP(Node); }
395
396 /// The depth, in the dependence graph, for a node.
397 unsigned getDepth(SUnit *Node) { return Node->getDepth(); }
398
399 /// The maximum unweighted length of a path from an arbitrary node to the
400 /// given node in which each edge has latency 0
402 return ScheduleInfo[Node->NodeNum].ZeroLatencyDepth;
403 }
404
405 /// The height, in the dependence graph, for a node.
406 unsigned getHeight(SUnit *Node) { return Node->getHeight(); }
407
408 /// The maximum unweighted length of a path from the given node to an
409 /// arbitrary node in which each edge has latency 0
411 return ScheduleInfo[Node->NodeNum].ZeroLatencyHeight;
412 }
413
414 void applyInstrChange(MachineInstr *MI, SMSchedule &Schedule);
415
416 void fixupRegisterOverlaps(std::deque<SUnit *> &Instrs);
417
418 /// Return the new base register that was stored away for the changed
419 /// instruction.
422 InstrChanges.find(SU);
423 if (It != InstrChanges.end())
424 return It->second.first;
425 return Register();
426 }
427
428 void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {
429 Mutations.push_back(std::move(Mutation));
430 }
431
432 static bool classof(const ScheduleDAGInstrs *DAG) { return true; }
433
434 const SwingSchedulerDDG *getDDG() const { return DDG.get(); }
435
436private:
437 /// Set the policy for this loop, allowing the target to override it.
438 void initPolicy();
439 LoopCarriedEdges addLoopCarriedDependences();
440 void updatePhiDependences();
441 void changeDependences();
442 unsigned calculateResMII();
443 unsigned calculateRecMII(NodeSetType &RecNodeSets);
444 void findCircuits(NodeSetType &NodeSets);
445 void fuseRecs(NodeSetType &NodeSets);
446 void removeDuplicateNodes(NodeSetType &NodeSets);
447 void computeNodeFunctions(NodeSetType &NodeSets);
448 void registerPressureFilter(NodeSetType &NodeSets);
449 void colocateNodeSets(NodeSetType &NodeSets);
450 void checkNodeSets(NodeSetType &NodeSets);
451 void groupRemainingNodes(NodeSetType &NodeSets);
452 void addConnectedNodes(SUnit *SU, NodeSet &NewSet,
453 SetVector<SUnit *> &NodesAdded);
454 void computeNodeOrder(NodeSetType &NodeSets);
455 void checkValidNodeOrder(const NodeSetType &Circuits) const;
456 bool schedulePipeline(SMSchedule &Schedule);
457 MachineInstr *findDefInLoop(Register Reg);
458 bool canUseLastOffsetValue(MachineInstr *MI, unsigned &BasePos,
459 unsigned &OffsetPos, Register &NewBase,
460 int64_t &NewOffset);
461 void postProcessDAG();
462 /// Set the Minimum Initiation Interval for this schedule attempt.
463 void setMII(unsigned ResMII, unsigned RecMII);
464 /// Set the Maximum Initiation Interval for this schedule attempt.
465 void setMAX_II();
466};
467
468/// A NodeSet contains a set of SUnit DAG nodes with additional information
469/// that assigns a priority to the set.
470class NodeSet {
471 SetVector<SUnit *> Nodes;
472 bool HasRecurrence = false;
473 unsigned RecMII = 0;
474 int MaxMOV = 0;
475 unsigned MaxDepth = 0;
476 unsigned Colocate = 0;
477 SUnit *ExceedPressure = nullptr;
478 unsigned Latency = 0;
479
480public:
482
483 NodeSet() = default;
485 : Nodes(S, E), HasRecurrence(true) {
486 // Calculate the latency of this node set.
487 // Example to demonstrate the calculation:
488 // Given: N0 -> N1 -> N2 -> N0
489 // Edges:
490 // (N0 -> N1, 3)
491 // (N0 -> N1, 5)
492 // (N1 -> N2, 2)
493 // (N2 -> N0, 1)
494 // The total latency which is a lower bound of the recurrence MII is the
495 // longest path from N0 back to N0 given only the edges of this node set.
496 // In this example, the latency is: 5 + 2 + 1 = 8.
497 //
498 // Hold a map from each SUnit in the circle to the maximum distance from the
499 // source node by only considering the nodes.
500 const SwingSchedulerDDG *DDG = DAG->getDDG();
501 DenseMap<SUnit *, unsigned> SUnitToDistance;
502 for (auto *Node : Nodes)
503 SUnitToDistance[Node] = 0;
504
505 for (unsigned I = 1, E = Nodes.size(); I <= E; ++I) {
506 SUnit *U = Nodes[I - 1];
507 SUnit *V = Nodes[I % Nodes.size()];
508 for (const SwingSchedulerDDGEdge &Succ : DDG->getOutEdges(U)) {
509 SUnit *SuccSUnit = Succ.getDst();
510 if (V != SuccSUnit)
511 continue;
512 unsigned &DU = SUnitToDistance[U];
513 unsigned &DV = SUnitToDistance[V];
514 if (DU + Succ.getLatency() > DV)
515 DV = DU + Succ.getLatency();
516 }
517 }
518 // Handle a back-edge in loop carried dependencies
519 SUnit *FirstNode = Nodes[0];
520 SUnit *LastNode = Nodes[Nodes.size() - 1];
521
522 for (SUnit *SU : DDG->getExtraOutEdges(LastNode)) {
523 // If we have an order dep that is potentially loop carried then a
524 // back-edge exists between the last node and the first node in extra
525 // edges. Handle it manually by adding 1 to the distance of the last node.
526 if (SU != FirstNode)
527 continue;
528 unsigned &First = SUnitToDistance[FirstNode];
529 unsigned Last = SUnitToDistance[LastNode];
530 First = std::max(First, Last + 1);
531 }
532
533 // The latency is the distance from the source node to itself.
534 Latency = SUnitToDistance[Nodes.front()];
535 }
536
537 bool insert(SUnit *SU) { return Nodes.insert(SU); }
538
539 void insert(iterator S, iterator E) { Nodes.insert(S, E); }
540
541 template <typename UnaryPredicate> bool remove_if(UnaryPredicate P) {
542 return Nodes.remove_if(P);
543 }
544
545 unsigned count(SUnit *SU) const { return Nodes.count(SU); }
546
547 bool hasRecurrence() { return HasRecurrence; };
548
549 unsigned size() const { return Nodes.size(); }
550
551 bool empty() const { return Nodes.empty(); }
552
553 SUnit *getNode(unsigned i) const { return Nodes[i]; };
554
555 void setRecMII(unsigned mii) { RecMII = mii; };
556
557 void setColocate(unsigned c) { Colocate = c; };
558
559 void setExceedPressure(SUnit *SU) { ExceedPressure = SU; }
560
561 bool isExceedSU(SUnit *SU) { return ExceedPressure == SU; }
562
563 int compareRecMII(NodeSet &RHS) { return RecMII - RHS.RecMII; }
564
565 int getRecMII() { return RecMII; }
566
567 /// Summarize node functions for the entire node set.
569 for (SUnit *SU : *this) {
570 MaxMOV = std::max(MaxMOV, SSD->getMOV(SU));
571 MaxDepth = std::max(MaxDepth, SSD->getDepth(SU));
572 }
573 }
574
575 unsigned getLatency() { return Latency; }
576
577 unsigned getMaxDepth() { return MaxDepth; }
578
579 void clear() {
580 Nodes.clear();
581 RecMII = 0;
582 HasRecurrence = false;
583 MaxMOV = 0;
584 MaxDepth = 0;
585 Colocate = 0;
586 ExceedPressure = nullptr;
587 }
588
589 operator SetVector<SUnit *> &() { return Nodes; }
590
591 /// Sort the node sets by importance. First, rank them by recurrence MII,
592 /// then by mobility (least mobile done first), and finally by depth.
593 /// Each node set may contain a colocate value which is used as the first
594 /// tie breaker, if it's set.
595 bool operator>(const NodeSet &RHS) const {
596 if (RecMII == RHS.RecMII) {
597 if (Colocate != 0 && RHS.Colocate != 0 && Colocate != RHS.Colocate)
598 return Colocate < RHS.Colocate;
599 if (MaxMOV == RHS.MaxMOV)
600 return MaxDepth > RHS.MaxDepth;
601 return MaxMOV < RHS.MaxMOV;
602 }
603 return RecMII > RHS.RecMII;
604 }
605
606 bool operator==(const NodeSet &RHS) const {
607 return RecMII == RHS.RecMII && MaxMOV == RHS.MaxMOV &&
608 MaxDepth == RHS.MaxDepth;
609 }
610
611 bool operator!=(const NodeSet &RHS) const { return !operator==(RHS); }
612
613 iterator begin() { return Nodes.begin(); }
614 iterator end() { return Nodes.end(); }
615
616#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
617 LLVM_ABI void print(raw_ostream &os) const;
618 LLVM_DUMP_METHOD void dump() const;
619#endif
620};
621
622// 16 was selected based on the number of ProcResource kinds for all
623// existing Subtargets, so that SmallVector don't need to resize too often.
624static const int DefaultProcResSize = 16;
625
627private:
628 const MCSubtargetInfo *STI;
629 const MCSchedModel &SM;
630 const TargetSubtargetInfo *ST;
631 const TargetInstrInfo *TII;
633 const bool UseDFA;
634 /// DFA resources for each slot
636 /// Modulo Reservation Table. When a resource with ID R is consumed in cycle
637 /// C, it is counted in MRT[C mod II][R]. (Used when UseDFA == F)
639 /// The number of scheduled micro operations for each slot. Micro operations
640 /// are assumed to be scheduled one per cycle, starting with the cycle in
641 /// which the instruction is scheduled.
642 llvm::SmallVector<int> NumScheduledMops;
643 /// Each processor resource is associated with a so-called processor resource
644 /// mask. This vector allows to correlate processor resource IDs with
645 /// processor resource masks. There is exactly one element per each processor
646 /// resource declared by the scheduling model.
648 int InitiationInterval = 0;
649 /// The number of micro operations that can be scheduled at a cycle.
650 int IssueWidth;
651
652 int calculateResMIIDFA() const;
653 /// Check if MRT is overbooked
654 bool isOverbooked() const;
655 /// Reserve resources on MRT
656 void reserveResources(const MCSchedClassDesc *SCDesc, int Cycle);
657 /// Unreserve resources on MRT
658 void unreserveResources(const MCSchedClassDesc *SCDesc, int Cycle);
659
660 /// Return M satisfying Dividend = Divisor * X + M, 0 < M < Divisor.
661 /// The slot on MRT to reserve a resource for the cycle C is positiveModulo(C,
662 /// II).
663 int positiveModulo(int Dividend, int Divisor) const {
664 assert(Divisor > 0);
665 int R = Dividend % Divisor;
666 if (R < 0)
667 R += Divisor;
668 return R;
669 }
670
671#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
672 LLVM_DUMP_METHOD void dumpMRT() const;
673#endif
674
675public:
677 ScheduleDAGInstrs *DAG);
678
681
682 /// Check if the resources occupied by a machine instruction are available
683 /// in the current state.
684 LLVM_ABI bool canReserveResources(SUnit &SU, int Cycle);
685
686 /// Reserve the resources occupied by a machine instruction and change the
687 /// current state to reflect that change.
688 LLVM_ABI void reserveResources(SUnit &SU, int Cycle);
689
690 LLVM_ABI int calculateResMII() const;
691
692 /// Initialize resources with the initiation interval II.
693 LLVM_ABI void init(int II);
694};
695
696/// This class represents the scheduled code. The main data structure is a
697/// map from scheduled cycle to instructions. During scheduling, the
698/// data structure explicitly represents all stages/iterations. When
699/// the algorithm finshes, the schedule is collapsed into a single stage,
700/// which represents instructions from different loop iterations.
701///
702/// The SMS algorithm allows negative values for cycles, so the first cycle
703/// in the schedule is the smallest cycle value.
705private:
706 /// Map from execution cycle to instructions.
707 DenseMap<int, std::deque<SUnit *>> ScheduledInstrs;
708
709 /// Map from instruction to execution cycle.
710 std::map<SUnit *, int> InstrToCycle;
711
712 /// Keep track of the first cycle value in the schedule. It starts
713 /// as zero, but the algorithm allows negative values.
714 int FirstCycle = 0;
715
716 /// Keep track of the last cycle value in the schedule.
717 int LastCycle = 0;
718
719 /// The initiation interval (II) for the schedule.
720 int InitiationInterval = 0;
721
722 /// Target machine information.
723 const TargetSubtargetInfo &ST;
724
725 /// Virtual register information.
727
728 ResourceManager ProcItinResources;
729
730public:
732 : ST(mf->getSubtarget()), MRI(mf->getRegInfo()),
733 ProcItinResources(&ST, DAG) {}
734
735 void reset() {
736 ScheduledInstrs.clear();
737 InstrToCycle.clear();
738 FirstCycle = 0;
739 LastCycle = 0;
740 InitiationInterval = 0;
741 }
742
743 /// Set the initiation interval for this schedule.
745 InitiationInterval = ii;
746 ProcItinResources.init(ii);
747 }
748
749 /// Return the initiation interval for this schedule.
750 int getInitiationInterval() const { return InitiationInterval; }
751
752 /// Return the first cycle in the completed schedule. This
753 /// can be a negative value.
754 int getFirstCycle() const { return FirstCycle; }
755
756 /// Return the last cycle in the finalized schedule.
757 int getFinalCycle() const { return FirstCycle + InitiationInterval - 1; }
758
759 LLVM_ABI void computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
760 int II, SwingSchedulerDAG *DAG);
761 LLVM_ABI bool insert(SUnit *SU, int StartCycle, int EndCycle, int II);
762
763 /// Iterators for the cycle to instruction map.
767
768 /// Return true if the instruction is scheduled at the specified stage.
769 bool isScheduledAtStage(SUnit *SU, unsigned StageNum) {
770 return (stageScheduled(SU) == (int)StageNum);
771 }
772
773 /// Return the stage for a scheduled instruction. Return -1 if
774 /// the instruction has not been scheduled.
775 int stageScheduled(SUnit *SU) const {
776 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
777 if (it == InstrToCycle.end())
778 return -1;
779 return (it->second - FirstCycle) / InitiationInterval;
780 }
781
782 /// Return the cycle for a scheduled instruction. This function normalizes
783 /// the first cycle to be 0.
784 unsigned cycleScheduled(SUnit *SU) const {
785 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
786 assert(it != InstrToCycle.end() && "Instruction hasn't been scheduled.");
787 return (it->second - FirstCycle) % InitiationInterval;
788 }
789
790 /// Return the maximum stage count needed for this schedule.
791 unsigned getMaxStageCount() {
792 return (LastCycle - FirstCycle) / InitiationInterval;
793 }
794
795 /// Return the instructions that are scheduled at the specified cycle.
796 std::deque<SUnit *> &getInstructions(int cycle) {
797 return ScheduledInstrs[cycle];
798 }
799
801 computeUnpipelineableNodes(SwingSchedulerDAG *SSD,
803
804 LLVM_ABI std::deque<SUnit *>
805 reorderInstructions(const SwingSchedulerDAG *SSD,
806 const std::deque<SUnit *> &Instrs) const;
807
808 LLVM_ABI bool
809 normalizeNonPipelinedInstructions(SwingSchedulerDAG *SSD,
811 LLVM_ABI bool isValidSchedule(SwingSchedulerDAG *SSD);
812 LLVM_ABI void finalizeSchedule(SwingSchedulerDAG *SSD);
813 LLVM_ABI void orderDependence(const SwingSchedulerDAG *SSD, SUnit *SU,
814 std::deque<SUnit *> &Insts) const;
815 LLVM_ABI bool isLoopCarried(const SwingSchedulerDAG *SSD,
816 MachineInstr &Phi) const;
817 LLVM_ABI bool isLoopCarriedDefOfUse(const SwingSchedulerDAG *SSD,
818 MachineInstr *Def,
819 MachineOperand &MO) const;
820
821 LLVM_ABI bool
822 onlyHasLoopCarriedOutputOrOrderPreds(SUnit *SU,
823 const SwingSchedulerDDG *DDG) const;
824 LLVM_ABI void print(raw_ostream &os) const;
825 LLVM_ABI void dump() const;
826};
827
828} // end namespace llvm
829
830#endif // LLVM_CODEGEN_MACHINEPIPELINER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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:690
const HexagonInstrInfo * TII
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:409
iterator end()
Definition DenseMap.h:686
Generic base class for all target subtargets.
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:345
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.
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.
SwingSchedulerDAG(MachineFunction &MF, const MachineLoopInfo *MLI, MachineOptimizationRemarkEmitter *ORE, MachineLoop &L, LiveIntervals &lis, const RegisterClassInfo &rci, unsigned II, TargetInstrInfo::PipelinerLoopInfo *PLI, AliasAnalysis *AA)
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:880
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:130
Machine model for scheduling, bundling, and heuristics.
Definition MCSchedule.h:274
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.