1044eb2f6SDimitry Andric //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
2b915e9e0SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6b915e9e0SDimitry Andric //
7b915e9e0SDimitry Andric //===----------------------------------------------------------------------===//
8b915e9e0SDimitry Andric //
9b915e9e0SDimitry Andric // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
10b915e9e0SDimitry Andric //
11b915e9e0SDimitry Andric // This SMS implementation is a target-independent back-end pass. When enabled,
12b915e9e0SDimitry Andric // the pass runs just prior to the register allocation pass, while the machine
13b915e9e0SDimitry Andric // IR is in SSA form. If software pipelining is successful, then the original
14b915e9e0SDimitry Andric // loop is replaced by the optimized loop. The optimized loop contains one or
15b915e9e0SDimitry Andric // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
16b915e9e0SDimitry Andric // the instructions cannot be scheduled in a given MII, we increase the MII by
17b915e9e0SDimitry Andric // one and try again.
18b915e9e0SDimitry Andric //
19b915e9e0SDimitry Andric // The SMS implementation is an extension of the ScheduleDAGInstrs class. We
20b915e9e0SDimitry Andric // represent loop carried dependences in the DAG as order edges to the Phi
21b915e9e0SDimitry Andric // nodes. We also perform several passes over the DAG to eliminate unnecessary
22b915e9e0SDimitry Andric // edges that inhibit the ability to pipeline. The implementation uses the
23b915e9e0SDimitry Andric // DFAPacketizer class to compute the minimum initiation interval and the check
24b915e9e0SDimitry Andric // where an instruction may be inserted in the pipelined schedule.
25b915e9e0SDimitry Andric //
26b915e9e0SDimitry Andric // In order for the SMS pass to work, several target specific hooks need to be
27b915e9e0SDimitry Andric // implemented to get information about the loop structure and to rewrite
28b915e9e0SDimitry Andric // instructions.
29b915e9e0SDimitry Andric //
30b915e9e0SDimitry Andric //===----------------------------------------------------------------------===//
31b915e9e0SDimitry Andric
32145449b1SDimitry Andric #include "llvm/CodeGen/MachinePipeliner.h"
33b915e9e0SDimitry Andric #include "llvm/ADT/ArrayRef.h"
34b915e9e0SDimitry Andric #include "llvm/ADT/BitVector.h"
35b915e9e0SDimitry Andric #include "llvm/ADT/DenseMap.h"
36b915e9e0SDimitry Andric #include "llvm/ADT/MapVector.h"
37b915e9e0SDimitry Andric #include "llvm/ADT/PriorityQueue.h"
384df029ccSDimitry Andric #include "llvm/ADT/STLExtras.h"
39344a3780SDimitry Andric #include "llvm/ADT/SetOperations.h"
40b915e9e0SDimitry Andric #include "llvm/ADT/SetVector.h"
41b915e9e0SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
42b915e9e0SDimitry Andric #include "llvm/ADT/SmallSet.h"
43b915e9e0SDimitry Andric #include "llvm/ADT/SmallVector.h"
44b915e9e0SDimitry Andric #include "llvm/ADT/Statistic.h"
457ab83427SDimitry Andric #include "llvm/ADT/iterator_range.h"
46b915e9e0SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
47e3b55780SDimitry Andric #include "llvm/Analysis/CycleAnalysis.h"
48b915e9e0SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
49145449b1SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
50b915e9e0SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
51b915e9e0SDimitry Andric #include "llvm/CodeGen/DFAPacketizer.h"
52044eb2f6SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
53b915e9e0SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
54b915e9e0SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
55b915e9e0SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
56b915e9e0SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
57b915e9e0SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
58b915e9e0SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
59b915e9e0SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h"
60b915e9e0SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
61b915e9e0SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
62b915e9e0SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
631d5ae102SDimitry Andric #include "llvm/CodeGen/ModuloSchedule.h"
644df029ccSDimitry Andric #include "llvm/CodeGen/Register.h"
654df029ccSDimitry Andric #include "llvm/CodeGen/RegisterClassInfo.h"
66b915e9e0SDimitry Andric #include "llvm/CodeGen/RegisterPressure.h"
67b915e9e0SDimitry Andric #include "llvm/CodeGen/ScheduleDAG.h"
68b915e9e0SDimitry Andric #include "llvm/CodeGen/ScheduleDAGMutation.h"
694df029ccSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
70044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
71ac9a064cSDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
72044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
73044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
74eb11fae6SDimitry Andric #include "llvm/Config/llvm-config.h"
75b915e9e0SDimitry Andric #include "llvm/IR/Attributes.h"
76044eb2f6SDimitry Andric #include "llvm/IR/Function.h"
77044eb2f6SDimitry Andric #include "llvm/MC/LaneBitmask.h"
78044eb2f6SDimitry Andric #include "llvm/MC/MCInstrDesc.h"
79b915e9e0SDimitry Andric #include "llvm/MC/MCInstrItineraries.h"
80044eb2f6SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
81044eb2f6SDimitry Andric #include "llvm/Pass.h"
82b915e9e0SDimitry Andric #include "llvm/Support/CommandLine.h"
83044eb2f6SDimitry Andric #include "llvm/Support/Compiler.h"
84b915e9e0SDimitry Andric #include "llvm/Support/Debug.h"
85b915e9e0SDimitry Andric #include "llvm/Support/MathExtras.h"
86b915e9e0SDimitry Andric #include "llvm/Support/raw_ostream.h"
87b915e9e0SDimitry Andric #include <algorithm>
88b915e9e0SDimitry Andric #include <cassert>
89b915e9e0SDimitry Andric #include <climits>
90b915e9e0SDimitry Andric #include <cstdint>
91b915e9e0SDimitry Andric #include <deque>
92b915e9e0SDimitry Andric #include <functional>
93e3b55780SDimitry Andric #include <iomanip>
94b915e9e0SDimitry Andric #include <iterator>
95b915e9e0SDimitry Andric #include <map>
96044eb2f6SDimitry Andric #include <memory>
97e3b55780SDimitry Andric #include <sstream>
98b915e9e0SDimitry Andric #include <tuple>
99b915e9e0SDimitry Andric #include <utility>
100b915e9e0SDimitry Andric #include <vector>
101b915e9e0SDimitry Andric
102b915e9e0SDimitry Andric using namespace llvm;
103b915e9e0SDimitry Andric
104b915e9e0SDimitry Andric #define DEBUG_TYPE "pipeliner"
105b915e9e0SDimitry Andric
106b915e9e0SDimitry Andric STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
107b915e9e0SDimitry Andric STATISTIC(NumPipelined, "Number of loops software pipelined");
108eb11fae6SDimitry Andric STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
109e6d15924SDimitry Andric STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch");
110e6d15924SDimitry Andric STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop");
111e6d15924SDimitry Andric STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader");
112e6d15924SDimitry Andric STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large");
113e6d15924SDimitry Andric STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII");
114e6d15924SDimitry Andric STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found");
115e6d15924SDimitry Andric STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage");
116e6d15924SDimitry Andric STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages");
117b915e9e0SDimitry Andric
118b915e9e0SDimitry Andric /// A command line option to turn software pipelining on or off.
119b915e9e0SDimitry Andric static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
120b915e9e0SDimitry Andric cl::desc("Enable Software Pipelining"));
121b915e9e0SDimitry Andric
122b915e9e0SDimitry Andric /// A command line option to enable SWP at -Os.
123b915e9e0SDimitry Andric static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
124b915e9e0SDimitry Andric cl::desc("Enable SWP at Os."), cl::Hidden,
125b915e9e0SDimitry Andric cl::init(false));
126b915e9e0SDimitry Andric
127b915e9e0SDimitry Andric /// A command line argument to limit minimum initial interval for pipelining.
128b915e9e0SDimitry Andric static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
129eb11fae6SDimitry Andric cl::desc("Size limit for the MII."),
130b915e9e0SDimitry Andric cl::Hidden, cl::init(27));
131b915e9e0SDimitry Andric
132e3b55780SDimitry Andric /// A command line argument to force pipeliner to use specified initial
133e3b55780SDimitry Andric /// interval.
134e3b55780SDimitry Andric static cl::opt<int> SwpForceII("pipeliner-force-ii",
135e3b55780SDimitry Andric cl::desc("Force pipeliner to use specified II."),
136e3b55780SDimitry Andric cl::Hidden, cl::init(-1));
137e3b55780SDimitry Andric
138b915e9e0SDimitry Andric /// A command line argument to limit the number of stages in the pipeline.
139b915e9e0SDimitry Andric static cl::opt<int>
140b915e9e0SDimitry Andric SwpMaxStages("pipeliner-max-stages",
141b915e9e0SDimitry Andric cl::desc("Maximum stages allowed in the generated scheduled."),
142b915e9e0SDimitry Andric cl::Hidden, cl::init(3));
143b915e9e0SDimitry Andric
144b915e9e0SDimitry Andric /// A command line option to disable the pruning of chain dependences due to
145b915e9e0SDimitry Andric /// an unrelated Phi.
146b915e9e0SDimitry Andric static cl::opt<bool>
147b915e9e0SDimitry Andric SwpPruneDeps("pipeliner-prune-deps",
148b915e9e0SDimitry Andric cl::desc("Prune dependences between unrelated Phi nodes."),
149b915e9e0SDimitry Andric cl::Hidden, cl::init(true));
150b915e9e0SDimitry Andric
151b915e9e0SDimitry Andric /// A command line option to disable the pruning of loop carried order
152b915e9e0SDimitry Andric /// dependences.
153b915e9e0SDimitry Andric static cl::opt<bool>
154b915e9e0SDimitry Andric SwpPruneLoopCarried("pipeliner-prune-loop-carried",
155b915e9e0SDimitry Andric cl::desc("Prune loop carried order dependences."),
156b915e9e0SDimitry Andric cl::Hidden, cl::init(true));
157b915e9e0SDimitry Andric
158b915e9e0SDimitry Andric #ifndef NDEBUG
159b915e9e0SDimitry Andric static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
160b915e9e0SDimitry Andric #endif
161b915e9e0SDimitry Andric
162b915e9e0SDimitry Andric static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
163145449b1SDimitry Andric cl::ReallyHidden,
164145449b1SDimitry Andric cl::desc("Ignore RecMII"));
165b915e9e0SDimitry Andric
166e6d15924SDimitry Andric static cl::opt<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden,
167e6d15924SDimitry Andric cl::init(false));
168e6d15924SDimitry Andric static cl::opt<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden,
169e6d15924SDimitry Andric cl::init(false));
170e6d15924SDimitry Andric
1711d5ae102SDimitry Andric static cl::opt<bool> EmitTestAnnotations(
1721d5ae102SDimitry Andric "pipeliner-annotate-for-testing", cl::Hidden, cl::init(false),
1731d5ae102SDimitry Andric cl::desc("Instead of emitting the pipelined code, annotate instructions "
1741d5ae102SDimitry Andric "with the generated schedule for feeding into the "
1751d5ae102SDimitry Andric "-modulo-schedule-test pass"));
1761d5ae102SDimitry Andric
1771d5ae102SDimitry Andric static cl::opt<bool> ExperimentalCodeGen(
1781d5ae102SDimitry Andric "pipeliner-experimental-cg", cl::Hidden, cl::init(false),
1791d5ae102SDimitry Andric cl::desc(
1801d5ae102SDimitry Andric "Use the experimental peeling code generator for software pipelining"));
1811d5ae102SDimitry Andric
1824df029ccSDimitry Andric static cl::opt<int> SwpIISearchRange("pipeliner-ii-search-range",
1834df029ccSDimitry Andric cl::desc("Range to search for II"),
1844df029ccSDimitry Andric cl::Hidden, cl::init(10));
1854df029ccSDimitry Andric
1864df029ccSDimitry Andric static cl::opt<bool>
1874df029ccSDimitry Andric LimitRegPressure("pipeliner-register-pressure", cl::Hidden, cl::init(false),
1884df029ccSDimitry Andric cl::desc("Limit register pressure of scheduled loop"));
1894df029ccSDimitry Andric
1904df029ccSDimitry Andric static cl::opt<int>
1914df029ccSDimitry Andric RegPressureMargin("pipeliner-register-pressure-margin", cl::Hidden,
1924df029ccSDimitry Andric cl::init(5),
1934df029ccSDimitry Andric cl::desc("Margin representing the unused percentage of "
1944df029ccSDimitry Andric "the register pressure limit"));
1954df029ccSDimitry Andric
196ac9a064cSDimitry Andric static cl::opt<bool>
197ac9a064cSDimitry Andric MVECodeGen("pipeliner-mve-cg", cl::Hidden, cl::init(false),
198ac9a064cSDimitry Andric cl::desc("Use the MVE code generator for software pipelining"));
199ac9a064cSDimitry Andric
200d8e91e46SDimitry Andric namespace llvm {
201b915e9e0SDimitry Andric
202d8e91e46SDimitry Andric // A command line option to enable the CopyToPhi DAG mutation.
203145449b1SDimitry Andric cl::opt<bool> SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
204145449b1SDimitry Andric cl::init(true),
205d8e91e46SDimitry Andric cl::desc("Enable CopyToPhi DAG Mutation"));
206b915e9e0SDimitry Andric
207e3b55780SDimitry Andric /// A command line argument to force pipeliner to use specified issue
208e3b55780SDimitry Andric /// width.
209e3b55780SDimitry Andric cl::opt<int> SwpForceIssueWidth(
210e3b55780SDimitry Andric "pipeliner-force-issue-width",
211e3b55780SDimitry Andric cl::desc("Force pipeliner to use specified issue width."), cl::Hidden,
212e3b55780SDimitry Andric cl::init(-1));
213e3b55780SDimitry Andric
214ac9a064cSDimitry Andric /// A command line argument to set the window scheduling option.
215ac9a064cSDimitry Andric cl::opt<WindowSchedulingFlag> WindowSchedulingOption(
216ac9a064cSDimitry Andric "window-sched", cl::Hidden, cl::init(WindowSchedulingFlag::WS_On),
217ac9a064cSDimitry Andric cl::desc("Set how to use window scheduling algorithm."),
218ac9a064cSDimitry Andric cl::values(clEnumValN(WindowSchedulingFlag::WS_Off, "off",
219ac9a064cSDimitry Andric "Turn off window algorithm."),
220ac9a064cSDimitry Andric clEnumValN(WindowSchedulingFlag::WS_On, "on",
221ac9a064cSDimitry Andric "Use window algorithm after SMS algorithm fails."),
222ac9a064cSDimitry Andric clEnumValN(WindowSchedulingFlag::WS_Force, "force",
223ac9a064cSDimitry Andric "Use window algorithm instead of SMS algorithm.")));
224ac9a064cSDimitry Andric
225d8e91e46SDimitry Andric } // end namespace llvm
226b915e9e0SDimitry Andric
227b915e9e0SDimitry Andric unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
228b915e9e0SDimitry Andric char MachinePipeliner::ID = 0;
229b915e9e0SDimitry Andric #ifndef NDEBUG
230b915e9e0SDimitry Andric int MachinePipeliner::NumTries = 0;
231b915e9e0SDimitry Andric #endif
232b915e9e0SDimitry Andric char &llvm::MachinePipelinerID = MachinePipeliner::ID;
233044eb2f6SDimitry Andric
234ab44ce3dSDimitry Andric INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
235b915e9e0SDimitry Andric "Modulo Software Pipelining", false, false)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)236b915e9e0SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
237ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
238ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
239ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)
240ab44ce3dSDimitry Andric INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
241b915e9e0SDimitry Andric "Modulo Software Pipelining", false, false)
242b915e9e0SDimitry Andric
243b915e9e0SDimitry Andric /// The "main" function for implementing Swing Modulo Scheduling.
244b915e9e0SDimitry Andric bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
245044eb2f6SDimitry Andric if (skipFunction(mf.getFunction()))
246b915e9e0SDimitry Andric return false;
247b915e9e0SDimitry Andric
248b915e9e0SDimitry Andric if (!EnableSWP)
249b915e9e0SDimitry Andric return false;
250b915e9e0SDimitry Andric
251c0981da4SDimitry Andric if (mf.getFunction().getAttributes().hasFnAttr(Attribute::OptimizeForSize) &&
252b915e9e0SDimitry Andric !EnableSWPOptSize.getPosition())
253b915e9e0SDimitry Andric return false;
254b915e9e0SDimitry Andric
255e6d15924SDimitry Andric if (!mf.getSubtarget().enableMachinePipeliner())
256e6d15924SDimitry Andric return false;
257e6d15924SDimitry Andric
258e6d15924SDimitry Andric // Cannot pipeline loops without instruction itineraries if we are using
259e6d15924SDimitry Andric // DFA for the pipeliner.
260e6d15924SDimitry Andric if (mf.getSubtarget().useDFAforSMS() &&
261e6d15924SDimitry Andric (!mf.getSubtarget().getInstrItineraryData() ||
262e6d15924SDimitry Andric mf.getSubtarget().getInstrItineraryData()->isEmpty()))
263e6d15924SDimitry Andric return false;
264e6d15924SDimitry Andric
265b915e9e0SDimitry Andric MF = &mf;
266ac9a064cSDimitry Andric MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
267ac9a064cSDimitry Andric MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
268cfca06d7SDimitry Andric ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
269b915e9e0SDimitry Andric TII = MF->getSubtarget().getInstrInfo();
270b915e9e0SDimitry Andric RegClassInfo.runOnMachineFunction(*MF);
271b915e9e0SDimitry Andric
2724b4fe385SDimitry Andric for (const auto &L : *MLI)
273b915e9e0SDimitry Andric scheduleLoop(*L);
274b915e9e0SDimitry Andric
275b915e9e0SDimitry Andric return false;
276b915e9e0SDimitry Andric }
277b915e9e0SDimitry Andric
278b915e9e0SDimitry Andric /// Attempt to perform the SMS algorithm on the specified loop. This function is
279b915e9e0SDimitry Andric /// the main entry point for the algorithm. The function identifies candidate
280b915e9e0SDimitry Andric /// loops, calculates the minimum initiation interval, and attempts to schedule
281b915e9e0SDimitry Andric /// the loop.
scheduleLoop(MachineLoop & L)282b915e9e0SDimitry Andric bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
283b915e9e0SDimitry Andric bool Changed = false;
2844b4fe385SDimitry Andric for (const auto &InnerLoop : L)
285b915e9e0SDimitry Andric Changed |= scheduleLoop(*InnerLoop);
286b915e9e0SDimitry Andric
287b915e9e0SDimitry Andric #ifndef NDEBUG
288b915e9e0SDimitry Andric // Stop trying after reaching the limit (if any).
289b915e9e0SDimitry Andric int Limit = SwpLoopLimit;
290b915e9e0SDimitry Andric if (Limit >= 0) {
291b915e9e0SDimitry Andric if (NumTries >= SwpLoopLimit)
292b915e9e0SDimitry Andric return Changed;
293b915e9e0SDimitry Andric NumTries++;
294b915e9e0SDimitry Andric }
295b915e9e0SDimitry Andric #endif
296b915e9e0SDimitry Andric
297e6d15924SDimitry Andric setPragmaPipelineOptions(L);
298e6d15924SDimitry Andric if (!canPipelineLoop(L)) {
299e6d15924SDimitry Andric LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
300cfca06d7SDimitry Andric ORE->emit([&]() {
301cfca06d7SDimitry Andric return MachineOptimizationRemarkMissed(DEBUG_TYPE, "canPipelineLoop",
302cfca06d7SDimitry Andric L.getStartLoc(), L.getHeader())
303cfca06d7SDimitry Andric << "Failed to pipeline loop";
304cfca06d7SDimitry Andric });
305cfca06d7SDimitry Andric
306145449b1SDimitry Andric LI.LoopPipelinerInfo.reset();
307b915e9e0SDimitry Andric return Changed;
308e6d15924SDimitry Andric }
309b915e9e0SDimitry Andric
310b915e9e0SDimitry Andric ++NumTrytoPipeline;
311ac9a064cSDimitry Andric if (useSwingModuloScheduler())
312b915e9e0SDimitry Andric Changed = swingModuloScheduler(L);
313b915e9e0SDimitry Andric
314ac9a064cSDimitry Andric if (useWindowScheduler(Changed))
315ac9a064cSDimitry Andric Changed = runWindowScheduler(L);
316ac9a064cSDimitry Andric
317145449b1SDimitry Andric LI.LoopPipelinerInfo.reset();
318b915e9e0SDimitry Andric return Changed;
319b915e9e0SDimitry Andric }
320b915e9e0SDimitry Andric
setPragmaPipelineOptions(MachineLoop & L)321e6d15924SDimitry Andric void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
322cfca06d7SDimitry Andric // Reset the pragma for the next loop in iteration.
323cfca06d7SDimitry Andric disabledByPragma = false;
324b60736ecSDimitry Andric II_setByPragma = 0;
325cfca06d7SDimitry Andric
326e6d15924SDimitry Andric MachineBasicBlock *LBLK = L.getTopBlock();
327e6d15924SDimitry Andric
328e6d15924SDimitry Andric if (LBLK == nullptr)
329e6d15924SDimitry Andric return;
330e6d15924SDimitry Andric
331e6d15924SDimitry Andric const BasicBlock *BBLK = LBLK->getBasicBlock();
332e6d15924SDimitry Andric if (BBLK == nullptr)
333e6d15924SDimitry Andric return;
334e6d15924SDimitry Andric
335e6d15924SDimitry Andric const Instruction *TI = BBLK->getTerminator();
336e6d15924SDimitry Andric if (TI == nullptr)
337e6d15924SDimitry Andric return;
338e6d15924SDimitry Andric
339e6d15924SDimitry Andric MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
340e6d15924SDimitry Andric if (LoopID == nullptr)
341e6d15924SDimitry Andric return;
342e6d15924SDimitry Andric
343e6d15924SDimitry Andric assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
344e6d15924SDimitry Andric assert(LoopID->getOperand(0) == LoopID && "invalid loop");
345e6d15924SDimitry Andric
346ac9a064cSDimitry Andric for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
347ac9a064cSDimitry Andric MDNode *MD = dyn_cast<MDNode>(MDO);
348e6d15924SDimitry Andric
349e6d15924SDimitry Andric if (MD == nullptr)
350e6d15924SDimitry Andric continue;
351e6d15924SDimitry Andric
352e6d15924SDimitry Andric MDString *S = dyn_cast<MDString>(MD->getOperand(0));
353e6d15924SDimitry Andric
354e6d15924SDimitry Andric if (S == nullptr)
355e6d15924SDimitry Andric continue;
356e6d15924SDimitry Andric
357e6d15924SDimitry Andric if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
358e6d15924SDimitry Andric assert(MD->getNumOperands() == 2 &&
359e6d15924SDimitry Andric "Pipeline initiation interval hint metadata should have two operands.");
360e6d15924SDimitry Andric II_setByPragma =
361e6d15924SDimitry Andric mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
362e6d15924SDimitry Andric assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
363e6d15924SDimitry Andric } else if (S->getString() == "llvm.loop.pipeline.disable") {
364e6d15924SDimitry Andric disabledByPragma = true;
365e6d15924SDimitry Andric }
366e6d15924SDimitry Andric }
367e6d15924SDimitry Andric }
368e6d15924SDimitry Andric
369b915e9e0SDimitry Andric /// Return true if the loop can be software pipelined. The algorithm is
370b915e9e0SDimitry Andric /// restricted to loops with a single basic block. Make sure that the
371b915e9e0SDimitry Andric /// branch in the loop can be analyzed.
canPipelineLoop(MachineLoop & L)372b915e9e0SDimitry Andric bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
373cfca06d7SDimitry Andric if (L.getNumBlocks() != 1) {
374cfca06d7SDimitry Andric ORE->emit([&]() {
375cfca06d7SDimitry Andric return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
376cfca06d7SDimitry Andric L.getStartLoc(), L.getHeader())
377cfca06d7SDimitry Andric << "Not a single basic block: "
378cfca06d7SDimitry Andric << ore::NV("NumBlocks", L.getNumBlocks());
379cfca06d7SDimitry Andric });
380b915e9e0SDimitry Andric return false;
381cfca06d7SDimitry Andric }
382b915e9e0SDimitry Andric
383cfca06d7SDimitry Andric if (disabledByPragma) {
384cfca06d7SDimitry Andric ORE->emit([&]() {
385cfca06d7SDimitry Andric return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
386cfca06d7SDimitry Andric L.getStartLoc(), L.getHeader())
387cfca06d7SDimitry Andric << "Disabled by Pragma.";
388cfca06d7SDimitry Andric });
389e6d15924SDimitry Andric return false;
390cfca06d7SDimitry Andric }
391e6d15924SDimitry Andric
392b915e9e0SDimitry Andric // Check if the branch can't be understood because we can't do pipelining
393b915e9e0SDimitry Andric // if that's the case.
394b915e9e0SDimitry Andric LI.TBB = nullptr;
395b915e9e0SDimitry Andric LI.FBB = nullptr;
396b915e9e0SDimitry Andric LI.BrCond.clear();
397e6d15924SDimitry Andric if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
398cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << "Unable to analyzeBranch, can NOT pipeline Loop\n");
399e6d15924SDimitry Andric NumFailBranch++;
400cfca06d7SDimitry Andric ORE->emit([&]() {
401cfca06d7SDimitry Andric return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
402cfca06d7SDimitry Andric L.getStartLoc(), L.getHeader())
403cfca06d7SDimitry Andric << "The branch can't be understood";
404cfca06d7SDimitry Andric });
405b915e9e0SDimitry Andric return false;
406e6d15924SDimitry Andric }
407b915e9e0SDimitry Andric
408b915e9e0SDimitry Andric LI.LoopInductionVar = nullptr;
409b915e9e0SDimitry Andric LI.LoopCompare = nullptr;
410145449b1SDimitry Andric LI.LoopPipelinerInfo = TII->analyzeLoopForPipelining(L.getTopBlock());
411145449b1SDimitry Andric if (!LI.LoopPipelinerInfo) {
412cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << "Unable to analyzeLoop, can NOT pipeline Loop\n");
413e6d15924SDimitry Andric NumFailLoop++;
414cfca06d7SDimitry Andric ORE->emit([&]() {
415cfca06d7SDimitry Andric return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
416cfca06d7SDimitry Andric L.getStartLoc(), L.getHeader())
417cfca06d7SDimitry Andric << "The loop structure is not supported";
418cfca06d7SDimitry Andric });
419b915e9e0SDimitry Andric return false;
420e6d15924SDimitry Andric }
421b915e9e0SDimitry Andric
422e6d15924SDimitry Andric if (!L.getLoopPreheader()) {
423cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << "Preheader not found, can NOT pipeline Loop\n");
424e6d15924SDimitry Andric NumFailPreheader++;
425cfca06d7SDimitry Andric ORE->emit([&]() {
426cfca06d7SDimitry Andric return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "canPipelineLoop",
427cfca06d7SDimitry Andric L.getStartLoc(), L.getHeader())
428cfca06d7SDimitry Andric << "No loop preheader found";
429cfca06d7SDimitry Andric });
430b915e9e0SDimitry Andric return false;
431e6d15924SDimitry Andric }
432b915e9e0SDimitry Andric
433eb11fae6SDimitry Andric // Remove any subregisters from inputs to phi nodes.
434eb11fae6SDimitry Andric preprocessPhiNodes(*L.getHeader());
435b915e9e0SDimitry Andric return true;
436b915e9e0SDimitry Andric }
437b915e9e0SDimitry Andric
preprocessPhiNodes(MachineBasicBlock & B)438eb11fae6SDimitry Andric void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
439eb11fae6SDimitry Andric MachineRegisterInfo &MRI = MF->getRegInfo();
440ac9a064cSDimitry Andric SlotIndexes &Slots =
441ac9a064cSDimitry Andric *getAnalysis<LiveIntervalsWrapperPass>().getLIS().getSlotIndexes();
442eb11fae6SDimitry Andric
443c0981da4SDimitry Andric for (MachineInstr &PI : B.phis()) {
444eb11fae6SDimitry Andric MachineOperand &DefOp = PI.getOperand(0);
445eb11fae6SDimitry Andric assert(DefOp.getSubReg() == 0);
446eb11fae6SDimitry Andric auto *RC = MRI.getRegClass(DefOp.getReg());
447eb11fae6SDimitry Andric
448eb11fae6SDimitry Andric for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
449eb11fae6SDimitry Andric MachineOperand &RegOp = PI.getOperand(i);
450eb11fae6SDimitry Andric if (RegOp.getSubReg() == 0)
451eb11fae6SDimitry Andric continue;
452eb11fae6SDimitry Andric
453eb11fae6SDimitry Andric // If the operand uses a subregister, replace it with a new register
454eb11fae6SDimitry Andric // without subregisters, and generate a copy to the new register.
4551d5ae102SDimitry Andric Register NewReg = MRI.createVirtualRegister(RC);
456eb11fae6SDimitry Andric MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
457eb11fae6SDimitry Andric MachineBasicBlock::iterator At = PredB.getFirstTerminator();
458eb11fae6SDimitry Andric const DebugLoc &DL = PredB.findDebugLoc(At);
459eb11fae6SDimitry Andric auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
460eb11fae6SDimitry Andric .addReg(RegOp.getReg(), getRegState(RegOp),
461eb11fae6SDimitry Andric RegOp.getSubReg());
462eb11fae6SDimitry Andric Slots.insertMachineInstrInMaps(*Copy);
463eb11fae6SDimitry Andric RegOp.setReg(NewReg);
464eb11fae6SDimitry Andric RegOp.setSubReg(0);
465eb11fae6SDimitry Andric }
466eb11fae6SDimitry Andric }
467eb11fae6SDimitry Andric }
468eb11fae6SDimitry Andric
469b915e9e0SDimitry Andric /// The SMS algorithm consists of the following main steps:
470b915e9e0SDimitry Andric /// 1. Computation and analysis of the dependence graph.
471b915e9e0SDimitry Andric /// 2. Ordering of the nodes (instructions).
472b915e9e0SDimitry Andric /// 3. Attempt to Schedule the loop.
swingModuloScheduler(MachineLoop & L)473b915e9e0SDimitry Andric bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
474b915e9e0SDimitry Andric assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
475b915e9e0SDimitry Andric
476ac9a064cSDimitry Andric SwingSchedulerDAG SMS(
477ac9a064cSDimitry Andric *this, L, getAnalysis<LiveIntervalsWrapperPass>().getLIS(), RegClassInfo,
478145449b1SDimitry Andric II_setByPragma, LI.LoopPipelinerInfo.get());
479b915e9e0SDimitry Andric
480b915e9e0SDimitry Andric MachineBasicBlock *MBB = L.getHeader();
481b915e9e0SDimitry Andric // The kernel should not include any terminator instructions. These
482b915e9e0SDimitry Andric // will be added back later.
483b915e9e0SDimitry Andric SMS.startBlock(MBB);
484b915e9e0SDimitry Andric
485b915e9e0SDimitry Andric // Compute the number of 'real' instructions in the basic block by
486b915e9e0SDimitry Andric // ignoring terminators.
487b915e9e0SDimitry Andric unsigned size = MBB->size();
488b915e9e0SDimitry Andric for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
489b915e9e0SDimitry Andric E = MBB->instr_end();
490b915e9e0SDimitry Andric I != E; ++I, --size)
491b915e9e0SDimitry Andric ;
492b915e9e0SDimitry Andric
493b915e9e0SDimitry Andric SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
494b915e9e0SDimitry Andric SMS.schedule();
495b915e9e0SDimitry Andric SMS.exitRegion();
496b915e9e0SDimitry Andric
497b915e9e0SDimitry Andric SMS.finishBlock();
498b915e9e0SDimitry Andric return SMS.hasNewSchedule();
499b915e9e0SDimitry Andric }
500b915e9e0SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const501b60736ecSDimitry Andric void MachinePipeliner::getAnalysisUsage(AnalysisUsage &AU) const {
502b60736ecSDimitry Andric AU.addRequired<AAResultsWrapperPass>();
503b60736ecSDimitry Andric AU.addPreserved<AAResultsWrapperPass>();
504ac9a064cSDimitry Andric AU.addRequired<MachineLoopInfoWrapperPass>();
505ac9a064cSDimitry Andric AU.addRequired<MachineDominatorTreeWrapperPass>();
506ac9a064cSDimitry Andric AU.addRequired<LiveIntervalsWrapperPass>();
507b60736ecSDimitry Andric AU.addRequired<MachineOptimizationRemarkEmitterPass>();
508ac9a064cSDimitry Andric AU.addRequired<TargetPassConfig>();
509b60736ecSDimitry Andric MachineFunctionPass::getAnalysisUsage(AU);
510b60736ecSDimitry Andric }
511b60736ecSDimitry Andric
runWindowScheduler(MachineLoop & L)512ac9a064cSDimitry Andric bool MachinePipeliner::runWindowScheduler(MachineLoop &L) {
513ac9a064cSDimitry Andric MachineSchedContext Context;
514ac9a064cSDimitry Andric Context.MF = MF;
515ac9a064cSDimitry Andric Context.MLI = MLI;
516ac9a064cSDimitry Andric Context.MDT = MDT;
517ac9a064cSDimitry Andric Context.PassConfig = &getAnalysis<TargetPassConfig>();
518ac9a064cSDimitry Andric Context.AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
519ac9a064cSDimitry Andric Context.LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
520ac9a064cSDimitry Andric Context.RegClassInfo->runOnMachineFunction(*MF);
521ac9a064cSDimitry Andric WindowScheduler WS(&Context, L);
522ac9a064cSDimitry Andric return WS.run();
523ac9a064cSDimitry Andric }
524ac9a064cSDimitry Andric
useSwingModuloScheduler()525ac9a064cSDimitry Andric bool MachinePipeliner::useSwingModuloScheduler() {
526ac9a064cSDimitry Andric // SwingModuloScheduler does not work when WindowScheduler is forced.
527ac9a064cSDimitry Andric return WindowSchedulingOption != WindowSchedulingFlag::WS_Force;
528ac9a064cSDimitry Andric }
529ac9a064cSDimitry Andric
useWindowScheduler(bool Changed)530ac9a064cSDimitry Andric bool MachinePipeliner::useWindowScheduler(bool Changed) {
5317432c960SDimitry Andric // WindowScheduler does not work for following cases:
5327432c960SDimitry Andric // 1. when it is off.
5337432c960SDimitry Andric // 2. when SwingModuloScheduler is successfully scheduled.
5347432c960SDimitry Andric // 3. when pragma II is enabled.
5357432c960SDimitry Andric if (II_setByPragma) {
5367432c960SDimitry Andric LLVM_DEBUG(dbgs() << "Window scheduling is disabled when "
5377432c960SDimitry Andric "llvm.loop.pipeline.initiationinterval is set.\n");
5387432c960SDimitry Andric return false;
5397432c960SDimitry Andric }
5407432c960SDimitry Andric
541ac9a064cSDimitry Andric return WindowSchedulingOption == WindowSchedulingFlag::WS_Force ||
542ac9a064cSDimitry Andric (WindowSchedulingOption == WindowSchedulingFlag::WS_On && !Changed);
543ac9a064cSDimitry Andric }
544ac9a064cSDimitry Andric
setMII(unsigned ResMII,unsigned RecMII)545e6d15924SDimitry Andric void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
546e3b55780SDimitry Andric if (SwpForceII > 0)
547e3b55780SDimitry Andric MII = SwpForceII;
548e3b55780SDimitry Andric else if (II_setByPragma > 0)
549e6d15924SDimitry Andric MII = II_setByPragma;
550e6d15924SDimitry Andric else
551e6d15924SDimitry Andric MII = std::max(ResMII, RecMII);
552e6d15924SDimitry Andric }
553e6d15924SDimitry Andric
setMAX_II()554e6d15924SDimitry Andric void SwingSchedulerDAG::setMAX_II() {
555e3b55780SDimitry Andric if (SwpForceII > 0)
556e3b55780SDimitry Andric MAX_II = SwpForceII;
557e3b55780SDimitry Andric else if (II_setByPragma > 0)
558e6d15924SDimitry Andric MAX_II = II_setByPragma;
559e6d15924SDimitry Andric else
5604df029ccSDimitry Andric MAX_II = MII + SwpIISearchRange;
561e6d15924SDimitry Andric }
562e6d15924SDimitry Andric
563b915e9e0SDimitry Andric /// We override the schedule function in ScheduleDAGInstrs to implement the
564b915e9e0SDimitry Andric /// scheduling part of the Swing Modulo Scheduling algorithm.
schedule()565b915e9e0SDimitry Andric void SwingSchedulerDAG::schedule() {
566b915e9e0SDimitry Andric AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
567b915e9e0SDimitry Andric buildSchedGraph(AA);
568b915e9e0SDimitry Andric addLoopCarriedDependences(AA);
569b915e9e0SDimitry Andric updatePhiDependences();
570b915e9e0SDimitry Andric Topo.InitDAGTopologicalSorting();
571b915e9e0SDimitry Andric changeDependences();
5727fa27ce4SDimitry Andric postProcessDAG();
573d8e91e46SDimitry Andric LLVM_DEBUG(dump());
574b915e9e0SDimitry Andric
575b915e9e0SDimitry Andric NodeSetType NodeSets;
576b915e9e0SDimitry Andric findCircuits(NodeSets);
577eb11fae6SDimitry Andric NodeSetType Circuits = NodeSets;
578b915e9e0SDimitry Andric
579b915e9e0SDimitry Andric // Calculate the MII.
580b915e9e0SDimitry Andric unsigned ResMII = calculateResMII();
581b915e9e0SDimitry Andric unsigned RecMII = calculateRecMII(NodeSets);
582b915e9e0SDimitry Andric
583b915e9e0SDimitry Andric fuseRecs(NodeSets);
584b915e9e0SDimitry Andric
585b915e9e0SDimitry Andric // This flag is used for testing and can cause correctness problems.
586b915e9e0SDimitry Andric if (SwpIgnoreRecMII)
587b915e9e0SDimitry Andric RecMII = 0;
588b915e9e0SDimitry Andric
589e6d15924SDimitry Andric setMII(ResMII, RecMII);
590e6d15924SDimitry Andric setMAX_II();
591e6d15924SDimitry Andric
592e6d15924SDimitry Andric LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
593e6d15924SDimitry Andric << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
594b915e9e0SDimitry Andric
595b915e9e0SDimitry Andric // Can't schedule a loop without a valid MII.
596e6d15924SDimitry Andric if (MII == 0) {
597cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << "Invalid Minimal Initiation Interval: 0\n");
598e6d15924SDimitry Andric NumFailZeroMII++;
599cfca06d7SDimitry Andric Pass.ORE->emit([&]() {
600cfca06d7SDimitry Andric return MachineOptimizationRemarkAnalysis(
601cfca06d7SDimitry Andric DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
602cfca06d7SDimitry Andric << "Invalid Minimal Initiation Interval: 0";
603cfca06d7SDimitry Andric });
604b915e9e0SDimitry Andric return;
605e6d15924SDimitry Andric }
606b915e9e0SDimitry Andric
607b915e9e0SDimitry Andric // Don't pipeline large loops.
608e6d15924SDimitry Andric if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
609e6d15924SDimitry Andric LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
610145449b1SDimitry Andric << ", we don't pipeline large loops\n");
611e6d15924SDimitry Andric NumFailLargeMaxMII++;
612cfca06d7SDimitry Andric Pass.ORE->emit([&]() {
613cfca06d7SDimitry Andric return MachineOptimizationRemarkAnalysis(
614cfca06d7SDimitry Andric DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
615cfca06d7SDimitry Andric << "Minimal Initiation Interval too large: "
616cfca06d7SDimitry Andric << ore::NV("MII", (int)MII) << " > "
617cfca06d7SDimitry Andric << ore::NV("SwpMaxMii", SwpMaxMii) << "."
618cfca06d7SDimitry Andric << "Refer to -pipeliner-max-mii.";
619cfca06d7SDimitry Andric });
620b915e9e0SDimitry Andric return;
621e6d15924SDimitry Andric }
622b915e9e0SDimitry Andric
623b915e9e0SDimitry Andric computeNodeFunctions(NodeSets);
624b915e9e0SDimitry Andric
625b915e9e0SDimitry Andric registerPressureFilter(NodeSets);
626b915e9e0SDimitry Andric
627b915e9e0SDimitry Andric colocateNodeSets(NodeSets);
628b915e9e0SDimitry Andric
629b915e9e0SDimitry Andric checkNodeSets(NodeSets);
630b915e9e0SDimitry Andric
631eb11fae6SDimitry Andric LLVM_DEBUG({
632b915e9e0SDimitry Andric for (auto &I : NodeSets) {
633b915e9e0SDimitry Andric dbgs() << " Rec NodeSet ";
634b915e9e0SDimitry Andric I.dump();
635b915e9e0SDimitry Andric }
636b915e9e0SDimitry Andric });
637b915e9e0SDimitry Andric
638e6d15924SDimitry Andric llvm::stable_sort(NodeSets, std::greater<NodeSet>());
639b915e9e0SDimitry Andric
640b915e9e0SDimitry Andric groupRemainingNodes(NodeSets);
641b915e9e0SDimitry Andric
642b915e9e0SDimitry Andric removeDuplicateNodes(NodeSets);
643b915e9e0SDimitry Andric
644eb11fae6SDimitry Andric LLVM_DEBUG({
645b915e9e0SDimitry Andric for (auto &I : NodeSets) {
646b915e9e0SDimitry Andric dbgs() << " NodeSet ";
647b915e9e0SDimitry Andric I.dump();
648b915e9e0SDimitry Andric }
649b915e9e0SDimitry Andric });
650b915e9e0SDimitry Andric
651b915e9e0SDimitry Andric computeNodeOrder(NodeSets);
652b915e9e0SDimitry Andric
653eb11fae6SDimitry Andric // check for node order issues
654eb11fae6SDimitry Andric checkValidNodeOrder(Circuits);
655eb11fae6SDimitry Andric
656e3b55780SDimitry Andric SMSchedule Schedule(Pass.MF, this);
657b915e9e0SDimitry Andric Scheduled = schedulePipeline(Schedule);
658b915e9e0SDimitry Andric
659e6d15924SDimitry Andric if (!Scheduled){
660e6d15924SDimitry Andric LLVM_DEBUG(dbgs() << "No schedule found, return\n");
661e6d15924SDimitry Andric NumFailNoSchedule++;
662cfca06d7SDimitry Andric Pass.ORE->emit([&]() {
663cfca06d7SDimitry Andric return MachineOptimizationRemarkAnalysis(
664cfca06d7SDimitry Andric DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
665cfca06d7SDimitry Andric << "Unable to find schedule";
666cfca06d7SDimitry Andric });
667b915e9e0SDimitry Andric return;
668e6d15924SDimitry Andric }
669b915e9e0SDimitry Andric
670b915e9e0SDimitry Andric unsigned numStages = Schedule.getMaxStageCount();
671b915e9e0SDimitry Andric // No need to generate pipeline if there are no overlapped iterations.
672e6d15924SDimitry Andric if (numStages == 0) {
673cfca06d7SDimitry Andric LLVM_DEBUG(dbgs() << "No overlapped iterations, skip.\n");
674e6d15924SDimitry Andric NumFailZeroStage++;
675cfca06d7SDimitry Andric Pass.ORE->emit([&]() {
676cfca06d7SDimitry Andric return MachineOptimizationRemarkAnalysis(
677cfca06d7SDimitry Andric DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
678cfca06d7SDimitry Andric << "No need to pipeline - no overlapped iterations in schedule.";
679cfca06d7SDimitry Andric });
680b915e9e0SDimitry Andric return;
681e6d15924SDimitry Andric }
682b915e9e0SDimitry Andric // Check that the maximum stage count is less than user-defined limit.
683e6d15924SDimitry Andric if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
684e6d15924SDimitry Andric LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
685e6d15924SDimitry Andric << " : too many stages, abort\n");
686e6d15924SDimitry Andric NumFailLargeMaxStage++;
687cfca06d7SDimitry Andric Pass.ORE->emit([&]() {
688cfca06d7SDimitry Andric return MachineOptimizationRemarkAnalysis(
689cfca06d7SDimitry Andric DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
690cfca06d7SDimitry Andric << "Too many stages in schedule: "
691cfca06d7SDimitry Andric << ore::NV("numStages", (int)numStages) << " > "
692cfca06d7SDimitry Andric << ore::NV("SwpMaxStages", SwpMaxStages)
693cfca06d7SDimitry Andric << ". Refer to -pipeliner-max-stages.";
694cfca06d7SDimitry Andric });
695b915e9e0SDimitry Andric return;
696e6d15924SDimitry Andric }
697b915e9e0SDimitry Andric
698cfca06d7SDimitry Andric Pass.ORE->emit([&]() {
699cfca06d7SDimitry Andric return MachineOptimizationRemark(DEBUG_TYPE, "schedule", Loop.getStartLoc(),
700cfca06d7SDimitry Andric Loop.getHeader())
701cfca06d7SDimitry Andric << "Pipelined succesfully!";
702cfca06d7SDimitry Andric });
703cfca06d7SDimitry Andric
7041d5ae102SDimitry Andric // Generate the schedule as a ModuloSchedule.
7051d5ae102SDimitry Andric DenseMap<MachineInstr *, int> Cycles, Stages;
7061d5ae102SDimitry Andric std::vector<MachineInstr *> OrderedInsts;
7071d5ae102SDimitry Andric for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
7081d5ae102SDimitry Andric ++Cycle) {
7091d5ae102SDimitry Andric for (SUnit *SU : Schedule.getInstructions(Cycle)) {
7101d5ae102SDimitry Andric OrderedInsts.push_back(SU->getInstr());
7111d5ae102SDimitry Andric Cycles[SU->getInstr()] = Cycle;
7121d5ae102SDimitry Andric Stages[SU->getInstr()] = Schedule.stageScheduled(SU);
7131d5ae102SDimitry Andric }
7141d5ae102SDimitry Andric }
7151d5ae102SDimitry Andric DenseMap<MachineInstr *, std::pair<unsigned, int64_t>> NewInstrChanges;
7161d5ae102SDimitry Andric for (auto &KV : NewMIs) {
7171d5ae102SDimitry Andric Cycles[KV.first] = Cycles[KV.second];
7181d5ae102SDimitry Andric Stages[KV.first] = Stages[KV.second];
7191d5ae102SDimitry Andric NewInstrChanges[KV.first] = InstrChanges[getSUnit(KV.first)];
7201d5ae102SDimitry Andric }
7211d5ae102SDimitry Andric
7221d5ae102SDimitry Andric ModuloSchedule MS(MF, &Loop, std::move(OrderedInsts), std::move(Cycles),
7231d5ae102SDimitry Andric std::move(Stages));
7241d5ae102SDimitry Andric if (EmitTestAnnotations) {
7251d5ae102SDimitry Andric assert(NewInstrChanges.empty() &&
7261d5ae102SDimitry Andric "Cannot serialize a schedule with InstrChanges!");
7271d5ae102SDimitry Andric ModuloScheduleTestAnnotater MSTI(MF, MS);
7281d5ae102SDimitry Andric MSTI.annotate();
7291d5ae102SDimitry Andric return;
7301d5ae102SDimitry Andric }
7311d5ae102SDimitry Andric // The experimental code generator can't work if there are InstChanges.
7321d5ae102SDimitry Andric if (ExperimentalCodeGen && NewInstrChanges.empty()) {
7331d5ae102SDimitry Andric PeelingModuloScheduleExpander MSE(MF, MS, &LIS);
7341d5ae102SDimitry Andric MSE.expand();
735ac9a064cSDimitry Andric } else if (MVECodeGen && NewInstrChanges.empty() &&
736ac9a064cSDimitry Andric LoopPipelinerInfo->isMVEExpanderSupported() &&
737ac9a064cSDimitry Andric ModuloScheduleExpanderMVE::canApply(Loop)) {
738ac9a064cSDimitry Andric ModuloScheduleExpanderMVE MSE(MF, MS, LIS);
739ac9a064cSDimitry Andric MSE.expand();
7401d5ae102SDimitry Andric } else {
7411d5ae102SDimitry Andric ModuloScheduleExpander MSE(MF, MS, LIS, std::move(NewInstrChanges));
7421d5ae102SDimitry Andric MSE.expand();
7431d5ae102SDimitry Andric MSE.cleanup();
7441d5ae102SDimitry Andric }
745b915e9e0SDimitry Andric ++NumPipelined;
746b915e9e0SDimitry Andric }
747b915e9e0SDimitry Andric
748b915e9e0SDimitry Andric /// Clean up after the software pipeliner runs.
finishBlock()749b915e9e0SDimitry Andric void SwingSchedulerDAG::finishBlock() {
7501d5ae102SDimitry Andric for (auto &KV : NewMIs)
75177fc4c14SDimitry Andric MF.deleteMachineInstr(KV.second);
752b915e9e0SDimitry Andric NewMIs.clear();
753b915e9e0SDimitry Andric
754b915e9e0SDimitry Andric // Call the superclass.
755b915e9e0SDimitry Andric ScheduleDAGInstrs::finishBlock();
756b915e9e0SDimitry Andric }
757b915e9e0SDimitry Andric
758b915e9e0SDimitry Andric /// Return the register values for the operands of a Phi instruction.
759b915e9e0SDimitry Andric /// This function assume the instruction is a Phi.
getPhiRegs(MachineInstr & Phi,MachineBasicBlock * Loop,unsigned & InitVal,unsigned & LoopVal)760b915e9e0SDimitry Andric static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
761b915e9e0SDimitry Andric unsigned &InitVal, unsigned &LoopVal) {
762b915e9e0SDimitry Andric assert(Phi.isPHI() && "Expecting a Phi.");
763b915e9e0SDimitry Andric
764b915e9e0SDimitry Andric InitVal = 0;
765b915e9e0SDimitry Andric LoopVal = 0;
766b915e9e0SDimitry Andric for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
767b915e9e0SDimitry Andric if (Phi.getOperand(i + 1).getMBB() != Loop)
768b915e9e0SDimitry Andric InitVal = Phi.getOperand(i).getReg();
76971d5a254SDimitry Andric else
770b915e9e0SDimitry Andric LoopVal = Phi.getOperand(i).getReg();
771b915e9e0SDimitry Andric
772b915e9e0SDimitry Andric assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
773b915e9e0SDimitry Andric }
774b915e9e0SDimitry Andric
775eb11fae6SDimitry Andric /// Return the Phi register value that comes the loop block.
getLoopPhiReg(const MachineInstr & Phi,const MachineBasicBlock * LoopBB)7764df029ccSDimitry Andric static unsigned getLoopPhiReg(const MachineInstr &Phi,
7774df029ccSDimitry Andric const MachineBasicBlock *LoopBB) {
778b915e9e0SDimitry Andric for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
779b915e9e0SDimitry Andric if (Phi.getOperand(i + 1).getMBB() == LoopBB)
780b915e9e0SDimitry Andric return Phi.getOperand(i).getReg();
781b915e9e0SDimitry Andric return 0;
782b915e9e0SDimitry Andric }
783b915e9e0SDimitry Andric
784b915e9e0SDimitry Andric /// Return true if SUb can be reached from SUa following the chain edges.
isSuccOrder(SUnit * SUa,SUnit * SUb)785b915e9e0SDimitry Andric static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
786b915e9e0SDimitry Andric SmallPtrSet<SUnit *, 8> Visited;
787b915e9e0SDimitry Andric SmallVector<SUnit *, 8> Worklist;
788b915e9e0SDimitry Andric Worklist.push_back(SUa);
789b915e9e0SDimitry Andric while (!Worklist.empty()) {
790b915e9e0SDimitry Andric const SUnit *SU = Worklist.pop_back_val();
7914b4fe385SDimitry Andric for (const auto &SI : SU->Succs) {
792b915e9e0SDimitry Andric SUnit *SuccSU = SI.getSUnit();
793b915e9e0SDimitry Andric if (SI.getKind() == SDep::Order) {
794b915e9e0SDimitry Andric if (Visited.count(SuccSU))
795b915e9e0SDimitry Andric continue;
796b915e9e0SDimitry Andric if (SuccSU == SUb)
797b915e9e0SDimitry Andric return true;
798b915e9e0SDimitry Andric Worklist.push_back(SuccSU);
799b915e9e0SDimitry Andric Visited.insert(SuccSU);
800b915e9e0SDimitry Andric }
801b915e9e0SDimitry Andric }
802b915e9e0SDimitry Andric }
803b915e9e0SDimitry Andric return false;
804b915e9e0SDimitry Andric }
805b915e9e0SDimitry Andric
806b915e9e0SDimitry Andric /// Return true if the instruction causes a chain between memory
807b915e9e0SDimitry Andric /// references before and after it.
isDependenceBarrier(MachineInstr & MI)8084b4fe385SDimitry Andric static bool isDependenceBarrier(MachineInstr &MI) {
809e6d15924SDimitry Andric return MI.isCall() || MI.mayRaiseFPException() ||
810e6d15924SDimitry Andric MI.hasUnmodeledSideEffects() ||
811b915e9e0SDimitry Andric (MI.hasOrderedMemoryRef() &&
8124b4fe385SDimitry Andric (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad()));
813b915e9e0SDimitry Andric }
814b915e9e0SDimitry Andric
815b915e9e0SDimitry Andric /// Return the underlying objects for the memory references of an instruction.
816b915e9e0SDimitry Andric /// This function calls the code in ValueTracking, but first checks that the
817b915e9e0SDimitry Andric /// instruction has a memory operand.
getUnderlyingObjects(const MachineInstr * MI,SmallVectorImpl<const Value * > & Objs)818e6d15924SDimitry Andric static void getUnderlyingObjects(const MachineInstr *MI,
819b60736ecSDimitry Andric SmallVectorImpl<const Value *> &Objs) {
820b915e9e0SDimitry Andric if (!MI->hasOneMemOperand())
821b915e9e0SDimitry Andric return;
822b915e9e0SDimitry Andric MachineMemOperand *MM = *MI->memoperands_begin();
823b915e9e0SDimitry Andric if (!MM->getValue())
824b915e9e0SDimitry Andric return;
825b60736ecSDimitry Andric getUnderlyingObjects(MM->getValue(), Objs);
826e6d15924SDimitry Andric for (const Value *V : Objs) {
827eb11fae6SDimitry Andric if (!isIdentifiedObject(V)) {
828eb11fae6SDimitry Andric Objs.clear();
829eb11fae6SDimitry Andric return;
830eb11fae6SDimitry Andric }
831eb11fae6SDimitry Andric }
832b915e9e0SDimitry Andric }
833b915e9e0SDimitry Andric
834b915e9e0SDimitry Andric /// Add a chain edge between a load and store if the store can be an
835b915e9e0SDimitry Andric /// alias of the load on a subsequent iteration, i.e., a loop carried
836b915e9e0SDimitry Andric /// dependence. This code is very similar to the code in ScheduleDAGInstrs
837b915e9e0SDimitry Andric /// but that code doesn't create loop carried dependences.
addLoopCarriedDependences(AliasAnalysis * AA)838b915e9e0SDimitry Andric void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
839e6d15924SDimitry Andric MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads;
840eb11fae6SDimitry Andric Value *UnknownValue =
841eb11fae6SDimitry Andric UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
842b915e9e0SDimitry Andric for (auto &SU : SUnits) {
843b915e9e0SDimitry Andric MachineInstr &MI = *SU.getInstr();
8444b4fe385SDimitry Andric if (isDependenceBarrier(MI))
845b915e9e0SDimitry Andric PendingLoads.clear();
846b915e9e0SDimitry Andric else if (MI.mayLoad()) {
847e6d15924SDimitry Andric SmallVector<const Value *, 4> Objs;
848b60736ecSDimitry Andric ::getUnderlyingObjects(&MI, Objs);
849eb11fae6SDimitry Andric if (Objs.empty())
850eb11fae6SDimitry Andric Objs.push_back(UnknownValue);
8514b4fe385SDimitry Andric for (const auto *V : Objs) {
852b915e9e0SDimitry Andric SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
853b915e9e0SDimitry Andric SUs.push_back(&SU);
854b915e9e0SDimitry Andric }
855b915e9e0SDimitry Andric } else if (MI.mayStore()) {
856e6d15924SDimitry Andric SmallVector<const Value *, 4> Objs;
857b60736ecSDimitry Andric ::getUnderlyingObjects(&MI, Objs);
858eb11fae6SDimitry Andric if (Objs.empty())
859eb11fae6SDimitry Andric Objs.push_back(UnknownValue);
8604b4fe385SDimitry Andric for (const auto *V : Objs) {
861e6d15924SDimitry Andric MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I =
862b915e9e0SDimitry Andric PendingLoads.find(V);
863b915e9e0SDimitry Andric if (I == PendingLoads.end())
864b915e9e0SDimitry Andric continue;
8654b4fe385SDimitry Andric for (auto *Load : I->second) {
866b915e9e0SDimitry Andric if (isSuccOrder(Load, &SU))
867b915e9e0SDimitry Andric continue;
868b915e9e0SDimitry Andric MachineInstr &LdMI = *Load->getInstr();
869b915e9e0SDimitry Andric // First, perform the cheaper check that compares the base register.
870b915e9e0SDimitry Andric // If they are the same and the load offset is less than the store
871b915e9e0SDimitry Andric // offset, then mark the dependence as loop carried potentially.
872e6d15924SDimitry Andric const MachineOperand *BaseOp1, *BaseOp2;
873b915e9e0SDimitry Andric int64_t Offset1, Offset2;
874cfca06d7SDimitry Andric bool Offset1IsScalable, Offset2IsScalable;
875cfca06d7SDimitry Andric if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1,
876cfca06d7SDimitry Andric Offset1IsScalable, TRI) &&
877cfca06d7SDimitry Andric TII->getMemOperandWithOffset(MI, BaseOp2, Offset2,
878cfca06d7SDimitry Andric Offset2IsScalable, TRI)) {
879d8e91e46SDimitry Andric if (BaseOp1->isIdenticalTo(*BaseOp2) &&
880cfca06d7SDimitry Andric Offset1IsScalable == Offset2IsScalable &&
881d8e91e46SDimitry Andric (int)Offset1 < (int)Offset2) {
8821d5ae102SDimitry Andric assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI) &&
883b915e9e0SDimitry Andric "What happened to the chain edge?");
884eb11fae6SDimitry Andric SDep Dep(Load, SDep::Barrier);
885eb11fae6SDimitry Andric Dep.setLatency(1);
886eb11fae6SDimitry Andric SU.addPred(Dep);
887b915e9e0SDimitry Andric continue;
888b915e9e0SDimitry Andric }
889eb11fae6SDimitry Andric }
890b915e9e0SDimitry Andric // Second, the more expensive check that uses alias analysis on the
891b915e9e0SDimitry Andric // base registers. If they alias, and the load offset is less than
892b915e9e0SDimitry Andric // the store offset, the mark the dependence as loop carried.
893b915e9e0SDimitry Andric if (!AA) {
894eb11fae6SDimitry Andric SDep Dep(Load, SDep::Barrier);
895eb11fae6SDimitry Andric Dep.setLatency(1);
896eb11fae6SDimitry Andric SU.addPred(Dep);
897b915e9e0SDimitry Andric continue;
898b915e9e0SDimitry Andric }
899b915e9e0SDimitry Andric MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
900b915e9e0SDimitry Andric MachineMemOperand *MMO2 = *MI.memoperands_begin();
901b915e9e0SDimitry Andric if (!MMO1->getValue() || !MMO2->getValue()) {
902eb11fae6SDimitry Andric SDep Dep(Load, SDep::Barrier);
903eb11fae6SDimitry Andric Dep.setLatency(1);
904eb11fae6SDimitry Andric SU.addPred(Dep);
905b915e9e0SDimitry Andric continue;
906b915e9e0SDimitry Andric }
907b915e9e0SDimitry Andric if (MMO1->getValue() == MMO2->getValue() &&
908b915e9e0SDimitry Andric MMO1->getOffset() <= MMO2->getOffset()) {
909eb11fae6SDimitry Andric SDep Dep(Load, SDep::Barrier);
910eb11fae6SDimitry Andric Dep.setLatency(1);
911eb11fae6SDimitry Andric SU.addPred(Dep);
912b915e9e0SDimitry Andric continue;
913b915e9e0SDimitry Andric }
914344a3780SDimitry Andric if (!AA->isNoAlias(
915b60736ecSDimitry Andric MemoryLocation::getAfter(MMO1->getValue(), MMO1->getAAInfo()),
916344a3780SDimitry Andric MemoryLocation::getAfter(MMO2->getValue(),
917344a3780SDimitry Andric MMO2->getAAInfo()))) {
918eb11fae6SDimitry Andric SDep Dep(Load, SDep::Barrier);
919eb11fae6SDimitry Andric Dep.setLatency(1);
920eb11fae6SDimitry Andric SU.addPred(Dep);
921eb11fae6SDimitry Andric }
922b915e9e0SDimitry Andric }
923b915e9e0SDimitry Andric }
924b915e9e0SDimitry Andric }
925b915e9e0SDimitry Andric }
926b915e9e0SDimitry Andric }
927b915e9e0SDimitry Andric
928b915e9e0SDimitry Andric /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
929b915e9e0SDimitry Andric /// processes dependences for PHIs. This function adds true dependences
930b915e9e0SDimitry Andric /// from a PHI to a use, and a loop carried dependence from the use to the
931b915e9e0SDimitry Andric /// PHI. The loop carried dependence is represented as an anti dependence
932b915e9e0SDimitry Andric /// edge. This function also removes chain dependences between unrelated
933b915e9e0SDimitry Andric /// PHIs.
updatePhiDependences()934b915e9e0SDimitry Andric void SwingSchedulerDAG::updatePhiDependences() {
935b915e9e0SDimitry Andric SmallVector<SDep, 4> RemoveDeps;
936b915e9e0SDimitry Andric const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
937b915e9e0SDimitry Andric
938b915e9e0SDimitry Andric // Iterate over each DAG node.
939b915e9e0SDimitry Andric for (SUnit &I : SUnits) {
940b915e9e0SDimitry Andric RemoveDeps.clear();
941b915e9e0SDimitry Andric // Set to true if the instruction has an operand defined by a Phi.
942b915e9e0SDimitry Andric unsigned HasPhiUse = 0;
943b915e9e0SDimitry Andric unsigned HasPhiDef = 0;
944b915e9e0SDimitry Andric MachineInstr *MI = I.getInstr();
945b915e9e0SDimitry Andric // Iterate over each operand, and we process the definitions.
9467fa27ce4SDimitry Andric for (const MachineOperand &MO : MI->operands()) {
9477fa27ce4SDimitry Andric if (!MO.isReg())
948b915e9e0SDimitry Andric continue;
9497fa27ce4SDimitry Andric Register Reg = MO.getReg();
9507fa27ce4SDimitry Andric if (MO.isDef()) {
951b915e9e0SDimitry Andric // If the register is used by a Phi, then create an anti dependence.
952b915e9e0SDimitry Andric for (MachineRegisterInfo::use_instr_iterator
953b915e9e0SDimitry Andric UI = MRI.use_instr_begin(Reg),
954b915e9e0SDimitry Andric UE = MRI.use_instr_end();
955b915e9e0SDimitry Andric UI != UE; ++UI) {
956b915e9e0SDimitry Andric MachineInstr *UseMI = &*UI;
957b915e9e0SDimitry Andric SUnit *SU = getSUnit(UseMI);
958b915e9e0SDimitry Andric if (SU != nullptr && UseMI->isPHI()) {
959b915e9e0SDimitry Andric if (!MI->isPHI()) {
960b915e9e0SDimitry Andric SDep Dep(SU, SDep::Anti, Reg);
961eb11fae6SDimitry Andric Dep.setLatency(1);
962b915e9e0SDimitry Andric I.addPred(Dep);
963b915e9e0SDimitry Andric } else {
964b915e9e0SDimitry Andric HasPhiDef = Reg;
965b915e9e0SDimitry Andric // Add a chain edge to a dependent Phi that isn't an existing
966b915e9e0SDimitry Andric // predecessor.
967b915e9e0SDimitry Andric if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
968b915e9e0SDimitry Andric I.addPred(SDep(SU, SDep::Barrier));
969b915e9e0SDimitry Andric }
970b915e9e0SDimitry Andric }
971b915e9e0SDimitry Andric }
9727fa27ce4SDimitry Andric } else if (MO.isUse()) {
973b915e9e0SDimitry Andric // If the register is defined by a Phi, then create a true dependence.
974b915e9e0SDimitry Andric MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
975b915e9e0SDimitry Andric if (DefMI == nullptr)
976b915e9e0SDimitry Andric continue;
977b915e9e0SDimitry Andric SUnit *SU = getSUnit(DefMI);
978b915e9e0SDimitry Andric if (SU != nullptr && DefMI->isPHI()) {
979b915e9e0SDimitry Andric if (!MI->isPHI()) {
980b915e9e0SDimitry Andric SDep Dep(SU, SDep::Data, Reg);
981b915e9e0SDimitry Andric Dep.setLatency(0);
982ac9a064cSDimitry Andric ST.adjustSchedDependency(SU, 0, &I, MO.getOperandNo(), Dep,
983ac9a064cSDimitry Andric &SchedModel);
984b915e9e0SDimitry Andric I.addPred(Dep);
985b915e9e0SDimitry Andric } else {
986b915e9e0SDimitry Andric HasPhiUse = Reg;
987b915e9e0SDimitry Andric // Add a chain edge to a dependent Phi that isn't an existing
988b915e9e0SDimitry Andric // predecessor.
989b915e9e0SDimitry Andric if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
990b915e9e0SDimitry Andric I.addPred(SDep(SU, SDep::Barrier));
991b915e9e0SDimitry Andric }
992b915e9e0SDimitry Andric }
993b915e9e0SDimitry Andric }
994b915e9e0SDimitry Andric }
995b915e9e0SDimitry Andric // Remove order dependences from an unrelated Phi.
996b915e9e0SDimitry Andric if (!SwpPruneDeps)
997b915e9e0SDimitry Andric continue;
998b915e9e0SDimitry Andric for (auto &PI : I.Preds) {
999b915e9e0SDimitry Andric MachineInstr *PMI = PI.getSUnit()->getInstr();
1000b915e9e0SDimitry Andric if (PMI->isPHI() && PI.getKind() == SDep::Order) {
1001b915e9e0SDimitry Andric if (I.getInstr()->isPHI()) {
1002b915e9e0SDimitry Andric if (PMI->getOperand(0).getReg() == HasPhiUse)
1003b915e9e0SDimitry Andric continue;
1004b915e9e0SDimitry Andric if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
1005b915e9e0SDimitry Andric continue;
1006b915e9e0SDimitry Andric }
1007b915e9e0SDimitry Andric RemoveDeps.push_back(PI);
1008b915e9e0SDimitry Andric }
1009b915e9e0SDimitry Andric }
1010ac9a064cSDimitry Andric for (const SDep &D : RemoveDeps)
1011ac9a064cSDimitry Andric I.removePred(D);
1012b915e9e0SDimitry Andric }
1013b915e9e0SDimitry Andric }
1014b915e9e0SDimitry Andric
1015b915e9e0SDimitry Andric /// Iterate over each DAG node and see if we can change any dependences
1016b915e9e0SDimitry Andric /// in order to reduce the recurrence MII.
changeDependences()1017b915e9e0SDimitry Andric void SwingSchedulerDAG::changeDependences() {
1018b915e9e0SDimitry Andric // See if an instruction can use a value from the previous iteration.
1019b915e9e0SDimitry Andric // If so, we update the base and offset of the instruction and change
1020b915e9e0SDimitry Andric // the dependences.
1021b915e9e0SDimitry Andric for (SUnit &I : SUnits) {
1022b915e9e0SDimitry Andric unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
1023b915e9e0SDimitry Andric int64_t NewOffset = 0;
1024b915e9e0SDimitry Andric if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
1025b915e9e0SDimitry Andric NewOffset))
1026b915e9e0SDimitry Andric continue;
1027b915e9e0SDimitry Andric
1028b915e9e0SDimitry Andric // Get the MI and SUnit for the instruction that defines the original base.
10291d5ae102SDimitry Andric Register OrigBase = I.getInstr()->getOperand(BasePos).getReg();
1030b915e9e0SDimitry Andric MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
1031b915e9e0SDimitry Andric if (!DefMI)
1032b915e9e0SDimitry Andric continue;
1033b915e9e0SDimitry Andric SUnit *DefSU = getSUnit(DefMI);
1034b915e9e0SDimitry Andric if (!DefSU)
1035b915e9e0SDimitry Andric continue;
1036b915e9e0SDimitry Andric // Get the MI and SUnit for the instruction that defins the new base.
1037b915e9e0SDimitry Andric MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
1038b915e9e0SDimitry Andric if (!LastMI)
1039b915e9e0SDimitry Andric continue;
1040b915e9e0SDimitry Andric SUnit *LastSU = getSUnit(LastMI);
1041b915e9e0SDimitry Andric if (!LastSU)
1042b915e9e0SDimitry Andric continue;
1043b915e9e0SDimitry Andric
1044b915e9e0SDimitry Andric if (Topo.IsReachable(&I, LastSU))
1045b915e9e0SDimitry Andric continue;
1046b915e9e0SDimitry Andric
1047b915e9e0SDimitry Andric // Remove the dependence. The value now depends on a prior iteration.
1048b915e9e0SDimitry Andric SmallVector<SDep, 4> Deps;
1049344a3780SDimitry Andric for (const SDep &P : I.Preds)
1050344a3780SDimitry Andric if (P.getSUnit() == DefSU)
1051344a3780SDimitry Andric Deps.push_back(P);
1052ac9a064cSDimitry Andric for (const SDep &D : Deps) {
1053ac9a064cSDimitry Andric Topo.RemovePred(&I, D.getSUnit());
1054ac9a064cSDimitry Andric I.removePred(D);
1055b915e9e0SDimitry Andric }
1056b915e9e0SDimitry Andric // Remove the chain dependence between the instructions.
1057b915e9e0SDimitry Andric Deps.clear();
1058b915e9e0SDimitry Andric for (auto &P : LastSU->Preds)
1059b915e9e0SDimitry Andric if (P.getSUnit() == &I && P.getKind() == SDep::Order)
1060b915e9e0SDimitry Andric Deps.push_back(P);
1061ac9a064cSDimitry Andric for (const SDep &D : Deps) {
1062ac9a064cSDimitry Andric Topo.RemovePred(LastSU, D.getSUnit());
1063ac9a064cSDimitry Andric LastSU->removePred(D);
1064b915e9e0SDimitry Andric }
1065b915e9e0SDimitry Andric
1066b915e9e0SDimitry Andric // Add a dependence between the new instruction and the instruction
1067b915e9e0SDimitry Andric // that defines the new base.
1068b915e9e0SDimitry Andric SDep Dep(&I, SDep::Anti, NewBase);
1069d8e91e46SDimitry Andric Topo.AddPred(LastSU, &I);
1070b915e9e0SDimitry Andric LastSU->addPred(Dep);
1071b915e9e0SDimitry Andric
1072b915e9e0SDimitry Andric // Remember the base and offset information so that we can update the
1073b915e9e0SDimitry Andric // instruction during code generation.
1074b915e9e0SDimitry Andric InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
1075b915e9e0SDimitry Andric }
1076b915e9e0SDimitry Andric }
1077b915e9e0SDimitry Andric
10784df029ccSDimitry Andric /// Create an instruction stream that represents a single iteration and stage of
10794df029ccSDimitry Andric /// each instruction. This function differs from SMSchedule::finalizeSchedule in
10804df029ccSDimitry Andric /// that this doesn't have any side-effect to SwingSchedulerDAG. That is, this
10814df029ccSDimitry Andric /// function is an approximation of SMSchedule::finalizeSchedule with all
10824df029ccSDimitry Andric /// non-const operations removed.
computeScheduledInsts(const SwingSchedulerDAG * SSD,SMSchedule & Schedule,std::vector<MachineInstr * > & OrderedInsts,DenseMap<MachineInstr *,unsigned> & Stages)10834df029ccSDimitry Andric static void computeScheduledInsts(const SwingSchedulerDAG *SSD,
10844df029ccSDimitry Andric SMSchedule &Schedule,
10854df029ccSDimitry Andric std::vector<MachineInstr *> &OrderedInsts,
10864df029ccSDimitry Andric DenseMap<MachineInstr *, unsigned> &Stages) {
10874df029ccSDimitry Andric DenseMap<int, std::deque<SUnit *>> Instrs;
10884df029ccSDimitry Andric
10894df029ccSDimitry Andric // Move all instructions to the first stage from the later stages.
10904df029ccSDimitry Andric for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
10914df029ccSDimitry Andric ++Cycle) {
10924df029ccSDimitry Andric for (int Stage = 0, LastStage = Schedule.getMaxStageCount();
10934df029ccSDimitry Andric Stage <= LastStage; ++Stage) {
10944df029ccSDimitry Andric for (SUnit *SU : llvm::reverse(Schedule.getInstructions(
10954df029ccSDimitry Andric Cycle + Stage * Schedule.getInitiationInterval()))) {
10964df029ccSDimitry Andric Instrs[Cycle].push_front(SU);
10974df029ccSDimitry Andric }
10984df029ccSDimitry Andric }
10994df029ccSDimitry Andric }
11004df029ccSDimitry Andric
11014df029ccSDimitry Andric for (int Cycle = Schedule.getFirstCycle(); Cycle <= Schedule.getFinalCycle();
11024df029ccSDimitry Andric ++Cycle) {
11034df029ccSDimitry Andric std::deque<SUnit *> &CycleInstrs = Instrs[Cycle];
11044df029ccSDimitry Andric CycleInstrs = Schedule.reorderInstructions(SSD, CycleInstrs);
11054df029ccSDimitry Andric for (SUnit *SU : CycleInstrs) {
11064df029ccSDimitry Andric MachineInstr *MI = SU->getInstr();
11074df029ccSDimitry Andric OrderedInsts.push_back(MI);
11084df029ccSDimitry Andric Stages[MI] = Schedule.stageScheduled(SU);
11094df029ccSDimitry Andric }
11104df029ccSDimitry Andric }
11114df029ccSDimitry Andric }
11124df029ccSDimitry Andric
1113b915e9e0SDimitry Andric namespace {
1114b915e9e0SDimitry Andric
1115b915e9e0SDimitry Andric // FuncUnitSorter - Comparison operator used to sort instructions by
1116b915e9e0SDimitry Andric // the number of functional unit choices.
1117b915e9e0SDimitry Andric struct FuncUnitSorter {
1118b915e9e0SDimitry Andric const InstrItineraryData *InstrItins;
1119e6d15924SDimitry Andric const MCSubtargetInfo *STI;
1120cfca06d7SDimitry Andric DenseMap<InstrStage::FuncUnits, unsigned> Resources;
1121b915e9e0SDimitry Andric
FuncUnitSorter__anonb07039a60d11::FuncUnitSorter1122e6d15924SDimitry Andric FuncUnitSorter(const TargetSubtargetInfo &TSI)
1123e6d15924SDimitry Andric : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
1124044eb2f6SDimitry Andric
1125b915e9e0SDimitry Andric // Compute the number of functional unit alternatives needed
1126b915e9e0SDimitry Andric // at each stage, and take the minimum value. We prioritize the
1127b915e9e0SDimitry Andric // instructions by the least number of choices first.
minFuncUnits__anonb07039a60d11::FuncUnitSorter1128cfca06d7SDimitry Andric unsigned minFuncUnits(const MachineInstr *Inst,
1129cfca06d7SDimitry Andric InstrStage::FuncUnits &F) const {
1130e6d15924SDimitry Andric unsigned SchedClass = Inst->getDesc().getSchedClass();
1131b915e9e0SDimitry Andric unsigned min = UINT_MAX;
1132e6d15924SDimitry Andric if (InstrItins && !InstrItins->isEmpty()) {
1133e6d15924SDimitry Andric for (const InstrStage &IS :
1134e6d15924SDimitry Andric make_range(InstrItins->beginStage(SchedClass),
1135e6d15924SDimitry Andric InstrItins->endStage(SchedClass))) {
1136cfca06d7SDimitry Andric InstrStage::FuncUnits funcUnits = IS.getUnits();
1137e3b55780SDimitry Andric unsigned numAlternatives = llvm::popcount(funcUnits);
1138b915e9e0SDimitry Andric if (numAlternatives < min) {
1139b915e9e0SDimitry Andric min = numAlternatives;
1140b915e9e0SDimitry Andric F = funcUnits;
1141b915e9e0SDimitry Andric }
1142b915e9e0SDimitry Andric }
1143b915e9e0SDimitry Andric return min;
1144b915e9e0SDimitry Andric }
1145e6d15924SDimitry Andric if (STI && STI->getSchedModel().hasInstrSchedModel()) {
1146e6d15924SDimitry Andric const MCSchedClassDesc *SCDesc =
1147e6d15924SDimitry Andric STI->getSchedModel().getSchedClassDesc(SchedClass);
1148e6d15924SDimitry Andric if (!SCDesc->isValid())
1149e6d15924SDimitry Andric // No valid Schedule Class Desc for schedClass, should be
1150e6d15924SDimitry Andric // Pseudo/PostRAPseudo
1151e6d15924SDimitry Andric return min;
1152e6d15924SDimitry Andric
1153e6d15924SDimitry Andric for (const MCWriteProcResEntry &PRE :
1154e6d15924SDimitry Andric make_range(STI->getWriteProcResBegin(SCDesc),
1155e6d15924SDimitry Andric STI->getWriteProcResEnd(SCDesc))) {
1156b1c73532SDimitry Andric if (!PRE.ReleaseAtCycle)
1157e6d15924SDimitry Andric continue;
1158e6d15924SDimitry Andric const MCProcResourceDesc *ProcResource =
1159e6d15924SDimitry Andric STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
1160e6d15924SDimitry Andric unsigned NumUnits = ProcResource->NumUnits;
1161e6d15924SDimitry Andric if (NumUnits < min) {
1162e6d15924SDimitry Andric min = NumUnits;
1163e6d15924SDimitry Andric F = PRE.ProcResourceIdx;
1164e6d15924SDimitry Andric }
1165e6d15924SDimitry Andric }
1166e6d15924SDimitry Andric return min;
1167e6d15924SDimitry Andric }
1168e6d15924SDimitry Andric llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1169e6d15924SDimitry Andric }
1170b915e9e0SDimitry Andric
1171b915e9e0SDimitry Andric // Compute the critical resources needed by the instruction. This
1172b915e9e0SDimitry Andric // function records the functional units needed by instructions that
1173b915e9e0SDimitry Andric // must use only one functional unit. We use this as a tie breaker
1174b915e9e0SDimitry Andric // for computing the resource MII. The instrutions that require
1175b915e9e0SDimitry Andric // the same, highly used, functional unit have high priority.
calcCriticalResources__anonb07039a60d11::FuncUnitSorter1176b915e9e0SDimitry Andric void calcCriticalResources(MachineInstr &MI) {
1177b915e9e0SDimitry Andric unsigned SchedClass = MI.getDesc().getSchedClass();
1178e6d15924SDimitry Andric if (InstrItins && !InstrItins->isEmpty()) {
1179e6d15924SDimitry Andric for (const InstrStage &IS :
1180e6d15924SDimitry Andric make_range(InstrItins->beginStage(SchedClass),
1181e6d15924SDimitry Andric InstrItins->endStage(SchedClass))) {
1182cfca06d7SDimitry Andric InstrStage::FuncUnits FuncUnits = IS.getUnits();
1183e3b55780SDimitry Andric if (llvm::popcount(FuncUnits) == 1)
1184b915e9e0SDimitry Andric Resources[FuncUnits]++;
1185b915e9e0SDimitry Andric }
1186e6d15924SDimitry Andric return;
1187e6d15924SDimitry Andric }
1188e6d15924SDimitry Andric if (STI && STI->getSchedModel().hasInstrSchedModel()) {
1189e6d15924SDimitry Andric const MCSchedClassDesc *SCDesc =
1190e6d15924SDimitry Andric STI->getSchedModel().getSchedClassDesc(SchedClass);
1191e6d15924SDimitry Andric if (!SCDesc->isValid())
1192e6d15924SDimitry Andric // No valid Schedule Class Desc for schedClass, should be
1193e6d15924SDimitry Andric // Pseudo/PostRAPseudo
1194e6d15924SDimitry Andric return;
1195e6d15924SDimitry Andric
1196e6d15924SDimitry Andric for (const MCWriteProcResEntry &PRE :
1197e6d15924SDimitry Andric make_range(STI->getWriteProcResBegin(SCDesc),
1198e6d15924SDimitry Andric STI->getWriteProcResEnd(SCDesc))) {
1199b1c73532SDimitry Andric if (!PRE.ReleaseAtCycle)
1200e6d15924SDimitry Andric continue;
1201e6d15924SDimitry Andric Resources[PRE.ProcResourceIdx]++;
1202e6d15924SDimitry Andric }
1203e6d15924SDimitry Andric return;
1204e6d15924SDimitry Andric }
1205e6d15924SDimitry Andric llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1206b915e9e0SDimitry Andric }
1207b915e9e0SDimitry Andric
1208b915e9e0SDimitry Andric /// Return true if IS1 has less priority than IS2.
operator ()__anonb07039a60d11::FuncUnitSorter1209b915e9e0SDimitry Andric bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
1210cfca06d7SDimitry Andric InstrStage::FuncUnits F1 = 0, F2 = 0;
1211b915e9e0SDimitry Andric unsigned MFUs1 = minFuncUnits(IS1, F1);
1212b915e9e0SDimitry Andric unsigned MFUs2 = minFuncUnits(IS2, F2);
12131d5ae102SDimitry Andric if (MFUs1 == MFUs2)
1214b915e9e0SDimitry Andric return Resources.lookup(F1) < Resources.lookup(F2);
1215b915e9e0SDimitry Andric return MFUs1 > MFUs2;
1216b915e9e0SDimitry Andric }
1217b915e9e0SDimitry Andric };
1218b915e9e0SDimitry Andric
12194df029ccSDimitry Andric /// Calculate the maximum register pressure of the scheduled instructions stream
12204df029ccSDimitry Andric class HighRegisterPressureDetector {
12214df029ccSDimitry Andric MachineBasicBlock *OrigMBB;
12224df029ccSDimitry Andric const MachineFunction &MF;
12234df029ccSDimitry Andric const MachineRegisterInfo &MRI;
12244df029ccSDimitry Andric const TargetRegisterInfo *TRI;
12254df029ccSDimitry Andric
12264df029ccSDimitry Andric const unsigned PSetNum;
12274df029ccSDimitry Andric
12284df029ccSDimitry Andric // Indexed by PSet ID
12294df029ccSDimitry Andric // InitSetPressure takes into account the register pressure of live-in
12304df029ccSDimitry Andric // registers. It's not depend on how the loop is scheduled, so it's enough to
12314df029ccSDimitry Andric // calculate them once at the beginning.
12324df029ccSDimitry Andric std::vector<unsigned> InitSetPressure;
12334df029ccSDimitry Andric
12344df029ccSDimitry Andric // Indexed by PSet ID
12354df029ccSDimitry Andric // Upper limit for each register pressure set
12364df029ccSDimitry Andric std::vector<unsigned> PressureSetLimit;
12374df029ccSDimitry Andric
12384df029ccSDimitry Andric DenseMap<MachineInstr *, RegisterOperands> ROMap;
12394df029ccSDimitry Andric
12404df029ccSDimitry Andric using Instr2LastUsesTy = DenseMap<MachineInstr *, SmallDenseSet<Register, 4>>;
12414df029ccSDimitry Andric
12424df029ccSDimitry Andric public:
12434df029ccSDimitry Andric using OrderedInstsTy = std::vector<MachineInstr *>;
12444df029ccSDimitry Andric using Instr2StageTy = DenseMap<MachineInstr *, unsigned>;
12454df029ccSDimitry Andric
12464df029ccSDimitry Andric private:
dumpRegisterPressures(const std::vector<unsigned> & Pressures)12474df029ccSDimitry Andric static void dumpRegisterPressures(const std::vector<unsigned> &Pressures) {
12484df029ccSDimitry Andric if (Pressures.size() == 0) {
12494df029ccSDimitry Andric dbgs() << "[]";
12504df029ccSDimitry Andric } else {
12514df029ccSDimitry Andric char Prefix = '[';
12524df029ccSDimitry Andric for (unsigned P : Pressures) {
12534df029ccSDimitry Andric dbgs() << Prefix << P;
12544df029ccSDimitry Andric Prefix = ' ';
12554df029ccSDimitry Andric }
12564df029ccSDimitry Andric dbgs() << ']';
12574df029ccSDimitry Andric }
12584df029ccSDimitry Andric }
12594df029ccSDimitry Andric
dumpPSet(Register Reg) const12604df029ccSDimitry Andric void dumpPSet(Register Reg) const {
12614df029ccSDimitry Andric dbgs() << "Reg=" << printReg(Reg, TRI, 0, &MRI) << " PSet=";
12624df029ccSDimitry Andric for (auto PSetIter = MRI.getPressureSets(Reg); PSetIter.isValid();
12634df029ccSDimitry Andric ++PSetIter) {
12644df029ccSDimitry Andric dbgs() << *PSetIter << ' ';
12654df029ccSDimitry Andric }
12664df029ccSDimitry Andric dbgs() << '\n';
12674df029ccSDimitry Andric }
12684df029ccSDimitry Andric
increaseRegisterPressure(std::vector<unsigned> & Pressure,Register Reg) const12694df029ccSDimitry Andric void increaseRegisterPressure(std::vector<unsigned> &Pressure,
12704df029ccSDimitry Andric Register Reg) const {
12714df029ccSDimitry Andric auto PSetIter = MRI.getPressureSets(Reg);
12724df029ccSDimitry Andric unsigned Weight = PSetIter.getWeight();
12734df029ccSDimitry Andric for (; PSetIter.isValid(); ++PSetIter)
12744df029ccSDimitry Andric Pressure[*PSetIter] += Weight;
12754df029ccSDimitry Andric }
12764df029ccSDimitry Andric
decreaseRegisterPressure(std::vector<unsigned> & Pressure,Register Reg) const12774df029ccSDimitry Andric void decreaseRegisterPressure(std::vector<unsigned> &Pressure,
12784df029ccSDimitry Andric Register Reg) const {
12794df029ccSDimitry Andric auto PSetIter = MRI.getPressureSets(Reg);
12804df029ccSDimitry Andric unsigned Weight = PSetIter.getWeight();
12814df029ccSDimitry Andric for (; PSetIter.isValid(); ++PSetIter) {
12824df029ccSDimitry Andric auto &P = Pressure[*PSetIter];
12834df029ccSDimitry Andric assert(P >= Weight &&
12844df029ccSDimitry Andric "register pressure must be greater than or equal weight");
12854df029ccSDimitry Andric P -= Weight;
12864df029ccSDimitry Andric }
12874df029ccSDimitry Andric }
12884df029ccSDimitry Andric
12894df029ccSDimitry Andric // Return true if Reg is fixed one, for example, stack pointer
isFixedRegister(Register Reg) const12904df029ccSDimitry Andric bool isFixedRegister(Register Reg) const {
12914df029ccSDimitry Andric return Reg.isPhysical() && TRI->isFixedRegister(MF, Reg.asMCReg());
12924df029ccSDimitry Andric }
12934df029ccSDimitry Andric
isDefinedInThisLoop(Register Reg) const12944df029ccSDimitry Andric bool isDefinedInThisLoop(Register Reg) const {
12954df029ccSDimitry Andric return Reg.isVirtual() && MRI.getVRegDef(Reg)->getParent() == OrigMBB;
12964df029ccSDimitry Andric }
12974df029ccSDimitry Andric
12984df029ccSDimitry Andric // Search for live-in variables. They are factored into the register pressure
12994df029ccSDimitry Andric // from the begining. Live-in variables used by every iteration should be
13004df029ccSDimitry Andric // considered as alive throughout the loop. For example, the variable `c` in
13014df029ccSDimitry Andric // following code. \code
13024df029ccSDimitry Andric // int c = ...;
13034df029ccSDimitry Andric // for (int i = 0; i < n; i++)
13044df029ccSDimitry Andric // a[i] += b[i] + c;
13054df029ccSDimitry Andric // \endcode
computeLiveIn()13064df029ccSDimitry Andric void computeLiveIn() {
13074df029ccSDimitry Andric DenseSet<Register> Used;
13084df029ccSDimitry Andric for (auto &MI : *OrigMBB) {
13094df029ccSDimitry Andric if (MI.isDebugInstr())
13104df029ccSDimitry Andric continue;
1311ac9a064cSDimitry Andric for (auto &Use : ROMap[&MI].Uses) {
13124df029ccSDimitry Andric auto Reg = Use.RegUnit;
13134df029ccSDimitry Andric // Ignore the variable that appears only on one side of phi instruction
13144df029ccSDimitry Andric // because it's used only at the first iteration.
13154df029ccSDimitry Andric if (MI.isPHI() && Reg != getLoopPhiReg(MI, OrigMBB))
13164df029ccSDimitry Andric continue;
13174df029ccSDimitry Andric if (isFixedRegister(Reg))
13184df029ccSDimitry Andric continue;
13194df029ccSDimitry Andric if (isDefinedInThisLoop(Reg))
13204df029ccSDimitry Andric continue;
13214df029ccSDimitry Andric Used.insert(Reg);
13224df029ccSDimitry Andric }
13234df029ccSDimitry Andric }
13244df029ccSDimitry Andric
13254df029ccSDimitry Andric for (auto LiveIn : Used)
13264df029ccSDimitry Andric increaseRegisterPressure(InitSetPressure, LiveIn);
13274df029ccSDimitry Andric }
13284df029ccSDimitry Andric
13294df029ccSDimitry Andric // Calculate the upper limit of each pressure set
computePressureSetLimit(const RegisterClassInfo & RCI)13304df029ccSDimitry Andric void computePressureSetLimit(const RegisterClassInfo &RCI) {
13314df029ccSDimitry Andric for (unsigned PSet = 0; PSet < PSetNum; PSet++)
1332ac9a064cSDimitry Andric PressureSetLimit[PSet] = TRI->getRegPressureSetLimit(MF, PSet);
13334df029ccSDimitry Andric
13344df029ccSDimitry Andric // We assume fixed registers, such as stack pointer, are already in use.
13354df029ccSDimitry Andric // Therefore subtracting the weight of the fixed registers from the limit of
13364df029ccSDimitry Andric // each pressure set in advance.
13374df029ccSDimitry Andric SmallDenseSet<Register, 8> FixedRegs;
13384df029ccSDimitry Andric for (const TargetRegisterClass *TRC : TRI->regclasses()) {
13394df029ccSDimitry Andric for (const MCPhysReg Reg : *TRC)
13404df029ccSDimitry Andric if (isFixedRegister(Reg))
13414df029ccSDimitry Andric FixedRegs.insert(Reg);
13424df029ccSDimitry Andric }
13434df029ccSDimitry Andric
13444df029ccSDimitry Andric LLVM_DEBUG({
13454df029ccSDimitry Andric for (auto Reg : FixedRegs) {
13464df029ccSDimitry Andric dbgs() << printReg(Reg, TRI, 0, &MRI) << ": [";
13474df029ccSDimitry Andric const int *Sets = TRI->getRegUnitPressureSets(Reg);
13484df029ccSDimitry Andric for (; *Sets != -1; Sets++) {
13494df029ccSDimitry Andric dbgs() << TRI->getRegPressureSetName(*Sets) << ", ";
13504df029ccSDimitry Andric }
13514df029ccSDimitry Andric dbgs() << "]\n";
13524df029ccSDimitry Andric }
13534df029ccSDimitry Andric });
13544df029ccSDimitry Andric
13554df029ccSDimitry Andric for (auto Reg : FixedRegs) {
13564df029ccSDimitry Andric LLVM_DEBUG(dbgs() << "fixed register: " << printReg(Reg, TRI, 0, &MRI)
13574df029ccSDimitry Andric << "\n");
13584df029ccSDimitry Andric auto PSetIter = MRI.getPressureSets(Reg);
13594df029ccSDimitry Andric unsigned Weight = PSetIter.getWeight();
13604df029ccSDimitry Andric for (; PSetIter.isValid(); ++PSetIter) {
13614df029ccSDimitry Andric unsigned &Limit = PressureSetLimit[*PSetIter];
13624df029ccSDimitry Andric assert(Limit >= Weight &&
13634df029ccSDimitry Andric "register pressure limit must be greater than or equal weight");
13644df029ccSDimitry Andric Limit -= Weight;
13654df029ccSDimitry Andric LLVM_DEBUG(dbgs() << "PSet=" << *PSetIter << " Limit=" << Limit
13664df029ccSDimitry Andric << " (decreased by " << Weight << ")\n");
13674df029ccSDimitry Andric }
13684df029ccSDimitry Andric }
13694df029ccSDimitry Andric }
13704df029ccSDimitry Andric
13714df029ccSDimitry Andric // There are two patterns of last-use.
13724df029ccSDimitry Andric // - by an instruction of the current iteration
13734df029ccSDimitry Andric // - by a phi instruction of the next iteration (loop carried value)
13744df029ccSDimitry Andric //
13754df029ccSDimitry Andric // Furthermore, following two groups of instructions are executed
13764df029ccSDimitry Andric // simultaneously
13774df029ccSDimitry Andric // - next iteration's phi instructions in i-th stage
13784df029ccSDimitry Andric // - current iteration's instructions in i+1-th stage
13794df029ccSDimitry Andric //
13804df029ccSDimitry Andric // This function calculates the last-use of each register while taking into
13814df029ccSDimitry Andric // account the above two patterns.
computeLastUses(const OrderedInstsTy & OrderedInsts,Instr2StageTy & Stages) const13824df029ccSDimitry Andric Instr2LastUsesTy computeLastUses(const OrderedInstsTy &OrderedInsts,
13834df029ccSDimitry Andric Instr2StageTy &Stages) const {
13844df029ccSDimitry Andric // We treat virtual registers that are defined and used in this loop.
13854df029ccSDimitry Andric // Following virtual register will be ignored
13864df029ccSDimitry Andric // - live-in one
13874df029ccSDimitry Andric // - defined but not used in the loop (potentially live-out)
13884df029ccSDimitry Andric DenseSet<Register> TargetRegs;
13894df029ccSDimitry Andric const auto UpdateTargetRegs = [this, &TargetRegs](Register Reg) {
13904df029ccSDimitry Andric if (isDefinedInThisLoop(Reg))
13914df029ccSDimitry Andric TargetRegs.insert(Reg);
13924df029ccSDimitry Andric };
13934df029ccSDimitry Andric for (MachineInstr *MI : OrderedInsts) {
13944df029ccSDimitry Andric if (MI->isPHI()) {
13954df029ccSDimitry Andric Register Reg = getLoopPhiReg(*MI, OrigMBB);
13964df029ccSDimitry Andric UpdateTargetRegs(Reg);
13974df029ccSDimitry Andric } else {
1398ac9a064cSDimitry Andric for (auto &Use : ROMap.find(MI)->getSecond().Uses)
13994df029ccSDimitry Andric UpdateTargetRegs(Use.RegUnit);
14004df029ccSDimitry Andric }
14014df029ccSDimitry Andric }
14024df029ccSDimitry Andric
14034df029ccSDimitry Andric const auto InstrScore = [&Stages](MachineInstr *MI) {
14044df029ccSDimitry Andric return Stages[MI] + MI->isPHI();
14054df029ccSDimitry Andric };
14064df029ccSDimitry Andric
14074df029ccSDimitry Andric DenseMap<Register, MachineInstr *> LastUseMI;
14084df029ccSDimitry Andric for (MachineInstr *MI : llvm::reverse(OrderedInsts)) {
1409ac9a064cSDimitry Andric for (auto &Use : ROMap.find(MI)->getSecond().Uses) {
14104df029ccSDimitry Andric auto Reg = Use.RegUnit;
14114df029ccSDimitry Andric if (!TargetRegs.contains(Reg))
14124df029ccSDimitry Andric continue;
14134df029ccSDimitry Andric auto Ite = LastUseMI.find(Reg);
14144df029ccSDimitry Andric if (Ite == LastUseMI.end()) {
14154df029ccSDimitry Andric LastUseMI[Reg] = MI;
14164df029ccSDimitry Andric } else {
14174df029ccSDimitry Andric MachineInstr *Orig = Ite->second;
14184df029ccSDimitry Andric MachineInstr *New = MI;
14194df029ccSDimitry Andric if (InstrScore(Orig) < InstrScore(New))
14204df029ccSDimitry Andric LastUseMI[Reg] = New;
14214df029ccSDimitry Andric }
14224df029ccSDimitry Andric }
14234df029ccSDimitry Andric }
14244df029ccSDimitry Andric
14254df029ccSDimitry Andric Instr2LastUsesTy LastUses;
14264df029ccSDimitry Andric for (auto &Entry : LastUseMI)
14274df029ccSDimitry Andric LastUses[Entry.second].insert(Entry.first);
14284df029ccSDimitry Andric return LastUses;
14294df029ccSDimitry Andric }
14304df029ccSDimitry Andric
14314df029ccSDimitry Andric // Compute the maximum register pressure of the kernel. We'll simulate #Stage
14324df029ccSDimitry Andric // iterations and check the register pressure at the point where all stages
14334df029ccSDimitry Andric // overlapping.
14344df029ccSDimitry Andric //
14354df029ccSDimitry Andric // An example of unrolled loop where #Stage is 4..
14364df029ccSDimitry Andric // Iter i+0 i+1 i+2 i+3
14374df029ccSDimitry Andric // ------------------------
14384df029ccSDimitry Andric // Stage 0
14394df029ccSDimitry Andric // Stage 1 0
14404df029ccSDimitry Andric // Stage 2 1 0
14414df029ccSDimitry Andric // Stage 3 2 1 0 <- All stages overlap
14424df029ccSDimitry Andric //
14434df029ccSDimitry Andric std::vector<unsigned>
computeMaxSetPressure(const OrderedInstsTy & OrderedInsts,Instr2StageTy & Stages,const unsigned StageCount) const14444df029ccSDimitry Andric computeMaxSetPressure(const OrderedInstsTy &OrderedInsts,
14454df029ccSDimitry Andric Instr2StageTy &Stages,
14464df029ccSDimitry Andric const unsigned StageCount) const {
14474df029ccSDimitry Andric using RegSetTy = SmallDenseSet<Register, 16>;
14484df029ccSDimitry Andric
14494df029ccSDimitry Andric // Indexed by #Iter. To treat "local" variables of each stage separately, we
14504df029ccSDimitry Andric // manage the liveness of the registers independently by iterations.
14514df029ccSDimitry Andric SmallVector<RegSetTy> LiveRegSets(StageCount);
14524df029ccSDimitry Andric
14534df029ccSDimitry Andric auto CurSetPressure = InitSetPressure;
14544df029ccSDimitry Andric auto MaxSetPressure = InitSetPressure;
14554df029ccSDimitry Andric auto LastUses = computeLastUses(OrderedInsts, Stages);
14564df029ccSDimitry Andric
14574df029ccSDimitry Andric LLVM_DEBUG({
14584df029ccSDimitry Andric dbgs() << "Ordered instructions:\n";
14594df029ccSDimitry Andric for (MachineInstr *MI : OrderedInsts) {
14604df029ccSDimitry Andric dbgs() << "Stage " << Stages[MI] << ": ";
14614df029ccSDimitry Andric MI->dump();
14624df029ccSDimitry Andric }
14634df029ccSDimitry Andric });
14644df029ccSDimitry Andric
14654df029ccSDimitry Andric const auto InsertReg = [this, &CurSetPressure](RegSetTy &RegSet,
14664df029ccSDimitry Andric Register Reg) {
14674df029ccSDimitry Andric if (!Reg.isValid() || isFixedRegister(Reg))
14684df029ccSDimitry Andric return;
14694df029ccSDimitry Andric
14704df029ccSDimitry Andric bool Inserted = RegSet.insert(Reg).second;
14714df029ccSDimitry Andric if (!Inserted)
14724df029ccSDimitry Andric return;
14734df029ccSDimitry Andric
14744df029ccSDimitry Andric LLVM_DEBUG(dbgs() << "insert " << printReg(Reg, TRI, 0, &MRI) << "\n");
14754df029ccSDimitry Andric increaseRegisterPressure(CurSetPressure, Reg);
14764df029ccSDimitry Andric LLVM_DEBUG(dumpPSet(Reg));
14774df029ccSDimitry Andric };
14784df029ccSDimitry Andric
14794df029ccSDimitry Andric const auto EraseReg = [this, &CurSetPressure](RegSetTy &RegSet,
14804df029ccSDimitry Andric Register Reg) {
14814df029ccSDimitry Andric if (!Reg.isValid() || isFixedRegister(Reg))
14824df029ccSDimitry Andric return;
14834df029ccSDimitry Andric
14844df029ccSDimitry Andric // live-in register
14854df029ccSDimitry Andric if (!RegSet.contains(Reg))
14864df029ccSDimitry Andric return;
14874df029ccSDimitry Andric
14884df029ccSDimitry Andric LLVM_DEBUG(dbgs() << "erase " << printReg(Reg, TRI, 0, &MRI) << "\n");
14894df029ccSDimitry Andric RegSet.erase(Reg);
14904df029ccSDimitry Andric decreaseRegisterPressure(CurSetPressure, Reg);
14914df029ccSDimitry Andric LLVM_DEBUG(dumpPSet(Reg));
14924df029ccSDimitry Andric };
14934df029ccSDimitry Andric
14944df029ccSDimitry Andric for (unsigned I = 0; I < StageCount; I++) {
14954df029ccSDimitry Andric for (MachineInstr *MI : OrderedInsts) {
14964df029ccSDimitry Andric const auto Stage = Stages[MI];
14974df029ccSDimitry Andric if (I < Stage)
14984df029ccSDimitry Andric continue;
14994df029ccSDimitry Andric
15004df029ccSDimitry Andric const unsigned Iter = I - Stage;
15014df029ccSDimitry Andric
1502ac9a064cSDimitry Andric for (auto &Def : ROMap.find(MI)->getSecond().Defs)
15034df029ccSDimitry Andric InsertReg(LiveRegSets[Iter], Def.RegUnit);
15044df029ccSDimitry Andric
15054df029ccSDimitry Andric for (auto LastUse : LastUses[MI]) {
15064df029ccSDimitry Andric if (MI->isPHI()) {
15074df029ccSDimitry Andric if (Iter != 0)
15084df029ccSDimitry Andric EraseReg(LiveRegSets[Iter - 1], LastUse);
15094df029ccSDimitry Andric } else {
15104df029ccSDimitry Andric EraseReg(LiveRegSets[Iter], LastUse);
15114df029ccSDimitry Andric }
15124df029ccSDimitry Andric }
15134df029ccSDimitry Andric
15144df029ccSDimitry Andric for (unsigned PSet = 0; PSet < PSetNum; PSet++)
15154df029ccSDimitry Andric MaxSetPressure[PSet] =
15164df029ccSDimitry Andric std::max(MaxSetPressure[PSet], CurSetPressure[PSet]);
15174df029ccSDimitry Andric
15184df029ccSDimitry Andric LLVM_DEBUG({
15194df029ccSDimitry Andric dbgs() << "CurSetPressure=";
15204df029ccSDimitry Andric dumpRegisterPressures(CurSetPressure);
15214df029ccSDimitry Andric dbgs() << " iter=" << Iter << " stage=" << Stage << ":";
15224df029ccSDimitry Andric MI->dump();
15234df029ccSDimitry Andric });
15244df029ccSDimitry Andric }
15254df029ccSDimitry Andric }
15264df029ccSDimitry Andric
15274df029ccSDimitry Andric return MaxSetPressure;
15284df029ccSDimitry Andric }
15294df029ccSDimitry Andric
15304df029ccSDimitry Andric public:
HighRegisterPressureDetector(MachineBasicBlock * OrigMBB,const MachineFunction & MF)15314df029ccSDimitry Andric HighRegisterPressureDetector(MachineBasicBlock *OrigMBB,
15324df029ccSDimitry Andric const MachineFunction &MF)
15334df029ccSDimitry Andric : OrigMBB(OrigMBB), MF(MF), MRI(MF.getRegInfo()),
15344df029ccSDimitry Andric TRI(MF.getSubtarget().getRegisterInfo()),
15354df029ccSDimitry Andric PSetNum(TRI->getNumRegPressureSets()), InitSetPressure(PSetNum, 0),
15364df029ccSDimitry Andric PressureSetLimit(PSetNum, 0) {}
15374df029ccSDimitry Andric
15384df029ccSDimitry Andric // Used to calculate register pressure, which is independent of loop
15394df029ccSDimitry Andric // scheduling.
init(const RegisterClassInfo & RCI)15404df029ccSDimitry Andric void init(const RegisterClassInfo &RCI) {
15414df029ccSDimitry Andric for (MachineInstr &MI : *OrigMBB) {
15424df029ccSDimitry Andric if (MI.isDebugInstr())
15434df029ccSDimitry Andric continue;
15444df029ccSDimitry Andric ROMap[&MI].collect(MI, *TRI, MRI, false, true);
15454df029ccSDimitry Andric }
15464df029ccSDimitry Andric
15474df029ccSDimitry Andric computeLiveIn();
15484df029ccSDimitry Andric computePressureSetLimit(RCI);
15494df029ccSDimitry Andric }
15504df029ccSDimitry Andric
15514df029ccSDimitry Andric // Calculate the maximum register pressures of the loop and check if they
15524df029ccSDimitry Andric // exceed the limit
detect(const SwingSchedulerDAG * SSD,SMSchedule & Schedule,const unsigned MaxStage) const15534df029ccSDimitry Andric bool detect(const SwingSchedulerDAG *SSD, SMSchedule &Schedule,
15544df029ccSDimitry Andric const unsigned MaxStage) const {
15554df029ccSDimitry Andric assert(0 <= RegPressureMargin && RegPressureMargin <= 100 &&
15564df029ccSDimitry Andric "the percentage of the margin must be between 0 to 100");
15574df029ccSDimitry Andric
15584df029ccSDimitry Andric OrderedInstsTy OrderedInsts;
15594df029ccSDimitry Andric Instr2StageTy Stages;
15604df029ccSDimitry Andric computeScheduledInsts(SSD, Schedule, OrderedInsts, Stages);
15614df029ccSDimitry Andric const auto MaxSetPressure =
15624df029ccSDimitry Andric computeMaxSetPressure(OrderedInsts, Stages, MaxStage + 1);
15634df029ccSDimitry Andric
15644df029ccSDimitry Andric LLVM_DEBUG({
15654df029ccSDimitry Andric dbgs() << "Dump MaxSetPressure:\n";
15664df029ccSDimitry Andric for (unsigned I = 0; I < MaxSetPressure.size(); I++) {
15674df029ccSDimitry Andric dbgs() << format("MaxSetPressure[%d]=%d\n", I, MaxSetPressure[I]);
15684df029ccSDimitry Andric }
15694df029ccSDimitry Andric dbgs() << '\n';
15704df029ccSDimitry Andric });
15714df029ccSDimitry Andric
15724df029ccSDimitry Andric for (unsigned PSet = 0; PSet < PSetNum; PSet++) {
15734df029ccSDimitry Andric unsigned Limit = PressureSetLimit[PSet];
15744df029ccSDimitry Andric unsigned Margin = Limit * RegPressureMargin / 100;
15754df029ccSDimitry Andric LLVM_DEBUG(dbgs() << "PSet=" << PSet << " Limit=" << Limit
15764df029ccSDimitry Andric << " Margin=" << Margin << "\n");
15774df029ccSDimitry Andric if (Limit < MaxSetPressure[PSet] + Margin) {
15784df029ccSDimitry Andric LLVM_DEBUG(
15794df029ccSDimitry Andric dbgs()
15804df029ccSDimitry Andric << "Rejected the schedule because of too high register pressure\n");
15814df029ccSDimitry Andric return true;
15824df029ccSDimitry Andric }
15834df029ccSDimitry Andric }
15844df029ccSDimitry Andric return false;
15854df029ccSDimitry Andric }
15864df029ccSDimitry Andric };
15874df029ccSDimitry Andric
1588b915e9e0SDimitry Andric } // end anonymous namespace
1589b915e9e0SDimitry Andric
1590b915e9e0SDimitry Andric /// Calculate the resource constrained minimum initiation interval for the
1591b915e9e0SDimitry Andric /// specified loop. We use the DFA to model the resources needed for
1592b915e9e0SDimitry Andric /// each instruction, and we ignore dependences. A different DFA is created
1593b915e9e0SDimitry Andric /// for each cycle that is required. When adding a new instruction, we attempt
1594b915e9e0SDimitry Andric /// to add it to each existing DFA, until a legal space is found. If the
1595b915e9e0SDimitry Andric /// instruction cannot be reserved in an existing DFA, we create a new one.
calculateResMII()1596b915e9e0SDimitry Andric unsigned SwingSchedulerDAG::calculateResMII() {
1597e6d15924SDimitry Andric LLVM_DEBUG(dbgs() << "calculateResMII:\n");
1598e3b55780SDimitry Andric ResourceManager RM(&MF.getSubtarget(), this);
1599e3b55780SDimitry Andric return RM.calculateResMII();
1600b915e9e0SDimitry Andric }
1601b915e9e0SDimitry Andric
1602b915e9e0SDimitry Andric /// Calculate the recurrence-constrainted minimum initiation interval.
1603b915e9e0SDimitry Andric /// Iterate over each circuit. Compute the delay(c) and distance(c)
1604b915e9e0SDimitry Andric /// for each circuit. The II needs to satisfy the inequality
1605b915e9e0SDimitry Andric /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1606eb11fae6SDimitry Andric /// II that satisfies the inequality, and the RecMII is the maximum
1607b915e9e0SDimitry Andric /// of those values.
calculateRecMII(NodeSetType & NodeSets)1608b915e9e0SDimitry Andric unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1609b915e9e0SDimitry Andric unsigned RecMII = 0;
1610b915e9e0SDimitry Andric
1611b915e9e0SDimitry Andric for (NodeSet &Nodes : NodeSets) {
1612044eb2f6SDimitry Andric if (Nodes.empty())
1613b915e9e0SDimitry Andric continue;
1614b915e9e0SDimitry Andric
1615eb11fae6SDimitry Andric unsigned Delay = Nodes.getLatency();
1616b915e9e0SDimitry Andric unsigned Distance = 1;
1617b915e9e0SDimitry Andric
1618b915e9e0SDimitry Andric // ii = ceil(delay / distance)
1619b915e9e0SDimitry Andric unsigned CurMII = (Delay + Distance - 1) / Distance;
1620b915e9e0SDimitry Andric Nodes.setRecMII(CurMII);
1621b915e9e0SDimitry Andric if (CurMII > RecMII)
1622b915e9e0SDimitry Andric RecMII = CurMII;
1623b915e9e0SDimitry Andric }
1624b915e9e0SDimitry Andric
1625b915e9e0SDimitry Andric return RecMII;
1626b915e9e0SDimitry Andric }
1627b915e9e0SDimitry Andric
1628b915e9e0SDimitry Andric /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1629b915e9e0SDimitry Andric /// but we do this to find the circuits, and then change them back.
swapAntiDependences(std::vector<SUnit> & SUnits)1630b915e9e0SDimitry Andric static void swapAntiDependences(std::vector<SUnit> &SUnits) {
1631b915e9e0SDimitry Andric SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
163277fc4c14SDimitry Andric for (SUnit &SU : SUnits) {
163377fc4c14SDimitry Andric for (SDep &Pred : SU.Preds)
163477fc4c14SDimitry Andric if (Pred.getKind() == SDep::Anti)
163577fc4c14SDimitry Andric DepsAdded.push_back(std::make_pair(&SU, Pred));
1636b915e9e0SDimitry Andric }
1637344a3780SDimitry Andric for (std::pair<SUnit *, SDep> &P : DepsAdded) {
1638b915e9e0SDimitry Andric // Remove this anti dependency and add one in the reverse direction.
1639344a3780SDimitry Andric SUnit *SU = P.first;
1640344a3780SDimitry Andric SDep &D = P.second;
1641b915e9e0SDimitry Andric SUnit *TargetSU = D.getSUnit();
1642b915e9e0SDimitry Andric unsigned Reg = D.getReg();
1643b915e9e0SDimitry Andric unsigned Lat = D.getLatency();
1644b915e9e0SDimitry Andric SU->removePred(D);
1645b915e9e0SDimitry Andric SDep Dep(SU, SDep::Anti, Reg);
1646b915e9e0SDimitry Andric Dep.setLatency(Lat);
1647b915e9e0SDimitry Andric TargetSU->addPred(Dep);
1648b915e9e0SDimitry Andric }
1649b915e9e0SDimitry Andric }
1650b915e9e0SDimitry Andric
1651b915e9e0SDimitry Andric /// Create the adjacency structure of the nodes in the graph.
createAdjacencyStructure(SwingSchedulerDAG * DAG)1652b915e9e0SDimitry Andric void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1653b915e9e0SDimitry Andric SwingSchedulerDAG *DAG) {
1654b915e9e0SDimitry Andric BitVector Added(SUnits.size());
1655eb11fae6SDimitry Andric DenseMap<int, int> OutputDeps;
1656b915e9e0SDimitry Andric for (int i = 0, e = SUnits.size(); i != e; ++i) {
1657b915e9e0SDimitry Andric Added.reset();
1658b915e9e0SDimitry Andric // Add any successor to the adjacency matrix and exclude duplicates.
1659b915e9e0SDimitry Andric for (auto &SI : SUnits[i].Succs) {
1660eb11fae6SDimitry Andric // Only create a back-edge on the first and last nodes of a dependence
1661eb11fae6SDimitry Andric // chain. This records any chains and adds them later.
1662eb11fae6SDimitry Andric if (SI.getKind() == SDep::Output) {
1663eb11fae6SDimitry Andric int N = SI.getSUnit()->NodeNum;
1664eb11fae6SDimitry Andric int BackEdge = i;
1665eb11fae6SDimitry Andric auto Dep = OutputDeps.find(BackEdge);
1666eb11fae6SDimitry Andric if (Dep != OutputDeps.end()) {
1667eb11fae6SDimitry Andric BackEdge = Dep->second;
1668eb11fae6SDimitry Andric OutputDeps.erase(Dep);
1669eb11fae6SDimitry Andric }
1670eb11fae6SDimitry Andric OutputDeps[N] = BackEdge;
1671eb11fae6SDimitry Andric }
1672d8e91e46SDimitry Andric // Do not process a boundary node, an artificial node.
1673d8e91e46SDimitry Andric // A back-edge is processed only if it goes to a Phi.
1674d8e91e46SDimitry Andric if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
1675b915e9e0SDimitry Andric (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
1676b915e9e0SDimitry Andric continue;
1677b915e9e0SDimitry Andric int N = SI.getSUnit()->NodeNum;
1678b915e9e0SDimitry Andric if (!Added.test(N)) {
1679b915e9e0SDimitry Andric AdjK[i].push_back(N);
1680b915e9e0SDimitry Andric Added.set(N);
1681b915e9e0SDimitry Andric }
1682b915e9e0SDimitry Andric }
1683b915e9e0SDimitry Andric // A chain edge between a store and a load is treated as a back-edge in the
1684b915e9e0SDimitry Andric // adjacency matrix.
1685b915e9e0SDimitry Andric for (auto &PI : SUnits[i].Preds) {
1686b915e9e0SDimitry Andric if (!SUnits[i].getInstr()->mayStore() ||
1687eb11fae6SDimitry Andric !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
1688b915e9e0SDimitry Andric continue;
1689b915e9e0SDimitry Andric if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1690b915e9e0SDimitry Andric int N = PI.getSUnit()->NodeNum;
1691b915e9e0SDimitry Andric if (!Added.test(N)) {
1692b915e9e0SDimitry Andric AdjK[i].push_back(N);
1693b915e9e0SDimitry Andric Added.set(N);
1694b915e9e0SDimitry Andric }
1695b915e9e0SDimitry Andric }
1696b915e9e0SDimitry Andric }
1697b915e9e0SDimitry Andric }
1698d8e91e46SDimitry Andric // Add back-edges in the adjacency matrix for the output dependences.
1699eb11fae6SDimitry Andric for (auto &OD : OutputDeps)
1700eb11fae6SDimitry Andric if (!Added.test(OD.second)) {
1701eb11fae6SDimitry Andric AdjK[OD.first].push_back(OD.second);
1702eb11fae6SDimitry Andric Added.set(OD.second);
1703eb11fae6SDimitry Andric }
1704b915e9e0SDimitry Andric }
1705b915e9e0SDimitry Andric
1706b915e9e0SDimitry Andric /// Identify an elementary circuit in the dependence graph starting at the
1707b915e9e0SDimitry Andric /// specified node.
circuit(int V,int S,NodeSetType & NodeSets,bool HasBackedge)1708b915e9e0SDimitry Andric bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
1709b915e9e0SDimitry Andric bool HasBackedge) {
1710b915e9e0SDimitry Andric SUnit *SV = &SUnits[V];
1711b915e9e0SDimitry Andric bool F = false;
1712b915e9e0SDimitry Andric Stack.insert(SV);
1713b915e9e0SDimitry Andric Blocked.set(V);
1714b915e9e0SDimitry Andric
1715b915e9e0SDimitry Andric for (auto W : AdjK[V]) {
1716b915e9e0SDimitry Andric if (NumPaths > MaxPaths)
1717b915e9e0SDimitry Andric break;
1718b915e9e0SDimitry Andric if (W < S)
1719b915e9e0SDimitry Andric continue;
1720b915e9e0SDimitry Andric if (W == S) {
1721b915e9e0SDimitry Andric if (!HasBackedge)
1722b915e9e0SDimitry Andric NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
1723b915e9e0SDimitry Andric F = true;
1724b915e9e0SDimitry Andric ++NumPaths;
1725b915e9e0SDimitry Andric break;
1726b915e9e0SDimitry Andric } else if (!Blocked.test(W)) {
1727d8e91e46SDimitry Andric if (circuit(W, S, NodeSets,
1728d8e91e46SDimitry Andric Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
1729b915e9e0SDimitry Andric F = true;
1730b915e9e0SDimitry Andric }
1731b915e9e0SDimitry Andric }
1732b915e9e0SDimitry Andric
1733b915e9e0SDimitry Andric if (F)
1734b915e9e0SDimitry Andric unblock(V);
1735b915e9e0SDimitry Andric else {
1736b915e9e0SDimitry Andric for (auto W : AdjK[V]) {
1737b915e9e0SDimitry Andric if (W < S)
1738b915e9e0SDimitry Andric continue;
1739b915e9e0SDimitry Andric B[W].insert(SV);
1740b915e9e0SDimitry Andric }
1741b915e9e0SDimitry Andric }
1742b915e9e0SDimitry Andric Stack.pop_back();
1743b915e9e0SDimitry Andric return F;
1744b915e9e0SDimitry Andric }
1745b915e9e0SDimitry Andric
1746b915e9e0SDimitry Andric /// Unblock a node in the circuit finding algorithm.
unblock(int U)1747b915e9e0SDimitry Andric void SwingSchedulerDAG::Circuits::unblock(int U) {
1748b915e9e0SDimitry Andric Blocked.reset(U);
1749b915e9e0SDimitry Andric SmallPtrSet<SUnit *, 4> &BU = B[U];
1750b915e9e0SDimitry Andric while (!BU.empty()) {
1751b915e9e0SDimitry Andric SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1752b915e9e0SDimitry Andric assert(SI != BU.end() && "Invalid B set.");
1753b915e9e0SDimitry Andric SUnit *W = *SI;
1754b915e9e0SDimitry Andric BU.erase(W);
1755b915e9e0SDimitry Andric if (Blocked.test(W->NodeNum))
1756b915e9e0SDimitry Andric unblock(W->NodeNum);
1757b915e9e0SDimitry Andric }
1758b915e9e0SDimitry Andric }
1759b915e9e0SDimitry Andric
1760b915e9e0SDimitry Andric /// Identify all the elementary circuits in the dependence graph using
1761b915e9e0SDimitry Andric /// Johnson's circuit algorithm.
findCircuits(NodeSetType & NodeSets)1762b915e9e0SDimitry Andric void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1763b915e9e0SDimitry Andric // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1764b915e9e0SDimitry Andric // but we do this to find the circuits, and then change them back.
1765b915e9e0SDimitry Andric swapAntiDependences(SUnits);
1766b915e9e0SDimitry Andric
1767d8e91e46SDimitry Andric Circuits Cir(SUnits, Topo);
1768b915e9e0SDimitry Andric // Create the adjacency structure.
1769b915e9e0SDimitry Andric Cir.createAdjacencyStructure(this);
1770b915e9e0SDimitry Andric for (int i = 0, e = SUnits.size(); i != e; ++i) {
1771b915e9e0SDimitry Andric Cir.reset();
1772b915e9e0SDimitry Andric Cir.circuit(i, i, NodeSets);
1773b915e9e0SDimitry Andric }
1774b915e9e0SDimitry Andric
1775b915e9e0SDimitry Andric // Change the dependences back so that we've created a DAG again.
1776b915e9e0SDimitry Andric swapAntiDependences(SUnits);
1777b915e9e0SDimitry Andric }
1778b915e9e0SDimitry Andric
1779d8e91e46SDimitry Andric // Create artificial dependencies between the source of COPY/REG_SEQUENCE that
1780d8e91e46SDimitry Andric // is loop-carried to the USE in next iteration. This will help pipeliner avoid
1781d8e91e46SDimitry Andric // additional copies that are needed across iterations. An artificial dependence
1782d8e91e46SDimitry Andric // edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
1783d8e91e46SDimitry Andric
1784d8e91e46SDimitry Andric // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
1785d8e91e46SDimitry Andric // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
1786d8e91e46SDimitry Andric // PHI-------True-Dep------> USEOfPhi
1787d8e91e46SDimitry Andric
1788d8e91e46SDimitry Andric // The mutation creates
1789d8e91e46SDimitry Andric // USEOfPHI -------Artificial-Dep---> SRCOfCopy
1790d8e91e46SDimitry Andric
1791d8e91e46SDimitry Andric // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
1792d8e91e46SDimitry Andric // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
1793d8e91e46SDimitry Andric // late to avoid additional copies across iterations. The possible scheduling
1794d8e91e46SDimitry Andric // order would be
1795d8e91e46SDimitry Andric // USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE.
1796d8e91e46SDimitry Andric
apply(ScheduleDAGInstrs * DAG)1797d8e91e46SDimitry Andric void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
1798d8e91e46SDimitry Andric for (SUnit &SU : DAG->SUnits) {
1799d8e91e46SDimitry Andric // Find the COPY/REG_SEQUENCE instruction.
1800d8e91e46SDimitry Andric if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
1801d8e91e46SDimitry Andric continue;
1802d8e91e46SDimitry Andric
1803d8e91e46SDimitry Andric // Record the loop carried PHIs.
1804d8e91e46SDimitry Andric SmallVector<SUnit *, 4> PHISUs;
1805d8e91e46SDimitry Andric // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
1806d8e91e46SDimitry Andric SmallVector<SUnit *, 4> SrcSUs;
1807d8e91e46SDimitry Andric
1808d8e91e46SDimitry Andric for (auto &Dep : SU.Preds) {
1809d8e91e46SDimitry Andric SUnit *TmpSU = Dep.getSUnit();
1810d8e91e46SDimitry Andric MachineInstr *TmpMI = TmpSU->getInstr();
1811d8e91e46SDimitry Andric SDep::Kind DepKind = Dep.getKind();
1812d8e91e46SDimitry Andric // Save the loop carried PHI.
1813d8e91e46SDimitry Andric if (DepKind == SDep::Anti && TmpMI->isPHI())
1814d8e91e46SDimitry Andric PHISUs.push_back(TmpSU);
1815d8e91e46SDimitry Andric // Save the source of COPY/REG_SEQUENCE.
1816d8e91e46SDimitry Andric // If the source has no pre-decessors, we will end up creating cycles.
1817d8e91e46SDimitry Andric else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
1818d8e91e46SDimitry Andric SrcSUs.push_back(TmpSU);
1819d8e91e46SDimitry Andric }
1820d8e91e46SDimitry Andric
1821d8e91e46SDimitry Andric if (PHISUs.size() == 0 || SrcSUs.size() == 0)
1822d8e91e46SDimitry Andric continue;
1823d8e91e46SDimitry Andric
1824d8e91e46SDimitry Andric // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
1825d8e91e46SDimitry Andric // SUnit to the container.
1826d8e91e46SDimitry Andric SmallVector<SUnit *, 8> UseSUs;
1827706b4fc4SDimitry Andric // Do not use iterator based loop here as we are updating the container.
1828706b4fc4SDimitry Andric for (size_t Index = 0; Index < PHISUs.size(); ++Index) {
1829706b4fc4SDimitry Andric for (auto &Dep : PHISUs[Index]->Succs) {
1830d8e91e46SDimitry Andric if (Dep.getKind() != SDep::Data)
1831d8e91e46SDimitry Andric continue;
1832d8e91e46SDimitry Andric
1833d8e91e46SDimitry Andric SUnit *TmpSU = Dep.getSUnit();
1834d8e91e46SDimitry Andric MachineInstr *TmpMI = TmpSU->getInstr();
1835d8e91e46SDimitry Andric if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
1836d8e91e46SDimitry Andric PHISUs.push_back(TmpSU);
1837d8e91e46SDimitry Andric continue;
1838d8e91e46SDimitry Andric }
1839d8e91e46SDimitry Andric UseSUs.push_back(TmpSU);
1840d8e91e46SDimitry Andric }
1841d8e91e46SDimitry Andric }
1842d8e91e46SDimitry Andric
1843d8e91e46SDimitry Andric if (UseSUs.size() == 0)
1844d8e91e46SDimitry Andric continue;
1845d8e91e46SDimitry Andric
1846d8e91e46SDimitry Andric SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
1847d8e91e46SDimitry Andric // Add the artificial dependencies if it does not form a cycle.
18484b4fe385SDimitry Andric for (auto *I : UseSUs) {
18494b4fe385SDimitry Andric for (auto *Src : SrcSUs) {
1850d8e91e46SDimitry Andric if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
1851d8e91e46SDimitry Andric Src->addPred(SDep(I, SDep::Artificial));
1852d8e91e46SDimitry Andric SDAG->Topo.AddPred(Src, I);
1853d8e91e46SDimitry Andric }
1854d8e91e46SDimitry Andric }
1855d8e91e46SDimitry Andric }
1856d8e91e46SDimitry Andric }
1857d8e91e46SDimitry Andric }
1858d8e91e46SDimitry Andric
1859b915e9e0SDimitry Andric /// Return true for DAG nodes that we ignore when computing the cost functions.
1860eb11fae6SDimitry Andric /// We ignore the back-edge recurrence in order to avoid unbounded recursion
1861b915e9e0SDimitry Andric /// in the calculation of the ASAP, ALAP, etc functions.
ignoreDependence(const SDep & D,bool isPred)1862b915e9e0SDimitry Andric static bool ignoreDependence(const SDep &D, bool isPred) {
1863145449b1SDimitry Andric if (D.isArtificial() || D.getSUnit()->isBoundaryNode())
1864b915e9e0SDimitry Andric return true;
1865b915e9e0SDimitry Andric return D.getKind() == SDep::Anti && isPred;
1866b915e9e0SDimitry Andric }
1867b915e9e0SDimitry Andric
1868b915e9e0SDimitry Andric /// Compute several functions need to order the nodes for scheduling.
1869b915e9e0SDimitry Andric /// ASAP - Earliest time to schedule a node.
1870b915e9e0SDimitry Andric /// ALAP - Latest time to schedule a node.
1871b915e9e0SDimitry Andric /// MOV - Mobility function, difference between ALAP and ASAP.
1872b915e9e0SDimitry Andric /// D - Depth of each node.
1873b915e9e0SDimitry Andric /// H - Height of each node.
computeNodeFunctions(NodeSetType & NodeSets)1874b915e9e0SDimitry Andric void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
1875b915e9e0SDimitry Andric ScheduleInfo.resize(SUnits.size());
1876b915e9e0SDimitry Andric
1877eb11fae6SDimitry Andric LLVM_DEBUG({
1878344a3780SDimitry Andric for (int I : Topo) {
1879344a3780SDimitry Andric const SUnit &SU = SUnits[I];
1880d8e91e46SDimitry Andric dumpNode(SU);
1881b915e9e0SDimitry Andric }
1882b915e9e0SDimitry Andric });
1883b915e9e0SDimitry Andric
1884b915e9e0SDimitry Andric int maxASAP = 0;
1885eb11fae6SDimitry Andric // Compute ASAP and ZeroLatencyDepth.
1886344a3780SDimitry Andric for (int I : Topo) {
1887b915e9e0SDimitry Andric int asap = 0;
1888eb11fae6SDimitry Andric int zeroLatencyDepth = 0;
1889344a3780SDimitry Andric SUnit *SU = &SUnits[I];
1890f65dcba8SDimitry Andric for (const SDep &P : SU->Preds) {
1891f65dcba8SDimitry Andric SUnit *pred = P.getSUnit();
1892f65dcba8SDimitry Andric if (P.getLatency() == 0)
1893eb11fae6SDimitry Andric zeroLatencyDepth =
1894eb11fae6SDimitry Andric std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
1895f65dcba8SDimitry Andric if (ignoreDependence(P, true))
1896b915e9e0SDimitry Andric continue;
1897f65dcba8SDimitry Andric asap = std::max(asap, (int)(getASAP(pred) + P.getLatency() -
1898f65dcba8SDimitry Andric getDistance(pred, SU, P) * MII));
1899b915e9e0SDimitry Andric }
1900b915e9e0SDimitry Andric maxASAP = std::max(maxASAP, asap);
1901344a3780SDimitry Andric ScheduleInfo[I].ASAP = asap;
1902344a3780SDimitry Andric ScheduleInfo[I].ZeroLatencyDepth = zeroLatencyDepth;
1903b915e9e0SDimitry Andric }
1904b915e9e0SDimitry Andric
1905eb11fae6SDimitry Andric // Compute ALAP, ZeroLatencyHeight, and MOV.
190677fc4c14SDimitry Andric for (int I : llvm::reverse(Topo)) {
1907b915e9e0SDimitry Andric int alap = maxASAP;
1908eb11fae6SDimitry Andric int zeroLatencyHeight = 0;
190977fc4c14SDimitry Andric SUnit *SU = &SUnits[I];
191077fc4c14SDimitry Andric for (const SDep &S : SU->Succs) {
191177fc4c14SDimitry Andric SUnit *succ = S.getSUnit();
1912145449b1SDimitry Andric if (succ->isBoundaryNode())
1913145449b1SDimitry Andric continue;
191477fc4c14SDimitry Andric if (S.getLatency() == 0)
1915eb11fae6SDimitry Andric zeroLatencyHeight =
1916eb11fae6SDimitry Andric std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
191777fc4c14SDimitry Andric if (ignoreDependence(S, true))
1918b915e9e0SDimitry Andric continue;
191977fc4c14SDimitry Andric alap = std::min(alap, (int)(getALAP(succ) - S.getLatency() +
192077fc4c14SDimitry Andric getDistance(SU, succ, S) * MII));
1921b915e9e0SDimitry Andric }
1922b915e9e0SDimitry Andric
192377fc4c14SDimitry Andric ScheduleInfo[I].ALAP = alap;
192477fc4c14SDimitry Andric ScheduleInfo[I].ZeroLatencyHeight = zeroLatencyHeight;
1925b915e9e0SDimitry Andric }
1926b915e9e0SDimitry Andric
1927b915e9e0SDimitry Andric // After computing the node functions, compute the summary for each node set.
1928b915e9e0SDimitry Andric for (NodeSet &I : NodeSets)
1929b915e9e0SDimitry Andric I.computeNodeSetInfo(this);
1930b915e9e0SDimitry Andric
1931eb11fae6SDimitry Andric LLVM_DEBUG({
1932b915e9e0SDimitry Andric for (unsigned i = 0; i < SUnits.size(); i++) {
1933b915e9e0SDimitry Andric dbgs() << "\tNode " << i << ":\n";
1934b915e9e0SDimitry Andric dbgs() << "\t ASAP = " << getASAP(&SUnits[i]) << "\n";
1935b915e9e0SDimitry Andric dbgs() << "\t ALAP = " << getALAP(&SUnits[i]) << "\n";
1936b915e9e0SDimitry Andric dbgs() << "\t MOV = " << getMOV(&SUnits[i]) << "\n";
1937b915e9e0SDimitry Andric dbgs() << "\t D = " << getDepth(&SUnits[i]) << "\n";
1938b915e9e0SDimitry Andric dbgs() << "\t H = " << getHeight(&SUnits[i]) << "\n";
1939eb11fae6SDimitry Andric dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
1940eb11fae6SDimitry Andric dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
1941b915e9e0SDimitry Andric }
1942b915e9e0SDimitry Andric });
1943b915e9e0SDimitry Andric }
1944b915e9e0SDimitry Andric
1945b915e9e0SDimitry Andric /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1946b915e9e0SDimitry Andric /// as the predecessors of the elements of NodeOrder that are not also in
1947b915e9e0SDimitry Andric /// NodeOrder.
pred_L(SetVector<SUnit * > & NodeOrder,SmallSetVector<SUnit *,8> & Preds,const NodeSet * S=nullptr)1948b915e9e0SDimitry Andric static bool pred_L(SetVector<SUnit *> &NodeOrder,
1949b915e9e0SDimitry Andric SmallSetVector<SUnit *, 8> &Preds,
1950b915e9e0SDimitry Andric const NodeSet *S = nullptr) {
1951b915e9e0SDimitry Andric Preds.clear();
1952f65dcba8SDimitry Andric for (const SUnit *SU : NodeOrder) {
1953f65dcba8SDimitry Andric for (const SDep &Pred : SU->Preds) {
1954344a3780SDimitry Andric if (S && S->count(Pred.getSUnit()) == 0)
1955b915e9e0SDimitry Andric continue;
1956344a3780SDimitry Andric if (ignoreDependence(Pred, true))
1957b915e9e0SDimitry Andric continue;
1958344a3780SDimitry Andric if (NodeOrder.count(Pred.getSUnit()) == 0)
1959344a3780SDimitry Andric Preds.insert(Pred.getSUnit());
1960b915e9e0SDimitry Andric }
1961b915e9e0SDimitry Andric // Back-edges are predecessors with an anti-dependence.
1962f65dcba8SDimitry Andric for (const SDep &Succ : SU->Succs) {
1963344a3780SDimitry Andric if (Succ.getKind() != SDep::Anti)
1964b915e9e0SDimitry Andric continue;
1965344a3780SDimitry Andric if (S && S->count(Succ.getSUnit()) == 0)
1966b915e9e0SDimitry Andric continue;
1967344a3780SDimitry Andric if (NodeOrder.count(Succ.getSUnit()) == 0)
1968344a3780SDimitry Andric Preds.insert(Succ.getSUnit());
1969b915e9e0SDimitry Andric }
1970b915e9e0SDimitry Andric }
1971044eb2f6SDimitry Andric return !Preds.empty();
1972b915e9e0SDimitry Andric }
1973b915e9e0SDimitry Andric
1974b915e9e0SDimitry Andric /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1975b915e9e0SDimitry Andric /// as the successors of the elements of NodeOrder that are not also in
1976b915e9e0SDimitry Andric /// NodeOrder.
succ_L(SetVector<SUnit * > & NodeOrder,SmallSetVector<SUnit *,8> & Succs,const NodeSet * S=nullptr)1977b915e9e0SDimitry Andric static bool succ_L(SetVector<SUnit *> &NodeOrder,
1978b915e9e0SDimitry Andric SmallSetVector<SUnit *, 8> &Succs,
1979b915e9e0SDimitry Andric const NodeSet *S = nullptr) {
1980b915e9e0SDimitry Andric Succs.clear();
198177fc4c14SDimitry Andric for (const SUnit *SU : NodeOrder) {
198277fc4c14SDimitry Andric for (const SDep &Succ : SU->Succs) {
1983344a3780SDimitry Andric if (S && S->count(Succ.getSUnit()) == 0)
1984b915e9e0SDimitry Andric continue;
1985344a3780SDimitry Andric if (ignoreDependence(Succ, false))
1986b915e9e0SDimitry Andric continue;
1987344a3780SDimitry Andric if (NodeOrder.count(Succ.getSUnit()) == 0)
1988344a3780SDimitry Andric Succs.insert(Succ.getSUnit());
1989b915e9e0SDimitry Andric }
199077fc4c14SDimitry Andric for (const SDep &Pred : SU->Preds) {
1991344a3780SDimitry Andric if (Pred.getKind() != SDep::Anti)
1992b915e9e0SDimitry Andric continue;
1993344a3780SDimitry Andric if (S && S->count(Pred.getSUnit()) == 0)
1994b915e9e0SDimitry Andric continue;
1995344a3780SDimitry Andric if (NodeOrder.count(Pred.getSUnit()) == 0)
1996344a3780SDimitry Andric Succs.insert(Pred.getSUnit());
1997b915e9e0SDimitry Andric }
1998b915e9e0SDimitry Andric }
1999044eb2f6SDimitry Andric return !Succs.empty();
2000b915e9e0SDimitry Andric }
2001b915e9e0SDimitry Andric
2002b915e9e0SDimitry Andric /// Return true if there is a path from the specified node to any of the nodes
2003b915e9e0SDimitry Andric /// in DestNodes. Keep track and return the nodes in any path.
computePath(SUnit * Cur,SetVector<SUnit * > & Path,SetVector<SUnit * > & DestNodes,SetVector<SUnit * > & Exclude,SmallPtrSet<SUnit *,8> & Visited)2004b915e9e0SDimitry Andric static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
2005b915e9e0SDimitry Andric SetVector<SUnit *> &DestNodes,
2006b915e9e0SDimitry Andric SetVector<SUnit *> &Exclude,
2007b915e9e0SDimitry Andric SmallPtrSet<SUnit *, 8> &Visited) {
2008b915e9e0SDimitry Andric if (Cur->isBoundaryNode())
2009b915e9e0SDimitry Andric return false;
2010b60736ecSDimitry Andric if (Exclude.contains(Cur))
2011b915e9e0SDimitry Andric return false;
2012b60736ecSDimitry Andric if (DestNodes.contains(Cur))
2013b915e9e0SDimitry Andric return true;
2014b915e9e0SDimitry Andric if (!Visited.insert(Cur).second)
2015b60736ecSDimitry Andric return Path.contains(Cur);
2016b915e9e0SDimitry Andric bool FoundPath = false;
2017b915e9e0SDimitry Andric for (auto &SI : Cur->Succs)
2018145449b1SDimitry Andric if (!ignoreDependence(SI, false))
2019145449b1SDimitry Andric FoundPath |=
2020145449b1SDimitry Andric computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
2021b915e9e0SDimitry Andric for (auto &PI : Cur->Preds)
2022b915e9e0SDimitry Andric if (PI.getKind() == SDep::Anti)
2023b915e9e0SDimitry Andric FoundPath |=
2024b915e9e0SDimitry Andric computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
2025b915e9e0SDimitry Andric if (FoundPath)
2026b915e9e0SDimitry Andric Path.insert(Cur);
2027b915e9e0SDimitry Andric return FoundPath;
2028b915e9e0SDimitry Andric }
2029b915e9e0SDimitry Andric
2030b915e9e0SDimitry Andric /// Compute the live-out registers for the instructions in a node-set.
2031b915e9e0SDimitry Andric /// The live-out registers are those that are defined in the node-set,
2032b915e9e0SDimitry Andric /// but not used. Except for use operands of Phis.
computeLiveOuts(MachineFunction & MF,RegPressureTracker & RPTracker,NodeSet & NS)2033b915e9e0SDimitry Andric static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
2034b915e9e0SDimitry Andric NodeSet &NS) {
2035b915e9e0SDimitry Andric const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2036b915e9e0SDimitry Andric MachineRegisterInfo &MRI = MF.getRegInfo();
2037b915e9e0SDimitry Andric SmallVector<RegisterMaskPair, 8> LiveOutRegs;
2038b915e9e0SDimitry Andric SmallSet<unsigned, 4> Uses;
2039b915e9e0SDimitry Andric for (SUnit *SU : NS) {
2040b915e9e0SDimitry Andric const MachineInstr *MI = SU->getInstr();
2041b915e9e0SDimitry Andric if (MI->isPHI())
2042b915e9e0SDimitry Andric continue;
20437fa27ce4SDimitry Andric for (const MachineOperand &MO : MI->all_uses()) {
20441d5ae102SDimitry Andric Register Reg = MO.getReg();
2045e3b55780SDimitry Andric if (Reg.isVirtual())
2046b915e9e0SDimitry Andric Uses.insert(Reg);
2047b915e9e0SDimitry Andric else if (MRI.isAllocatable(Reg))
20487fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
20497fa27ce4SDimitry Andric Uses.insert(Unit);
2050b915e9e0SDimitry Andric }
2051b915e9e0SDimitry Andric }
2052b915e9e0SDimitry Andric for (SUnit *SU : NS)
20537fa27ce4SDimitry Andric for (const MachineOperand &MO : SU->getInstr()->all_defs())
20547fa27ce4SDimitry Andric if (!MO.isDead()) {
20551d5ae102SDimitry Andric Register Reg = MO.getReg();
2056e3b55780SDimitry Andric if (Reg.isVirtual()) {
2057b915e9e0SDimitry Andric if (!Uses.count(Reg))
2058b915e9e0SDimitry Andric LiveOutRegs.push_back(RegisterMaskPair(Reg,
2059b915e9e0SDimitry Andric LaneBitmask::getNone()));
2060b915e9e0SDimitry Andric } else if (MRI.isAllocatable(Reg)) {
20617fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(Reg.asMCReg()))
20627fa27ce4SDimitry Andric if (!Uses.count(Unit))
20637fa27ce4SDimitry Andric LiveOutRegs.push_back(
20647fa27ce4SDimitry Andric RegisterMaskPair(Unit, LaneBitmask::getNone()));
2065b915e9e0SDimitry Andric }
2066b915e9e0SDimitry Andric }
2067b915e9e0SDimitry Andric RPTracker.addLiveRegs(LiveOutRegs);
2068b915e9e0SDimitry Andric }
2069b915e9e0SDimitry Andric
2070b915e9e0SDimitry Andric /// A heuristic to filter nodes in recurrent node-sets if the register
2071b915e9e0SDimitry Andric /// pressure of a set is too high.
registerPressureFilter(NodeSetType & NodeSets)2072b915e9e0SDimitry Andric void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
2073b915e9e0SDimitry Andric for (auto &NS : NodeSets) {
2074b915e9e0SDimitry Andric // Skip small node-sets since they won't cause register pressure problems.
2075b915e9e0SDimitry Andric if (NS.size() <= 2)
2076b915e9e0SDimitry Andric continue;
2077b915e9e0SDimitry Andric IntervalPressure RecRegPressure;
2078b915e9e0SDimitry Andric RegPressureTracker RecRPTracker(RecRegPressure);
2079b915e9e0SDimitry Andric RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
2080b915e9e0SDimitry Andric computeLiveOuts(MF, RecRPTracker, NS);
2081b915e9e0SDimitry Andric RecRPTracker.closeBottom();
2082b915e9e0SDimitry Andric
2083b915e9e0SDimitry Andric std::vector<SUnit *> SUnits(NS.begin(), NS.end());
2084d8e91e46SDimitry Andric llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
2085b915e9e0SDimitry Andric return A->NodeNum > B->NodeNum;
2086b915e9e0SDimitry Andric });
2087b915e9e0SDimitry Andric
2088b915e9e0SDimitry Andric for (auto &SU : SUnits) {
2089b915e9e0SDimitry Andric // Since we're computing the register pressure for a subset of the
2090b915e9e0SDimitry Andric // instructions in a block, we need to set the tracker for each
2091b915e9e0SDimitry Andric // instruction in the node-set. The tracker is set to the instruction
2092b915e9e0SDimitry Andric // just after the one we're interested in.
2093b915e9e0SDimitry Andric MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
2094b915e9e0SDimitry Andric RecRPTracker.setPos(std::next(CurInstI));
2095b915e9e0SDimitry Andric
2096b915e9e0SDimitry Andric RegPressureDelta RPDelta;
2097b915e9e0SDimitry Andric ArrayRef<PressureChange> CriticalPSets;
2098b915e9e0SDimitry Andric RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
2099b915e9e0SDimitry Andric CriticalPSets,
2100b915e9e0SDimitry Andric RecRegPressure.MaxSetPressure);
2101b915e9e0SDimitry Andric if (RPDelta.Excess.isValid()) {
2102eb11fae6SDimitry Andric LLVM_DEBUG(
2103eb11fae6SDimitry Andric dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
2104b915e9e0SDimitry Andric << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
2105145449b1SDimitry Andric << ":" << RPDelta.Excess.getUnitInc() << "\n");
2106b915e9e0SDimitry Andric NS.setExceedPressure(SU);
2107b915e9e0SDimitry Andric break;
2108b915e9e0SDimitry Andric }
2109b915e9e0SDimitry Andric RecRPTracker.recede();
2110b915e9e0SDimitry Andric }
2111b915e9e0SDimitry Andric }
2112b915e9e0SDimitry Andric }
2113b915e9e0SDimitry Andric
2114b915e9e0SDimitry Andric /// A heuristic to colocate node sets that have the same set of
2115b915e9e0SDimitry Andric /// successors.
colocateNodeSets(NodeSetType & NodeSets)2116b915e9e0SDimitry Andric void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
2117b915e9e0SDimitry Andric unsigned Colocate = 0;
2118b915e9e0SDimitry Andric for (int i = 0, e = NodeSets.size(); i < e; ++i) {
2119b915e9e0SDimitry Andric NodeSet &N1 = NodeSets[i];
2120b915e9e0SDimitry Andric SmallSetVector<SUnit *, 8> S1;
2121b915e9e0SDimitry Andric if (N1.empty() || !succ_L(N1, S1))
2122b915e9e0SDimitry Andric continue;
2123b915e9e0SDimitry Andric for (int j = i + 1; j < e; ++j) {
2124b915e9e0SDimitry Andric NodeSet &N2 = NodeSets[j];
2125b915e9e0SDimitry Andric if (N1.compareRecMII(N2) != 0)
2126b915e9e0SDimitry Andric continue;
2127b915e9e0SDimitry Andric SmallSetVector<SUnit *, 8> S2;
2128b915e9e0SDimitry Andric if (N2.empty() || !succ_L(N2, S2))
2129b915e9e0SDimitry Andric continue;
2130344a3780SDimitry Andric if (llvm::set_is_subset(S1, S2) && S1.size() == S2.size()) {
2131b915e9e0SDimitry Andric N1.setColocate(++Colocate);
2132b915e9e0SDimitry Andric N2.setColocate(Colocate);
2133b915e9e0SDimitry Andric break;
2134b915e9e0SDimitry Andric }
2135b915e9e0SDimitry Andric }
2136b915e9e0SDimitry Andric }
2137b915e9e0SDimitry Andric }
2138b915e9e0SDimitry Andric
2139b915e9e0SDimitry Andric /// Check if the existing node-sets are profitable. If not, then ignore the
2140b915e9e0SDimitry Andric /// recurrent node-sets, and attempt to schedule all nodes together. This is
2141eb11fae6SDimitry Andric /// a heuristic. If the MII is large and all the recurrent node-sets are small,
2142eb11fae6SDimitry Andric /// then it's best to try to schedule all instructions together instead of
2143eb11fae6SDimitry Andric /// starting with the recurrent node-sets.
checkNodeSets(NodeSetType & NodeSets)2144b915e9e0SDimitry Andric void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
2145b915e9e0SDimitry Andric // Look for loops with a large MII.
2146eb11fae6SDimitry Andric if (MII < 17)
2147b915e9e0SDimitry Andric return;
2148b915e9e0SDimitry Andric // Check if the node-set contains only a simple add recurrence.
2149eb11fae6SDimitry Andric for (auto &NS : NodeSets) {
2150eb11fae6SDimitry Andric if (NS.getRecMII() > 2)
2151b915e9e0SDimitry Andric return;
2152eb11fae6SDimitry Andric if (NS.getMaxDepth() > MII)
2153b915e9e0SDimitry Andric return;
2154b915e9e0SDimitry Andric }
2155eb11fae6SDimitry Andric NodeSets.clear();
2156eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
2157b915e9e0SDimitry Andric }
2158b915e9e0SDimitry Andric
2159b915e9e0SDimitry Andric /// Add the nodes that do not belong to a recurrence set into groups
2160145449b1SDimitry Andric /// based upon connected components.
groupRemainingNodes(NodeSetType & NodeSets)2161b915e9e0SDimitry Andric void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
2162b915e9e0SDimitry Andric SetVector<SUnit *> NodesAdded;
2163b915e9e0SDimitry Andric SmallPtrSet<SUnit *, 8> Visited;
2164b915e9e0SDimitry Andric // Add the nodes that are on a path between the previous node sets and
2165b915e9e0SDimitry Andric // the current node set.
2166b915e9e0SDimitry Andric for (NodeSet &I : NodeSets) {
2167b915e9e0SDimitry Andric SmallSetVector<SUnit *, 8> N;
2168b915e9e0SDimitry Andric // Add the nodes from the current node set to the previous node set.
2169b915e9e0SDimitry Andric if (succ_L(I, N)) {
2170b915e9e0SDimitry Andric SetVector<SUnit *> Path;
2171b915e9e0SDimitry Andric for (SUnit *NI : N) {
2172b915e9e0SDimitry Andric Visited.clear();
2173b915e9e0SDimitry Andric computePath(NI, Path, NodesAdded, I, Visited);
2174b915e9e0SDimitry Andric }
2175044eb2f6SDimitry Andric if (!Path.empty())
2176b915e9e0SDimitry Andric I.insert(Path.begin(), Path.end());
2177b915e9e0SDimitry Andric }
2178b915e9e0SDimitry Andric // Add the nodes from the previous node set to the current node set.
2179b915e9e0SDimitry Andric N.clear();
2180b915e9e0SDimitry Andric if (succ_L(NodesAdded, N)) {
2181b915e9e0SDimitry Andric SetVector<SUnit *> Path;
2182b915e9e0SDimitry Andric for (SUnit *NI : N) {
2183b915e9e0SDimitry Andric Visited.clear();
2184b915e9e0SDimitry Andric computePath(NI, Path, I, NodesAdded, Visited);
2185b915e9e0SDimitry Andric }
2186044eb2f6SDimitry Andric if (!Path.empty())
2187b915e9e0SDimitry Andric I.insert(Path.begin(), Path.end());
2188b915e9e0SDimitry Andric }
2189b915e9e0SDimitry Andric NodesAdded.insert(I.begin(), I.end());
2190b915e9e0SDimitry Andric }
2191b915e9e0SDimitry Andric
2192b915e9e0SDimitry Andric // Create a new node set with the connected nodes of any successor of a node
2193b915e9e0SDimitry Andric // in a recurrent set.
2194b915e9e0SDimitry Andric NodeSet NewSet;
2195b915e9e0SDimitry Andric SmallSetVector<SUnit *, 8> N;
2196b915e9e0SDimitry Andric if (succ_L(NodesAdded, N))
2197b915e9e0SDimitry Andric for (SUnit *I : N)
2198b915e9e0SDimitry Andric addConnectedNodes(I, NewSet, NodesAdded);
2199044eb2f6SDimitry Andric if (!NewSet.empty())
2200b915e9e0SDimitry Andric NodeSets.push_back(NewSet);
2201b915e9e0SDimitry Andric
2202b915e9e0SDimitry Andric // Create a new node set with the connected nodes of any predecessor of a node
2203b915e9e0SDimitry Andric // in a recurrent set.
2204b915e9e0SDimitry Andric NewSet.clear();
2205b915e9e0SDimitry Andric if (pred_L(NodesAdded, N))
2206b915e9e0SDimitry Andric for (SUnit *I : N)
2207b915e9e0SDimitry Andric addConnectedNodes(I, NewSet, NodesAdded);
2208044eb2f6SDimitry Andric if (!NewSet.empty())
2209b915e9e0SDimitry Andric NodeSets.push_back(NewSet);
2210b915e9e0SDimitry Andric
2211eb11fae6SDimitry Andric // Create new nodes sets with the connected nodes any remaining node that
2212b915e9e0SDimitry Andric // has no predecessor.
2213344a3780SDimitry Andric for (SUnit &SU : SUnits) {
2214344a3780SDimitry Andric if (NodesAdded.count(&SU) == 0) {
2215b915e9e0SDimitry Andric NewSet.clear();
2216344a3780SDimitry Andric addConnectedNodes(&SU, NewSet, NodesAdded);
2217044eb2f6SDimitry Andric if (!NewSet.empty())
2218b915e9e0SDimitry Andric NodeSets.push_back(NewSet);
2219b915e9e0SDimitry Andric }
2220b915e9e0SDimitry Andric }
2221b915e9e0SDimitry Andric }
2222b915e9e0SDimitry Andric
2223e6d15924SDimitry Andric /// Add the node to the set, and add all of its connected nodes to the set.
addConnectedNodes(SUnit * SU,NodeSet & NewSet,SetVector<SUnit * > & NodesAdded)2224b915e9e0SDimitry Andric void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
2225b915e9e0SDimitry Andric SetVector<SUnit *> &NodesAdded) {
2226b915e9e0SDimitry Andric NewSet.insert(SU);
2227b915e9e0SDimitry Andric NodesAdded.insert(SU);
2228b915e9e0SDimitry Andric for (auto &SI : SU->Succs) {
2229b915e9e0SDimitry Andric SUnit *Successor = SI.getSUnit();
2230145449b1SDimitry Andric if (!SI.isArtificial() && !Successor->isBoundaryNode() &&
2231145449b1SDimitry Andric NodesAdded.count(Successor) == 0)
2232b915e9e0SDimitry Andric addConnectedNodes(Successor, NewSet, NodesAdded);
2233b915e9e0SDimitry Andric }
2234b915e9e0SDimitry Andric for (auto &PI : SU->Preds) {
2235b915e9e0SDimitry Andric SUnit *Predecessor = PI.getSUnit();
2236b915e9e0SDimitry Andric if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
2237b915e9e0SDimitry Andric addConnectedNodes(Predecessor, NewSet, NodesAdded);
2238b915e9e0SDimitry Andric }
2239b915e9e0SDimitry Andric }
2240b915e9e0SDimitry Andric
2241b915e9e0SDimitry Andric /// Return true if Set1 contains elements in Set2. The elements in common
2242b915e9e0SDimitry Andric /// are returned in a different container.
isIntersect(SmallSetVector<SUnit *,8> & Set1,const NodeSet & Set2,SmallSetVector<SUnit *,8> & Result)2243b915e9e0SDimitry Andric static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
2244b915e9e0SDimitry Andric SmallSetVector<SUnit *, 8> &Result) {
2245b915e9e0SDimitry Andric Result.clear();
2246145449b1SDimitry Andric for (SUnit *SU : Set1) {
2247b915e9e0SDimitry Andric if (Set2.count(SU) != 0)
2248b915e9e0SDimitry Andric Result.insert(SU);
2249b915e9e0SDimitry Andric }
2250b915e9e0SDimitry Andric return !Result.empty();
2251b915e9e0SDimitry Andric }
2252b915e9e0SDimitry Andric
2253b915e9e0SDimitry Andric /// Merge the recurrence node sets that have the same initial node.
fuseRecs(NodeSetType & NodeSets)2254b915e9e0SDimitry Andric void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
2255b915e9e0SDimitry Andric for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
2256b915e9e0SDimitry Andric ++I) {
2257b915e9e0SDimitry Andric NodeSet &NI = *I;
2258b915e9e0SDimitry Andric for (NodeSetType::iterator J = I + 1; J != E;) {
2259b915e9e0SDimitry Andric NodeSet &NJ = *J;
2260b915e9e0SDimitry Andric if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
2261b915e9e0SDimitry Andric if (NJ.compareRecMII(NI) > 0)
2262b915e9e0SDimitry Andric NI.setRecMII(NJ.getRecMII());
2263344a3780SDimitry Andric for (SUnit *SU : *J)
2264344a3780SDimitry Andric I->insert(SU);
2265b915e9e0SDimitry Andric NodeSets.erase(J);
2266b915e9e0SDimitry Andric E = NodeSets.end();
2267b915e9e0SDimitry Andric } else {
2268b915e9e0SDimitry Andric ++J;
2269b915e9e0SDimitry Andric }
2270b915e9e0SDimitry Andric }
2271b915e9e0SDimitry Andric }
2272b915e9e0SDimitry Andric }
2273b915e9e0SDimitry Andric
2274b915e9e0SDimitry Andric /// Remove nodes that have been scheduled in previous NodeSets.
removeDuplicateNodes(NodeSetType & NodeSets)2275b915e9e0SDimitry Andric void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
2276b915e9e0SDimitry Andric for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
2277b915e9e0SDimitry Andric ++I)
2278b915e9e0SDimitry Andric for (NodeSetType::iterator J = I + 1; J != E;) {
2279b915e9e0SDimitry Andric J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
2280b915e9e0SDimitry Andric
2281044eb2f6SDimitry Andric if (J->empty()) {
2282b915e9e0SDimitry Andric NodeSets.erase(J);
2283b915e9e0SDimitry Andric E = NodeSets.end();
2284b915e9e0SDimitry Andric } else {
2285b915e9e0SDimitry Andric ++J;
2286b915e9e0SDimitry Andric }
2287b915e9e0SDimitry Andric }
2288b915e9e0SDimitry Andric }
2289b915e9e0SDimitry Andric
2290b915e9e0SDimitry Andric /// Compute an ordered list of the dependence graph nodes, which
2291b915e9e0SDimitry Andric /// indicates the order that the nodes will be scheduled. This is a
2292b915e9e0SDimitry Andric /// two-level algorithm. First, a partial order is created, which
2293b915e9e0SDimitry Andric /// consists of a list of sets ordered from highest to lowest priority.
computeNodeOrder(NodeSetType & NodeSets)2294b915e9e0SDimitry Andric void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
2295b915e9e0SDimitry Andric SmallSetVector<SUnit *, 8> R;
2296b915e9e0SDimitry Andric NodeOrder.clear();
2297b915e9e0SDimitry Andric
2298b915e9e0SDimitry Andric for (auto &Nodes : NodeSets) {
2299eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
2300b915e9e0SDimitry Andric OrderKind Order;
2301b915e9e0SDimitry Andric SmallSetVector<SUnit *, 8> N;
2302344a3780SDimitry Andric if (pred_L(NodeOrder, N) && llvm::set_is_subset(N, Nodes)) {
2303b915e9e0SDimitry Andric R.insert(N.begin(), N.end());
2304b915e9e0SDimitry Andric Order = BottomUp;
2305eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Bottom up (preds) ");
2306344a3780SDimitry Andric } else if (succ_L(NodeOrder, N) && llvm::set_is_subset(N, Nodes)) {
2307b915e9e0SDimitry Andric R.insert(N.begin(), N.end());
2308b915e9e0SDimitry Andric Order = TopDown;
2309eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Top down (succs) ");
2310b915e9e0SDimitry Andric } else if (isIntersect(N, Nodes, R)) {
2311b915e9e0SDimitry Andric // If some of the successors are in the existing node-set, then use the
2312b915e9e0SDimitry Andric // top-down ordering.
2313b915e9e0SDimitry Andric Order = TopDown;
2314eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Top down (intersect) ");
2315b915e9e0SDimitry Andric } else if (NodeSets.size() == 1) {
23164b4fe385SDimitry Andric for (const auto &N : Nodes)
2317b915e9e0SDimitry Andric if (N->Succs.size() == 0)
2318b915e9e0SDimitry Andric R.insert(N);
2319b915e9e0SDimitry Andric Order = BottomUp;
2320eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Bottom up (all) ");
2321b915e9e0SDimitry Andric } else {
2322b915e9e0SDimitry Andric // Find the node with the highest ASAP.
2323b915e9e0SDimitry Andric SUnit *maxASAP = nullptr;
2324b915e9e0SDimitry Andric for (SUnit *SU : Nodes) {
2325eb11fae6SDimitry Andric if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
2326eb11fae6SDimitry Andric (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
2327b915e9e0SDimitry Andric maxASAP = SU;
2328b915e9e0SDimitry Andric }
2329b915e9e0SDimitry Andric R.insert(maxASAP);
2330b915e9e0SDimitry Andric Order = BottomUp;
2331eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << " Bottom up (default) ");
2332b915e9e0SDimitry Andric }
2333b915e9e0SDimitry Andric
2334b915e9e0SDimitry Andric while (!R.empty()) {
2335b915e9e0SDimitry Andric if (Order == TopDown) {
2336b915e9e0SDimitry Andric // Choose the node with the maximum height. If more than one, choose
2337eb11fae6SDimitry Andric // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
2338eb11fae6SDimitry Andric // choose the node with the lowest MOV.
2339b915e9e0SDimitry Andric while (!R.empty()) {
2340b915e9e0SDimitry Andric SUnit *maxHeight = nullptr;
2341b915e9e0SDimitry Andric for (SUnit *I : R) {
2342b915e9e0SDimitry Andric if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
2343b915e9e0SDimitry Andric maxHeight = I;
2344b915e9e0SDimitry Andric else if (getHeight(I) == getHeight(maxHeight) &&
2345eb11fae6SDimitry Andric getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
2346b915e9e0SDimitry Andric maxHeight = I;
2347eb11fae6SDimitry Andric else if (getHeight(I) == getHeight(maxHeight) &&
2348eb11fae6SDimitry Andric getZeroLatencyHeight(I) ==
2349eb11fae6SDimitry Andric getZeroLatencyHeight(maxHeight) &&
2350eb11fae6SDimitry Andric getMOV(I) < getMOV(maxHeight))
2351b915e9e0SDimitry Andric maxHeight = I;
2352b915e9e0SDimitry Andric }
2353b915e9e0SDimitry Andric NodeOrder.insert(maxHeight);
2354eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
2355b915e9e0SDimitry Andric R.remove(maxHeight);
2356b915e9e0SDimitry Andric for (const auto &I : maxHeight->Succs) {
2357b915e9e0SDimitry Andric if (Nodes.count(I.getSUnit()) == 0)
2358b915e9e0SDimitry Andric continue;
2359b60736ecSDimitry Andric if (NodeOrder.contains(I.getSUnit()))
2360b915e9e0SDimitry Andric continue;
2361b915e9e0SDimitry Andric if (ignoreDependence(I, false))
2362b915e9e0SDimitry Andric continue;
2363b915e9e0SDimitry Andric R.insert(I.getSUnit());
2364b915e9e0SDimitry Andric }
2365b915e9e0SDimitry Andric // Back-edges are predecessors with an anti-dependence.
2366b915e9e0SDimitry Andric for (const auto &I : maxHeight->Preds) {
2367b915e9e0SDimitry Andric if (I.getKind() != SDep::Anti)
2368b915e9e0SDimitry Andric continue;
2369b915e9e0SDimitry Andric if (Nodes.count(I.getSUnit()) == 0)
2370b915e9e0SDimitry Andric continue;
2371b60736ecSDimitry Andric if (NodeOrder.contains(I.getSUnit()))
2372b915e9e0SDimitry Andric continue;
2373b915e9e0SDimitry Andric R.insert(I.getSUnit());
2374b915e9e0SDimitry Andric }
2375b915e9e0SDimitry Andric }
2376b915e9e0SDimitry Andric Order = BottomUp;
2377eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "\n Switching order to bottom up ");
2378b915e9e0SDimitry Andric SmallSetVector<SUnit *, 8> N;
2379b915e9e0SDimitry Andric if (pred_L(NodeOrder, N, &Nodes))
2380b915e9e0SDimitry Andric R.insert(N.begin(), N.end());
2381b915e9e0SDimitry Andric } else {
2382b915e9e0SDimitry Andric // Choose the node with the maximum depth. If more than one, choose
2383eb11fae6SDimitry Andric // the node with the maximum ZeroLatencyDepth. If still more than one,
2384eb11fae6SDimitry Andric // choose the node with the lowest MOV.
2385b915e9e0SDimitry Andric while (!R.empty()) {
2386b915e9e0SDimitry Andric SUnit *maxDepth = nullptr;
2387b915e9e0SDimitry Andric for (SUnit *I : R) {
2388b915e9e0SDimitry Andric if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
2389b915e9e0SDimitry Andric maxDepth = I;
2390b915e9e0SDimitry Andric else if (getDepth(I) == getDepth(maxDepth) &&
2391eb11fae6SDimitry Andric getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
2392b915e9e0SDimitry Andric maxDepth = I;
2393eb11fae6SDimitry Andric else if (getDepth(I) == getDepth(maxDepth) &&
2394eb11fae6SDimitry Andric getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
2395eb11fae6SDimitry Andric getMOV(I) < getMOV(maxDepth))
2396b915e9e0SDimitry Andric maxDepth = I;
2397b915e9e0SDimitry Andric }
2398b915e9e0SDimitry Andric NodeOrder.insert(maxDepth);
2399eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
2400b915e9e0SDimitry Andric R.remove(maxDepth);
2401b915e9e0SDimitry Andric if (Nodes.isExceedSU(maxDepth)) {
2402b915e9e0SDimitry Andric Order = TopDown;
2403b915e9e0SDimitry Andric R.clear();
2404b915e9e0SDimitry Andric R.insert(Nodes.getNode(0));
2405b915e9e0SDimitry Andric break;
2406b915e9e0SDimitry Andric }
2407b915e9e0SDimitry Andric for (const auto &I : maxDepth->Preds) {
2408b915e9e0SDimitry Andric if (Nodes.count(I.getSUnit()) == 0)
2409b915e9e0SDimitry Andric continue;
2410b60736ecSDimitry Andric if (NodeOrder.contains(I.getSUnit()))
2411b915e9e0SDimitry Andric continue;
2412b915e9e0SDimitry Andric R.insert(I.getSUnit());
2413b915e9e0SDimitry Andric }
2414b915e9e0SDimitry Andric // Back-edges are predecessors with an anti-dependence.
2415b915e9e0SDimitry Andric for (const auto &I : maxDepth->Succs) {
2416b915e9e0SDimitry Andric if (I.getKind() != SDep::Anti)
2417b915e9e0SDimitry Andric continue;
2418b915e9e0SDimitry Andric if (Nodes.count(I.getSUnit()) == 0)
2419b915e9e0SDimitry Andric continue;
2420b60736ecSDimitry Andric if (NodeOrder.contains(I.getSUnit()))
2421b915e9e0SDimitry Andric continue;
2422b915e9e0SDimitry Andric R.insert(I.getSUnit());
2423b915e9e0SDimitry Andric }
2424b915e9e0SDimitry Andric }
2425b915e9e0SDimitry Andric Order = TopDown;
2426eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "\n Switching order to top down ");
2427b915e9e0SDimitry Andric SmallSetVector<SUnit *, 8> N;
2428b915e9e0SDimitry Andric if (succ_L(NodeOrder, N, &Nodes))
2429b915e9e0SDimitry Andric R.insert(N.begin(), N.end());
2430b915e9e0SDimitry Andric }
2431b915e9e0SDimitry Andric }
2432eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
2433b915e9e0SDimitry Andric }
2434b915e9e0SDimitry Andric
2435eb11fae6SDimitry Andric LLVM_DEBUG({
2436b915e9e0SDimitry Andric dbgs() << "Node order: ";
2437b915e9e0SDimitry Andric for (SUnit *I : NodeOrder)
2438b915e9e0SDimitry Andric dbgs() << " " << I->NodeNum << " ";
2439b915e9e0SDimitry Andric dbgs() << "\n";
2440b915e9e0SDimitry Andric });
2441b915e9e0SDimitry Andric }
2442b915e9e0SDimitry Andric
2443b915e9e0SDimitry Andric /// Process the nodes in the computed order and create the pipelined schedule
2444b915e9e0SDimitry Andric /// of the instructions, if possible. Return true if a schedule is found.
schedulePipeline(SMSchedule & Schedule)2445b915e9e0SDimitry Andric bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
2446e6d15924SDimitry Andric
2447e6d15924SDimitry Andric if (NodeOrder.empty()){
2448e6d15924SDimitry Andric LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
2449b915e9e0SDimitry Andric return false;
2450e6d15924SDimitry Andric }
2451b915e9e0SDimitry Andric
2452b915e9e0SDimitry Andric bool scheduleFound = false;
24534df029ccSDimitry Andric std::unique_ptr<HighRegisterPressureDetector> HRPDetector;
24544df029ccSDimitry Andric if (LimitRegPressure) {
24554df029ccSDimitry Andric HRPDetector =
24564df029ccSDimitry Andric std::make_unique<HighRegisterPressureDetector>(Loop.getHeader(), MF);
24574df029ccSDimitry Andric HRPDetector->init(RegClassInfo);
24584df029ccSDimitry Andric }
2459b915e9e0SDimitry Andric // Keep increasing II until a valid schedule is found.
2460344a3780SDimitry Andric for (unsigned II = MII; II <= MAX_II && !scheduleFound; ++II) {
2461b915e9e0SDimitry Andric Schedule.reset();
2462b915e9e0SDimitry Andric Schedule.setInitiationInterval(II);
2463eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
2464b915e9e0SDimitry Andric
2465b915e9e0SDimitry Andric SetVector<SUnit *>::iterator NI = NodeOrder.begin();
2466b915e9e0SDimitry Andric SetVector<SUnit *>::iterator NE = NodeOrder.end();
2467b915e9e0SDimitry Andric do {
2468b915e9e0SDimitry Andric SUnit *SU = *NI;
2469b915e9e0SDimitry Andric
2470b915e9e0SDimitry Andric // Compute the schedule time for the instruction, which is based
2471b915e9e0SDimitry Andric // upon the scheduled time for any predecessors/successors.
2472b915e9e0SDimitry Andric int EarlyStart = INT_MIN;
2473b915e9e0SDimitry Andric int LateStart = INT_MAX;
2474ac9a064cSDimitry Andric Schedule.computeStart(SU, &EarlyStart, &LateStart, II, this);
2475eb11fae6SDimitry Andric LLVM_DEBUG({
2476e6d15924SDimitry Andric dbgs() << "\n";
2477b915e9e0SDimitry Andric dbgs() << "Inst (" << SU->NodeNum << ") ";
2478b915e9e0SDimitry Andric SU->getInstr()->dump();
2479b915e9e0SDimitry Andric dbgs() << "\n";
2480b915e9e0SDimitry Andric });
2481ac9a064cSDimitry Andric LLVM_DEBUG(
2482ac9a064cSDimitry Andric dbgs() << format("\tes: %8x ls: %8x\n", EarlyStart, LateStart));
2483b915e9e0SDimitry Andric
2484ac9a064cSDimitry Andric if (EarlyStart > LateStart)
2485b915e9e0SDimitry Andric scheduleFound = false;
2486ac9a064cSDimitry Andric else if (EarlyStart != INT_MIN && LateStart == INT_MAX)
2487ac9a064cSDimitry Andric scheduleFound =
2488ac9a064cSDimitry Andric Schedule.insert(SU, EarlyStart, EarlyStart + (int)II - 1, II);
2489ac9a064cSDimitry Andric else if (EarlyStart == INT_MIN && LateStart != INT_MAX)
2490ac9a064cSDimitry Andric scheduleFound =
2491ac9a064cSDimitry Andric Schedule.insert(SU, LateStart, LateStart - (int)II + 1, II);
2492ac9a064cSDimitry Andric else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
2493ac9a064cSDimitry Andric LateStart = std::min(LateStart, EarlyStart + (int)II - 1);
2494ac9a064cSDimitry Andric // When scheduling a Phi it is better to start at the late cycle and
2495ac9a064cSDimitry Andric // go backwards. The default order may insert the Phi too far away
2496ac9a064cSDimitry Andric // from its first dependence.
2497ac9a064cSDimitry Andric // Also, do backward search when all scheduled predecessors are
2498ac9a064cSDimitry Andric // loop-carried output/order dependencies. Empirically, there are also
2499ac9a064cSDimitry Andric // cases where scheduling becomes possible with backward search.
2500ac9a064cSDimitry Andric if (SU->getInstr()->isPHI() ||
2501ac9a064cSDimitry Andric Schedule.onlyHasLoopCarriedOutputOrOrderPreds(SU, this))
2502ac9a064cSDimitry Andric scheduleFound = Schedule.insert(SU, LateStart, EarlyStart, II);
2503b915e9e0SDimitry Andric else
2504ac9a064cSDimitry Andric scheduleFound = Schedule.insert(SU, EarlyStart, LateStart, II);
2505b915e9e0SDimitry Andric } else {
2506b915e9e0SDimitry Andric int FirstCycle = Schedule.getFirstCycle();
2507b915e9e0SDimitry Andric scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
2508b915e9e0SDimitry Andric FirstCycle + getASAP(SU) + II - 1, II);
2509b915e9e0SDimitry Andric }
2510ac9a064cSDimitry Andric
2511b915e9e0SDimitry Andric // Even if we find a schedule, make sure the schedule doesn't exceed the
2512b915e9e0SDimitry Andric // allowable number of stages. We keep trying if this happens.
2513b915e9e0SDimitry Andric if (scheduleFound)
2514b915e9e0SDimitry Andric if (SwpMaxStages > -1 &&
2515b915e9e0SDimitry Andric Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
2516b915e9e0SDimitry Andric scheduleFound = false;
2517b915e9e0SDimitry Andric
2518eb11fae6SDimitry Andric LLVM_DEBUG({
2519b915e9e0SDimitry Andric if (!scheduleFound)
2520b915e9e0SDimitry Andric dbgs() << "\tCan't schedule\n";
2521b915e9e0SDimitry Andric });
2522b915e9e0SDimitry Andric } while (++NI != NE && scheduleFound);
2523b915e9e0SDimitry Andric
2524145449b1SDimitry Andric // If a schedule is found, ensure non-pipelined instructions are in stage 0
2525145449b1SDimitry Andric if (scheduleFound)
2526145449b1SDimitry Andric scheduleFound =
2527145449b1SDimitry Andric Schedule.normalizeNonPipelinedInstructions(this, LoopPipelinerInfo);
2528145449b1SDimitry Andric
2529b915e9e0SDimitry Andric // If a schedule is found, check if it is a valid schedule too.
2530b915e9e0SDimitry Andric if (scheduleFound)
2531b915e9e0SDimitry Andric scheduleFound = Schedule.isValidSchedule(this);
25324df029ccSDimitry Andric
25334df029ccSDimitry Andric // If a schedule was found and the option is enabled, check if the schedule
25344df029ccSDimitry Andric // might generate additional register spills/fills.
25354df029ccSDimitry Andric if (scheduleFound && LimitRegPressure)
25364df029ccSDimitry Andric scheduleFound =
25374df029ccSDimitry Andric !HRPDetector->detect(this, Schedule, Schedule.getMaxStageCount());
2538b915e9e0SDimitry Andric }
2539b915e9e0SDimitry Andric
2540344a3780SDimitry Andric LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound
2541344a3780SDimitry Andric << " (II=" << Schedule.getInitiationInterval()
2542e6d15924SDimitry Andric << ")\n");
2543b915e9e0SDimitry Andric
2544cfca06d7SDimitry Andric if (scheduleFound) {
2545e3b55780SDimitry Andric scheduleFound = LoopPipelinerInfo->shouldUseSchedule(*this, Schedule);
2546e3b55780SDimitry Andric if (!scheduleFound)
2547e3b55780SDimitry Andric LLVM_DEBUG(dbgs() << "Target rejected schedule\n");
2548e3b55780SDimitry Andric }
2549e3b55780SDimitry Andric
2550e3b55780SDimitry Andric if (scheduleFound) {
2551b915e9e0SDimitry Andric Schedule.finalizeSchedule(this);
2552cfca06d7SDimitry Andric Pass.ORE->emit([&]() {
2553cfca06d7SDimitry Andric return MachineOptimizationRemarkAnalysis(
2554cfca06d7SDimitry Andric DEBUG_TYPE, "schedule", Loop.getStartLoc(), Loop.getHeader())
2555344a3780SDimitry Andric << "Schedule found with Initiation Interval: "
2556344a3780SDimitry Andric << ore::NV("II", Schedule.getInitiationInterval())
2557cfca06d7SDimitry Andric << ", MaxStageCount: "
2558cfca06d7SDimitry Andric << ore::NV("MaxStageCount", Schedule.getMaxStageCount());
2559cfca06d7SDimitry Andric });
2560cfca06d7SDimitry Andric } else
2561b915e9e0SDimitry Andric Schedule.reset();
2562b915e9e0SDimitry Andric
2563b915e9e0SDimitry Andric return scheduleFound && Schedule.getMaxStageCount() > 0;
2564b915e9e0SDimitry Andric }
2565b915e9e0SDimitry Andric
2566b915e9e0SDimitry Andric /// Return true if we can compute the amount the instruction changes
2567b915e9e0SDimitry Andric /// during each iteration. Set Delta to the amount of the change.
computeDelta(MachineInstr & MI,unsigned & Delta)2568b915e9e0SDimitry Andric bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
2569b915e9e0SDimitry Andric const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2570e6d15924SDimitry Andric const MachineOperand *BaseOp;
2571b915e9e0SDimitry Andric int64_t Offset;
2572cfca06d7SDimitry Andric bool OffsetIsScalable;
2573cfca06d7SDimitry Andric if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
2574cfca06d7SDimitry Andric return false;
2575cfca06d7SDimitry Andric
2576cfca06d7SDimitry Andric // FIXME: This algorithm assumes instructions have fixed-size offsets.
2577cfca06d7SDimitry Andric if (OffsetIsScalable)
2578b915e9e0SDimitry Andric return false;
2579b915e9e0SDimitry Andric
2580d8e91e46SDimitry Andric if (!BaseOp->isReg())
2581d8e91e46SDimitry Andric return false;
2582d8e91e46SDimitry Andric
25831d5ae102SDimitry Andric Register BaseReg = BaseOp->getReg();
2584d8e91e46SDimitry Andric
2585b915e9e0SDimitry Andric MachineRegisterInfo &MRI = MF.getRegInfo();
2586b915e9e0SDimitry Andric // Check if there is a Phi. If so, get the definition in the loop.
2587b915e9e0SDimitry Andric MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
2588b915e9e0SDimitry Andric if (BaseDef && BaseDef->isPHI()) {
2589b915e9e0SDimitry Andric BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
2590b915e9e0SDimitry Andric BaseDef = MRI.getVRegDef(BaseReg);
2591b915e9e0SDimitry Andric }
2592b915e9e0SDimitry Andric if (!BaseDef)
2593b915e9e0SDimitry Andric return false;
2594b915e9e0SDimitry Andric
2595b915e9e0SDimitry Andric int D = 0;
2596b915e9e0SDimitry Andric if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
2597b915e9e0SDimitry Andric return false;
2598b915e9e0SDimitry Andric
2599b915e9e0SDimitry Andric Delta = D;
2600b915e9e0SDimitry Andric return true;
2601b915e9e0SDimitry Andric }
2602b915e9e0SDimitry Andric
2603b915e9e0SDimitry Andric /// Check if we can change the instruction to use an offset value from the
2604b915e9e0SDimitry Andric /// previous iteration. If so, return true and set the base and offset values
2605b915e9e0SDimitry Andric /// so that we can rewrite the load, if necessary.
2606b915e9e0SDimitry Andric /// v1 = Phi(v0, v3)
2607b915e9e0SDimitry Andric /// v2 = load v1, 0
2608b915e9e0SDimitry Andric /// v3 = post_store v1, 4, x
2609b915e9e0SDimitry Andric /// This function enables the load to be rewritten as v2 = load v3, 4.
canUseLastOffsetValue(MachineInstr * MI,unsigned & BasePos,unsigned & OffsetPos,unsigned & NewBase,int64_t & Offset)2610b915e9e0SDimitry Andric bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
2611b915e9e0SDimitry Andric unsigned &BasePos,
2612b915e9e0SDimitry Andric unsigned &OffsetPos,
2613b915e9e0SDimitry Andric unsigned &NewBase,
2614b915e9e0SDimitry Andric int64_t &Offset) {
2615b915e9e0SDimitry Andric // Get the load instruction.
2616b915e9e0SDimitry Andric if (TII->isPostIncrement(*MI))
2617b915e9e0SDimitry Andric return false;
2618b915e9e0SDimitry Andric unsigned BasePosLd, OffsetPosLd;
2619b915e9e0SDimitry Andric if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
2620b915e9e0SDimitry Andric return false;
26211d5ae102SDimitry Andric Register BaseReg = MI->getOperand(BasePosLd).getReg();
2622b915e9e0SDimitry Andric
2623b915e9e0SDimitry Andric // Look for the Phi instruction.
2624044eb2f6SDimitry Andric MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
2625b915e9e0SDimitry Andric MachineInstr *Phi = MRI.getVRegDef(BaseReg);
2626b915e9e0SDimitry Andric if (!Phi || !Phi->isPHI())
2627b915e9e0SDimitry Andric return false;
2628b915e9e0SDimitry Andric // Get the register defined in the loop block.
2629b915e9e0SDimitry Andric unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
2630b915e9e0SDimitry Andric if (!PrevReg)
2631b915e9e0SDimitry Andric return false;
2632b915e9e0SDimitry Andric
2633b915e9e0SDimitry Andric // Check for the post-increment load/store instruction.
2634b915e9e0SDimitry Andric MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
2635b915e9e0SDimitry Andric if (!PrevDef || PrevDef == MI)
2636b915e9e0SDimitry Andric return false;
2637b915e9e0SDimitry Andric
2638b915e9e0SDimitry Andric if (!TII->isPostIncrement(*PrevDef))
2639b915e9e0SDimitry Andric return false;
2640b915e9e0SDimitry Andric
2641b915e9e0SDimitry Andric unsigned BasePos1 = 0, OffsetPos1 = 0;
2642b915e9e0SDimitry Andric if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
2643b915e9e0SDimitry Andric return false;
2644b915e9e0SDimitry Andric
2645eb11fae6SDimitry Andric // Make sure that the instructions do not access the same memory location in
2646eb11fae6SDimitry Andric // the next iteration.
2647b915e9e0SDimitry Andric int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
2648b915e9e0SDimitry Andric int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
2649eb11fae6SDimitry Andric MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2650eb11fae6SDimitry Andric NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
2651eb11fae6SDimitry Andric bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
265277fc4c14SDimitry Andric MF.deleteMachineInstr(NewMI);
2653eb11fae6SDimitry Andric if (!Disjoint)
2654b915e9e0SDimitry Andric return false;
2655b915e9e0SDimitry Andric
2656b915e9e0SDimitry Andric // Set the return value once we determine that we return true.
2657b915e9e0SDimitry Andric BasePos = BasePosLd;
2658b915e9e0SDimitry Andric OffsetPos = OffsetPosLd;
2659b915e9e0SDimitry Andric NewBase = PrevReg;
2660b915e9e0SDimitry Andric Offset = StoreOffset;
2661b915e9e0SDimitry Andric return true;
2662b915e9e0SDimitry Andric }
2663b915e9e0SDimitry Andric
2664b915e9e0SDimitry Andric /// Apply changes to the instruction if needed. The changes are need
2665b915e9e0SDimitry Andric /// to improve the scheduling and depend up on the final schedule.
applyInstrChange(MachineInstr * MI,SMSchedule & Schedule)2666044eb2f6SDimitry Andric void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
2667044eb2f6SDimitry Andric SMSchedule &Schedule) {
2668b915e9e0SDimitry Andric SUnit *SU = getSUnit(MI);
2669b915e9e0SDimitry Andric DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2670b915e9e0SDimitry Andric InstrChanges.find(SU);
2671b915e9e0SDimitry Andric if (It != InstrChanges.end()) {
2672b915e9e0SDimitry Andric std::pair<unsigned, int64_t> RegAndOffset = It->second;
2673b915e9e0SDimitry Andric unsigned BasePos, OffsetPos;
2674b915e9e0SDimitry Andric if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
2675044eb2f6SDimitry Andric return;
26761d5ae102SDimitry Andric Register BaseReg = MI->getOperand(BasePos).getReg();
2677b915e9e0SDimitry Andric MachineInstr *LoopDef = findDefInLoop(BaseReg);
2678b915e9e0SDimitry Andric int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
2679b915e9e0SDimitry Andric int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
2680b915e9e0SDimitry Andric int BaseStageNum = Schedule.stageScheduled(SU);
2681b915e9e0SDimitry Andric int BaseCycleNum = Schedule.cycleScheduled(SU);
2682b915e9e0SDimitry Andric if (BaseStageNum < DefStageNum) {
2683b915e9e0SDimitry Andric MachineInstr *NewMI = MF.CloneMachineInstr(MI);
2684b915e9e0SDimitry Andric int OffsetDiff = DefStageNum - BaseStageNum;
2685b915e9e0SDimitry Andric if (DefCycleNum < BaseCycleNum) {
2686b915e9e0SDimitry Andric NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
2687b915e9e0SDimitry Andric if (OffsetDiff > 0)
2688b915e9e0SDimitry Andric --OffsetDiff;
2689b915e9e0SDimitry Andric }
2690b915e9e0SDimitry Andric int64_t NewOffset =
2691b915e9e0SDimitry Andric MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
2692b915e9e0SDimitry Andric NewMI->getOperand(OffsetPos).setImm(NewOffset);
2693b915e9e0SDimitry Andric SU->setInstr(NewMI);
2694b915e9e0SDimitry Andric MISUnitMap[NewMI] = SU;
26951d5ae102SDimitry Andric NewMIs[MI] = NewMI;
2696b915e9e0SDimitry Andric }
2697b915e9e0SDimitry Andric }
2698b915e9e0SDimitry Andric }
2699b915e9e0SDimitry Andric
27001d5ae102SDimitry Andric /// Return the instruction in the loop that defines the register.
27011d5ae102SDimitry Andric /// If the definition is a Phi, then follow the Phi operand to
27021d5ae102SDimitry Andric /// the instruction in the loop.
findDefInLoop(Register Reg)2703b60736ecSDimitry Andric MachineInstr *SwingSchedulerDAG::findDefInLoop(Register Reg) {
27041d5ae102SDimitry Andric SmallPtrSet<MachineInstr *, 8> Visited;
27051d5ae102SDimitry Andric MachineInstr *Def = MRI.getVRegDef(Reg);
27061d5ae102SDimitry Andric while (Def->isPHI()) {
27071d5ae102SDimitry Andric if (!Visited.insert(Def).second)
27081d5ae102SDimitry Andric break;
27091d5ae102SDimitry Andric for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
27101d5ae102SDimitry Andric if (Def->getOperand(i + 1).getMBB() == BB) {
27111d5ae102SDimitry Andric Def = MRI.getVRegDef(Def->getOperand(i).getReg());
27121d5ae102SDimitry Andric break;
27131d5ae102SDimitry Andric }
27141d5ae102SDimitry Andric }
27151d5ae102SDimitry Andric return Def;
27161d5ae102SDimitry Andric }
27171d5ae102SDimitry Andric
2718eb11fae6SDimitry Andric /// Return true for an order or output dependence that is loop carried
2719312c0ed1SDimitry Andric /// potentially. A dependence is loop carried if the destination defines a value
2720eb11fae6SDimitry Andric /// that may be used or defined by the source in a subsequent iteration.
isLoopCarriedDep(SUnit * Source,const SDep & Dep,bool isSucc)2721eb11fae6SDimitry Andric bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
2722b915e9e0SDimitry Andric bool isSucc) {
2723eb11fae6SDimitry Andric if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
2724145449b1SDimitry Andric Dep.isArtificial() || Dep.getSUnit()->isBoundaryNode())
2725b915e9e0SDimitry Andric return false;
2726b915e9e0SDimitry Andric
2727b915e9e0SDimitry Andric if (!SwpPruneLoopCarried)
2728b915e9e0SDimitry Andric return true;
2729b915e9e0SDimitry Andric
2730eb11fae6SDimitry Andric if (Dep.getKind() == SDep::Output)
2731eb11fae6SDimitry Andric return true;
2732eb11fae6SDimitry Andric
2733b915e9e0SDimitry Andric MachineInstr *SI = Source->getInstr();
2734b915e9e0SDimitry Andric MachineInstr *DI = Dep.getSUnit()->getInstr();
2735b915e9e0SDimitry Andric if (!isSucc)
2736b915e9e0SDimitry Andric std::swap(SI, DI);
2737b915e9e0SDimitry Andric assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
2738b915e9e0SDimitry Andric
2739b915e9e0SDimitry Andric // Assume ordered loads and stores may have a loop carried dependence.
2740b915e9e0SDimitry Andric if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
2741e6d15924SDimitry Andric SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
2742b915e9e0SDimitry Andric SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
2743b915e9e0SDimitry Andric return true;
2744b915e9e0SDimitry Andric
2745312c0ed1SDimitry Andric if (!DI->mayLoadOrStore() || !SI->mayLoadOrStore())
2746b915e9e0SDimitry Andric return false;
2747b915e9e0SDimitry Andric
2748312c0ed1SDimitry Andric // The conservative assumption is that a dependence between memory operations
2749312c0ed1SDimitry Andric // may be loop carried. The following code checks when it can be proved that
2750312c0ed1SDimitry Andric // there is no loop carried dependence.
2751b915e9e0SDimitry Andric unsigned DeltaS, DeltaD;
2752b915e9e0SDimitry Andric if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
2753b915e9e0SDimitry Andric return true;
2754b915e9e0SDimitry Andric
2755e6d15924SDimitry Andric const MachineOperand *BaseOpS, *BaseOpD;
2756b915e9e0SDimitry Andric int64_t OffsetS, OffsetD;
2757cfca06d7SDimitry Andric bool OffsetSIsScalable, OffsetDIsScalable;
2758b915e9e0SDimitry Andric const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2759cfca06d7SDimitry Andric if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, OffsetSIsScalable,
2760cfca06d7SDimitry Andric TRI) ||
2761cfca06d7SDimitry Andric !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, OffsetDIsScalable,
2762cfca06d7SDimitry Andric TRI))
2763b915e9e0SDimitry Andric return true;
2764b915e9e0SDimitry Andric
2765cfca06d7SDimitry Andric assert(!OffsetSIsScalable && !OffsetDIsScalable &&
2766cfca06d7SDimitry Andric "Expected offsets to be byte offsets");
2767cfca06d7SDimitry Andric
2768e3b55780SDimitry Andric MachineInstr *DefS = MRI.getVRegDef(BaseOpS->getReg());
2769e3b55780SDimitry Andric MachineInstr *DefD = MRI.getVRegDef(BaseOpD->getReg());
2770e3b55780SDimitry Andric if (!DefS || !DefD || !DefS->isPHI() || !DefD->isPHI())
2771e3b55780SDimitry Andric return true;
2772e3b55780SDimitry Andric
2773e3b55780SDimitry Andric unsigned InitValS = 0;
2774e3b55780SDimitry Andric unsigned LoopValS = 0;
2775e3b55780SDimitry Andric unsigned InitValD = 0;
2776e3b55780SDimitry Andric unsigned LoopValD = 0;
2777e3b55780SDimitry Andric getPhiRegs(*DefS, BB, InitValS, LoopValS);
2778e3b55780SDimitry Andric getPhiRegs(*DefD, BB, InitValD, LoopValD);
2779e3b55780SDimitry Andric MachineInstr *InitDefS = MRI.getVRegDef(InitValS);
2780e3b55780SDimitry Andric MachineInstr *InitDefD = MRI.getVRegDef(InitValD);
2781e3b55780SDimitry Andric
2782e3b55780SDimitry Andric if (!InitDefS->isIdenticalTo(*InitDefD))
2783b915e9e0SDimitry Andric return true;
2784b915e9e0SDimitry Andric
2785eb11fae6SDimitry Andric // Check that the base register is incremented by a constant value for each
2786eb11fae6SDimitry Andric // iteration.
2787e3b55780SDimitry Andric MachineInstr *LoopDefS = MRI.getVRegDef(LoopValS);
2788eb11fae6SDimitry Andric int D = 0;
2789e3b55780SDimitry Andric if (!LoopDefS || !TII->getIncrementValue(*LoopDefS, D))
2790eb11fae6SDimitry Andric return true;
2791eb11fae6SDimitry Andric
2792ac9a064cSDimitry Andric LocationSize AccessSizeS = (*SI->memoperands_begin())->getSize();
2793ac9a064cSDimitry Andric LocationSize AccessSizeD = (*DI->memoperands_begin())->getSize();
2794b915e9e0SDimitry Andric
2795b915e9e0SDimitry Andric // This is the main test, which checks the offset values and the loop
2796b915e9e0SDimitry Andric // increment value to determine if the accesses may be loop carried.
2797ac9a064cSDimitry Andric if (!AccessSizeS.hasValue() || !AccessSizeD.hasValue())
2798b915e9e0SDimitry Andric return true;
2799e6d15924SDimitry Andric
2800ac9a064cSDimitry Andric if (DeltaS != DeltaD || DeltaS < AccessSizeS.getValue() ||
2801ac9a064cSDimitry Andric DeltaD < AccessSizeD.getValue())
2802e6d15924SDimitry Andric return true;
2803e6d15924SDimitry Andric
2804ac9a064cSDimitry Andric return (OffsetS + (int64_t)AccessSizeS.getValue() <
2805ac9a064cSDimitry Andric OffsetD + (int64_t)AccessSizeD.getValue());
2806b915e9e0SDimitry Andric }
2807b915e9e0SDimitry Andric
postProcessDAG()28087fa27ce4SDimitry Andric void SwingSchedulerDAG::postProcessDAG() {
2809b915e9e0SDimitry Andric for (auto &M : Mutations)
2810b915e9e0SDimitry Andric M->apply(this);
2811b915e9e0SDimitry Andric }
2812b915e9e0SDimitry Andric
2813b915e9e0SDimitry Andric /// Try to schedule the node at the specified StartCycle and continue
2814b915e9e0SDimitry Andric /// until the node is schedule or the EndCycle is reached. This function
2815b915e9e0SDimitry Andric /// returns true if the node is scheduled. This routine may search either
2816b915e9e0SDimitry Andric /// forward or backward for a place to insert the instruction based upon
2817b915e9e0SDimitry Andric /// the relative values of StartCycle and EndCycle.
insert(SUnit * SU,int StartCycle,int EndCycle,int II)2818b915e9e0SDimitry Andric bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
2819b915e9e0SDimitry Andric bool forward = true;
2820e6d15924SDimitry Andric LLVM_DEBUG({
2821e6d15924SDimitry Andric dbgs() << "Trying to insert node between " << StartCycle << " and "
2822e6d15924SDimitry Andric << EndCycle << " II: " << II << "\n";
2823e6d15924SDimitry Andric });
2824b915e9e0SDimitry Andric if (StartCycle > EndCycle)
2825b915e9e0SDimitry Andric forward = false;
2826b915e9e0SDimitry Andric
2827b915e9e0SDimitry Andric // The terminating condition depends on the direction.
2828b915e9e0SDimitry Andric int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
2829b915e9e0SDimitry Andric for (int curCycle = StartCycle; curCycle != termCycle;
2830b915e9e0SDimitry Andric forward ? ++curCycle : --curCycle) {
2831b915e9e0SDimitry Andric
2832b915e9e0SDimitry Andric if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
2833e3b55780SDimitry Andric ProcItinResources.canReserveResources(*SU, curCycle)) {
2834eb11fae6SDimitry Andric LLVM_DEBUG({
2835b915e9e0SDimitry Andric dbgs() << "\tinsert at cycle " << curCycle << " ";
2836b915e9e0SDimitry Andric SU->getInstr()->dump();
2837b915e9e0SDimitry Andric });
2838b915e9e0SDimitry Andric
2839e3b55780SDimitry Andric if (!ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()))
2840e3b55780SDimitry Andric ProcItinResources.reserveResources(*SU, curCycle);
2841b915e9e0SDimitry Andric ScheduledInstrs[curCycle].push_back(SU);
2842b915e9e0SDimitry Andric InstrToCycle.insert(std::make_pair(SU, curCycle));
2843b915e9e0SDimitry Andric if (curCycle > LastCycle)
2844b915e9e0SDimitry Andric LastCycle = curCycle;
2845b915e9e0SDimitry Andric if (curCycle < FirstCycle)
2846b915e9e0SDimitry Andric FirstCycle = curCycle;
2847b915e9e0SDimitry Andric return true;
2848b915e9e0SDimitry Andric }
2849eb11fae6SDimitry Andric LLVM_DEBUG({
2850b915e9e0SDimitry Andric dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
2851b915e9e0SDimitry Andric SU->getInstr()->dump();
2852b915e9e0SDimitry Andric });
2853b915e9e0SDimitry Andric }
2854b915e9e0SDimitry Andric return false;
2855b915e9e0SDimitry Andric }
2856b915e9e0SDimitry Andric
2857b915e9e0SDimitry Andric // Return the cycle of the earliest scheduled instruction in the chain.
earliestCycleInChain(const SDep & Dep)2858b915e9e0SDimitry Andric int SMSchedule::earliestCycleInChain(const SDep &Dep) {
2859b915e9e0SDimitry Andric SmallPtrSet<SUnit *, 8> Visited;
2860b915e9e0SDimitry Andric SmallVector<SDep, 8> Worklist;
2861b915e9e0SDimitry Andric Worklist.push_back(Dep);
2862b915e9e0SDimitry Andric int EarlyCycle = INT_MAX;
2863b915e9e0SDimitry Andric while (!Worklist.empty()) {
2864b915e9e0SDimitry Andric const SDep &Cur = Worklist.pop_back_val();
2865b915e9e0SDimitry Andric SUnit *PrevSU = Cur.getSUnit();
2866b915e9e0SDimitry Andric if (Visited.count(PrevSU))
2867b915e9e0SDimitry Andric continue;
2868b915e9e0SDimitry Andric std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
2869b915e9e0SDimitry Andric if (it == InstrToCycle.end())
2870b915e9e0SDimitry Andric continue;
2871b915e9e0SDimitry Andric EarlyCycle = std::min(EarlyCycle, it->second);
2872b915e9e0SDimitry Andric for (const auto &PI : PrevSU->Preds)
2873cfca06d7SDimitry Andric if (PI.getKind() == SDep::Order || PI.getKind() == SDep::Output)
2874b915e9e0SDimitry Andric Worklist.push_back(PI);
2875b915e9e0SDimitry Andric Visited.insert(PrevSU);
2876b915e9e0SDimitry Andric }
2877b915e9e0SDimitry Andric return EarlyCycle;
2878b915e9e0SDimitry Andric }
2879b915e9e0SDimitry Andric
2880b915e9e0SDimitry Andric // Return the cycle of the latest scheduled instruction in the chain.
latestCycleInChain(const SDep & Dep)2881b915e9e0SDimitry Andric int SMSchedule::latestCycleInChain(const SDep &Dep) {
2882b915e9e0SDimitry Andric SmallPtrSet<SUnit *, 8> Visited;
2883b915e9e0SDimitry Andric SmallVector<SDep, 8> Worklist;
2884b915e9e0SDimitry Andric Worklist.push_back(Dep);
2885b915e9e0SDimitry Andric int LateCycle = INT_MIN;
2886b915e9e0SDimitry Andric while (!Worklist.empty()) {
2887b915e9e0SDimitry Andric const SDep &Cur = Worklist.pop_back_val();
2888b915e9e0SDimitry Andric SUnit *SuccSU = Cur.getSUnit();
2889145449b1SDimitry Andric if (Visited.count(SuccSU) || SuccSU->isBoundaryNode())
2890b915e9e0SDimitry Andric continue;
2891b915e9e0SDimitry Andric std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
2892b915e9e0SDimitry Andric if (it == InstrToCycle.end())
2893b915e9e0SDimitry Andric continue;
2894b915e9e0SDimitry Andric LateCycle = std::max(LateCycle, it->second);
2895b915e9e0SDimitry Andric for (const auto &SI : SuccSU->Succs)
2896cfca06d7SDimitry Andric if (SI.getKind() == SDep::Order || SI.getKind() == SDep::Output)
2897b915e9e0SDimitry Andric Worklist.push_back(SI);
2898b915e9e0SDimitry Andric Visited.insert(SuccSU);
2899b915e9e0SDimitry Andric }
2900b915e9e0SDimitry Andric return LateCycle;
2901b915e9e0SDimitry Andric }
2902b915e9e0SDimitry Andric
2903b915e9e0SDimitry Andric /// If an instruction has a use that spans multiple iterations, then
2904b915e9e0SDimitry Andric /// return true. These instructions are characterized by having a back-ege
2905b915e9e0SDimitry Andric /// to a Phi, which contains a reference to another Phi.
multipleIterations(SUnit * SU,SwingSchedulerDAG * DAG)2906b915e9e0SDimitry Andric static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
2907b915e9e0SDimitry Andric for (auto &P : SU->Preds)
2908b915e9e0SDimitry Andric if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
2909b915e9e0SDimitry Andric for (auto &S : P.getSUnit()->Succs)
2910eb11fae6SDimitry Andric if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
2911b915e9e0SDimitry Andric return P.getSUnit();
2912b915e9e0SDimitry Andric return nullptr;
2913b915e9e0SDimitry Andric }
2914b915e9e0SDimitry Andric
2915b915e9e0SDimitry Andric /// Compute the scheduling start slot for the instruction. The start slot
2916b915e9e0SDimitry Andric /// depends on any predecessor or successor nodes scheduled already.
computeStart(SUnit * SU,int * MaxEarlyStart,int * MinLateStart,int II,SwingSchedulerDAG * DAG)2917b915e9e0SDimitry Andric void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
2918ac9a064cSDimitry Andric int II, SwingSchedulerDAG *DAG) {
2919b915e9e0SDimitry Andric // Iterate over each instruction that has been scheduled already. The start
2920eb11fae6SDimitry Andric // slot computation depends on whether the previously scheduled instruction
2921b915e9e0SDimitry Andric // is a predecessor or successor of the specified instruction.
2922b915e9e0SDimitry Andric for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
2923b915e9e0SDimitry Andric
2924b915e9e0SDimitry Andric // Iterate over each instruction in the current cycle.
2925b915e9e0SDimitry Andric for (SUnit *I : getInstructions(cycle)) {
2926b915e9e0SDimitry Andric // Because we're processing a DAG for the dependences, we recognize
2927b915e9e0SDimitry Andric // the back-edge in recurrences by anti dependences.
2928b915e9e0SDimitry Andric for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
2929b915e9e0SDimitry Andric const SDep &Dep = SU->Preds[i];
2930b915e9e0SDimitry Andric if (Dep.getSUnit() == I) {
2931b915e9e0SDimitry Andric if (!DAG->isBackedge(SU, Dep)) {
2932eb11fae6SDimitry Andric int EarlyStart = cycle + Dep.getLatency() -
2933b915e9e0SDimitry Andric DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
2934b915e9e0SDimitry Andric *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
2935eb11fae6SDimitry Andric if (DAG->isLoopCarriedDep(SU, Dep, false)) {
2936b915e9e0SDimitry Andric int End = earliestCycleInChain(Dep) + (II - 1);
2937ac9a064cSDimitry Andric *MinLateStart = std::min(*MinLateStart, End);
2938b915e9e0SDimitry Andric }
2939b915e9e0SDimitry Andric } else {
2940eb11fae6SDimitry Andric int LateStart = cycle - Dep.getLatency() +
2941b915e9e0SDimitry Andric DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
2942b915e9e0SDimitry Andric *MinLateStart = std::min(*MinLateStart, LateStart);
2943b915e9e0SDimitry Andric }
2944b915e9e0SDimitry Andric }
2945b915e9e0SDimitry Andric // For instruction that requires multiple iterations, make sure that
2946b915e9e0SDimitry Andric // the dependent instruction is not scheduled past the definition.
2947b915e9e0SDimitry Andric SUnit *BE = multipleIterations(I, DAG);
2948b915e9e0SDimitry Andric if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
2949b915e9e0SDimitry Andric !SU->isPred(I))
2950b915e9e0SDimitry Andric *MinLateStart = std::min(*MinLateStart, cycle);
2951b915e9e0SDimitry Andric }
2952eb11fae6SDimitry Andric for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
2953b915e9e0SDimitry Andric if (SU->Succs[i].getSUnit() == I) {
2954b915e9e0SDimitry Andric const SDep &Dep = SU->Succs[i];
2955b915e9e0SDimitry Andric if (!DAG->isBackedge(SU, Dep)) {
2956eb11fae6SDimitry Andric int LateStart = cycle - Dep.getLatency() +
2957b915e9e0SDimitry Andric DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
2958b915e9e0SDimitry Andric *MinLateStart = std::min(*MinLateStart, LateStart);
2959eb11fae6SDimitry Andric if (DAG->isLoopCarriedDep(SU, Dep)) {
2960b915e9e0SDimitry Andric int Start = latestCycleInChain(Dep) + 1 - II;
2961ac9a064cSDimitry Andric *MaxEarlyStart = std::max(*MaxEarlyStart, Start);
2962b915e9e0SDimitry Andric }
2963b915e9e0SDimitry Andric } else {
2964eb11fae6SDimitry Andric int EarlyStart = cycle + Dep.getLatency() -
2965b915e9e0SDimitry Andric DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
2966b915e9e0SDimitry Andric *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
2967b915e9e0SDimitry Andric }
2968b915e9e0SDimitry Andric }
2969b915e9e0SDimitry Andric }
2970b915e9e0SDimitry Andric }
2971b915e9e0SDimitry Andric }
2972eb11fae6SDimitry Andric }
2973b915e9e0SDimitry Andric
2974b915e9e0SDimitry Andric /// Order the instructions within a cycle so that the definitions occur
2975b915e9e0SDimitry Andric /// before the uses. Returns true if the instruction is added to the start
2976b915e9e0SDimitry Andric /// of the list, or false if added to the end.
orderDependence(const SwingSchedulerDAG * SSD,SUnit * SU,std::deque<SUnit * > & Insts) const29774df029ccSDimitry Andric void SMSchedule::orderDependence(const SwingSchedulerDAG *SSD, SUnit *SU,
29784df029ccSDimitry Andric std::deque<SUnit *> &Insts) const {
2979b915e9e0SDimitry Andric MachineInstr *MI = SU->getInstr();
2980b915e9e0SDimitry Andric bool OrderBeforeUse = false;
2981b915e9e0SDimitry Andric bool OrderAfterDef = false;
2982b915e9e0SDimitry Andric bool OrderBeforeDef = false;
2983b915e9e0SDimitry Andric unsigned MoveDef = 0;
2984b915e9e0SDimitry Andric unsigned MoveUse = 0;
2985b915e9e0SDimitry Andric int StageInst1 = stageScheduled(SU);
2986b915e9e0SDimitry Andric
2987b915e9e0SDimitry Andric unsigned Pos = 0;
2988b915e9e0SDimitry Andric for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
2989b915e9e0SDimitry Andric ++I, ++Pos) {
2990f65dcba8SDimitry Andric for (MachineOperand &MO : MI->operands()) {
2991e3b55780SDimitry Andric if (!MO.isReg() || !MO.getReg().isVirtual())
2992b915e9e0SDimitry Andric continue;
2993eb11fae6SDimitry Andric
29941d5ae102SDimitry Andric Register Reg = MO.getReg();
2995b915e9e0SDimitry Andric unsigned BasePos, OffsetPos;
2996b915e9e0SDimitry Andric if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
2997b915e9e0SDimitry Andric if (MI->getOperand(BasePos).getReg() == Reg)
2998b915e9e0SDimitry Andric if (unsigned NewReg = SSD->getInstrBaseReg(SU))
2999b915e9e0SDimitry Andric Reg = NewReg;
3000b915e9e0SDimitry Andric bool Reads, Writes;
3001b915e9e0SDimitry Andric std::tie(Reads, Writes) =
3002b915e9e0SDimitry Andric (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3003b915e9e0SDimitry Andric if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
3004b915e9e0SDimitry Andric OrderBeforeUse = true;
3005eb11fae6SDimitry Andric if (MoveUse == 0)
3006b915e9e0SDimitry Andric MoveUse = Pos;
3007b915e9e0SDimitry Andric } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
3008b915e9e0SDimitry Andric // Add the instruction after the scheduled instruction.
3009b915e9e0SDimitry Andric OrderAfterDef = true;
3010b915e9e0SDimitry Andric MoveDef = Pos;
3011b915e9e0SDimitry Andric } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
3012b915e9e0SDimitry Andric if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
3013b915e9e0SDimitry Andric OrderBeforeUse = true;
3014eb11fae6SDimitry Andric if (MoveUse == 0)
3015b915e9e0SDimitry Andric MoveUse = Pos;
3016b915e9e0SDimitry Andric } else {
3017b915e9e0SDimitry Andric OrderAfterDef = true;
3018b915e9e0SDimitry Andric MoveDef = Pos;
3019b915e9e0SDimitry Andric }
3020b915e9e0SDimitry Andric } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
3021b915e9e0SDimitry Andric OrderBeforeUse = true;
3022eb11fae6SDimitry Andric if (MoveUse == 0)
3023b915e9e0SDimitry Andric MoveUse = Pos;
3024b915e9e0SDimitry Andric if (MoveUse != 0) {
3025b915e9e0SDimitry Andric OrderAfterDef = true;
3026b915e9e0SDimitry Andric MoveDef = Pos - 1;
3027b915e9e0SDimitry Andric }
3028b915e9e0SDimitry Andric } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
3029b915e9e0SDimitry Andric // Add the instruction before the scheduled instruction.
3030b915e9e0SDimitry Andric OrderBeforeUse = true;
3031eb11fae6SDimitry Andric if (MoveUse == 0)
3032b915e9e0SDimitry Andric MoveUse = Pos;
3033b915e9e0SDimitry Andric } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
3034b915e9e0SDimitry Andric isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
3035eb11fae6SDimitry Andric if (MoveUse == 0) {
3036b915e9e0SDimitry Andric OrderBeforeDef = true;
3037b915e9e0SDimitry Andric MoveUse = Pos;
3038b915e9e0SDimitry Andric }
3039b915e9e0SDimitry Andric }
3040eb11fae6SDimitry Andric }
3041b915e9e0SDimitry Andric // Check for order dependences between instructions. Make sure the source
3042b915e9e0SDimitry Andric // is ordered before the destination.
3043eb11fae6SDimitry Andric for (auto &S : SU->Succs) {
3044eb11fae6SDimitry Andric if (S.getSUnit() != *I)
3045eb11fae6SDimitry Andric continue;
3046eb11fae6SDimitry Andric if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3047b915e9e0SDimitry Andric OrderBeforeUse = true;
3048eb11fae6SDimitry Andric if (Pos < MoveUse)
3049b915e9e0SDimitry Andric MoveUse = Pos;
3050b915e9e0SDimitry Andric }
3051e6d15924SDimitry Andric // We did not handle HW dependences in previous for loop,
3052e6d15924SDimitry Andric // and we normally set Latency = 0 for Anti deps,
3053e6d15924SDimitry Andric // so may have nodes in same cycle with Anti denpendent on HW regs.
3054e6d15924SDimitry Andric else if (S.getKind() == SDep::Anti && stageScheduled(*I) == StageInst1) {
3055e6d15924SDimitry Andric OrderBeforeUse = true;
3056e6d15924SDimitry Andric if ((MoveUse == 0) || (Pos < MoveUse))
3057e6d15924SDimitry Andric MoveUse = Pos;
3058e6d15924SDimitry Andric }
3059b915e9e0SDimitry Andric }
3060eb11fae6SDimitry Andric for (auto &P : SU->Preds) {
3061eb11fae6SDimitry Andric if (P.getSUnit() != *I)
3062eb11fae6SDimitry Andric continue;
3063eb11fae6SDimitry Andric if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3064b915e9e0SDimitry Andric OrderAfterDef = true;
3065b915e9e0SDimitry Andric MoveDef = Pos;
3066b915e9e0SDimitry Andric }
3067b915e9e0SDimitry Andric }
3068b915e9e0SDimitry Andric }
3069b915e9e0SDimitry Andric
3070b915e9e0SDimitry Andric // A circular dependence.
3071b915e9e0SDimitry Andric if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3072b915e9e0SDimitry Andric OrderBeforeUse = false;
3073b915e9e0SDimitry Andric
3074b915e9e0SDimitry Andric // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
3075b915e9e0SDimitry Andric // to a loop-carried dependence.
3076b915e9e0SDimitry Andric if (OrderBeforeDef)
3077b915e9e0SDimitry Andric OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3078b915e9e0SDimitry Andric
3079b915e9e0SDimitry Andric // The uncommon case when the instruction order needs to be updated because
3080b915e9e0SDimitry Andric // there is both a use and def.
3081b915e9e0SDimitry Andric if (OrderBeforeUse && OrderAfterDef) {
3082b915e9e0SDimitry Andric SUnit *UseSU = Insts.at(MoveUse);
3083b915e9e0SDimitry Andric SUnit *DefSU = Insts.at(MoveDef);
3084b915e9e0SDimitry Andric if (MoveUse > MoveDef) {
3085b915e9e0SDimitry Andric Insts.erase(Insts.begin() + MoveUse);
3086b915e9e0SDimitry Andric Insts.erase(Insts.begin() + MoveDef);
3087b915e9e0SDimitry Andric } else {
3088b915e9e0SDimitry Andric Insts.erase(Insts.begin() + MoveDef);
3089b915e9e0SDimitry Andric Insts.erase(Insts.begin() + MoveUse);
3090b915e9e0SDimitry Andric }
3091eb11fae6SDimitry Andric orderDependence(SSD, UseSU, Insts);
3092eb11fae6SDimitry Andric orderDependence(SSD, SU, Insts);
3093b915e9e0SDimitry Andric orderDependence(SSD, DefSU, Insts);
3094eb11fae6SDimitry Andric return;
3095b915e9e0SDimitry Andric }
3096b915e9e0SDimitry Andric // Put the new instruction first if there is a use in the list. Otherwise,
3097b915e9e0SDimitry Andric // put it at the end of the list.
3098b915e9e0SDimitry Andric if (OrderBeforeUse)
3099b915e9e0SDimitry Andric Insts.push_front(SU);
3100b915e9e0SDimitry Andric else
3101b915e9e0SDimitry Andric Insts.push_back(SU);
3102b915e9e0SDimitry Andric }
3103b915e9e0SDimitry Andric
3104b915e9e0SDimitry Andric /// Return true if the scheduled Phi has a loop carried operand.
isLoopCarried(const SwingSchedulerDAG * SSD,MachineInstr & Phi) const31054df029ccSDimitry Andric bool SMSchedule::isLoopCarried(const SwingSchedulerDAG *SSD,
31064df029ccSDimitry Andric MachineInstr &Phi) const {
3107b915e9e0SDimitry Andric if (!Phi.isPHI())
3108b915e9e0SDimitry Andric return false;
3109eb11fae6SDimitry Andric assert(Phi.isPHI() && "Expecting a Phi.");
3110b915e9e0SDimitry Andric SUnit *DefSU = SSD->getSUnit(&Phi);
3111b915e9e0SDimitry Andric unsigned DefCycle = cycleScheduled(DefSU);
3112b915e9e0SDimitry Andric int DefStage = stageScheduled(DefSU);
3113b915e9e0SDimitry Andric
3114b915e9e0SDimitry Andric unsigned InitVal = 0;
3115b915e9e0SDimitry Andric unsigned LoopVal = 0;
3116b915e9e0SDimitry Andric getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
3117b915e9e0SDimitry Andric SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
3118b915e9e0SDimitry Andric if (!UseSU)
3119b915e9e0SDimitry Andric return true;
3120b915e9e0SDimitry Andric if (UseSU->getInstr()->isPHI())
3121b915e9e0SDimitry Andric return true;
3122b915e9e0SDimitry Andric unsigned LoopCycle = cycleScheduled(UseSU);
3123b915e9e0SDimitry Andric int LoopStage = stageScheduled(UseSU);
3124b915e9e0SDimitry Andric return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
3125b915e9e0SDimitry Andric }
3126b915e9e0SDimitry Andric
3127b915e9e0SDimitry Andric /// Return true if the instruction is a definition that is loop carried
3128b915e9e0SDimitry Andric /// and defines the use on the next iteration.
3129b915e9e0SDimitry Andric /// v1 = phi(v2, v3)
3130b915e9e0SDimitry Andric /// (Def) v3 = op v1
3131b915e9e0SDimitry Andric /// (MO) = v1
3132b1c73532SDimitry Andric /// If MO appears before Def, then v1 and v3 may get assigned to the same
3133b915e9e0SDimitry Andric /// register.
isLoopCarriedDefOfUse(const SwingSchedulerDAG * SSD,MachineInstr * Def,MachineOperand & MO) const31344df029ccSDimitry Andric bool SMSchedule::isLoopCarriedDefOfUse(const SwingSchedulerDAG *SSD,
31354df029ccSDimitry Andric MachineInstr *Def,
31364df029ccSDimitry Andric MachineOperand &MO) const {
3137b915e9e0SDimitry Andric if (!MO.isReg())
3138b915e9e0SDimitry Andric return false;
3139b915e9e0SDimitry Andric if (Def->isPHI())
3140b915e9e0SDimitry Andric return false;
3141b915e9e0SDimitry Andric MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
3142b915e9e0SDimitry Andric if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
3143b915e9e0SDimitry Andric return false;
3144b915e9e0SDimitry Andric if (!isLoopCarried(SSD, *Phi))
3145b915e9e0SDimitry Andric return false;
3146b915e9e0SDimitry Andric unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
31477fa27ce4SDimitry Andric for (MachineOperand &DMO : Def->all_defs()) {
3148b915e9e0SDimitry Andric if (DMO.getReg() == LoopReg)
3149b915e9e0SDimitry Andric return true;
3150b915e9e0SDimitry Andric }
3151b915e9e0SDimitry Andric return false;
3152b915e9e0SDimitry Andric }
3153b915e9e0SDimitry Andric
3154ac9a064cSDimitry Andric /// Return true if all scheduled predecessors are loop-carried output/order
3155ac9a064cSDimitry Andric /// dependencies.
onlyHasLoopCarriedOutputOrOrderPreds(SUnit * SU,SwingSchedulerDAG * DAG) const3156ac9a064cSDimitry Andric bool SMSchedule::onlyHasLoopCarriedOutputOrOrderPreds(
3157ac9a064cSDimitry Andric SUnit *SU, SwingSchedulerDAG *DAG) const {
3158ac9a064cSDimitry Andric for (const SDep &Pred : SU->Preds)
3159ac9a064cSDimitry Andric if (InstrToCycle.count(Pred.getSUnit()) && !DAG->isBackedge(SU, Pred))
3160ac9a064cSDimitry Andric return false;
3161ac9a064cSDimitry Andric for (const SDep &Succ : SU->Succs)
3162ac9a064cSDimitry Andric if (InstrToCycle.count(Succ.getSUnit()) && DAG->isBackedge(SU, Succ))
3163ac9a064cSDimitry Andric return false;
3164ac9a064cSDimitry Andric return true;
3165ac9a064cSDimitry Andric }
3166ac9a064cSDimitry Andric
3167145449b1SDimitry Andric /// Determine transitive dependences of unpipelineable instructions
computeUnpipelineableNodes(SwingSchedulerDAG * SSD,TargetInstrInfo::PipelinerLoopInfo * PLI)3168145449b1SDimitry Andric SmallSet<SUnit *, 8> SMSchedule::computeUnpipelineableNodes(
3169145449b1SDimitry Andric SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI) {
3170145449b1SDimitry Andric SmallSet<SUnit *, 8> DoNotPipeline;
3171145449b1SDimitry Andric SmallVector<SUnit *, 8> Worklist;
3172145449b1SDimitry Andric
3173145449b1SDimitry Andric for (auto &SU : SSD->SUnits)
3174145449b1SDimitry Andric if (SU.isInstr() && PLI->shouldIgnoreForPipelining(SU.getInstr()))
3175145449b1SDimitry Andric Worklist.push_back(&SU);
3176145449b1SDimitry Andric
3177145449b1SDimitry Andric while (!Worklist.empty()) {
3178145449b1SDimitry Andric auto SU = Worklist.pop_back_val();
3179145449b1SDimitry Andric if (DoNotPipeline.count(SU))
3180145449b1SDimitry Andric continue;
3181145449b1SDimitry Andric LLVM_DEBUG(dbgs() << "Do not pipeline SU(" << SU->NodeNum << ")\n");
3182145449b1SDimitry Andric DoNotPipeline.insert(SU);
3183145449b1SDimitry Andric for (auto &Dep : SU->Preds)
3184145449b1SDimitry Andric Worklist.push_back(Dep.getSUnit());
3185145449b1SDimitry Andric if (SU->getInstr()->isPHI())
3186145449b1SDimitry Andric for (auto &Dep : SU->Succs)
3187145449b1SDimitry Andric if (Dep.getKind() == SDep::Anti)
3188145449b1SDimitry Andric Worklist.push_back(Dep.getSUnit());
3189145449b1SDimitry Andric }
3190145449b1SDimitry Andric return DoNotPipeline;
3191145449b1SDimitry Andric }
3192145449b1SDimitry Andric
3193145449b1SDimitry Andric // Determine all instructions upon which any unpipelineable instruction depends
3194145449b1SDimitry Andric // and ensure that they are in stage 0. If unable to do so, return false.
normalizeNonPipelinedInstructions(SwingSchedulerDAG * SSD,TargetInstrInfo::PipelinerLoopInfo * PLI)3195145449b1SDimitry Andric bool SMSchedule::normalizeNonPipelinedInstructions(
3196145449b1SDimitry Andric SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI) {
3197145449b1SDimitry Andric SmallSet<SUnit *, 8> DNP = computeUnpipelineableNodes(SSD, PLI);
3198145449b1SDimitry Andric
3199145449b1SDimitry Andric int NewLastCycle = INT_MIN;
3200145449b1SDimitry Andric for (SUnit &SU : SSD->SUnits) {
3201145449b1SDimitry Andric if (!SU.isInstr())
3202145449b1SDimitry Andric continue;
3203145449b1SDimitry Andric if (!DNP.contains(&SU) || stageScheduled(&SU) == 0) {
3204145449b1SDimitry Andric NewLastCycle = std::max(NewLastCycle, InstrToCycle[&SU]);
3205145449b1SDimitry Andric continue;
3206145449b1SDimitry Andric }
3207145449b1SDimitry Andric
3208145449b1SDimitry Andric // Put the non-pipelined instruction as early as possible in the schedule
3209145449b1SDimitry Andric int NewCycle = getFirstCycle();
3210145449b1SDimitry Andric for (auto &Dep : SU.Preds)
3211145449b1SDimitry Andric NewCycle = std::max(InstrToCycle[Dep.getSUnit()], NewCycle);
3212145449b1SDimitry Andric
3213145449b1SDimitry Andric int OldCycle = InstrToCycle[&SU];
3214145449b1SDimitry Andric if (OldCycle != NewCycle) {
3215145449b1SDimitry Andric InstrToCycle[&SU] = NewCycle;
3216145449b1SDimitry Andric auto &OldS = getInstructions(OldCycle);
3217b1c73532SDimitry Andric llvm::erase(OldS, &SU);
3218145449b1SDimitry Andric getInstructions(NewCycle).emplace_back(&SU);
3219145449b1SDimitry Andric LLVM_DEBUG(dbgs() << "SU(" << SU.NodeNum
3220145449b1SDimitry Andric << ") is not pipelined; moving from cycle " << OldCycle
3221145449b1SDimitry Andric << " to " << NewCycle << " Instr:" << *SU.getInstr());
3222145449b1SDimitry Andric }
3223145449b1SDimitry Andric NewLastCycle = std::max(NewLastCycle, NewCycle);
3224145449b1SDimitry Andric }
3225145449b1SDimitry Andric LastCycle = NewLastCycle;
3226145449b1SDimitry Andric return true;
3227145449b1SDimitry Andric }
3228145449b1SDimitry Andric
3229b915e9e0SDimitry Andric // Check if the generated schedule is valid. This function checks if
3230b915e9e0SDimitry Andric // an instruction that uses a physical register is scheduled in a
3231b915e9e0SDimitry Andric // different stage than the definition. The pipeliner does not handle
3232b915e9e0SDimitry Andric // physical register values that may cross a basic block boundary.
3233145449b1SDimitry Andric // Furthermore, if a physical def/use pair is assigned to the same
3234145449b1SDimitry Andric // cycle, orderDependence does not guarantee def/use ordering, so that
3235145449b1SDimitry Andric // case should be considered invalid. (The test checks for both
3236145449b1SDimitry Andric // earlier and same-cycle use to be more robust.)
isValidSchedule(SwingSchedulerDAG * SSD)3237b915e9e0SDimitry Andric bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
3238344a3780SDimitry Andric for (SUnit &SU : SSD->SUnits) {
3239b915e9e0SDimitry Andric if (!SU.hasPhysRegDefs)
3240b915e9e0SDimitry Andric continue;
3241b915e9e0SDimitry Andric int StageDef = stageScheduled(&SU);
3242145449b1SDimitry Andric int CycleDef = InstrToCycle[&SU];
3243b915e9e0SDimitry Andric assert(StageDef != -1 && "Instruction should have been scheduled.");
3244b915e9e0SDimitry Andric for (auto &SI : SU.Succs)
3245145449b1SDimitry Andric if (SI.isAssignedRegDep() && !SI.getSUnit()->isBoundaryNode())
3246145449b1SDimitry Andric if (Register::isPhysicalRegister(SI.getReg())) {
3247b915e9e0SDimitry Andric if (stageScheduled(SI.getSUnit()) != StageDef)
3248b915e9e0SDimitry Andric return false;
3249145449b1SDimitry Andric if (InstrToCycle[SI.getSUnit()] <= CycleDef)
3250145449b1SDimitry Andric return false;
3251145449b1SDimitry Andric }
3252b915e9e0SDimitry Andric }
3253b915e9e0SDimitry Andric return true;
3254b915e9e0SDimitry Andric }
3255b915e9e0SDimitry Andric
3256eb11fae6SDimitry Andric /// A property of the node order in swing-modulo-scheduling is
3257eb11fae6SDimitry Andric /// that for nodes outside circuits the following holds:
3258eb11fae6SDimitry Andric /// none of them is scheduled after both a successor and a
3259eb11fae6SDimitry Andric /// predecessor.
3260eb11fae6SDimitry Andric /// The method below checks whether the property is met.
3261eb11fae6SDimitry Andric /// If not, debug information is printed and statistics information updated.
3262eb11fae6SDimitry Andric /// Note that we do not use an assert statement.
3263eb11fae6SDimitry Andric /// The reason is that although an invalid node oder may prevent
3264eb11fae6SDimitry Andric /// the pipeliner from finding a pipelined schedule for arbitrary II,
3265eb11fae6SDimitry Andric /// it does not lead to the generation of incorrect code.
checkValidNodeOrder(const NodeSetType & Circuits) const3266eb11fae6SDimitry Andric void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
3267eb11fae6SDimitry Andric
3268eb11fae6SDimitry Andric // a sorted vector that maps each SUnit to its index in the NodeOrder
3269eb11fae6SDimitry Andric typedef std::pair<SUnit *, unsigned> UnitIndex;
3270eb11fae6SDimitry Andric std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
3271eb11fae6SDimitry Andric
3272eb11fae6SDimitry Andric for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
3273eb11fae6SDimitry Andric Indices.push_back(std::make_pair(NodeOrder[i], i));
3274eb11fae6SDimitry Andric
3275eb11fae6SDimitry Andric auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
3276eb11fae6SDimitry Andric return std::get<0>(i1) < std::get<0>(i2);
3277eb11fae6SDimitry Andric };
3278eb11fae6SDimitry Andric
3279eb11fae6SDimitry Andric // sort, so that we can perform a binary search
3280d8e91e46SDimitry Andric llvm::sort(Indices, CompareKey);
3281eb11fae6SDimitry Andric
3282eb11fae6SDimitry Andric bool Valid = true;
3283eb11fae6SDimitry Andric (void)Valid;
3284eb11fae6SDimitry Andric // for each SUnit in the NodeOrder, check whether
3285eb11fae6SDimitry Andric // it appears after both a successor and a predecessor
3286eb11fae6SDimitry Andric // of the SUnit. If this is the case, and the SUnit
3287eb11fae6SDimitry Andric // is not part of circuit, then the NodeOrder is not
3288eb11fae6SDimitry Andric // valid.
3289eb11fae6SDimitry Andric for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
3290eb11fae6SDimitry Andric SUnit *SU = NodeOrder[i];
3291eb11fae6SDimitry Andric unsigned Index = i;
3292eb11fae6SDimitry Andric
3293eb11fae6SDimitry Andric bool PredBefore = false;
3294eb11fae6SDimitry Andric bool SuccBefore = false;
3295eb11fae6SDimitry Andric
3296eb11fae6SDimitry Andric SUnit *Succ;
3297eb11fae6SDimitry Andric SUnit *Pred;
3298eb11fae6SDimitry Andric (void)Succ;
3299eb11fae6SDimitry Andric (void)Pred;
3300eb11fae6SDimitry Andric
3301eb11fae6SDimitry Andric for (SDep &PredEdge : SU->Preds) {
3302eb11fae6SDimitry Andric SUnit *PredSU = PredEdge.getSUnit();
3303e6d15924SDimitry Andric unsigned PredIndex = std::get<1>(
3304e6d15924SDimitry Andric *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey));
3305eb11fae6SDimitry Andric if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
3306eb11fae6SDimitry Andric PredBefore = true;
3307eb11fae6SDimitry Andric Pred = PredSU;
3308eb11fae6SDimitry Andric break;
3309eb11fae6SDimitry Andric }
3310eb11fae6SDimitry Andric }
3311eb11fae6SDimitry Andric
3312eb11fae6SDimitry Andric for (SDep &SuccEdge : SU->Succs) {
3313eb11fae6SDimitry Andric SUnit *SuccSU = SuccEdge.getSUnit();
3314e6d15924SDimitry Andric // Do not process a boundary node, it was not included in NodeOrder,
3315e6d15924SDimitry Andric // hence not in Indices either, call to std::lower_bound() below will
3316e6d15924SDimitry Andric // return Indices.end().
3317e6d15924SDimitry Andric if (SuccSU->isBoundaryNode())
3318e6d15924SDimitry Andric continue;
3319e6d15924SDimitry Andric unsigned SuccIndex = std::get<1>(
3320e6d15924SDimitry Andric *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey));
3321eb11fae6SDimitry Andric if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
3322eb11fae6SDimitry Andric SuccBefore = true;
3323eb11fae6SDimitry Andric Succ = SuccSU;
3324eb11fae6SDimitry Andric break;
3325eb11fae6SDimitry Andric }
3326eb11fae6SDimitry Andric }
3327eb11fae6SDimitry Andric
3328eb11fae6SDimitry Andric if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
3329eb11fae6SDimitry Andric // instructions in circuits are allowed to be scheduled
3330eb11fae6SDimitry Andric // after both a successor and predecessor.
3331e6d15924SDimitry Andric bool InCircuit = llvm::any_of(
3332e6d15924SDimitry Andric Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
3333eb11fae6SDimitry Andric if (InCircuit)
3334eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
3335eb11fae6SDimitry Andric else {
3336eb11fae6SDimitry Andric Valid = false;
3337eb11fae6SDimitry Andric NumNodeOrderIssues++;
3338eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Predecessor ";);
3339eb11fae6SDimitry Andric }
3340eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
3341eb11fae6SDimitry Andric << " are scheduled before node " << SU->NodeNum
3342eb11fae6SDimitry Andric << "\n";);
3343eb11fae6SDimitry Andric }
3344eb11fae6SDimitry Andric }
3345eb11fae6SDimitry Andric
3346eb11fae6SDimitry Andric LLVM_DEBUG({
3347eb11fae6SDimitry Andric if (!Valid)
3348eb11fae6SDimitry Andric dbgs() << "Invalid node order found!\n";
3349eb11fae6SDimitry Andric });
3350eb11fae6SDimitry Andric }
3351eb11fae6SDimitry Andric
3352044eb2f6SDimitry Andric /// Attempt to fix the degenerate cases when the instruction serialization
3353044eb2f6SDimitry Andric /// causes the register lifetimes to overlap. For example,
3354044eb2f6SDimitry Andric /// p' = store_pi(p, b)
3355044eb2f6SDimitry Andric /// = load p, offset
3356044eb2f6SDimitry Andric /// In this case p and p' overlap, which means that two registers are needed.
3357044eb2f6SDimitry Andric /// Instead, this function changes the load to use p' and updates the offset.
fixupRegisterOverlaps(std::deque<SUnit * > & Instrs)3358044eb2f6SDimitry Andric void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
3359044eb2f6SDimitry Andric unsigned OverlapReg = 0;
3360044eb2f6SDimitry Andric unsigned NewBaseReg = 0;
3361044eb2f6SDimitry Andric for (SUnit *SU : Instrs) {
3362044eb2f6SDimitry Andric MachineInstr *MI = SU->getInstr();
3363044eb2f6SDimitry Andric for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3364044eb2f6SDimitry Andric const MachineOperand &MO = MI->getOperand(i);
3365044eb2f6SDimitry Andric // Look for an instruction that uses p. The instruction occurs in the
3366044eb2f6SDimitry Andric // same cycle but occurs later in the serialized order.
3367044eb2f6SDimitry Andric if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
3368044eb2f6SDimitry Andric // Check that the instruction appears in the InstrChanges structure,
3369044eb2f6SDimitry Andric // which contains instructions that can have the offset updated.
3370044eb2f6SDimitry Andric DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3371044eb2f6SDimitry Andric InstrChanges.find(SU);
3372044eb2f6SDimitry Andric if (It != InstrChanges.end()) {
3373044eb2f6SDimitry Andric unsigned BasePos, OffsetPos;
3374044eb2f6SDimitry Andric // Update the base register and adjust the offset.
3375044eb2f6SDimitry Andric if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
3376044eb2f6SDimitry Andric MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3377044eb2f6SDimitry Andric NewMI->getOperand(BasePos).setReg(NewBaseReg);
3378044eb2f6SDimitry Andric int64_t NewOffset =
3379044eb2f6SDimitry Andric MI->getOperand(OffsetPos).getImm() - It->second.second;
3380044eb2f6SDimitry Andric NewMI->getOperand(OffsetPos).setImm(NewOffset);
3381044eb2f6SDimitry Andric SU->setInstr(NewMI);
3382044eb2f6SDimitry Andric MISUnitMap[NewMI] = SU;
33831d5ae102SDimitry Andric NewMIs[MI] = NewMI;
3384044eb2f6SDimitry Andric }
3385044eb2f6SDimitry Andric }
3386044eb2f6SDimitry Andric OverlapReg = 0;
3387044eb2f6SDimitry Andric NewBaseReg = 0;
3388044eb2f6SDimitry Andric break;
3389044eb2f6SDimitry Andric }
3390044eb2f6SDimitry Andric // Look for an instruction of the form p' = op(p), which uses and defines
3391044eb2f6SDimitry Andric // two virtual registers that get allocated to the same physical register.
3392044eb2f6SDimitry Andric unsigned TiedUseIdx = 0;
3393044eb2f6SDimitry Andric if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
3394044eb2f6SDimitry Andric // OverlapReg is p in the example above.
3395044eb2f6SDimitry Andric OverlapReg = MI->getOperand(TiedUseIdx).getReg();
3396044eb2f6SDimitry Andric // NewBaseReg is p' in the example above.
3397044eb2f6SDimitry Andric NewBaseReg = MI->getOperand(i).getReg();
3398044eb2f6SDimitry Andric break;
3399044eb2f6SDimitry Andric }
3400044eb2f6SDimitry Andric }
3401044eb2f6SDimitry Andric }
3402044eb2f6SDimitry Andric }
3403044eb2f6SDimitry Andric
34044df029ccSDimitry Andric std::deque<SUnit *>
reorderInstructions(const SwingSchedulerDAG * SSD,const std::deque<SUnit * > & Instrs) const34054df029ccSDimitry Andric SMSchedule::reorderInstructions(const SwingSchedulerDAG *SSD,
34064df029ccSDimitry Andric const std::deque<SUnit *> &Instrs) const {
34074df029ccSDimitry Andric std::deque<SUnit *> NewOrderPhi;
34084df029ccSDimitry Andric for (SUnit *SU : Instrs) {
34094df029ccSDimitry Andric if (SU->getInstr()->isPHI())
34104df029ccSDimitry Andric NewOrderPhi.push_back(SU);
34114df029ccSDimitry Andric }
34124df029ccSDimitry Andric std::deque<SUnit *> NewOrderI;
34134df029ccSDimitry Andric for (SUnit *SU : Instrs) {
34144df029ccSDimitry Andric if (!SU->getInstr()->isPHI())
34154df029ccSDimitry Andric orderDependence(SSD, SU, NewOrderI);
34164df029ccSDimitry Andric }
34174df029ccSDimitry Andric llvm::append_range(NewOrderPhi, NewOrderI);
34184df029ccSDimitry Andric return NewOrderPhi;
34194df029ccSDimitry Andric }
34204df029ccSDimitry Andric
3421b915e9e0SDimitry Andric /// After the schedule has been formed, call this function to combine
3422b915e9e0SDimitry Andric /// the instructions from the different stages/cycles. That is, this
3423b915e9e0SDimitry Andric /// function creates a schedule that represents a single iteration.
finalizeSchedule(SwingSchedulerDAG * SSD)3424b915e9e0SDimitry Andric void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
3425b915e9e0SDimitry Andric // Move all instructions to the first stage from later stages.
3426b915e9e0SDimitry Andric for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3427b915e9e0SDimitry Andric for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
3428b915e9e0SDimitry Andric ++stage) {
3429b915e9e0SDimitry Andric std::deque<SUnit *> &cycleInstrs =
3430b915e9e0SDimitry Andric ScheduledInstrs[cycle + (stage * InitiationInterval)];
343177fc4c14SDimitry Andric for (SUnit *SU : llvm::reverse(cycleInstrs))
343277fc4c14SDimitry Andric ScheduledInstrs[cycle].push_front(SU);
3433b915e9e0SDimitry Andric }
3434b915e9e0SDimitry Andric }
3435b915e9e0SDimitry Andric
3436b915e9e0SDimitry Andric // Erase all the elements in the later stages. Only one iteration should
3437b915e9e0SDimitry Andric // remain in the scheduled list, and it contains all the instructions.
3438b915e9e0SDimitry Andric for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
3439b915e9e0SDimitry Andric ScheduledInstrs.erase(cycle);
3440b915e9e0SDimitry Andric
3441b915e9e0SDimitry Andric // Change the registers in instruction as specified in the InstrChanges
3442b915e9e0SDimitry Andric // map. We need to use the new registers to create the correct order.
344377fc4c14SDimitry Andric for (const SUnit &SU : SSD->SUnits)
344477fc4c14SDimitry Andric SSD->applyInstrChange(SU.getInstr(), *this);
3445b915e9e0SDimitry Andric
3446b915e9e0SDimitry Andric // Reorder the instructions in each cycle to fix and improve the
3447b915e9e0SDimitry Andric // generated code.
3448b915e9e0SDimitry Andric for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
3449b915e9e0SDimitry Andric std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
34504df029ccSDimitry Andric cycleInstrs = reorderInstructions(SSD, cycleInstrs);
3451044eb2f6SDimitry Andric SSD->fixupRegisterOverlaps(cycleInstrs);
3452b915e9e0SDimitry Andric }
3453b915e9e0SDimitry Andric
3454eb11fae6SDimitry Andric LLVM_DEBUG(dump(););
3455b915e9e0SDimitry Andric }
3456b915e9e0SDimitry Andric
print(raw_ostream & os) const3457d8e91e46SDimitry Andric void NodeSet::print(raw_ostream &os) const {
3458d8e91e46SDimitry Andric os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
3459d8e91e46SDimitry Andric << " depth " << MaxDepth << " col " << Colocate << "\n";
3460d8e91e46SDimitry Andric for (const auto &I : Nodes)
3461d8e91e46SDimitry Andric os << " SU(" << I->NodeNum << ") " << *(I->getInstr());
3462d8e91e46SDimitry Andric os << "\n";
3463d8e91e46SDimitry Andric }
3464d8e91e46SDimitry Andric
3465044eb2f6SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3466b915e9e0SDimitry Andric /// Print the schedule information to the given output.
print(raw_ostream & os) const3467b915e9e0SDimitry Andric void SMSchedule::print(raw_ostream &os) const {
3468b915e9e0SDimitry Andric // Iterate over each cycle.
3469b915e9e0SDimitry Andric for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3470b915e9e0SDimitry Andric // Iterate over each instruction in the cycle.
3471b915e9e0SDimitry Andric const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
3472b915e9e0SDimitry Andric for (SUnit *CI : cycleInstrs->second) {
3473b915e9e0SDimitry Andric os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
3474b915e9e0SDimitry Andric os << "(" << CI->NodeNum << ") ";
3475b915e9e0SDimitry Andric CI->getInstr()->print(os);
3476b915e9e0SDimitry Andric os << "\n";
3477b915e9e0SDimitry Andric }
3478b915e9e0SDimitry Andric }
3479b915e9e0SDimitry Andric }
3480b915e9e0SDimitry Andric
3481b915e9e0SDimitry Andric /// Utility function used for debugging to print the schedule.
dump() const348271d5a254SDimitry Andric LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
dump() const3483d8e91e46SDimitry Andric LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
3484d8e91e46SDimitry Andric
dumpMRT() const3485e3b55780SDimitry Andric void ResourceManager::dumpMRT() const {
3486e3b55780SDimitry Andric LLVM_DEBUG({
3487e3b55780SDimitry Andric if (UseDFA)
3488e3b55780SDimitry Andric return;
3489e3b55780SDimitry Andric std::stringstream SS;
3490e3b55780SDimitry Andric SS << "MRT:\n";
3491e3b55780SDimitry Andric SS << std::setw(4) << "Slot";
3492e3b55780SDimitry Andric for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I)
3493e3b55780SDimitry Andric SS << std::setw(3) << I;
3494e3b55780SDimitry Andric SS << std::setw(7) << "#Mops"
3495e3b55780SDimitry Andric << "\n";
3496e3b55780SDimitry Andric for (int Slot = 0; Slot < InitiationInterval; ++Slot) {
3497e3b55780SDimitry Andric SS << std::setw(4) << Slot;
3498e3b55780SDimitry Andric for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I)
3499e3b55780SDimitry Andric SS << std::setw(3) << MRT[Slot][I];
3500e3b55780SDimitry Andric SS << std::setw(7) << NumScheduledMops[Slot] << "\n";
3501e3b55780SDimitry Andric }
3502e3b55780SDimitry Andric dbgs() << SS.str();
3503e3b55780SDimitry Andric });
3504e3b55780SDimitry Andric }
350571d5a254SDimitry Andric #endif
3506d8e91e46SDimitry Andric
initProcResourceVectors(const MCSchedModel & SM,SmallVectorImpl<uint64_t> & Masks)3507e6d15924SDimitry Andric void ResourceManager::initProcResourceVectors(
3508e6d15924SDimitry Andric const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
3509e6d15924SDimitry Andric unsigned ProcResourceID = 0;
3510d8e91e46SDimitry Andric
3511e6d15924SDimitry Andric // We currently limit the resource kinds to 64 and below so that we can use
3512e6d15924SDimitry Andric // uint64_t for Masks
3513e6d15924SDimitry Andric assert(SM.getNumProcResourceKinds() < 64 &&
3514e6d15924SDimitry Andric "Too many kinds of resources, unsupported");
3515e6d15924SDimitry Andric // Create a unique bitmask for every processor resource unit.
3516e6d15924SDimitry Andric // Skip resource at index 0, since it always references 'InvalidUnit'.
3517e6d15924SDimitry Andric Masks.resize(SM.getNumProcResourceKinds());
3518e6d15924SDimitry Andric for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3519e6d15924SDimitry Andric const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3520e6d15924SDimitry Andric if (Desc.SubUnitsIdxBegin)
3521e6d15924SDimitry Andric continue;
3522e6d15924SDimitry Andric Masks[I] = 1ULL << ProcResourceID;
3523e6d15924SDimitry Andric ProcResourceID++;
3524e6d15924SDimitry Andric }
3525e6d15924SDimitry Andric // Create a unique bitmask for every processor resource group.
3526e6d15924SDimitry Andric for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3527e6d15924SDimitry Andric const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3528e6d15924SDimitry Andric if (!Desc.SubUnitsIdxBegin)
3529e6d15924SDimitry Andric continue;
3530e6d15924SDimitry Andric Masks[I] = 1ULL << ProcResourceID;
3531e6d15924SDimitry Andric for (unsigned U = 0; U < Desc.NumUnits; ++U)
3532e6d15924SDimitry Andric Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
3533e6d15924SDimitry Andric ProcResourceID++;
3534e6d15924SDimitry Andric }
3535e6d15924SDimitry Andric LLVM_DEBUG({
3536e6d15924SDimitry Andric if (SwpShowResMask) {
3537e6d15924SDimitry Andric dbgs() << "ProcResourceDesc:\n";
3538e6d15924SDimitry Andric for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3539e6d15924SDimitry Andric const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
3540e6d15924SDimitry Andric dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
3541e6d15924SDimitry Andric ProcResource->Name, I, Masks[I],
3542e6d15924SDimitry Andric ProcResource->NumUnits);
3543e6d15924SDimitry Andric }
3544e6d15924SDimitry Andric dbgs() << " -----------------\n";
3545e6d15924SDimitry Andric }
3546e6d15924SDimitry Andric });
3547e6d15924SDimitry Andric }
3548e6d15924SDimitry Andric
canReserveResources(SUnit & SU,int Cycle)3549e3b55780SDimitry Andric bool ResourceManager::canReserveResources(SUnit &SU, int Cycle) {
3550e6d15924SDimitry Andric LLVM_DEBUG({
3551e6d15924SDimitry Andric if (SwpDebugResource)
3552e6d15924SDimitry Andric dbgs() << "canReserveResources:\n";
3553e6d15924SDimitry Andric });
3554e6d15924SDimitry Andric if (UseDFA)
3555e3b55780SDimitry Andric return DFAResources[positiveModulo(Cycle, InitiationInterval)]
3556e3b55780SDimitry Andric ->canReserveResources(&SU.getInstr()->getDesc());
3557e6d15924SDimitry Andric
3558e3b55780SDimitry Andric const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
3559e6d15924SDimitry Andric if (!SCDesc->isValid()) {
3560e6d15924SDimitry Andric LLVM_DEBUG({
3561e6d15924SDimitry Andric dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3562e3b55780SDimitry Andric dbgs() << "isPseudo:" << SU.getInstr()->isPseudo() << "\n";
3563e6d15924SDimitry Andric });
3564e6d15924SDimitry Andric return true;
3565e6d15924SDimitry Andric }
3566e6d15924SDimitry Andric
3567e3b55780SDimitry Andric reserveResources(SCDesc, Cycle);
3568e3b55780SDimitry Andric bool Result = !isOverbooked();
3569e3b55780SDimitry Andric unreserveResources(SCDesc, Cycle);
3570e3b55780SDimitry Andric
3571e3b55780SDimitry Andric LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return " << Result << "\n\n";);
3572e3b55780SDimitry Andric return Result;
3573e6d15924SDimitry Andric }
3574e6d15924SDimitry Andric
reserveResources(SUnit & SU,int Cycle)3575e3b55780SDimitry Andric void ResourceManager::reserveResources(SUnit &SU, int Cycle) {
3576e6d15924SDimitry Andric LLVM_DEBUG({
3577e6d15924SDimitry Andric if (SwpDebugResource)
3578e6d15924SDimitry Andric dbgs() << "reserveResources:\n";
3579e6d15924SDimitry Andric });
3580e6d15924SDimitry Andric if (UseDFA)
3581e3b55780SDimitry Andric return DFAResources[positiveModulo(Cycle, InitiationInterval)]
3582e3b55780SDimitry Andric ->reserveResources(&SU.getInstr()->getDesc());
3583e6d15924SDimitry Andric
3584e3b55780SDimitry Andric const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
3585e6d15924SDimitry Andric if (!SCDesc->isValid()) {
3586e6d15924SDimitry Andric LLVM_DEBUG({
3587e6d15924SDimitry Andric dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3588e3b55780SDimitry Andric dbgs() << "isPseudo:" << SU.getInstr()->isPseudo() << "\n";
3589e6d15924SDimitry Andric });
3590e6d15924SDimitry Andric return;
3591e6d15924SDimitry Andric }
3592e3b55780SDimitry Andric
3593e3b55780SDimitry Andric reserveResources(SCDesc, Cycle);
3594e3b55780SDimitry Andric
3595e3b55780SDimitry Andric LLVM_DEBUG({
3596e3b55780SDimitry Andric if (SwpDebugResource) {
3597e3b55780SDimitry Andric dumpMRT();
3598e3b55780SDimitry Andric dbgs() << "reserveResources: done!\n\n";
3599e3b55780SDimitry Andric }
3600e3b55780SDimitry Andric });
3601e3b55780SDimitry Andric }
3602e3b55780SDimitry Andric
reserveResources(const MCSchedClassDesc * SCDesc,int Cycle)3603e3b55780SDimitry Andric void ResourceManager::reserveResources(const MCSchedClassDesc *SCDesc,
3604e3b55780SDimitry Andric int Cycle) {
3605e3b55780SDimitry Andric assert(!UseDFA);
3606e3b55780SDimitry Andric for (const MCWriteProcResEntry &PRE : make_range(
3607e3b55780SDimitry Andric STI->getWriteProcResBegin(SCDesc), STI->getWriteProcResEnd(SCDesc)))
3608b1c73532SDimitry Andric for (int C = Cycle; C < Cycle + PRE.ReleaseAtCycle; ++C)
3609e3b55780SDimitry Andric ++MRT[positiveModulo(C, InitiationInterval)][PRE.ProcResourceIdx];
3610e3b55780SDimitry Andric
3611e3b55780SDimitry Andric for (int C = Cycle; C < Cycle + SCDesc->NumMicroOps; ++C)
3612e3b55780SDimitry Andric ++NumScheduledMops[positiveModulo(C, InitiationInterval)];
3613e3b55780SDimitry Andric }
3614e3b55780SDimitry Andric
unreserveResources(const MCSchedClassDesc * SCDesc,int Cycle)3615e3b55780SDimitry Andric void ResourceManager::unreserveResources(const MCSchedClassDesc *SCDesc,
3616e3b55780SDimitry Andric int Cycle) {
3617e3b55780SDimitry Andric assert(!UseDFA);
3618e3b55780SDimitry Andric for (const MCWriteProcResEntry &PRE : make_range(
3619e3b55780SDimitry Andric STI->getWriteProcResBegin(SCDesc), STI->getWriteProcResEnd(SCDesc)))
3620b1c73532SDimitry Andric for (int C = Cycle; C < Cycle + PRE.ReleaseAtCycle; ++C)
3621e3b55780SDimitry Andric --MRT[positiveModulo(C, InitiationInterval)][PRE.ProcResourceIdx];
3622e3b55780SDimitry Andric
3623e3b55780SDimitry Andric for (int C = Cycle; C < Cycle + SCDesc->NumMicroOps; ++C)
3624e3b55780SDimitry Andric --NumScheduledMops[positiveModulo(C, InitiationInterval)];
3625e3b55780SDimitry Andric }
3626e3b55780SDimitry Andric
isOverbooked() const3627e3b55780SDimitry Andric bool ResourceManager::isOverbooked() const {
3628e3b55780SDimitry Andric assert(!UseDFA);
3629e3b55780SDimitry Andric for (int Slot = 0; Slot < InitiationInterval; ++Slot) {
3630e3b55780SDimitry Andric for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3631e3b55780SDimitry Andric const MCProcResourceDesc *Desc = SM.getProcResource(I);
3632e3b55780SDimitry Andric if (MRT[Slot][I] > Desc->NumUnits)
3633e3b55780SDimitry Andric return true;
3634e3b55780SDimitry Andric }
3635e3b55780SDimitry Andric if (NumScheduledMops[Slot] > IssueWidth)
3636e3b55780SDimitry Andric return true;
3637e3b55780SDimitry Andric }
3638e3b55780SDimitry Andric return false;
3639e3b55780SDimitry Andric }
3640e3b55780SDimitry Andric
calculateResMIIDFA() const3641e3b55780SDimitry Andric int ResourceManager::calculateResMIIDFA() const {
3642e3b55780SDimitry Andric assert(UseDFA);
3643e3b55780SDimitry Andric
3644e3b55780SDimitry Andric // Sort the instructions by the number of available choices for scheduling,
3645e3b55780SDimitry Andric // least to most. Use the number of critical resources as the tie breaker.
3646e3b55780SDimitry Andric FuncUnitSorter FUS = FuncUnitSorter(*ST);
3647e3b55780SDimitry Andric for (SUnit &SU : DAG->SUnits)
3648e3b55780SDimitry Andric FUS.calcCriticalResources(*SU.getInstr());
3649e3b55780SDimitry Andric PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
3650e3b55780SDimitry Andric FuncUnitOrder(FUS);
3651e3b55780SDimitry Andric
3652e3b55780SDimitry Andric for (SUnit &SU : DAG->SUnits)
3653e3b55780SDimitry Andric FuncUnitOrder.push(SU.getInstr());
3654e3b55780SDimitry Andric
3655e3b55780SDimitry Andric SmallVector<std::unique_ptr<DFAPacketizer>, 8> Resources;
3656e3b55780SDimitry Andric Resources.push_back(
3657e3b55780SDimitry Andric std::unique_ptr<DFAPacketizer>(TII->CreateTargetScheduleState(*ST)));
3658e3b55780SDimitry Andric
3659e3b55780SDimitry Andric while (!FuncUnitOrder.empty()) {
3660e3b55780SDimitry Andric MachineInstr *MI = FuncUnitOrder.top();
3661e3b55780SDimitry Andric FuncUnitOrder.pop();
3662e3b55780SDimitry Andric if (TII->isZeroCost(MI->getOpcode()))
3663e3b55780SDimitry Andric continue;
3664e3b55780SDimitry Andric
3665e3b55780SDimitry Andric // Attempt to reserve the instruction in an existing DFA. At least one
3666e3b55780SDimitry Andric // DFA is needed for each cycle.
3667e3b55780SDimitry Andric unsigned NumCycles = DAG->getSUnit(MI)->Latency;
3668e3b55780SDimitry Andric unsigned ReservedCycles = 0;
3669e3b55780SDimitry Andric auto *RI = Resources.begin();
3670e3b55780SDimitry Andric auto *RE = Resources.end();
3671e3b55780SDimitry Andric LLVM_DEBUG({
3672e3b55780SDimitry Andric dbgs() << "Trying to reserve resource for " << NumCycles
3673e3b55780SDimitry Andric << " cycles for \n";
3674e3b55780SDimitry Andric MI->dump();
3675e3b55780SDimitry Andric });
3676e3b55780SDimitry Andric for (unsigned C = 0; C < NumCycles; ++C)
3677e3b55780SDimitry Andric while (RI != RE) {
3678e3b55780SDimitry Andric if ((*RI)->canReserveResources(*MI)) {
3679e3b55780SDimitry Andric (*RI)->reserveResources(*MI);
3680e3b55780SDimitry Andric ++ReservedCycles;
3681e3b55780SDimitry Andric break;
3682e3b55780SDimitry Andric }
3683e3b55780SDimitry Andric RI++;
3684e3b55780SDimitry Andric }
3685e3b55780SDimitry Andric LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
3686e3b55780SDimitry Andric << ", NumCycles:" << NumCycles << "\n");
3687e3b55780SDimitry Andric // Add new DFAs, if needed, to reserve resources.
3688e3b55780SDimitry Andric for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
3689e3b55780SDimitry Andric LLVM_DEBUG(if (SwpDebugResource) dbgs()
3690e3b55780SDimitry Andric << "NewResource created to reserve resources"
3691e3b55780SDimitry Andric << "\n");
3692e3b55780SDimitry Andric auto *NewResource = TII->CreateTargetScheduleState(*ST);
3693e3b55780SDimitry Andric assert(NewResource->canReserveResources(*MI) && "Reserve error.");
3694e3b55780SDimitry Andric NewResource->reserveResources(*MI);
3695e3b55780SDimitry Andric Resources.push_back(std::unique_ptr<DFAPacketizer>(NewResource));
3696e3b55780SDimitry Andric }
3697e3b55780SDimitry Andric }
3698e3b55780SDimitry Andric
3699e3b55780SDimitry Andric int Resmii = Resources.size();
3700e3b55780SDimitry Andric LLVM_DEBUG(dbgs() << "Return Res MII:" << Resmii << "\n");
3701e3b55780SDimitry Andric return Resmii;
3702e3b55780SDimitry Andric }
3703e3b55780SDimitry Andric
calculateResMII() const3704e3b55780SDimitry Andric int ResourceManager::calculateResMII() const {
3705e3b55780SDimitry Andric if (UseDFA)
3706e3b55780SDimitry Andric return calculateResMIIDFA();
3707e3b55780SDimitry Andric
3708e3b55780SDimitry Andric // Count each resource consumption and divide it by the number of units.
3709e3b55780SDimitry Andric // ResMII is the max value among them.
3710e3b55780SDimitry Andric
3711e3b55780SDimitry Andric int NumMops = 0;
3712e3b55780SDimitry Andric SmallVector<uint64_t> ResourceCount(SM.getNumProcResourceKinds());
3713e3b55780SDimitry Andric for (SUnit &SU : DAG->SUnits) {
3714e3b55780SDimitry Andric if (TII->isZeroCost(SU.getInstr()->getOpcode()))
3715e3b55780SDimitry Andric continue;
3716e3b55780SDimitry Andric
3717e3b55780SDimitry Andric const MCSchedClassDesc *SCDesc = DAG->getSchedClass(&SU);
3718e3b55780SDimitry Andric if (!SCDesc->isValid())
3719e3b55780SDimitry Andric continue;
3720e3b55780SDimitry Andric
3721e3b55780SDimitry Andric LLVM_DEBUG({
3722e3b55780SDimitry Andric if (SwpDebugResource) {
3723e3b55780SDimitry Andric DAG->dumpNode(SU);
3724e3b55780SDimitry Andric dbgs() << " #Mops: " << SCDesc->NumMicroOps << "\n"
3725e3b55780SDimitry Andric << " WriteProcRes: ";
3726e3b55780SDimitry Andric }
3727e3b55780SDimitry Andric });
3728e3b55780SDimitry Andric NumMops += SCDesc->NumMicroOps;
3729e6d15924SDimitry Andric for (const MCWriteProcResEntry &PRE :
3730e6d15924SDimitry Andric make_range(STI->getWriteProcResBegin(SCDesc),
3731e6d15924SDimitry Andric STI->getWriteProcResEnd(SCDesc))) {
3732e6d15924SDimitry Andric LLVM_DEBUG({
3733e6d15924SDimitry Andric if (SwpDebugResource) {
3734e3b55780SDimitry Andric const MCProcResourceDesc *Desc =
3735e6d15924SDimitry Andric SM.getProcResource(PRE.ProcResourceIdx);
3736b1c73532SDimitry Andric dbgs() << Desc->Name << ": " << PRE.ReleaseAtCycle << ", ";
3737e6d15924SDimitry Andric }
3738e6d15924SDimitry Andric });
3739b1c73532SDimitry Andric ResourceCount[PRE.ProcResourceIdx] += PRE.ReleaseAtCycle;
3740e6d15924SDimitry Andric }
3741e3b55780SDimitry Andric LLVM_DEBUG(if (SwpDebugResource) dbgs() << "\n");
3742e3b55780SDimitry Andric }
3743e3b55780SDimitry Andric
3744e3b55780SDimitry Andric int Result = (NumMops + IssueWidth - 1) / IssueWidth;
3745e6d15924SDimitry Andric LLVM_DEBUG({
3746e6d15924SDimitry Andric if (SwpDebugResource)
3747e3b55780SDimitry Andric dbgs() << "#Mops: " << NumMops << ", "
3748e3b55780SDimitry Andric << "IssueWidth: " << IssueWidth << ", "
3749e3b55780SDimitry Andric << "Cycles: " << Result << "\n";
3750e6d15924SDimitry Andric });
3751e3b55780SDimitry Andric
3752e3b55780SDimitry Andric LLVM_DEBUG({
3753e3b55780SDimitry Andric if (SwpDebugResource) {
3754e3b55780SDimitry Andric std::stringstream SS;
3755e3b55780SDimitry Andric SS << std::setw(2) << "ID" << std::setw(16) << "Name" << std::setw(10)
3756e3b55780SDimitry Andric << "Units" << std::setw(10) << "Consumed" << std::setw(10) << "Cycles"
3757e3b55780SDimitry Andric << "\n";
3758e3b55780SDimitry Andric dbgs() << SS.str();
3759e3b55780SDimitry Andric }
3760e3b55780SDimitry Andric });
3761e3b55780SDimitry Andric for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3762e3b55780SDimitry Andric const MCProcResourceDesc *Desc = SM.getProcResource(I);
3763e3b55780SDimitry Andric int Cycles = (ResourceCount[I] + Desc->NumUnits - 1) / Desc->NumUnits;
3764e3b55780SDimitry Andric LLVM_DEBUG({
3765e3b55780SDimitry Andric if (SwpDebugResource) {
3766e3b55780SDimitry Andric std::stringstream SS;
3767e3b55780SDimitry Andric SS << std::setw(2) << I << std::setw(16) << Desc->Name << std::setw(10)
3768e3b55780SDimitry Andric << Desc->NumUnits << std::setw(10) << ResourceCount[I]
3769e3b55780SDimitry Andric << std::setw(10) << Cycles << "\n";
3770e3b55780SDimitry Andric dbgs() << SS.str();
3771e3b55780SDimitry Andric }
3772e3b55780SDimitry Andric });
3773e3b55780SDimitry Andric if (Cycles > Result)
3774e3b55780SDimitry Andric Result = Cycles;
3775e3b55780SDimitry Andric }
3776e3b55780SDimitry Andric return Result;
3777e6d15924SDimitry Andric }
3778e6d15924SDimitry Andric
init(int II)3779e3b55780SDimitry Andric void ResourceManager::init(int II) {
3780e3b55780SDimitry Andric InitiationInterval = II;
3781e3b55780SDimitry Andric DFAResources.clear();
3782e3b55780SDimitry Andric DFAResources.resize(II);
3783e3b55780SDimitry Andric for (auto &I : DFAResources)
3784e3b55780SDimitry Andric I.reset(ST->getInstrInfo()->CreateTargetScheduleState(*ST));
3785e3b55780SDimitry Andric MRT.clear();
3786e3b55780SDimitry Andric MRT.resize(II, SmallVector<uint64_t>(SM.getNumProcResourceKinds()));
3787e3b55780SDimitry Andric NumScheduledMops.clear();
3788e3b55780SDimitry Andric NumScheduledMops.resize(II);
3789e6d15924SDimitry Andric }
3790