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