132a40564SEugene Zelenko //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
2254f889dSBrendon Cahoon //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6254f889dSBrendon Cahoon //
7254f889dSBrendon Cahoon //===----------------------------------------------------------------------===//
8254f889dSBrendon Cahoon //
9254f889dSBrendon Cahoon // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
10254f889dSBrendon Cahoon //
11254f889dSBrendon Cahoon // This SMS implementation is a target-independent back-end pass. When enabled,
12254f889dSBrendon Cahoon // the pass runs just prior to the register allocation pass, while the machine
13254f889dSBrendon Cahoon // IR is in SSA form. If software pipelining is successful, then the original
14254f889dSBrendon Cahoon // loop is replaced by the optimized loop. The optimized loop contains one or
15254f889dSBrendon Cahoon // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
16254f889dSBrendon Cahoon // the instructions cannot be scheduled in a given MII, we increase the MII by
17254f889dSBrendon Cahoon // one and try again.
18254f889dSBrendon Cahoon //
19254f889dSBrendon Cahoon // The SMS implementation is an extension of the ScheduleDAGInstrs class. We
20254f889dSBrendon Cahoon // represent loop carried dependences in the DAG as order edges to the Phi
21254f889dSBrendon Cahoon // nodes. We also perform several passes over the DAG to eliminate unnecessary
22254f889dSBrendon Cahoon // edges that inhibit the ability to pipeline. The implementation uses the
23254f889dSBrendon Cahoon // DFAPacketizer class to compute the minimum initiation interval and the check
24254f889dSBrendon Cahoon // where an instruction may be inserted in the pipelined schedule.
25254f889dSBrendon Cahoon //
26254f889dSBrendon Cahoon // In order for the SMS pass to work, several target specific hooks need to be
27254f889dSBrendon Cahoon // implemented to get information about the loop structure and to rewrite
28254f889dSBrendon Cahoon // instructions.
29254f889dSBrendon Cahoon //
30254f889dSBrendon Cahoon //===----------------------------------------------------------------------===//
31254f889dSBrendon Cahoon 
32cdc71612SEugene Zelenko #include "llvm/ADT/ArrayRef.h"
33cdc71612SEugene Zelenko #include "llvm/ADT/BitVector.h"
34254f889dSBrendon Cahoon #include "llvm/ADT/DenseMap.h"
35254f889dSBrendon Cahoon #include "llvm/ADT/MapVector.h"
36254f889dSBrendon Cahoon #include "llvm/ADT/PriorityQueue.h"
37254f889dSBrendon Cahoon #include "llvm/ADT/SetVector.h"
38254f889dSBrendon Cahoon #include "llvm/ADT/SmallPtrSet.h"
39254f889dSBrendon Cahoon #include "llvm/ADT/SmallSet.h"
40cdc71612SEugene Zelenko #include "llvm/ADT/SmallVector.h"
41254f889dSBrendon Cahoon #include "llvm/ADT/Statistic.h"
426bda14b3SChandler Carruth #include "llvm/ADT/iterator_range.h"
43254f889dSBrendon Cahoon #include "llvm/Analysis/AliasAnalysis.h"
44cdc71612SEugene Zelenko #include "llvm/Analysis/MemoryLocation.h"
45254f889dSBrendon Cahoon #include "llvm/Analysis/ValueTracking.h"
46254f889dSBrendon Cahoon #include "llvm/CodeGen/DFAPacketizer.h"
47f842297dSMatthias Braun #include "llvm/CodeGen/LiveIntervals.h"
48254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineBasicBlock.h"
49254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineDominators.h"
50cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineFunction.h"
51cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineFunctionPass.h"
52cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineInstr.h"
53254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineInstrBuilder.h"
54254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineLoopInfo.h"
55cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineMemOperand.h"
56cdc71612SEugene Zelenko #include "llvm/CodeGen/MachineOperand.h"
57fa2e3583SAdrian Prantl #include "llvm/CodeGen/MachinePipeliner.h"
58254f889dSBrendon Cahoon #include "llvm/CodeGen/MachineRegisterInfo.h"
59254f889dSBrendon Cahoon #include "llvm/CodeGen/RegisterPressure.h"
60cdc71612SEugene Zelenko #include "llvm/CodeGen/ScheduleDAG.h"
6188391248SKrzysztof Parzyszek #include "llvm/CodeGen/ScheduleDAGMutation.h"
62b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetOpcodes.h"
63b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetRegisterInfo.h"
64b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
65432a3883SNico Weber #include "llvm/Config/llvm-config.h"
66cdc71612SEugene Zelenko #include "llvm/IR/Attributes.h"
67cdc71612SEugene Zelenko #include "llvm/IR/DebugLoc.h"
6832a40564SEugene Zelenko #include "llvm/IR/Function.h"
6932a40564SEugene Zelenko #include "llvm/MC/LaneBitmask.h"
7032a40564SEugene Zelenko #include "llvm/MC/MCInstrDesc.h"
71254f889dSBrendon Cahoon #include "llvm/MC/MCInstrItineraries.h"
7232a40564SEugene Zelenko #include "llvm/MC/MCRegisterInfo.h"
7332a40564SEugene Zelenko #include "llvm/Pass.h"
74254f889dSBrendon Cahoon #include "llvm/Support/CommandLine.h"
7532a40564SEugene Zelenko #include "llvm/Support/Compiler.h"
76254f889dSBrendon Cahoon #include "llvm/Support/Debug.h"
77cdc71612SEugene Zelenko #include "llvm/Support/MathExtras.h"
78254f889dSBrendon Cahoon #include "llvm/Support/raw_ostream.h"
79cdc71612SEugene Zelenko #include <algorithm>
80cdc71612SEugene Zelenko #include <cassert>
81254f889dSBrendon Cahoon #include <climits>
82cdc71612SEugene Zelenko #include <cstdint>
83254f889dSBrendon Cahoon #include <deque>
84cdc71612SEugene Zelenko #include <functional>
85cdc71612SEugene Zelenko #include <iterator>
86254f889dSBrendon Cahoon #include <map>
8732a40564SEugene Zelenko #include <memory>
88cdc71612SEugene Zelenko #include <tuple>
89cdc71612SEugene Zelenko #include <utility>
90cdc71612SEugene Zelenko #include <vector>
91254f889dSBrendon Cahoon 
92254f889dSBrendon Cahoon using namespace llvm;
93254f889dSBrendon Cahoon 
94254f889dSBrendon Cahoon #define DEBUG_TYPE "pipeliner"
95254f889dSBrendon Cahoon 
96254f889dSBrendon Cahoon STATISTIC(NumTrytoPipeline, "Number of loops that we attempt to pipeline");
97254f889dSBrendon Cahoon STATISTIC(NumPipelined, "Number of loops software pipelined");
984b8bcf00SRoorda, Jan-Willem STATISTIC(NumNodeOrderIssues, "Number of node order issues found");
9918e7bf5cSJinsong Ji STATISTIC(NumFailBranch, "Pipeliner abort due to unknown branch");
10018e7bf5cSJinsong Ji STATISTIC(NumFailLoop, "Pipeliner abort due to unsupported loop");
10118e7bf5cSJinsong Ji STATISTIC(NumFailPreheader, "Pipeliner abort due to missing preheader");
10218e7bf5cSJinsong Ji STATISTIC(NumFailLargeMaxMII, "Pipeliner abort due to MaxMII too large");
10318e7bf5cSJinsong Ji STATISTIC(NumFailZeroMII, "Pipeliner abort due to zero MII");
10418e7bf5cSJinsong Ji STATISTIC(NumFailNoSchedule, "Pipeliner abort due to no schedule found");
10518e7bf5cSJinsong Ji STATISTIC(NumFailZeroStage, "Pipeliner abort due to zero stage");
10618e7bf5cSJinsong Ji STATISTIC(NumFailLargeMaxStage, "Pipeliner abort due to too many stages");
107254f889dSBrendon Cahoon 
108254f889dSBrendon Cahoon /// A command line option to turn software pipelining on or off.
109b7d3311cSBenjamin Kramer static cl::opt<bool> EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true),
110b7d3311cSBenjamin Kramer                                cl::ZeroOrMore,
111b7d3311cSBenjamin Kramer                                cl::desc("Enable Software Pipelining"));
112254f889dSBrendon Cahoon 
113254f889dSBrendon Cahoon /// A command line option to enable SWP at -Os.
114254f889dSBrendon Cahoon static cl::opt<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
115254f889dSBrendon Cahoon                                       cl::desc("Enable SWP at Os."), cl::Hidden,
116254f889dSBrendon Cahoon                                       cl::init(false));
117254f889dSBrendon Cahoon 
118254f889dSBrendon Cahoon /// A command line argument to limit minimum initial interval for pipelining.
119254f889dSBrendon Cahoon static cl::opt<int> SwpMaxMii("pipeliner-max-mii",
1208f976ba0SHiroshi Inoue                               cl::desc("Size limit for the MII."),
121254f889dSBrendon Cahoon                               cl::Hidden, cl::init(27));
122254f889dSBrendon Cahoon 
123254f889dSBrendon Cahoon /// A command line argument to limit the number of stages in the pipeline.
124254f889dSBrendon Cahoon static cl::opt<int>
125254f889dSBrendon Cahoon     SwpMaxStages("pipeliner-max-stages",
126254f889dSBrendon Cahoon                  cl::desc("Maximum stages allowed in the generated scheduled."),
127254f889dSBrendon Cahoon                  cl::Hidden, cl::init(3));
128254f889dSBrendon Cahoon 
129254f889dSBrendon Cahoon /// A command line option to disable the pruning of chain dependences due to
130254f889dSBrendon Cahoon /// an unrelated Phi.
131254f889dSBrendon Cahoon static cl::opt<bool>
132254f889dSBrendon Cahoon     SwpPruneDeps("pipeliner-prune-deps",
133254f889dSBrendon Cahoon                  cl::desc("Prune dependences between unrelated Phi nodes."),
134254f889dSBrendon Cahoon                  cl::Hidden, cl::init(true));
135254f889dSBrendon Cahoon 
136254f889dSBrendon Cahoon /// A command line option to disable the pruning of loop carried order
137254f889dSBrendon Cahoon /// dependences.
138254f889dSBrendon Cahoon static cl::opt<bool>
139254f889dSBrendon Cahoon     SwpPruneLoopCarried("pipeliner-prune-loop-carried",
140254f889dSBrendon Cahoon                         cl::desc("Prune loop carried order dependences."),
141254f889dSBrendon Cahoon                         cl::Hidden, cl::init(true));
142254f889dSBrendon Cahoon 
143254f889dSBrendon Cahoon #ifndef NDEBUG
144254f889dSBrendon Cahoon static cl::opt<int> SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1));
145254f889dSBrendon Cahoon #endif
146254f889dSBrendon Cahoon 
147254f889dSBrendon Cahoon static cl::opt<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
148254f889dSBrendon Cahoon                                      cl::ReallyHidden, cl::init(false),
149254f889dSBrendon Cahoon                                      cl::ZeroOrMore, cl::desc("Ignore RecMII"));
150254f889dSBrendon Cahoon 
151ba43840bSJinsong Ji static cl::opt<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden,
152ba43840bSJinsong Ji                                     cl::init(false));
153ba43840bSJinsong Ji static cl::opt<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden,
154ba43840bSJinsong Ji                                       cl::init(false));
155ba43840bSJinsong Ji 
156fa2e3583SAdrian Prantl namespace llvm {
157fa2e3583SAdrian Prantl 
15862ac69d4SSumanth Gundapaneni // A command line option to enable the CopyToPhi DAG mutation.
159fa2e3583SAdrian Prantl cl::opt<bool>
16000d4c386SAleksandr Urakov     SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden,
16162ac69d4SSumanth Gundapaneni                        cl::init(true), cl::ZeroOrMore,
16262ac69d4SSumanth Gundapaneni                        cl::desc("Enable CopyToPhi DAG Mutation"));
16362ac69d4SSumanth Gundapaneni 
164fa2e3583SAdrian Prantl } // end namespace llvm
165254f889dSBrendon Cahoon 
166254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
167254f889dSBrendon Cahoon char MachinePipeliner::ID = 0;
168254f889dSBrendon Cahoon #ifndef NDEBUG
169254f889dSBrendon Cahoon int MachinePipeliner::NumTries = 0;
170254f889dSBrendon Cahoon #endif
171254f889dSBrendon Cahoon char &llvm::MachinePipelinerID = MachinePipeliner::ID;
17232a40564SEugene Zelenko 
1731527baabSMatthias Braun INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE,
174254f889dSBrendon Cahoon                       "Modulo Software Pipelining", false, false)
175254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
176254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
177254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
178254f889dSBrendon Cahoon INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
1791527baabSMatthias Braun INITIALIZE_PASS_END(MachinePipeliner, DEBUG_TYPE,
180254f889dSBrendon Cahoon                     "Modulo Software Pipelining", false, false)
181254f889dSBrendon Cahoon 
182254f889dSBrendon Cahoon /// The "main" function for implementing Swing Modulo Scheduling.
183254f889dSBrendon Cahoon bool MachinePipeliner::runOnMachineFunction(MachineFunction &mf) {
184f1caa283SMatthias Braun   if (skipFunction(mf.getFunction()))
185254f889dSBrendon Cahoon     return false;
186254f889dSBrendon Cahoon 
187254f889dSBrendon Cahoon   if (!EnableSWP)
188254f889dSBrendon Cahoon     return false;
189254f889dSBrendon Cahoon 
190f1caa283SMatthias Braun   if (mf.getFunction().getAttributes().hasAttribute(
191b518054bSReid Kleckner           AttributeList::FunctionIndex, Attribute::OptimizeForSize) &&
192254f889dSBrendon Cahoon       !EnableSWPOptSize.getPosition())
193254f889dSBrendon Cahoon     return false;
194254f889dSBrendon Cahoon 
195ef2d6d99SJinsong Ji   if (!mf.getSubtarget().enableMachinePipeliner())
196ef2d6d99SJinsong Ji     return false;
197ef2d6d99SJinsong Ji 
198f6cb3bcbSJinsong Ji   // Cannot pipeline loops without instruction itineraries if we are using
199f6cb3bcbSJinsong Ji   // DFA for the pipeliner.
200f6cb3bcbSJinsong Ji   if (mf.getSubtarget().useDFAforSMS() &&
201f6cb3bcbSJinsong Ji       (!mf.getSubtarget().getInstrItineraryData() ||
202f6cb3bcbSJinsong Ji        mf.getSubtarget().getInstrItineraryData()->isEmpty()))
203f6cb3bcbSJinsong Ji     return false;
204f6cb3bcbSJinsong Ji 
205254f889dSBrendon Cahoon   MF = &mf;
206254f889dSBrendon Cahoon   MLI = &getAnalysis<MachineLoopInfo>();
207254f889dSBrendon Cahoon   MDT = &getAnalysis<MachineDominatorTree>();
208254f889dSBrendon Cahoon   TII = MF->getSubtarget().getInstrInfo();
209254f889dSBrendon Cahoon   RegClassInfo.runOnMachineFunction(*MF);
210254f889dSBrendon Cahoon 
211254f889dSBrendon Cahoon   for (auto &L : *MLI)
212254f889dSBrendon Cahoon     scheduleLoop(*L);
213254f889dSBrendon Cahoon 
214254f889dSBrendon Cahoon   return false;
215254f889dSBrendon Cahoon }
216254f889dSBrendon Cahoon 
217254f889dSBrendon Cahoon /// Attempt to perform the SMS algorithm on the specified loop. This function is
218254f889dSBrendon Cahoon /// the main entry point for the algorithm.  The function identifies candidate
219254f889dSBrendon Cahoon /// loops, calculates the minimum initiation interval, and attempts to schedule
220254f889dSBrendon Cahoon /// the loop.
221254f889dSBrendon Cahoon bool MachinePipeliner::scheduleLoop(MachineLoop &L) {
222254f889dSBrendon Cahoon   bool Changed = false;
223254f889dSBrendon Cahoon   for (auto &InnerLoop : L)
224254f889dSBrendon Cahoon     Changed |= scheduleLoop(*InnerLoop);
225254f889dSBrendon Cahoon 
226254f889dSBrendon Cahoon #ifndef NDEBUG
227254f889dSBrendon Cahoon   // Stop trying after reaching the limit (if any).
228254f889dSBrendon Cahoon   int Limit = SwpLoopLimit;
229254f889dSBrendon Cahoon   if (Limit >= 0) {
230254f889dSBrendon Cahoon     if (NumTries >= SwpLoopLimit)
231254f889dSBrendon Cahoon       return Changed;
232254f889dSBrendon Cahoon     NumTries++;
233254f889dSBrendon Cahoon   }
234254f889dSBrendon Cahoon #endif
235254f889dSBrendon Cahoon 
23659d99731SBrendon Cahoon   setPragmaPipelineOptions(L);
23759d99731SBrendon Cahoon   if (!canPipelineLoop(L)) {
23859d99731SBrendon Cahoon     LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
239254f889dSBrendon Cahoon     return Changed;
24059d99731SBrendon Cahoon   }
241254f889dSBrendon Cahoon 
242254f889dSBrendon Cahoon   ++NumTrytoPipeline;
243254f889dSBrendon Cahoon 
244254f889dSBrendon Cahoon   Changed = swingModuloScheduler(L);
245254f889dSBrendon Cahoon 
246254f889dSBrendon Cahoon   return Changed;
247254f889dSBrendon Cahoon }
248254f889dSBrendon Cahoon 
24959d99731SBrendon Cahoon void MachinePipeliner::setPragmaPipelineOptions(MachineLoop &L) {
25059d99731SBrendon Cahoon   MachineBasicBlock *LBLK = L.getTopBlock();
25159d99731SBrendon Cahoon 
25259d99731SBrendon Cahoon   if (LBLK == nullptr)
25359d99731SBrendon Cahoon     return;
25459d99731SBrendon Cahoon 
25559d99731SBrendon Cahoon   const BasicBlock *BBLK = LBLK->getBasicBlock();
25659d99731SBrendon Cahoon   if (BBLK == nullptr)
25759d99731SBrendon Cahoon     return;
25859d99731SBrendon Cahoon 
25959d99731SBrendon Cahoon   const Instruction *TI = BBLK->getTerminator();
26059d99731SBrendon Cahoon   if (TI == nullptr)
26159d99731SBrendon Cahoon     return;
26259d99731SBrendon Cahoon 
26359d99731SBrendon Cahoon   MDNode *LoopID = TI->getMetadata(LLVMContext::MD_loop);
26459d99731SBrendon Cahoon   if (LoopID == nullptr)
26559d99731SBrendon Cahoon     return;
26659d99731SBrendon Cahoon 
26759d99731SBrendon Cahoon   assert(LoopID->getNumOperands() > 0 && "requires atleast one operand");
26859d99731SBrendon Cahoon   assert(LoopID->getOperand(0) == LoopID && "invalid loop");
26959d99731SBrendon Cahoon 
27059d99731SBrendon Cahoon   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
27159d99731SBrendon Cahoon     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
27259d99731SBrendon Cahoon 
27359d99731SBrendon Cahoon     if (MD == nullptr)
27459d99731SBrendon Cahoon       continue;
27559d99731SBrendon Cahoon 
27659d99731SBrendon Cahoon     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
27759d99731SBrendon Cahoon 
27859d99731SBrendon Cahoon     if (S == nullptr)
27959d99731SBrendon Cahoon       continue;
28059d99731SBrendon Cahoon 
28159d99731SBrendon Cahoon     if (S->getString() == "llvm.loop.pipeline.initiationinterval") {
28259d99731SBrendon Cahoon       assert(MD->getNumOperands() == 2 &&
28359d99731SBrendon Cahoon              "Pipeline initiation interval hint metadata should have two operands.");
28459d99731SBrendon Cahoon       II_setByPragma =
28559d99731SBrendon Cahoon           mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
28659d99731SBrendon Cahoon       assert(II_setByPragma >= 1 && "Pipeline initiation interval must be positive.");
28759d99731SBrendon Cahoon     } else if (S->getString() == "llvm.loop.pipeline.disable") {
28859d99731SBrendon Cahoon       disabledByPragma = true;
28959d99731SBrendon Cahoon     }
29059d99731SBrendon Cahoon   }
29159d99731SBrendon Cahoon }
29259d99731SBrendon Cahoon 
293254f889dSBrendon Cahoon /// Return true if the loop can be software pipelined.  The algorithm is
294254f889dSBrendon Cahoon /// restricted to loops with a single basic block.  Make sure that the
295254f889dSBrendon Cahoon /// branch in the loop can be analyzed.
296254f889dSBrendon Cahoon bool MachinePipeliner::canPipelineLoop(MachineLoop &L) {
297254f889dSBrendon Cahoon   if (L.getNumBlocks() != 1)
298254f889dSBrendon Cahoon     return false;
299254f889dSBrendon Cahoon 
30059d99731SBrendon Cahoon   if (disabledByPragma)
30159d99731SBrendon Cahoon     return false;
30259d99731SBrendon Cahoon 
303254f889dSBrendon Cahoon   // Check if the branch can't be understood because we can't do pipelining
304254f889dSBrendon Cahoon   // if that's the case.
305254f889dSBrendon Cahoon   LI.TBB = nullptr;
306254f889dSBrendon Cahoon   LI.FBB = nullptr;
307254f889dSBrendon Cahoon   LI.BrCond.clear();
30818e7bf5cSJinsong Ji   if (TII->analyzeBranch(*L.getHeader(), LI.TBB, LI.FBB, LI.BrCond)) {
30918e7bf5cSJinsong Ji     LLVM_DEBUG(
31018e7bf5cSJinsong Ji         dbgs() << "Unable to analyzeBranch, can NOT pipeline current Loop\n");
31118e7bf5cSJinsong Ji     NumFailBranch++;
312254f889dSBrendon Cahoon     return false;
31318e7bf5cSJinsong Ji   }
314254f889dSBrendon Cahoon 
315254f889dSBrendon Cahoon   LI.LoopInductionVar = nullptr;
316254f889dSBrendon Cahoon   LI.LoopCompare = nullptr;
31718e7bf5cSJinsong Ji   if (TII->analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare)) {
31818e7bf5cSJinsong Ji     LLVM_DEBUG(
31918e7bf5cSJinsong Ji         dbgs() << "Unable to analyzeLoop, can NOT pipeline current Loop\n");
32018e7bf5cSJinsong Ji     NumFailLoop++;
321254f889dSBrendon Cahoon     return false;
32218e7bf5cSJinsong Ji   }
323254f889dSBrendon Cahoon 
32418e7bf5cSJinsong Ji   if (!L.getLoopPreheader()) {
32518e7bf5cSJinsong Ji     LLVM_DEBUG(
32618e7bf5cSJinsong Ji         dbgs() << "Preheader not found, can NOT pipeline current Loop\n");
32718e7bf5cSJinsong Ji     NumFailPreheader++;
328254f889dSBrendon Cahoon     return false;
32918e7bf5cSJinsong Ji   }
330254f889dSBrendon Cahoon 
331c715a5d2SKrzysztof Parzyszek   // Remove any subregisters from inputs to phi nodes.
332c715a5d2SKrzysztof Parzyszek   preprocessPhiNodes(*L.getHeader());
333254f889dSBrendon Cahoon   return true;
334254f889dSBrendon Cahoon }
335254f889dSBrendon Cahoon 
336c715a5d2SKrzysztof Parzyszek void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock &B) {
337c715a5d2SKrzysztof Parzyszek   MachineRegisterInfo &MRI = MF->getRegInfo();
338c715a5d2SKrzysztof Parzyszek   SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
339c715a5d2SKrzysztof Parzyszek 
340c715a5d2SKrzysztof Parzyszek   for (MachineInstr &PI : make_range(B.begin(), B.getFirstNonPHI())) {
341c715a5d2SKrzysztof Parzyszek     MachineOperand &DefOp = PI.getOperand(0);
342c715a5d2SKrzysztof Parzyszek     assert(DefOp.getSubReg() == 0);
343c715a5d2SKrzysztof Parzyszek     auto *RC = MRI.getRegClass(DefOp.getReg());
344c715a5d2SKrzysztof Parzyszek 
345c715a5d2SKrzysztof Parzyszek     for (unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
346c715a5d2SKrzysztof Parzyszek       MachineOperand &RegOp = PI.getOperand(i);
347c715a5d2SKrzysztof Parzyszek       if (RegOp.getSubReg() == 0)
348c715a5d2SKrzysztof Parzyszek         continue;
349c715a5d2SKrzysztof Parzyszek 
350c715a5d2SKrzysztof Parzyszek       // If the operand uses a subregister, replace it with a new register
351c715a5d2SKrzysztof Parzyszek       // without subregisters, and generate a copy to the new register.
352c715a5d2SKrzysztof Parzyszek       unsigned NewReg = MRI.createVirtualRegister(RC);
353c715a5d2SKrzysztof Parzyszek       MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
354c715a5d2SKrzysztof Parzyszek       MachineBasicBlock::iterator At = PredB.getFirstTerminator();
355c715a5d2SKrzysztof Parzyszek       const DebugLoc &DL = PredB.findDebugLoc(At);
356c715a5d2SKrzysztof Parzyszek       auto Copy = BuildMI(PredB, At, DL, TII->get(TargetOpcode::COPY), NewReg)
357c715a5d2SKrzysztof Parzyszek                     .addReg(RegOp.getReg(), getRegState(RegOp),
358c715a5d2SKrzysztof Parzyszek                             RegOp.getSubReg());
359c715a5d2SKrzysztof Parzyszek       Slots.insertMachineInstrInMaps(*Copy);
360c715a5d2SKrzysztof Parzyszek       RegOp.setReg(NewReg);
361c715a5d2SKrzysztof Parzyszek       RegOp.setSubReg(0);
362c715a5d2SKrzysztof Parzyszek     }
363c715a5d2SKrzysztof Parzyszek   }
364c715a5d2SKrzysztof Parzyszek }
365c715a5d2SKrzysztof Parzyszek 
366254f889dSBrendon Cahoon /// The SMS algorithm consists of the following main steps:
367254f889dSBrendon Cahoon /// 1. Computation and analysis of the dependence graph.
368254f889dSBrendon Cahoon /// 2. Ordering of the nodes (instructions).
369254f889dSBrendon Cahoon /// 3. Attempt to Schedule the loop.
370254f889dSBrendon Cahoon bool MachinePipeliner::swingModuloScheduler(MachineLoop &L) {
371254f889dSBrendon Cahoon   assert(L.getBlocks().size() == 1 && "SMS works on single blocks only.");
372254f889dSBrendon Cahoon 
37359d99731SBrendon Cahoon   SwingSchedulerDAG SMS(*this, L, getAnalysis<LiveIntervals>(), RegClassInfo,
37459d99731SBrendon Cahoon                         II_setByPragma);
375254f889dSBrendon Cahoon 
376254f889dSBrendon Cahoon   MachineBasicBlock *MBB = L.getHeader();
377254f889dSBrendon Cahoon   // The kernel should not include any terminator instructions.  These
378254f889dSBrendon Cahoon   // will be added back later.
379254f889dSBrendon Cahoon   SMS.startBlock(MBB);
380254f889dSBrendon Cahoon 
381254f889dSBrendon Cahoon   // Compute the number of 'real' instructions in the basic block by
382254f889dSBrendon Cahoon   // ignoring terminators.
383254f889dSBrendon Cahoon   unsigned size = MBB->size();
384254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator I = MBB->getFirstTerminator(),
385254f889dSBrendon Cahoon                                    E = MBB->instr_end();
386254f889dSBrendon Cahoon        I != E; ++I, --size)
387254f889dSBrendon Cahoon     ;
388254f889dSBrendon Cahoon 
389254f889dSBrendon Cahoon   SMS.enterRegion(MBB, MBB->begin(), MBB->getFirstTerminator(), size);
390254f889dSBrendon Cahoon   SMS.schedule();
391254f889dSBrendon Cahoon   SMS.exitRegion();
392254f889dSBrendon Cahoon 
393254f889dSBrendon Cahoon   SMS.finishBlock();
394254f889dSBrendon Cahoon   return SMS.hasNewSchedule();
395254f889dSBrendon Cahoon }
396254f889dSBrendon Cahoon 
39759d99731SBrendon Cahoon void SwingSchedulerDAG::setMII(unsigned ResMII, unsigned RecMII) {
39859d99731SBrendon Cahoon   if (II_setByPragma > 0)
39959d99731SBrendon Cahoon     MII = II_setByPragma;
40059d99731SBrendon Cahoon   else
40159d99731SBrendon Cahoon     MII = std::max(ResMII, RecMII);
40259d99731SBrendon Cahoon }
40359d99731SBrendon Cahoon 
40459d99731SBrendon Cahoon void SwingSchedulerDAG::setMAX_II() {
40559d99731SBrendon Cahoon   if (II_setByPragma > 0)
40659d99731SBrendon Cahoon     MAX_II = II_setByPragma;
40759d99731SBrendon Cahoon   else
40859d99731SBrendon Cahoon     MAX_II = MII + 10;
40959d99731SBrendon Cahoon }
41059d99731SBrendon Cahoon 
411254f889dSBrendon Cahoon /// We override the schedule function in ScheduleDAGInstrs to implement the
412254f889dSBrendon Cahoon /// scheduling part of the Swing Modulo Scheduling algorithm.
413254f889dSBrendon Cahoon void SwingSchedulerDAG::schedule() {
414254f889dSBrendon Cahoon   AliasAnalysis *AA = &Pass.getAnalysis<AAResultsWrapperPass>().getAAResults();
415254f889dSBrendon Cahoon   buildSchedGraph(AA);
416254f889dSBrendon Cahoon   addLoopCarriedDependences(AA);
417254f889dSBrendon Cahoon   updatePhiDependences();
418254f889dSBrendon Cahoon   Topo.InitDAGTopologicalSorting();
419254f889dSBrendon Cahoon   changeDependences();
42062ac69d4SSumanth Gundapaneni   postprocessDAG();
421726e12cfSMatthias Braun   LLVM_DEBUG(dump());
422254f889dSBrendon Cahoon 
423254f889dSBrendon Cahoon   NodeSetType NodeSets;
424254f889dSBrendon Cahoon   findCircuits(NodeSets);
4254b8bcf00SRoorda, Jan-Willem   NodeSetType Circuits = NodeSets;
426254f889dSBrendon Cahoon 
427254f889dSBrendon Cahoon   // Calculate the MII.
428254f889dSBrendon Cahoon   unsigned ResMII = calculateResMII();
429254f889dSBrendon Cahoon   unsigned RecMII = calculateRecMII(NodeSets);
430254f889dSBrendon Cahoon 
431254f889dSBrendon Cahoon   fuseRecs(NodeSets);
432254f889dSBrendon Cahoon 
433254f889dSBrendon Cahoon   // This flag is used for testing and can cause correctness problems.
434254f889dSBrendon Cahoon   if (SwpIgnoreRecMII)
435254f889dSBrendon Cahoon     RecMII = 0;
436254f889dSBrendon Cahoon 
43759d99731SBrendon Cahoon   setMII(ResMII, RecMII);
43859d99731SBrendon Cahoon   setMAX_II();
43959d99731SBrendon Cahoon 
44059d99731SBrendon Cahoon   LLVM_DEBUG(dbgs() << "MII = " << MII << " MAX_II = " << MAX_II
44159d99731SBrendon Cahoon                     << " (rec=" << RecMII << ", res=" << ResMII << ")\n");
442254f889dSBrendon Cahoon 
443254f889dSBrendon Cahoon   // Can't schedule a loop without a valid MII.
44418e7bf5cSJinsong Ji   if (MII == 0) {
44518e7bf5cSJinsong Ji     LLVM_DEBUG(
44618e7bf5cSJinsong Ji         dbgs()
44718e7bf5cSJinsong Ji         << "0 is not a valid Minimal Initiation Interval, can NOT schedule\n");
44818e7bf5cSJinsong Ji     NumFailZeroMII++;
449254f889dSBrendon Cahoon     return;
45018e7bf5cSJinsong Ji   }
451254f889dSBrendon Cahoon 
452254f889dSBrendon Cahoon   // Don't pipeline large loops.
45318e7bf5cSJinsong Ji   if (SwpMaxMii != -1 && (int)MII > SwpMaxMii) {
45418e7bf5cSJinsong Ji     LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
45518e7bf5cSJinsong Ji                       << ", we don't pipleline large loops\n");
45618e7bf5cSJinsong Ji     NumFailLargeMaxMII++;
457254f889dSBrendon Cahoon     return;
45818e7bf5cSJinsong Ji   }
459254f889dSBrendon Cahoon 
460254f889dSBrendon Cahoon   computeNodeFunctions(NodeSets);
461254f889dSBrendon Cahoon 
462254f889dSBrendon Cahoon   registerPressureFilter(NodeSets);
463254f889dSBrendon Cahoon 
464254f889dSBrendon Cahoon   colocateNodeSets(NodeSets);
465254f889dSBrendon Cahoon 
466254f889dSBrendon Cahoon   checkNodeSets(NodeSets);
467254f889dSBrendon Cahoon 
468d34e60caSNicola Zaghen   LLVM_DEBUG({
469254f889dSBrendon Cahoon     for (auto &I : NodeSets) {
470254f889dSBrendon Cahoon       dbgs() << "  Rec NodeSet ";
471254f889dSBrendon Cahoon       I.dump();
472254f889dSBrendon Cahoon     }
473254f889dSBrendon Cahoon   });
474254f889dSBrendon Cahoon 
475efd94c56SFangrui Song   llvm::stable_sort(NodeSets, std::greater<NodeSet>());
476254f889dSBrendon Cahoon 
477254f889dSBrendon Cahoon   groupRemainingNodes(NodeSets);
478254f889dSBrendon Cahoon 
479254f889dSBrendon Cahoon   removeDuplicateNodes(NodeSets);
480254f889dSBrendon Cahoon 
481d34e60caSNicola Zaghen   LLVM_DEBUG({
482254f889dSBrendon Cahoon     for (auto &I : NodeSets) {
483254f889dSBrendon Cahoon       dbgs() << "  NodeSet ";
484254f889dSBrendon Cahoon       I.dump();
485254f889dSBrendon Cahoon     }
486254f889dSBrendon Cahoon   });
487254f889dSBrendon Cahoon 
488254f889dSBrendon Cahoon   computeNodeOrder(NodeSets);
489254f889dSBrendon Cahoon 
4904b8bcf00SRoorda, Jan-Willem   // check for node order issues
4914b8bcf00SRoorda, Jan-Willem   checkValidNodeOrder(Circuits);
4924b8bcf00SRoorda, Jan-Willem 
493254f889dSBrendon Cahoon   SMSchedule Schedule(Pass.MF);
494254f889dSBrendon Cahoon   Scheduled = schedulePipeline(Schedule);
495254f889dSBrendon Cahoon 
49618e7bf5cSJinsong Ji   if (!Scheduled){
49718e7bf5cSJinsong Ji     LLVM_DEBUG(dbgs() << "No schedule found, return\n");
49818e7bf5cSJinsong Ji     NumFailNoSchedule++;
499254f889dSBrendon Cahoon     return;
50018e7bf5cSJinsong Ji   }
501254f889dSBrendon Cahoon 
502254f889dSBrendon Cahoon   unsigned numStages = Schedule.getMaxStageCount();
503254f889dSBrendon Cahoon   // No need to generate pipeline if there are no overlapped iterations.
50418e7bf5cSJinsong Ji   if (numStages == 0) {
50518e7bf5cSJinsong Ji     LLVM_DEBUG(
50618e7bf5cSJinsong Ji         dbgs() << "No overlapped iterations, no need to generate pipeline\n");
50718e7bf5cSJinsong Ji     NumFailZeroStage++;
508254f889dSBrendon Cahoon     return;
50918e7bf5cSJinsong Ji   }
510254f889dSBrendon Cahoon   // Check that the maximum stage count is less than user-defined limit.
51118e7bf5cSJinsong Ji   if (SwpMaxStages > -1 && (int)numStages > SwpMaxStages) {
51218e7bf5cSJinsong Ji     LLVM_DEBUG(dbgs() << "numStages:" << numStages << ">" << SwpMaxStages
51318e7bf5cSJinsong Ji                       << " : too many stages, abort\n");
51418e7bf5cSJinsong Ji     NumFailLargeMaxStage++;
515254f889dSBrendon Cahoon     return;
51618e7bf5cSJinsong Ji   }
517254f889dSBrendon Cahoon 
518254f889dSBrendon Cahoon   generatePipelinedLoop(Schedule);
519254f889dSBrendon Cahoon   ++NumPipelined;
520254f889dSBrendon Cahoon }
521254f889dSBrendon Cahoon 
522254f889dSBrendon Cahoon /// Clean up after the software pipeliner runs.
523254f889dSBrendon Cahoon void SwingSchedulerDAG::finishBlock() {
524254f889dSBrendon Cahoon   for (MachineInstr *I : NewMIs)
525254f889dSBrendon Cahoon     MF.DeleteMachineInstr(I);
526254f889dSBrendon Cahoon   NewMIs.clear();
527254f889dSBrendon Cahoon 
528254f889dSBrendon Cahoon   // Call the superclass.
529254f889dSBrendon Cahoon   ScheduleDAGInstrs::finishBlock();
530254f889dSBrendon Cahoon }
531254f889dSBrendon Cahoon 
532254f889dSBrendon Cahoon /// Return the register values for  the operands of a Phi instruction.
533254f889dSBrendon Cahoon /// This function assume the instruction is a Phi.
534254f889dSBrendon Cahoon static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
535254f889dSBrendon Cahoon                        unsigned &InitVal, unsigned &LoopVal) {
536254f889dSBrendon Cahoon   assert(Phi.isPHI() && "Expecting a Phi.");
537254f889dSBrendon Cahoon 
538254f889dSBrendon Cahoon   InitVal = 0;
539254f889dSBrendon Cahoon   LoopVal = 0;
540254f889dSBrendon Cahoon   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
541254f889dSBrendon Cahoon     if (Phi.getOperand(i + 1).getMBB() != Loop)
542254f889dSBrendon Cahoon       InitVal = Phi.getOperand(i).getReg();
543fbfb19b1SSimon Pilgrim     else
544254f889dSBrendon Cahoon       LoopVal = Phi.getOperand(i).getReg();
545254f889dSBrendon Cahoon 
546254f889dSBrendon Cahoon   assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
547254f889dSBrendon Cahoon }
548254f889dSBrendon Cahoon 
549254f889dSBrendon Cahoon /// Return the Phi register value that comes from the incoming block.
550254f889dSBrendon Cahoon static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
551254f889dSBrendon Cahoon   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
552254f889dSBrendon Cahoon     if (Phi.getOperand(i + 1).getMBB() != LoopBB)
553254f889dSBrendon Cahoon       return Phi.getOperand(i).getReg();
554254f889dSBrendon Cahoon   return 0;
555254f889dSBrendon Cahoon }
556254f889dSBrendon Cahoon 
5578f976ba0SHiroshi Inoue /// Return the Phi register value that comes the loop block.
558254f889dSBrendon Cahoon static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
559254f889dSBrendon Cahoon   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
560254f889dSBrendon Cahoon     if (Phi.getOperand(i + 1).getMBB() == LoopBB)
561254f889dSBrendon Cahoon       return Phi.getOperand(i).getReg();
562254f889dSBrendon Cahoon   return 0;
563254f889dSBrendon Cahoon }
564254f889dSBrendon Cahoon 
565254f889dSBrendon Cahoon /// Return true if SUb can be reached from SUa following the chain edges.
566254f889dSBrendon Cahoon static bool isSuccOrder(SUnit *SUa, SUnit *SUb) {
567254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 8> Visited;
568254f889dSBrendon Cahoon   SmallVector<SUnit *, 8> Worklist;
569254f889dSBrendon Cahoon   Worklist.push_back(SUa);
570254f889dSBrendon Cahoon   while (!Worklist.empty()) {
571254f889dSBrendon Cahoon     const SUnit *SU = Worklist.pop_back_val();
572254f889dSBrendon Cahoon     for (auto &SI : SU->Succs) {
573254f889dSBrendon Cahoon       SUnit *SuccSU = SI.getSUnit();
574254f889dSBrendon Cahoon       if (SI.getKind() == SDep::Order) {
575254f889dSBrendon Cahoon         if (Visited.count(SuccSU))
576254f889dSBrendon Cahoon           continue;
577254f889dSBrendon Cahoon         if (SuccSU == SUb)
578254f889dSBrendon Cahoon           return true;
579254f889dSBrendon Cahoon         Worklist.push_back(SuccSU);
580254f889dSBrendon Cahoon         Visited.insert(SuccSU);
581254f889dSBrendon Cahoon       }
582254f889dSBrendon Cahoon     }
583254f889dSBrendon Cahoon   }
584254f889dSBrendon Cahoon   return false;
585254f889dSBrendon Cahoon }
586254f889dSBrendon Cahoon 
587254f889dSBrendon Cahoon /// Return true if the instruction causes a chain between memory
588254f889dSBrendon Cahoon /// references before and after it.
589254f889dSBrendon Cahoon static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA) {
5906c5d5ce5SUlrich Weigand   return MI.isCall() || MI.mayRaiseFPException() ||
5916c5d5ce5SUlrich Weigand          MI.hasUnmodeledSideEffects() ||
592254f889dSBrendon Cahoon          (MI.hasOrderedMemoryRef() &&
593d98cf00cSJustin Lebar           (!MI.mayLoad() || !MI.isDereferenceableInvariantLoad(AA)));
594254f889dSBrendon Cahoon }
595254f889dSBrendon Cahoon 
596254f889dSBrendon Cahoon /// Return the underlying objects for the memory references of an instruction.
597254f889dSBrendon Cahoon /// This function calls the code in ValueTracking, but first checks that the
598254f889dSBrendon Cahoon /// instruction has a memory operand.
59971e8c6f2SBjorn Pettersson static void getUnderlyingObjects(const MachineInstr *MI,
60071e8c6f2SBjorn Pettersson                                  SmallVectorImpl<const Value *> &Objs,
601254f889dSBrendon Cahoon                                  const DataLayout &DL) {
602254f889dSBrendon Cahoon   if (!MI->hasOneMemOperand())
603254f889dSBrendon Cahoon     return;
604254f889dSBrendon Cahoon   MachineMemOperand *MM = *MI->memoperands_begin();
605254f889dSBrendon Cahoon   if (!MM->getValue())
606254f889dSBrendon Cahoon     return;
60771e8c6f2SBjorn Pettersson   GetUnderlyingObjects(MM->getValue(), Objs, DL);
60871e8c6f2SBjorn Pettersson   for (const Value *V : Objs) {
6099f041b18SKrzysztof Parzyszek     if (!isIdentifiedObject(V)) {
6109f041b18SKrzysztof Parzyszek       Objs.clear();
6119f041b18SKrzysztof Parzyszek       return;
6129f041b18SKrzysztof Parzyszek     }
6139f041b18SKrzysztof Parzyszek     Objs.push_back(V);
6149f041b18SKrzysztof Parzyszek   }
615254f889dSBrendon Cahoon }
616254f889dSBrendon Cahoon 
617254f889dSBrendon Cahoon /// Add a chain edge between a load and store if the store can be an
618254f889dSBrendon Cahoon /// alias of the load on a subsequent iteration, i.e., a loop carried
619254f889dSBrendon Cahoon /// dependence. This code is very similar to the code in ScheduleDAGInstrs
620254f889dSBrendon Cahoon /// but that code doesn't create loop carried dependences.
621254f889dSBrendon Cahoon void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis *AA) {
62271e8c6f2SBjorn Pettersson   MapVector<const Value *, SmallVector<SUnit *, 4>> PendingLoads;
6239f041b18SKrzysztof Parzyszek   Value *UnknownValue =
6249f041b18SKrzysztof Parzyszek     UndefValue::get(Type::getVoidTy(MF.getFunction().getContext()));
625254f889dSBrendon Cahoon   for (auto &SU : SUnits) {
626254f889dSBrendon Cahoon     MachineInstr &MI = *SU.getInstr();
627254f889dSBrendon Cahoon     if (isDependenceBarrier(MI, AA))
628254f889dSBrendon Cahoon       PendingLoads.clear();
629254f889dSBrendon Cahoon     else if (MI.mayLoad()) {
63071e8c6f2SBjorn Pettersson       SmallVector<const Value *, 4> Objs;
631254f889dSBrendon Cahoon       getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
6329f041b18SKrzysztof Parzyszek       if (Objs.empty())
6339f041b18SKrzysztof Parzyszek         Objs.push_back(UnknownValue);
634254f889dSBrendon Cahoon       for (auto V : Objs) {
635254f889dSBrendon Cahoon         SmallVector<SUnit *, 4> &SUs = PendingLoads[V];
636254f889dSBrendon Cahoon         SUs.push_back(&SU);
637254f889dSBrendon Cahoon       }
638254f889dSBrendon Cahoon     } else if (MI.mayStore()) {
63971e8c6f2SBjorn Pettersson       SmallVector<const Value *, 4> Objs;
640254f889dSBrendon Cahoon       getUnderlyingObjects(&MI, Objs, MF.getDataLayout());
6419f041b18SKrzysztof Parzyszek       if (Objs.empty())
6429f041b18SKrzysztof Parzyszek         Objs.push_back(UnknownValue);
643254f889dSBrendon Cahoon       for (auto V : Objs) {
64471e8c6f2SBjorn Pettersson         MapVector<const Value *, SmallVector<SUnit *, 4>>::iterator I =
645254f889dSBrendon Cahoon             PendingLoads.find(V);
646254f889dSBrendon Cahoon         if (I == PendingLoads.end())
647254f889dSBrendon Cahoon           continue;
648254f889dSBrendon Cahoon         for (auto Load : I->second) {
649254f889dSBrendon Cahoon           if (isSuccOrder(Load, &SU))
650254f889dSBrendon Cahoon             continue;
651254f889dSBrendon Cahoon           MachineInstr &LdMI = *Load->getInstr();
652254f889dSBrendon Cahoon           // First, perform the cheaper check that compares the base register.
653254f889dSBrendon Cahoon           // If they are the same and the load offset is less than the store
654254f889dSBrendon Cahoon           // offset, then mark the dependence as loop carried potentially.
655238c9d63SBjorn Pettersson           const MachineOperand *BaseOp1, *BaseOp2;
656254f889dSBrendon Cahoon           int64_t Offset1, Offset2;
657d7eebd6dSFrancis Visoiu Mistrih           if (TII->getMemOperandWithOffset(LdMI, BaseOp1, Offset1, TRI) &&
658d7eebd6dSFrancis Visoiu Mistrih               TII->getMemOperandWithOffset(MI, BaseOp2, Offset2, TRI)) {
659d7eebd6dSFrancis Visoiu Mistrih             if (BaseOp1->isIdenticalTo(*BaseOp2) &&
660d7eebd6dSFrancis Visoiu Mistrih                 (int)Offset1 < (int)Offset2) {
661254f889dSBrendon Cahoon               assert(TII->areMemAccessesTriviallyDisjoint(LdMI, MI, AA) &&
662254f889dSBrendon Cahoon                      "What happened to the chain edge?");
663c715a5d2SKrzysztof Parzyszek               SDep Dep(Load, SDep::Barrier);
664c715a5d2SKrzysztof Parzyszek               Dep.setLatency(1);
665c715a5d2SKrzysztof Parzyszek               SU.addPred(Dep);
666254f889dSBrendon Cahoon               continue;
667254f889dSBrendon Cahoon             }
6689f041b18SKrzysztof Parzyszek           }
669254f889dSBrendon Cahoon           // Second, the more expensive check that uses alias analysis on the
670254f889dSBrendon Cahoon           // base registers. If they alias, and the load offset is less than
671254f889dSBrendon Cahoon           // the store offset, the mark the dependence as loop carried.
672254f889dSBrendon Cahoon           if (!AA) {
673c715a5d2SKrzysztof Parzyszek             SDep Dep(Load, SDep::Barrier);
674c715a5d2SKrzysztof Parzyszek             Dep.setLatency(1);
675c715a5d2SKrzysztof Parzyszek             SU.addPred(Dep);
676254f889dSBrendon Cahoon             continue;
677254f889dSBrendon Cahoon           }
678254f889dSBrendon Cahoon           MachineMemOperand *MMO1 = *LdMI.memoperands_begin();
679254f889dSBrendon Cahoon           MachineMemOperand *MMO2 = *MI.memoperands_begin();
680254f889dSBrendon Cahoon           if (!MMO1->getValue() || !MMO2->getValue()) {
681c715a5d2SKrzysztof Parzyszek             SDep Dep(Load, SDep::Barrier);
682c715a5d2SKrzysztof Parzyszek             Dep.setLatency(1);
683c715a5d2SKrzysztof Parzyszek             SU.addPred(Dep);
684254f889dSBrendon Cahoon             continue;
685254f889dSBrendon Cahoon           }
686254f889dSBrendon Cahoon           if (MMO1->getValue() == MMO2->getValue() &&
687254f889dSBrendon Cahoon               MMO1->getOffset() <= MMO2->getOffset()) {
688c715a5d2SKrzysztof Parzyszek             SDep Dep(Load, SDep::Barrier);
689c715a5d2SKrzysztof Parzyszek             Dep.setLatency(1);
690c715a5d2SKrzysztof Parzyszek             SU.addPred(Dep);
691254f889dSBrendon Cahoon             continue;
692254f889dSBrendon Cahoon           }
693254f889dSBrendon Cahoon           AliasResult AAResult = AA->alias(
6946ef8002cSGeorge Burgess IV               MemoryLocation(MMO1->getValue(), LocationSize::unknown(),
695254f889dSBrendon Cahoon                              MMO1->getAAInfo()),
6966ef8002cSGeorge Burgess IV               MemoryLocation(MMO2->getValue(), LocationSize::unknown(),
697254f889dSBrendon Cahoon                              MMO2->getAAInfo()));
698254f889dSBrendon Cahoon 
699c715a5d2SKrzysztof Parzyszek           if (AAResult != NoAlias) {
700c715a5d2SKrzysztof Parzyszek             SDep Dep(Load, SDep::Barrier);
701c715a5d2SKrzysztof Parzyszek             Dep.setLatency(1);
702c715a5d2SKrzysztof Parzyszek             SU.addPred(Dep);
703c715a5d2SKrzysztof Parzyszek           }
704254f889dSBrendon Cahoon         }
705254f889dSBrendon Cahoon       }
706254f889dSBrendon Cahoon     }
707254f889dSBrendon Cahoon   }
708254f889dSBrendon Cahoon }
709254f889dSBrendon Cahoon 
710254f889dSBrendon Cahoon /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
711254f889dSBrendon Cahoon /// processes dependences for PHIs. This function adds true dependences
712254f889dSBrendon Cahoon /// from a PHI to a use, and a loop carried dependence from the use to the
713254f889dSBrendon Cahoon /// PHI. The loop carried dependence is represented as an anti dependence
714254f889dSBrendon Cahoon /// edge. This function also removes chain dependences between unrelated
715254f889dSBrendon Cahoon /// PHIs.
716254f889dSBrendon Cahoon void SwingSchedulerDAG::updatePhiDependences() {
717254f889dSBrendon Cahoon   SmallVector<SDep, 4> RemoveDeps;
718254f889dSBrendon Cahoon   const TargetSubtargetInfo &ST = MF.getSubtarget<TargetSubtargetInfo>();
719254f889dSBrendon Cahoon 
720254f889dSBrendon Cahoon   // Iterate over each DAG node.
721254f889dSBrendon Cahoon   for (SUnit &I : SUnits) {
722254f889dSBrendon Cahoon     RemoveDeps.clear();
723254f889dSBrendon Cahoon     // Set to true if the instruction has an operand defined by a Phi.
724254f889dSBrendon Cahoon     unsigned HasPhiUse = 0;
725254f889dSBrendon Cahoon     unsigned HasPhiDef = 0;
726254f889dSBrendon Cahoon     MachineInstr *MI = I.getInstr();
727254f889dSBrendon Cahoon     // Iterate over each operand, and we process the definitions.
728254f889dSBrendon Cahoon     for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
729254f889dSBrendon Cahoon                                     MOE = MI->operands_end();
730254f889dSBrendon Cahoon          MOI != MOE; ++MOI) {
731254f889dSBrendon Cahoon       if (!MOI->isReg())
732254f889dSBrendon Cahoon         continue;
733254f889dSBrendon Cahoon       unsigned Reg = MOI->getReg();
734254f889dSBrendon Cahoon       if (MOI->isDef()) {
735254f889dSBrendon Cahoon         // If the register is used by a Phi, then create an anti dependence.
736254f889dSBrendon Cahoon         for (MachineRegisterInfo::use_instr_iterator
737254f889dSBrendon Cahoon                  UI = MRI.use_instr_begin(Reg),
738254f889dSBrendon Cahoon                  UE = MRI.use_instr_end();
739254f889dSBrendon Cahoon              UI != UE; ++UI) {
740254f889dSBrendon Cahoon           MachineInstr *UseMI = &*UI;
741254f889dSBrendon Cahoon           SUnit *SU = getSUnit(UseMI);
742cdc71612SEugene Zelenko           if (SU != nullptr && UseMI->isPHI()) {
743254f889dSBrendon Cahoon             if (!MI->isPHI()) {
744254f889dSBrendon Cahoon               SDep Dep(SU, SDep::Anti, Reg);
745c715a5d2SKrzysztof Parzyszek               Dep.setLatency(1);
746254f889dSBrendon Cahoon               I.addPred(Dep);
747254f889dSBrendon Cahoon             } else {
748254f889dSBrendon Cahoon               HasPhiDef = Reg;
749254f889dSBrendon Cahoon               // Add a chain edge to a dependent Phi that isn't an existing
750254f889dSBrendon Cahoon               // predecessor.
751254f889dSBrendon Cahoon               if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
752254f889dSBrendon Cahoon                 I.addPred(SDep(SU, SDep::Barrier));
753254f889dSBrendon Cahoon             }
754254f889dSBrendon Cahoon           }
755254f889dSBrendon Cahoon         }
756254f889dSBrendon Cahoon       } else if (MOI->isUse()) {
757254f889dSBrendon Cahoon         // If the register is defined by a Phi, then create a true dependence.
758254f889dSBrendon Cahoon         MachineInstr *DefMI = MRI.getUniqueVRegDef(Reg);
759cdc71612SEugene Zelenko         if (DefMI == nullptr)
760254f889dSBrendon Cahoon           continue;
761254f889dSBrendon Cahoon         SUnit *SU = getSUnit(DefMI);
762cdc71612SEugene Zelenko         if (SU != nullptr && DefMI->isPHI()) {
763254f889dSBrendon Cahoon           if (!MI->isPHI()) {
764254f889dSBrendon Cahoon             SDep Dep(SU, SDep::Data, Reg);
765254f889dSBrendon Cahoon             Dep.setLatency(0);
766254f889dSBrendon Cahoon             ST.adjustSchedDependency(SU, &I, Dep);
767254f889dSBrendon Cahoon             I.addPred(Dep);
768254f889dSBrendon Cahoon           } else {
769254f889dSBrendon Cahoon             HasPhiUse = Reg;
770254f889dSBrendon Cahoon             // Add a chain edge to a dependent Phi that isn't an existing
771254f889dSBrendon Cahoon             // predecessor.
772254f889dSBrendon Cahoon             if (SU->NodeNum < I.NodeNum && !I.isPred(SU))
773254f889dSBrendon Cahoon               I.addPred(SDep(SU, SDep::Barrier));
774254f889dSBrendon Cahoon           }
775254f889dSBrendon Cahoon         }
776254f889dSBrendon Cahoon       }
777254f889dSBrendon Cahoon     }
778254f889dSBrendon Cahoon     // Remove order dependences from an unrelated Phi.
779254f889dSBrendon Cahoon     if (!SwpPruneDeps)
780254f889dSBrendon Cahoon       continue;
781254f889dSBrendon Cahoon     for (auto &PI : I.Preds) {
782254f889dSBrendon Cahoon       MachineInstr *PMI = PI.getSUnit()->getInstr();
783254f889dSBrendon Cahoon       if (PMI->isPHI() && PI.getKind() == SDep::Order) {
784254f889dSBrendon Cahoon         if (I.getInstr()->isPHI()) {
785254f889dSBrendon Cahoon           if (PMI->getOperand(0).getReg() == HasPhiUse)
786254f889dSBrendon Cahoon             continue;
787254f889dSBrendon Cahoon           if (getLoopPhiReg(*PMI, PMI->getParent()) == HasPhiDef)
788254f889dSBrendon Cahoon             continue;
789254f889dSBrendon Cahoon         }
790254f889dSBrendon Cahoon         RemoveDeps.push_back(PI);
791254f889dSBrendon Cahoon       }
792254f889dSBrendon Cahoon     }
793254f889dSBrendon Cahoon     for (int i = 0, e = RemoveDeps.size(); i != e; ++i)
794254f889dSBrendon Cahoon       I.removePred(RemoveDeps[i]);
795254f889dSBrendon Cahoon   }
796254f889dSBrendon Cahoon }
797254f889dSBrendon Cahoon 
798254f889dSBrendon Cahoon /// Iterate over each DAG node and see if we can change any dependences
799254f889dSBrendon Cahoon /// in order to reduce the recurrence MII.
800254f889dSBrendon Cahoon void SwingSchedulerDAG::changeDependences() {
801254f889dSBrendon Cahoon   // See if an instruction can use a value from the previous iteration.
802254f889dSBrendon Cahoon   // If so, we update the base and offset of the instruction and change
803254f889dSBrendon Cahoon   // the dependences.
804254f889dSBrendon Cahoon   for (SUnit &I : SUnits) {
805254f889dSBrendon Cahoon     unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
806254f889dSBrendon Cahoon     int64_t NewOffset = 0;
807254f889dSBrendon Cahoon     if (!canUseLastOffsetValue(I.getInstr(), BasePos, OffsetPos, NewBase,
808254f889dSBrendon Cahoon                                NewOffset))
809254f889dSBrendon Cahoon       continue;
810254f889dSBrendon Cahoon 
811254f889dSBrendon Cahoon     // Get the MI and SUnit for the instruction that defines the original base.
812254f889dSBrendon Cahoon     unsigned OrigBase = I.getInstr()->getOperand(BasePos).getReg();
813254f889dSBrendon Cahoon     MachineInstr *DefMI = MRI.getUniqueVRegDef(OrigBase);
814254f889dSBrendon Cahoon     if (!DefMI)
815254f889dSBrendon Cahoon       continue;
816254f889dSBrendon Cahoon     SUnit *DefSU = getSUnit(DefMI);
817254f889dSBrendon Cahoon     if (!DefSU)
818254f889dSBrendon Cahoon       continue;
819254f889dSBrendon Cahoon     // Get the MI and SUnit for the instruction that defins the new base.
820254f889dSBrendon Cahoon     MachineInstr *LastMI = MRI.getUniqueVRegDef(NewBase);
821254f889dSBrendon Cahoon     if (!LastMI)
822254f889dSBrendon Cahoon       continue;
823254f889dSBrendon Cahoon     SUnit *LastSU = getSUnit(LastMI);
824254f889dSBrendon Cahoon     if (!LastSU)
825254f889dSBrendon Cahoon       continue;
826254f889dSBrendon Cahoon 
827254f889dSBrendon Cahoon     if (Topo.IsReachable(&I, LastSU))
828254f889dSBrendon Cahoon       continue;
829254f889dSBrendon Cahoon 
830254f889dSBrendon Cahoon     // Remove the dependence. The value now depends on a prior iteration.
831254f889dSBrendon Cahoon     SmallVector<SDep, 4> Deps;
832254f889dSBrendon Cahoon     for (SUnit::pred_iterator P = I.Preds.begin(), E = I.Preds.end(); P != E;
833254f889dSBrendon Cahoon          ++P)
834254f889dSBrendon Cahoon       if (P->getSUnit() == DefSU)
835254f889dSBrendon Cahoon         Deps.push_back(*P);
836254f889dSBrendon Cahoon     for (int i = 0, e = Deps.size(); i != e; i++) {
837254f889dSBrendon Cahoon       Topo.RemovePred(&I, Deps[i].getSUnit());
838254f889dSBrendon Cahoon       I.removePred(Deps[i]);
839254f889dSBrendon Cahoon     }
840254f889dSBrendon Cahoon     // Remove the chain dependence between the instructions.
841254f889dSBrendon Cahoon     Deps.clear();
842254f889dSBrendon Cahoon     for (auto &P : LastSU->Preds)
843254f889dSBrendon Cahoon       if (P.getSUnit() == &I && P.getKind() == SDep::Order)
844254f889dSBrendon Cahoon         Deps.push_back(P);
845254f889dSBrendon Cahoon     for (int i = 0, e = Deps.size(); i != e; i++) {
846254f889dSBrendon Cahoon       Topo.RemovePred(LastSU, Deps[i].getSUnit());
847254f889dSBrendon Cahoon       LastSU->removePred(Deps[i]);
848254f889dSBrendon Cahoon     }
849254f889dSBrendon Cahoon 
850254f889dSBrendon Cahoon     // Add a dependence between the new instruction and the instruction
851254f889dSBrendon Cahoon     // that defines the new base.
852254f889dSBrendon Cahoon     SDep Dep(&I, SDep::Anti, NewBase);
8538916e438SSumanth Gundapaneni     Topo.AddPred(LastSU, &I);
854254f889dSBrendon Cahoon     LastSU->addPred(Dep);
855254f889dSBrendon Cahoon 
856254f889dSBrendon Cahoon     // Remember the base and offset information so that we can update the
857254f889dSBrendon Cahoon     // instruction during code generation.
858254f889dSBrendon Cahoon     InstrChanges[&I] = std::make_pair(NewBase, NewOffset);
859254f889dSBrendon Cahoon   }
860254f889dSBrendon Cahoon }
861254f889dSBrendon Cahoon 
862254f889dSBrendon Cahoon namespace {
863cdc71612SEugene Zelenko 
864254f889dSBrendon Cahoon // FuncUnitSorter - Comparison operator used to sort instructions by
865254f889dSBrendon Cahoon // the number of functional unit choices.
866254f889dSBrendon Cahoon struct FuncUnitSorter {
867254f889dSBrendon Cahoon   const InstrItineraryData *InstrItins;
868f6cb3bcbSJinsong Ji   const MCSubtargetInfo *STI;
869254f889dSBrendon Cahoon   DenseMap<unsigned, unsigned> Resources;
870254f889dSBrendon Cahoon 
871f6cb3bcbSJinsong Ji   FuncUnitSorter(const TargetSubtargetInfo &TSI)
872f6cb3bcbSJinsong Ji       : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
87332a40564SEugene Zelenko 
874254f889dSBrendon Cahoon   // Compute the number of functional unit alternatives needed
875254f889dSBrendon Cahoon   // at each stage, and take the minimum value. We prioritize the
876254f889dSBrendon Cahoon   // instructions by the least number of choices first.
877254f889dSBrendon Cahoon   unsigned minFuncUnits(const MachineInstr *Inst, unsigned &F) const {
878f6cb3bcbSJinsong Ji     unsigned SchedClass = Inst->getDesc().getSchedClass();
879254f889dSBrendon Cahoon     unsigned min = UINT_MAX;
880f6cb3bcbSJinsong Ji     if (InstrItins && !InstrItins->isEmpty()) {
881f6cb3bcbSJinsong Ji       for (const InstrStage &IS :
882f6cb3bcbSJinsong Ji            make_range(InstrItins->beginStage(SchedClass),
883f6cb3bcbSJinsong Ji                       InstrItins->endStage(SchedClass))) {
884f6cb3bcbSJinsong Ji         unsigned funcUnits = IS.getUnits();
885254f889dSBrendon Cahoon         unsigned numAlternatives = countPopulation(funcUnits);
886254f889dSBrendon Cahoon         if (numAlternatives < min) {
887254f889dSBrendon Cahoon           min = numAlternatives;
888254f889dSBrendon Cahoon           F = funcUnits;
889254f889dSBrendon Cahoon         }
890254f889dSBrendon Cahoon       }
891254f889dSBrendon Cahoon       return min;
892254f889dSBrendon Cahoon     }
893f6cb3bcbSJinsong Ji     if (STI && STI->getSchedModel().hasInstrSchedModel()) {
894f6cb3bcbSJinsong Ji       const MCSchedClassDesc *SCDesc =
895f6cb3bcbSJinsong Ji           STI->getSchedModel().getSchedClassDesc(SchedClass);
896f6cb3bcbSJinsong Ji       if (!SCDesc->isValid())
897f6cb3bcbSJinsong Ji         // No valid Schedule Class Desc for schedClass, should be
898f6cb3bcbSJinsong Ji         // Pseudo/PostRAPseudo
899f6cb3bcbSJinsong Ji         return min;
900f6cb3bcbSJinsong Ji 
901f6cb3bcbSJinsong Ji       for (const MCWriteProcResEntry &PRE :
902f6cb3bcbSJinsong Ji            make_range(STI->getWriteProcResBegin(SCDesc),
903f6cb3bcbSJinsong Ji                       STI->getWriteProcResEnd(SCDesc))) {
904f6cb3bcbSJinsong Ji         if (!PRE.Cycles)
905f6cb3bcbSJinsong Ji           continue;
906f6cb3bcbSJinsong Ji         const MCProcResourceDesc *ProcResource =
907f6cb3bcbSJinsong Ji             STI->getSchedModel().getProcResource(PRE.ProcResourceIdx);
908f6cb3bcbSJinsong Ji         unsigned NumUnits = ProcResource->NumUnits;
909f6cb3bcbSJinsong Ji         if (NumUnits < min) {
910f6cb3bcbSJinsong Ji           min = NumUnits;
911f6cb3bcbSJinsong Ji           F = PRE.ProcResourceIdx;
912f6cb3bcbSJinsong Ji         }
913f6cb3bcbSJinsong Ji       }
914f6cb3bcbSJinsong Ji       return min;
915f6cb3bcbSJinsong Ji     }
916f6cb3bcbSJinsong Ji     llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
917f6cb3bcbSJinsong Ji   }
918254f889dSBrendon Cahoon 
919254f889dSBrendon Cahoon   // Compute the critical resources needed by the instruction. This
920254f889dSBrendon Cahoon   // function records the functional units needed by instructions that
921254f889dSBrendon Cahoon   // must use only one functional unit. We use this as a tie breaker
922254f889dSBrendon Cahoon   // for computing the resource MII. The instrutions that require
923254f889dSBrendon Cahoon   // the same, highly used, functional unit have high priority.
924254f889dSBrendon Cahoon   void calcCriticalResources(MachineInstr &MI) {
925254f889dSBrendon Cahoon     unsigned SchedClass = MI.getDesc().getSchedClass();
926f6cb3bcbSJinsong Ji     if (InstrItins && !InstrItins->isEmpty()) {
927f6cb3bcbSJinsong Ji       for (const InstrStage &IS :
928f6cb3bcbSJinsong Ji            make_range(InstrItins->beginStage(SchedClass),
929f6cb3bcbSJinsong Ji                       InstrItins->endStage(SchedClass))) {
930f6cb3bcbSJinsong Ji         unsigned FuncUnits = IS.getUnits();
931254f889dSBrendon Cahoon         if (countPopulation(FuncUnits) == 1)
932254f889dSBrendon Cahoon           Resources[FuncUnits]++;
933254f889dSBrendon Cahoon       }
934f6cb3bcbSJinsong Ji       return;
935f6cb3bcbSJinsong Ji     }
936f6cb3bcbSJinsong Ji     if (STI && STI->getSchedModel().hasInstrSchedModel()) {
937f6cb3bcbSJinsong Ji       const MCSchedClassDesc *SCDesc =
938f6cb3bcbSJinsong Ji           STI->getSchedModel().getSchedClassDesc(SchedClass);
939f6cb3bcbSJinsong Ji       if (!SCDesc->isValid())
940f6cb3bcbSJinsong Ji         // No valid Schedule Class Desc for schedClass, should be
941f6cb3bcbSJinsong Ji         // Pseudo/PostRAPseudo
942f6cb3bcbSJinsong Ji         return;
943f6cb3bcbSJinsong Ji 
944f6cb3bcbSJinsong Ji       for (const MCWriteProcResEntry &PRE :
945f6cb3bcbSJinsong Ji            make_range(STI->getWriteProcResBegin(SCDesc),
946f6cb3bcbSJinsong Ji                       STI->getWriteProcResEnd(SCDesc))) {
947f6cb3bcbSJinsong Ji         if (!PRE.Cycles)
948f6cb3bcbSJinsong Ji           continue;
949f6cb3bcbSJinsong Ji         Resources[PRE.ProcResourceIdx]++;
950f6cb3bcbSJinsong Ji       }
951f6cb3bcbSJinsong Ji       return;
952f6cb3bcbSJinsong Ji     }
953f6cb3bcbSJinsong Ji     llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
954254f889dSBrendon Cahoon   }
955254f889dSBrendon Cahoon 
956254f889dSBrendon Cahoon   /// Return true if IS1 has less priority than IS2.
957254f889dSBrendon Cahoon   bool operator()(const MachineInstr *IS1, const MachineInstr *IS2) const {
958254f889dSBrendon Cahoon     unsigned F1 = 0, F2 = 0;
959254f889dSBrendon Cahoon     unsigned MFUs1 = minFuncUnits(IS1, F1);
960254f889dSBrendon Cahoon     unsigned MFUs2 = minFuncUnits(IS2, F2);
961254f889dSBrendon Cahoon     if (MFUs1 == 1 && MFUs2 == 1)
962254f889dSBrendon Cahoon       return Resources.lookup(F1) < Resources.lookup(F2);
963254f889dSBrendon Cahoon     return MFUs1 > MFUs2;
964254f889dSBrendon Cahoon   }
965254f889dSBrendon Cahoon };
966cdc71612SEugene Zelenko 
967cdc71612SEugene Zelenko } // end anonymous namespace
968254f889dSBrendon Cahoon 
969254f889dSBrendon Cahoon /// Calculate the resource constrained minimum initiation interval for the
970254f889dSBrendon Cahoon /// specified loop. We use the DFA to model the resources needed for
971254f889dSBrendon Cahoon /// each instruction, and we ignore dependences. A different DFA is created
972254f889dSBrendon Cahoon /// for each cycle that is required. When adding a new instruction, we attempt
973254f889dSBrendon Cahoon /// to add it to each existing DFA, until a legal space is found. If the
974254f889dSBrendon Cahoon /// instruction cannot be reserved in an existing DFA, we create a new one.
975254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::calculateResMII() {
976f6cb3bcbSJinsong Ji 
97718e7bf5cSJinsong Ji   LLVM_DEBUG(dbgs() << "calculateResMII:\n");
978f6cb3bcbSJinsong Ji   SmallVector<ResourceManager*, 8> Resources;
979254f889dSBrendon Cahoon   MachineBasicBlock *MBB = Loop.getHeader();
980f6cb3bcbSJinsong Ji   Resources.push_back(new ResourceManager(&MF.getSubtarget()));
981254f889dSBrendon Cahoon 
982254f889dSBrendon Cahoon   // Sort the instructions by the number of available choices for scheduling,
983254f889dSBrendon Cahoon   // least to most. Use the number of critical resources as the tie breaker.
984f6cb3bcbSJinsong Ji   FuncUnitSorter FUS = FuncUnitSorter(MF.getSubtarget());
985254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
986254f889dSBrendon Cahoon                                    E = MBB->getFirstTerminator();
987254f889dSBrendon Cahoon        I != E; ++I)
988254f889dSBrendon Cahoon     FUS.calcCriticalResources(*I);
989254f889dSBrendon Cahoon   PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
990254f889dSBrendon Cahoon       FuncUnitOrder(FUS);
991254f889dSBrendon Cahoon 
992254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator I = MBB->getFirstNonPHI(),
993254f889dSBrendon Cahoon                                    E = MBB->getFirstTerminator();
994254f889dSBrendon Cahoon        I != E; ++I)
995254f889dSBrendon Cahoon     FuncUnitOrder.push(&*I);
996254f889dSBrendon Cahoon 
997254f889dSBrendon Cahoon   while (!FuncUnitOrder.empty()) {
998254f889dSBrendon Cahoon     MachineInstr *MI = FuncUnitOrder.top();
999254f889dSBrendon Cahoon     FuncUnitOrder.pop();
1000254f889dSBrendon Cahoon     if (TII->isZeroCost(MI->getOpcode()))
1001254f889dSBrendon Cahoon       continue;
1002254f889dSBrendon Cahoon     // Attempt to reserve the instruction in an existing DFA. At least one
1003254f889dSBrendon Cahoon     // DFA is needed for each cycle.
1004254f889dSBrendon Cahoon     unsigned NumCycles = getSUnit(MI)->Latency;
1005254f889dSBrendon Cahoon     unsigned ReservedCycles = 0;
1006f6cb3bcbSJinsong Ji     SmallVectorImpl<ResourceManager *>::iterator RI = Resources.begin();
1007f6cb3bcbSJinsong Ji     SmallVectorImpl<ResourceManager *>::iterator RE = Resources.end();
100818e7bf5cSJinsong Ji     LLVM_DEBUG({
100918e7bf5cSJinsong Ji       dbgs() << "Trying to reserve resource for " << NumCycles
101018e7bf5cSJinsong Ji              << " cycles for \n";
101118e7bf5cSJinsong Ji       MI->dump();
101218e7bf5cSJinsong Ji     });
1013254f889dSBrendon Cahoon     for (unsigned C = 0; C < NumCycles; ++C)
1014254f889dSBrendon Cahoon       while (RI != RE) {
1015*fee855b5SJinsong Ji         if ((*RI)->canReserveResources(*MI)) {
1016*fee855b5SJinsong Ji           (*RI)->reserveResources(*MI);
1017254f889dSBrendon Cahoon           ++ReservedCycles;
1018254f889dSBrendon Cahoon           break;
1019254f889dSBrendon Cahoon         }
1020*fee855b5SJinsong Ji         RI++;
1021254f889dSBrendon Cahoon       }
102218e7bf5cSJinsong Ji     LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
102318e7bf5cSJinsong Ji                       << ", NumCycles:" << NumCycles << "\n");
1024254f889dSBrendon Cahoon     // Add new DFAs, if needed, to reserve resources.
1025254f889dSBrendon Cahoon     for (unsigned C = ReservedCycles; C < NumCycles; ++C) {
1026ba43840bSJinsong Ji       LLVM_DEBUG(if (SwpDebugResource) dbgs()
1027ba43840bSJinsong Ji                  << "NewResource created to reserve resources"
102818e7bf5cSJinsong Ji                  << "\n");
1029f6cb3bcbSJinsong Ji       ResourceManager *NewResource = new ResourceManager(&MF.getSubtarget());
1030254f889dSBrendon Cahoon       assert(NewResource->canReserveResources(*MI) && "Reserve error.");
1031254f889dSBrendon Cahoon       NewResource->reserveResources(*MI);
1032254f889dSBrendon Cahoon       Resources.push_back(NewResource);
1033254f889dSBrendon Cahoon     }
1034254f889dSBrendon Cahoon   }
1035254f889dSBrendon Cahoon   int Resmii = Resources.size();
103618e7bf5cSJinsong Ji   LLVM_DEBUG(dbgs() << "Retrun Res MII:" << Resmii << "\n");
1037254f889dSBrendon Cahoon   // Delete the memory for each of the DFAs that were created earlier.
1038f6cb3bcbSJinsong Ji   for (ResourceManager *RI : Resources) {
1039f6cb3bcbSJinsong Ji     ResourceManager *D = RI;
1040254f889dSBrendon Cahoon     delete D;
1041254f889dSBrendon Cahoon   }
1042254f889dSBrendon Cahoon   Resources.clear();
1043254f889dSBrendon Cahoon   return Resmii;
1044254f889dSBrendon Cahoon }
1045254f889dSBrendon Cahoon 
1046254f889dSBrendon Cahoon /// Calculate the recurrence-constrainted minimum initiation interval.
1047254f889dSBrendon Cahoon /// Iterate over each circuit.  Compute the delay(c) and distance(c)
1048254f889dSBrendon Cahoon /// for each circuit. The II needs to satisfy the inequality
1049254f889dSBrendon Cahoon /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1050c73b6d6bSHiroshi Inoue /// II that satisfies the inequality, and the RecMII is the maximum
1051254f889dSBrendon Cahoon /// of those values.
1052254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1053254f889dSBrendon Cahoon   unsigned RecMII = 0;
1054254f889dSBrendon Cahoon 
1055254f889dSBrendon Cahoon   for (NodeSet &Nodes : NodeSets) {
105632a40564SEugene Zelenko     if (Nodes.empty())
1057254f889dSBrendon Cahoon       continue;
1058254f889dSBrendon Cahoon 
1059a2122044SKrzysztof Parzyszek     unsigned Delay = Nodes.getLatency();
1060254f889dSBrendon Cahoon     unsigned Distance = 1;
1061254f889dSBrendon Cahoon 
1062254f889dSBrendon Cahoon     // ii = ceil(delay / distance)
1063254f889dSBrendon Cahoon     unsigned CurMII = (Delay + Distance - 1) / Distance;
1064254f889dSBrendon Cahoon     Nodes.setRecMII(CurMII);
1065254f889dSBrendon Cahoon     if (CurMII > RecMII)
1066254f889dSBrendon Cahoon       RecMII = CurMII;
1067254f889dSBrendon Cahoon   }
1068254f889dSBrendon Cahoon 
1069254f889dSBrendon Cahoon   return RecMII;
1070254f889dSBrendon Cahoon }
1071254f889dSBrendon Cahoon 
1072254f889dSBrendon Cahoon /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1073254f889dSBrendon Cahoon /// but we do this to find the circuits, and then change them back.
1074254f889dSBrendon Cahoon static void swapAntiDependences(std::vector<SUnit> &SUnits) {
1075254f889dSBrendon Cahoon   SmallVector<std::pair<SUnit *, SDep>, 8> DepsAdded;
1076254f889dSBrendon Cahoon   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1077254f889dSBrendon Cahoon     SUnit *SU = &SUnits[i];
1078254f889dSBrendon Cahoon     for (SUnit::pred_iterator IP = SU->Preds.begin(), EP = SU->Preds.end();
1079254f889dSBrendon Cahoon          IP != EP; ++IP) {
1080254f889dSBrendon Cahoon       if (IP->getKind() != SDep::Anti)
1081254f889dSBrendon Cahoon         continue;
1082254f889dSBrendon Cahoon       DepsAdded.push_back(std::make_pair(SU, *IP));
1083254f889dSBrendon Cahoon     }
1084254f889dSBrendon Cahoon   }
1085254f889dSBrendon Cahoon   for (SmallVector<std::pair<SUnit *, SDep>, 8>::iterator I = DepsAdded.begin(),
1086254f889dSBrendon Cahoon                                                           E = DepsAdded.end();
1087254f889dSBrendon Cahoon        I != E; ++I) {
1088254f889dSBrendon Cahoon     // Remove this anti dependency and add one in the reverse direction.
1089254f889dSBrendon Cahoon     SUnit *SU = I->first;
1090254f889dSBrendon Cahoon     SDep &D = I->second;
1091254f889dSBrendon Cahoon     SUnit *TargetSU = D.getSUnit();
1092254f889dSBrendon Cahoon     unsigned Reg = D.getReg();
1093254f889dSBrendon Cahoon     unsigned Lat = D.getLatency();
1094254f889dSBrendon Cahoon     SU->removePred(D);
1095254f889dSBrendon Cahoon     SDep Dep(SU, SDep::Anti, Reg);
1096254f889dSBrendon Cahoon     Dep.setLatency(Lat);
1097254f889dSBrendon Cahoon     TargetSU->addPred(Dep);
1098254f889dSBrendon Cahoon   }
1099254f889dSBrendon Cahoon }
1100254f889dSBrendon Cahoon 
1101254f889dSBrendon Cahoon /// Create the adjacency structure of the nodes in the graph.
1102254f889dSBrendon Cahoon void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1103254f889dSBrendon Cahoon     SwingSchedulerDAG *DAG) {
1104254f889dSBrendon Cahoon   BitVector Added(SUnits.size());
11058e1363dfSKrzysztof Parzyszek   DenseMap<int, int> OutputDeps;
1106254f889dSBrendon Cahoon   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1107254f889dSBrendon Cahoon     Added.reset();
1108254f889dSBrendon Cahoon     // Add any successor to the adjacency matrix and exclude duplicates.
1109254f889dSBrendon Cahoon     for (auto &SI : SUnits[i].Succs) {
11108e1363dfSKrzysztof Parzyszek       // Only create a back-edge on the first and last nodes of a dependence
11118e1363dfSKrzysztof Parzyszek       // chain. This records any chains and adds them later.
11128e1363dfSKrzysztof Parzyszek       if (SI.getKind() == SDep::Output) {
11138e1363dfSKrzysztof Parzyszek         int N = SI.getSUnit()->NodeNum;
11148e1363dfSKrzysztof Parzyszek         int BackEdge = i;
11158e1363dfSKrzysztof Parzyszek         auto Dep = OutputDeps.find(BackEdge);
11168e1363dfSKrzysztof Parzyszek         if (Dep != OutputDeps.end()) {
11178e1363dfSKrzysztof Parzyszek           BackEdge = Dep->second;
11188e1363dfSKrzysztof Parzyszek           OutputDeps.erase(Dep);
11198e1363dfSKrzysztof Parzyszek         }
11208e1363dfSKrzysztof Parzyszek         OutputDeps[N] = BackEdge;
11218e1363dfSKrzysztof Parzyszek       }
1122ada0f511SSumanth Gundapaneni       // Do not process a boundary node, an artificial node.
1123ada0f511SSumanth Gundapaneni       // A back-edge is processed only if it goes to a Phi.
1124ada0f511SSumanth Gundapaneni       if (SI.getSUnit()->isBoundaryNode() || SI.isArtificial() ||
1125254f889dSBrendon Cahoon           (SI.getKind() == SDep::Anti && !SI.getSUnit()->getInstr()->isPHI()))
1126254f889dSBrendon Cahoon         continue;
1127254f889dSBrendon Cahoon       int N = SI.getSUnit()->NodeNum;
1128254f889dSBrendon Cahoon       if (!Added.test(N)) {
1129254f889dSBrendon Cahoon         AdjK[i].push_back(N);
1130254f889dSBrendon Cahoon         Added.set(N);
1131254f889dSBrendon Cahoon       }
1132254f889dSBrendon Cahoon     }
1133254f889dSBrendon Cahoon     // A chain edge between a store and a load is treated as a back-edge in the
1134254f889dSBrendon Cahoon     // adjacency matrix.
1135254f889dSBrendon Cahoon     for (auto &PI : SUnits[i].Preds) {
1136254f889dSBrendon Cahoon       if (!SUnits[i].getInstr()->mayStore() ||
11378e1363dfSKrzysztof Parzyszek           !DAG->isLoopCarriedDep(&SUnits[i], PI, false))
1138254f889dSBrendon Cahoon         continue;
1139254f889dSBrendon Cahoon       if (PI.getKind() == SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1140254f889dSBrendon Cahoon         int N = PI.getSUnit()->NodeNum;
1141254f889dSBrendon Cahoon         if (!Added.test(N)) {
1142254f889dSBrendon Cahoon           AdjK[i].push_back(N);
1143254f889dSBrendon Cahoon           Added.set(N);
1144254f889dSBrendon Cahoon         }
1145254f889dSBrendon Cahoon       }
1146254f889dSBrendon Cahoon     }
1147254f889dSBrendon Cahoon   }
1148dad8c6a1SHiroshi Inoue   // Add back-edges in the adjacency matrix for the output dependences.
11498e1363dfSKrzysztof Parzyszek   for (auto &OD : OutputDeps)
11508e1363dfSKrzysztof Parzyszek     if (!Added.test(OD.second)) {
11518e1363dfSKrzysztof Parzyszek       AdjK[OD.first].push_back(OD.second);
11528e1363dfSKrzysztof Parzyszek       Added.set(OD.second);
11538e1363dfSKrzysztof Parzyszek     }
1154254f889dSBrendon Cahoon }
1155254f889dSBrendon Cahoon 
1156254f889dSBrendon Cahoon /// Identify an elementary circuit in the dependence graph starting at the
1157254f889dSBrendon Cahoon /// specified node.
1158254f889dSBrendon Cahoon bool SwingSchedulerDAG::Circuits::circuit(int V, int S, NodeSetType &NodeSets,
1159254f889dSBrendon Cahoon                                           bool HasBackedge) {
1160254f889dSBrendon Cahoon   SUnit *SV = &SUnits[V];
1161254f889dSBrendon Cahoon   bool F = false;
1162254f889dSBrendon Cahoon   Stack.insert(SV);
1163254f889dSBrendon Cahoon   Blocked.set(V);
1164254f889dSBrendon Cahoon 
1165254f889dSBrendon Cahoon   for (auto W : AdjK[V]) {
1166254f889dSBrendon Cahoon     if (NumPaths > MaxPaths)
1167254f889dSBrendon Cahoon       break;
1168254f889dSBrendon Cahoon     if (W < S)
1169254f889dSBrendon Cahoon       continue;
1170254f889dSBrendon Cahoon     if (W == S) {
1171254f889dSBrendon Cahoon       if (!HasBackedge)
1172254f889dSBrendon Cahoon         NodeSets.push_back(NodeSet(Stack.begin(), Stack.end()));
1173254f889dSBrendon Cahoon       F = true;
1174254f889dSBrendon Cahoon       ++NumPaths;
1175254f889dSBrendon Cahoon       break;
1176254f889dSBrendon Cahoon     } else if (!Blocked.test(W)) {
117777418a37SSumanth Gundapaneni       if (circuit(W, S, NodeSets,
117877418a37SSumanth Gundapaneni                   Node2Idx->at(W) < Node2Idx->at(V) ? true : HasBackedge))
1179254f889dSBrendon Cahoon         F = true;
1180254f889dSBrendon Cahoon     }
1181254f889dSBrendon Cahoon   }
1182254f889dSBrendon Cahoon 
1183254f889dSBrendon Cahoon   if (F)
1184254f889dSBrendon Cahoon     unblock(V);
1185254f889dSBrendon Cahoon   else {
1186254f889dSBrendon Cahoon     for (auto W : AdjK[V]) {
1187254f889dSBrendon Cahoon       if (W < S)
1188254f889dSBrendon Cahoon         continue;
1189254f889dSBrendon Cahoon       if (B[W].count(SV) == 0)
1190254f889dSBrendon Cahoon         B[W].insert(SV);
1191254f889dSBrendon Cahoon     }
1192254f889dSBrendon Cahoon   }
1193254f889dSBrendon Cahoon   Stack.pop_back();
1194254f889dSBrendon Cahoon   return F;
1195254f889dSBrendon Cahoon }
1196254f889dSBrendon Cahoon 
1197254f889dSBrendon Cahoon /// Unblock a node in the circuit finding algorithm.
1198254f889dSBrendon Cahoon void SwingSchedulerDAG::Circuits::unblock(int U) {
1199254f889dSBrendon Cahoon   Blocked.reset(U);
1200254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 4> &BU = B[U];
1201254f889dSBrendon Cahoon   while (!BU.empty()) {
1202254f889dSBrendon Cahoon     SmallPtrSet<SUnit *, 4>::iterator SI = BU.begin();
1203254f889dSBrendon Cahoon     assert(SI != BU.end() && "Invalid B set.");
1204254f889dSBrendon Cahoon     SUnit *W = *SI;
1205254f889dSBrendon Cahoon     BU.erase(W);
1206254f889dSBrendon Cahoon     if (Blocked.test(W->NodeNum))
1207254f889dSBrendon Cahoon       unblock(W->NodeNum);
1208254f889dSBrendon Cahoon   }
1209254f889dSBrendon Cahoon }
1210254f889dSBrendon Cahoon 
1211254f889dSBrendon Cahoon /// Identify all the elementary circuits in the dependence graph using
1212254f889dSBrendon Cahoon /// Johnson's circuit algorithm.
1213254f889dSBrendon Cahoon void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1214254f889dSBrendon Cahoon   // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1215254f889dSBrendon Cahoon   // but we do this to find the circuits, and then change them back.
1216254f889dSBrendon Cahoon   swapAntiDependences(SUnits);
1217254f889dSBrendon Cahoon 
121877418a37SSumanth Gundapaneni   Circuits Cir(SUnits, Topo);
1219254f889dSBrendon Cahoon   // Create the adjacency structure.
1220254f889dSBrendon Cahoon   Cir.createAdjacencyStructure(this);
1221254f889dSBrendon Cahoon   for (int i = 0, e = SUnits.size(); i != e; ++i) {
1222254f889dSBrendon Cahoon     Cir.reset();
1223254f889dSBrendon Cahoon     Cir.circuit(i, i, NodeSets);
1224254f889dSBrendon Cahoon   }
1225254f889dSBrendon Cahoon 
1226254f889dSBrendon Cahoon   // Change the dependences back so that we've created a DAG again.
1227254f889dSBrendon Cahoon   swapAntiDependences(SUnits);
1228254f889dSBrendon Cahoon }
1229254f889dSBrendon Cahoon 
123062ac69d4SSumanth Gundapaneni // Create artificial dependencies between the source of COPY/REG_SEQUENCE that
123162ac69d4SSumanth Gundapaneni // is loop-carried to the USE in next iteration. This will help pipeliner avoid
123262ac69d4SSumanth Gundapaneni // additional copies that are needed across iterations. An artificial dependence
123362ac69d4SSumanth Gundapaneni // edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
123462ac69d4SSumanth Gundapaneni 
123562ac69d4SSumanth Gundapaneni // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
123662ac69d4SSumanth Gundapaneni // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
123762ac69d4SSumanth Gundapaneni // PHI-------True-Dep------> USEOfPhi
123862ac69d4SSumanth Gundapaneni 
123962ac69d4SSumanth Gundapaneni // The mutation creates
124062ac69d4SSumanth Gundapaneni // USEOfPHI -------Artificial-Dep---> SRCOfCopy
124162ac69d4SSumanth Gundapaneni 
124262ac69d4SSumanth Gundapaneni // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
124362ac69d4SSumanth Gundapaneni // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
124462ac69d4SSumanth Gundapaneni // late  to avoid additional copies across iterations. The possible scheduling
124562ac69d4SSumanth Gundapaneni // order would be
124662ac69d4SSumanth Gundapaneni // USEOfPHI --- SRCOfCopy---  COPY/REG_SEQUENCE.
124762ac69d4SSumanth Gundapaneni 
124862ac69d4SSumanth Gundapaneni void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
124962ac69d4SSumanth Gundapaneni   for (SUnit &SU : DAG->SUnits) {
125062ac69d4SSumanth Gundapaneni     // Find the COPY/REG_SEQUENCE instruction.
125162ac69d4SSumanth Gundapaneni     if (!SU.getInstr()->isCopy() && !SU.getInstr()->isRegSequence())
125262ac69d4SSumanth Gundapaneni       continue;
125362ac69d4SSumanth Gundapaneni 
125462ac69d4SSumanth Gundapaneni     // Record the loop carried PHIs.
125562ac69d4SSumanth Gundapaneni     SmallVector<SUnit *, 4> PHISUs;
125662ac69d4SSumanth Gundapaneni     // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
125762ac69d4SSumanth Gundapaneni     SmallVector<SUnit *, 4> SrcSUs;
125862ac69d4SSumanth Gundapaneni 
125962ac69d4SSumanth Gundapaneni     for (auto &Dep : SU.Preds) {
126062ac69d4SSumanth Gundapaneni       SUnit *TmpSU = Dep.getSUnit();
126162ac69d4SSumanth Gundapaneni       MachineInstr *TmpMI = TmpSU->getInstr();
126262ac69d4SSumanth Gundapaneni       SDep::Kind DepKind = Dep.getKind();
126362ac69d4SSumanth Gundapaneni       // Save the loop carried PHI.
126462ac69d4SSumanth Gundapaneni       if (DepKind == SDep::Anti && TmpMI->isPHI())
126562ac69d4SSumanth Gundapaneni         PHISUs.push_back(TmpSU);
126662ac69d4SSumanth Gundapaneni       // Save the source of COPY/REG_SEQUENCE.
126762ac69d4SSumanth Gundapaneni       // If the source has no pre-decessors, we will end up creating cycles.
126862ac69d4SSumanth Gundapaneni       else if (DepKind == SDep::Data && !TmpMI->isPHI() && TmpSU->NumPreds > 0)
126962ac69d4SSumanth Gundapaneni         SrcSUs.push_back(TmpSU);
127062ac69d4SSumanth Gundapaneni     }
127162ac69d4SSumanth Gundapaneni 
127262ac69d4SSumanth Gundapaneni     if (PHISUs.size() == 0 || SrcSUs.size() == 0)
127362ac69d4SSumanth Gundapaneni       continue;
127462ac69d4SSumanth Gundapaneni 
127562ac69d4SSumanth Gundapaneni     // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
127662ac69d4SSumanth Gundapaneni     // SUnit to the container.
127762ac69d4SSumanth Gundapaneni     SmallVector<SUnit *, 8> UseSUs;
127862ac69d4SSumanth Gundapaneni     for (auto I = PHISUs.begin(); I != PHISUs.end(); ++I) {
127962ac69d4SSumanth Gundapaneni       for (auto &Dep : (*I)->Succs) {
128062ac69d4SSumanth Gundapaneni         if (Dep.getKind() != SDep::Data)
128162ac69d4SSumanth Gundapaneni           continue;
128262ac69d4SSumanth Gundapaneni 
128362ac69d4SSumanth Gundapaneni         SUnit *TmpSU = Dep.getSUnit();
128462ac69d4SSumanth Gundapaneni         MachineInstr *TmpMI = TmpSU->getInstr();
128562ac69d4SSumanth Gundapaneni         if (TmpMI->isPHI() || TmpMI->isRegSequence()) {
128662ac69d4SSumanth Gundapaneni           PHISUs.push_back(TmpSU);
128762ac69d4SSumanth Gundapaneni           continue;
128862ac69d4SSumanth Gundapaneni         }
128962ac69d4SSumanth Gundapaneni         UseSUs.push_back(TmpSU);
129062ac69d4SSumanth Gundapaneni       }
129162ac69d4SSumanth Gundapaneni     }
129262ac69d4SSumanth Gundapaneni 
129362ac69d4SSumanth Gundapaneni     if (UseSUs.size() == 0)
129462ac69d4SSumanth Gundapaneni       continue;
129562ac69d4SSumanth Gundapaneni 
129662ac69d4SSumanth Gundapaneni     SwingSchedulerDAG *SDAG = cast<SwingSchedulerDAG>(DAG);
129762ac69d4SSumanth Gundapaneni     // Add the artificial dependencies if it does not form a cycle.
129862ac69d4SSumanth Gundapaneni     for (auto I : UseSUs) {
129962ac69d4SSumanth Gundapaneni       for (auto Src : SrcSUs) {
130062ac69d4SSumanth Gundapaneni         if (!SDAG->Topo.IsReachable(I, Src) && Src != I) {
130162ac69d4SSumanth Gundapaneni           Src->addPred(SDep(I, SDep::Artificial));
130262ac69d4SSumanth Gundapaneni           SDAG->Topo.AddPred(Src, I);
130362ac69d4SSumanth Gundapaneni         }
130462ac69d4SSumanth Gundapaneni       }
130562ac69d4SSumanth Gundapaneni     }
130662ac69d4SSumanth Gundapaneni   }
130762ac69d4SSumanth Gundapaneni }
130862ac69d4SSumanth Gundapaneni 
1309254f889dSBrendon Cahoon /// Return true for DAG nodes that we ignore when computing the cost functions.
1310c73b6d6bSHiroshi Inoue /// We ignore the back-edge recurrence in order to avoid unbounded recursion
1311254f889dSBrendon Cahoon /// in the calculation of the ASAP, ALAP, etc functions.
1312254f889dSBrendon Cahoon static bool ignoreDependence(const SDep &D, bool isPred) {
1313254f889dSBrendon Cahoon   if (D.isArtificial())
1314254f889dSBrendon Cahoon     return true;
1315254f889dSBrendon Cahoon   return D.getKind() == SDep::Anti && isPred;
1316254f889dSBrendon Cahoon }
1317254f889dSBrendon Cahoon 
1318254f889dSBrendon Cahoon /// Compute several functions need to order the nodes for scheduling.
1319254f889dSBrendon Cahoon ///  ASAP - Earliest time to schedule a node.
1320254f889dSBrendon Cahoon ///  ALAP - Latest time to schedule a node.
1321254f889dSBrendon Cahoon ///  MOV - Mobility function, difference between ALAP and ASAP.
1322254f889dSBrendon Cahoon ///  D - Depth of each node.
1323254f889dSBrendon Cahoon ///  H - Height of each node.
1324254f889dSBrendon Cahoon void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
1325254f889dSBrendon Cahoon   ScheduleInfo.resize(SUnits.size());
1326254f889dSBrendon Cahoon 
1327d34e60caSNicola Zaghen   LLVM_DEBUG({
1328254f889dSBrendon Cahoon     for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1329254f889dSBrendon Cahoon                                                     E = Topo.end();
1330254f889dSBrendon Cahoon          I != E; ++I) {
1331726e12cfSMatthias Braun       const SUnit &SU = SUnits[*I];
1332726e12cfSMatthias Braun       dumpNode(SU);
1333254f889dSBrendon Cahoon     }
1334254f889dSBrendon Cahoon   });
1335254f889dSBrendon Cahoon 
1336254f889dSBrendon Cahoon   int maxASAP = 0;
13374b8bcf00SRoorda, Jan-Willem   // Compute ASAP and ZeroLatencyDepth.
1338254f889dSBrendon Cahoon   for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
1339254f889dSBrendon Cahoon                                                   E = Topo.end();
1340254f889dSBrendon Cahoon        I != E; ++I) {
1341254f889dSBrendon Cahoon     int asap = 0;
13424b8bcf00SRoorda, Jan-Willem     int zeroLatencyDepth = 0;
1343254f889dSBrendon Cahoon     SUnit *SU = &SUnits[*I];
1344254f889dSBrendon Cahoon     for (SUnit::const_pred_iterator IP = SU->Preds.begin(),
1345254f889dSBrendon Cahoon                                     EP = SU->Preds.end();
1346254f889dSBrendon Cahoon          IP != EP; ++IP) {
13474b8bcf00SRoorda, Jan-Willem       SUnit *pred = IP->getSUnit();
1348c715a5d2SKrzysztof Parzyszek       if (IP->getLatency() == 0)
13494b8bcf00SRoorda, Jan-Willem         zeroLatencyDepth =
13504b8bcf00SRoorda, Jan-Willem             std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
1351254f889dSBrendon Cahoon       if (ignoreDependence(*IP, true))
1352254f889dSBrendon Cahoon         continue;
1353c715a5d2SKrzysztof Parzyszek       asap = std::max(asap, (int)(getASAP(pred) + IP->getLatency() -
1354254f889dSBrendon Cahoon                                   getDistance(pred, SU, *IP) * MII));
1355254f889dSBrendon Cahoon     }
1356254f889dSBrendon Cahoon     maxASAP = std::max(maxASAP, asap);
1357254f889dSBrendon Cahoon     ScheduleInfo[*I].ASAP = asap;
13584b8bcf00SRoorda, Jan-Willem     ScheduleInfo[*I].ZeroLatencyDepth = zeroLatencyDepth;
1359254f889dSBrendon Cahoon   }
1360254f889dSBrendon Cahoon 
13614b8bcf00SRoorda, Jan-Willem   // Compute ALAP, ZeroLatencyHeight, and MOV.
1362254f889dSBrendon Cahoon   for (ScheduleDAGTopologicalSort::const_reverse_iterator I = Topo.rbegin(),
1363254f889dSBrendon Cahoon                                                           E = Topo.rend();
1364254f889dSBrendon Cahoon        I != E; ++I) {
1365254f889dSBrendon Cahoon     int alap = maxASAP;
13664b8bcf00SRoorda, Jan-Willem     int zeroLatencyHeight = 0;
1367254f889dSBrendon Cahoon     SUnit *SU = &SUnits[*I];
1368254f889dSBrendon Cahoon     for (SUnit::const_succ_iterator IS = SU->Succs.begin(),
1369254f889dSBrendon Cahoon                                     ES = SU->Succs.end();
1370254f889dSBrendon Cahoon          IS != ES; ++IS) {
13714b8bcf00SRoorda, Jan-Willem       SUnit *succ = IS->getSUnit();
1372c715a5d2SKrzysztof Parzyszek       if (IS->getLatency() == 0)
13734b8bcf00SRoorda, Jan-Willem         zeroLatencyHeight =
13744b8bcf00SRoorda, Jan-Willem             std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
1375254f889dSBrendon Cahoon       if (ignoreDependence(*IS, true))
1376254f889dSBrendon Cahoon         continue;
1377c715a5d2SKrzysztof Parzyszek       alap = std::min(alap, (int)(getALAP(succ) - IS->getLatency() +
1378254f889dSBrendon Cahoon                                   getDistance(SU, succ, *IS) * MII));
1379254f889dSBrendon Cahoon     }
1380254f889dSBrendon Cahoon 
1381254f889dSBrendon Cahoon     ScheduleInfo[*I].ALAP = alap;
13824b8bcf00SRoorda, Jan-Willem     ScheduleInfo[*I].ZeroLatencyHeight = zeroLatencyHeight;
1383254f889dSBrendon Cahoon   }
1384254f889dSBrendon Cahoon 
1385254f889dSBrendon Cahoon   // After computing the node functions, compute the summary for each node set.
1386254f889dSBrendon Cahoon   for (NodeSet &I : NodeSets)
1387254f889dSBrendon Cahoon     I.computeNodeSetInfo(this);
1388254f889dSBrendon Cahoon 
1389d34e60caSNicola Zaghen   LLVM_DEBUG({
1390254f889dSBrendon Cahoon     for (unsigned i = 0; i < SUnits.size(); i++) {
1391254f889dSBrendon Cahoon       dbgs() << "\tNode " << i << ":\n";
1392254f889dSBrendon Cahoon       dbgs() << "\t   ASAP = " << getASAP(&SUnits[i]) << "\n";
1393254f889dSBrendon Cahoon       dbgs() << "\t   ALAP = " << getALAP(&SUnits[i]) << "\n";
1394254f889dSBrendon Cahoon       dbgs() << "\t   MOV  = " << getMOV(&SUnits[i]) << "\n";
1395254f889dSBrendon Cahoon       dbgs() << "\t   D    = " << getDepth(&SUnits[i]) << "\n";
1396254f889dSBrendon Cahoon       dbgs() << "\t   H    = " << getHeight(&SUnits[i]) << "\n";
13974b8bcf00SRoorda, Jan-Willem       dbgs() << "\t   ZLD  = " << getZeroLatencyDepth(&SUnits[i]) << "\n";
13984b8bcf00SRoorda, Jan-Willem       dbgs() << "\t   ZLH  = " << getZeroLatencyHeight(&SUnits[i]) << "\n";
1399254f889dSBrendon Cahoon     }
1400254f889dSBrendon Cahoon   });
1401254f889dSBrendon Cahoon }
1402254f889dSBrendon Cahoon 
1403254f889dSBrendon Cahoon /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1404254f889dSBrendon Cahoon /// as the predecessors of the elements of NodeOrder that are not also in
1405254f889dSBrendon Cahoon /// NodeOrder.
1406254f889dSBrendon Cahoon static bool pred_L(SetVector<SUnit *> &NodeOrder,
1407254f889dSBrendon Cahoon                    SmallSetVector<SUnit *, 8> &Preds,
1408254f889dSBrendon Cahoon                    const NodeSet *S = nullptr) {
1409254f889dSBrendon Cahoon   Preds.clear();
1410254f889dSBrendon Cahoon   for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1411254f889dSBrendon Cahoon        I != E; ++I) {
1412254f889dSBrendon Cahoon     for (SUnit::pred_iterator PI = (*I)->Preds.begin(), PE = (*I)->Preds.end();
1413254f889dSBrendon Cahoon          PI != PE; ++PI) {
1414254f889dSBrendon Cahoon       if (S && S->count(PI->getSUnit()) == 0)
1415254f889dSBrendon Cahoon         continue;
1416254f889dSBrendon Cahoon       if (ignoreDependence(*PI, true))
1417254f889dSBrendon Cahoon         continue;
1418254f889dSBrendon Cahoon       if (NodeOrder.count(PI->getSUnit()) == 0)
1419254f889dSBrendon Cahoon         Preds.insert(PI->getSUnit());
1420254f889dSBrendon Cahoon     }
1421254f889dSBrendon Cahoon     // Back-edges are predecessors with an anti-dependence.
1422254f889dSBrendon Cahoon     for (SUnit::const_succ_iterator IS = (*I)->Succs.begin(),
1423254f889dSBrendon Cahoon                                     ES = (*I)->Succs.end();
1424254f889dSBrendon Cahoon          IS != ES; ++IS) {
1425254f889dSBrendon Cahoon       if (IS->getKind() != SDep::Anti)
1426254f889dSBrendon Cahoon         continue;
1427254f889dSBrendon Cahoon       if (S && S->count(IS->getSUnit()) == 0)
1428254f889dSBrendon Cahoon         continue;
1429254f889dSBrendon Cahoon       if (NodeOrder.count(IS->getSUnit()) == 0)
1430254f889dSBrendon Cahoon         Preds.insert(IS->getSUnit());
1431254f889dSBrendon Cahoon     }
1432254f889dSBrendon Cahoon   }
143332a40564SEugene Zelenko   return !Preds.empty();
1434254f889dSBrendon Cahoon }
1435254f889dSBrendon Cahoon 
1436254f889dSBrendon Cahoon /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1437254f889dSBrendon Cahoon /// as the successors of the elements of NodeOrder that are not also in
1438254f889dSBrendon Cahoon /// NodeOrder.
1439254f889dSBrendon Cahoon static bool succ_L(SetVector<SUnit *> &NodeOrder,
1440254f889dSBrendon Cahoon                    SmallSetVector<SUnit *, 8> &Succs,
1441254f889dSBrendon Cahoon                    const NodeSet *S = nullptr) {
1442254f889dSBrendon Cahoon   Succs.clear();
1443254f889dSBrendon Cahoon   for (SetVector<SUnit *>::iterator I = NodeOrder.begin(), E = NodeOrder.end();
1444254f889dSBrendon Cahoon        I != E; ++I) {
1445254f889dSBrendon Cahoon     for (SUnit::succ_iterator SI = (*I)->Succs.begin(), SE = (*I)->Succs.end();
1446254f889dSBrendon Cahoon          SI != SE; ++SI) {
1447254f889dSBrendon Cahoon       if (S && S->count(SI->getSUnit()) == 0)
1448254f889dSBrendon Cahoon         continue;
1449254f889dSBrendon Cahoon       if (ignoreDependence(*SI, false))
1450254f889dSBrendon Cahoon         continue;
1451254f889dSBrendon Cahoon       if (NodeOrder.count(SI->getSUnit()) == 0)
1452254f889dSBrendon Cahoon         Succs.insert(SI->getSUnit());
1453254f889dSBrendon Cahoon     }
1454254f889dSBrendon Cahoon     for (SUnit::const_pred_iterator PI = (*I)->Preds.begin(),
1455254f889dSBrendon Cahoon                                     PE = (*I)->Preds.end();
1456254f889dSBrendon Cahoon          PI != PE; ++PI) {
1457254f889dSBrendon Cahoon       if (PI->getKind() != SDep::Anti)
1458254f889dSBrendon Cahoon         continue;
1459254f889dSBrendon Cahoon       if (S && S->count(PI->getSUnit()) == 0)
1460254f889dSBrendon Cahoon         continue;
1461254f889dSBrendon Cahoon       if (NodeOrder.count(PI->getSUnit()) == 0)
1462254f889dSBrendon Cahoon         Succs.insert(PI->getSUnit());
1463254f889dSBrendon Cahoon     }
1464254f889dSBrendon Cahoon   }
146532a40564SEugene Zelenko   return !Succs.empty();
1466254f889dSBrendon Cahoon }
1467254f889dSBrendon Cahoon 
1468254f889dSBrendon Cahoon /// Return true if there is a path from the specified node to any of the nodes
1469254f889dSBrendon Cahoon /// in DestNodes. Keep track and return the nodes in any path.
1470254f889dSBrendon Cahoon static bool computePath(SUnit *Cur, SetVector<SUnit *> &Path,
1471254f889dSBrendon Cahoon                         SetVector<SUnit *> &DestNodes,
1472254f889dSBrendon Cahoon                         SetVector<SUnit *> &Exclude,
1473254f889dSBrendon Cahoon                         SmallPtrSet<SUnit *, 8> &Visited) {
1474254f889dSBrendon Cahoon   if (Cur->isBoundaryNode())
1475254f889dSBrendon Cahoon     return false;
1476254f889dSBrendon Cahoon   if (Exclude.count(Cur) != 0)
1477254f889dSBrendon Cahoon     return false;
1478254f889dSBrendon Cahoon   if (DestNodes.count(Cur) != 0)
1479254f889dSBrendon Cahoon     return true;
1480254f889dSBrendon Cahoon   if (!Visited.insert(Cur).second)
1481254f889dSBrendon Cahoon     return Path.count(Cur) != 0;
1482254f889dSBrendon Cahoon   bool FoundPath = false;
1483254f889dSBrendon Cahoon   for (auto &SI : Cur->Succs)
1484254f889dSBrendon Cahoon     FoundPath |= computePath(SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1485254f889dSBrendon Cahoon   for (auto &PI : Cur->Preds)
1486254f889dSBrendon Cahoon     if (PI.getKind() == SDep::Anti)
1487254f889dSBrendon Cahoon       FoundPath |=
1488254f889dSBrendon Cahoon           computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1489254f889dSBrendon Cahoon   if (FoundPath)
1490254f889dSBrendon Cahoon     Path.insert(Cur);
1491254f889dSBrendon Cahoon   return FoundPath;
1492254f889dSBrendon Cahoon }
1493254f889dSBrendon Cahoon 
1494254f889dSBrendon Cahoon /// Return true if Set1 is a subset of Set2.
1495254f889dSBrendon Cahoon template <class S1Ty, class S2Ty> static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
1496254f889dSBrendon Cahoon   for (typename S1Ty::iterator I = Set1.begin(), E = Set1.end(); I != E; ++I)
1497254f889dSBrendon Cahoon     if (Set2.count(*I) == 0)
1498254f889dSBrendon Cahoon       return false;
1499254f889dSBrendon Cahoon   return true;
1500254f889dSBrendon Cahoon }
1501254f889dSBrendon Cahoon 
1502254f889dSBrendon Cahoon /// Compute the live-out registers for the instructions in a node-set.
1503254f889dSBrendon Cahoon /// The live-out registers are those that are defined in the node-set,
1504254f889dSBrendon Cahoon /// but not used. Except for use operands of Phis.
1505254f889dSBrendon Cahoon static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker,
1506254f889dSBrendon Cahoon                             NodeSet &NS) {
1507254f889dSBrendon Cahoon   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1508254f889dSBrendon Cahoon   MachineRegisterInfo &MRI = MF.getRegInfo();
1509254f889dSBrendon Cahoon   SmallVector<RegisterMaskPair, 8> LiveOutRegs;
1510254f889dSBrendon Cahoon   SmallSet<unsigned, 4> Uses;
1511254f889dSBrendon Cahoon   for (SUnit *SU : NS) {
1512254f889dSBrendon Cahoon     const MachineInstr *MI = SU->getInstr();
1513254f889dSBrendon Cahoon     if (MI->isPHI())
1514254f889dSBrendon Cahoon       continue;
1515fc371558SMatthias Braun     for (const MachineOperand &MO : MI->operands())
1516fc371558SMatthias Braun       if (MO.isReg() && MO.isUse()) {
1517fc371558SMatthias Braun         unsigned Reg = MO.getReg();
1518254f889dSBrendon Cahoon         if (TargetRegisterInfo::isVirtualRegister(Reg))
1519254f889dSBrendon Cahoon           Uses.insert(Reg);
1520254f889dSBrendon Cahoon         else if (MRI.isAllocatable(Reg))
1521254f889dSBrendon Cahoon           for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1522254f889dSBrendon Cahoon             Uses.insert(*Units);
1523254f889dSBrendon Cahoon       }
1524254f889dSBrendon Cahoon   }
1525254f889dSBrendon Cahoon   for (SUnit *SU : NS)
1526fc371558SMatthias Braun     for (const MachineOperand &MO : SU->getInstr()->operands())
1527fc371558SMatthias Braun       if (MO.isReg() && MO.isDef() && !MO.isDead()) {
1528fc371558SMatthias Braun         unsigned Reg = MO.getReg();
1529254f889dSBrendon Cahoon         if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1530254f889dSBrendon Cahoon           if (!Uses.count(Reg))
153191b5cf84SKrzysztof Parzyszek             LiveOutRegs.push_back(RegisterMaskPair(Reg,
153291b5cf84SKrzysztof Parzyszek                                                    LaneBitmask::getNone()));
1533254f889dSBrendon Cahoon         } else if (MRI.isAllocatable(Reg)) {
1534254f889dSBrendon Cahoon           for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
1535254f889dSBrendon Cahoon             if (!Uses.count(*Units))
153691b5cf84SKrzysztof Parzyszek               LiveOutRegs.push_back(RegisterMaskPair(*Units,
153791b5cf84SKrzysztof Parzyszek                                                      LaneBitmask::getNone()));
1538254f889dSBrendon Cahoon         }
1539254f889dSBrendon Cahoon       }
1540254f889dSBrendon Cahoon   RPTracker.addLiveRegs(LiveOutRegs);
1541254f889dSBrendon Cahoon }
1542254f889dSBrendon Cahoon 
1543254f889dSBrendon Cahoon /// A heuristic to filter nodes in recurrent node-sets if the register
1544254f889dSBrendon Cahoon /// pressure of a set is too high.
1545254f889dSBrendon Cahoon void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1546254f889dSBrendon Cahoon   for (auto &NS : NodeSets) {
1547254f889dSBrendon Cahoon     // Skip small node-sets since they won't cause register pressure problems.
1548254f889dSBrendon Cahoon     if (NS.size() <= 2)
1549254f889dSBrendon Cahoon       continue;
1550254f889dSBrendon Cahoon     IntervalPressure RecRegPressure;
1551254f889dSBrendon Cahoon     RegPressureTracker RecRPTracker(RecRegPressure);
1552254f889dSBrendon Cahoon     RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(), false, true);
1553254f889dSBrendon Cahoon     computeLiveOuts(MF, RecRPTracker, NS);
1554254f889dSBrendon Cahoon     RecRPTracker.closeBottom();
1555254f889dSBrendon Cahoon 
1556254f889dSBrendon Cahoon     std::vector<SUnit *> SUnits(NS.begin(), NS.end());
15570cac726aSFangrui Song     llvm::sort(SUnits, [](const SUnit *A, const SUnit *B) {
1558254f889dSBrendon Cahoon       return A->NodeNum > B->NodeNum;
1559254f889dSBrendon Cahoon     });
1560254f889dSBrendon Cahoon 
1561254f889dSBrendon Cahoon     for (auto &SU : SUnits) {
1562254f889dSBrendon Cahoon       // Since we're computing the register pressure for a subset of the
1563254f889dSBrendon Cahoon       // instructions in a block, we need to set the tracker for each
1564254f889dSBrendon Cahoon       // instruction in the node-set. The tracker is set to the instruction
1565254f889dSBrendon Cahoon       // just after the one we're interested in.
1566254f889dSBrendon Cahoon       MachineBasicBlock::const_iterator CurInstI = SU->getInstr();
1567254f889dSBrendon Cahoon       RecRPTracker.setPos(std::next(CurInstI));
1568254f889dSBrendon Cahoon 
1569254f889dSBrendon Cahoon       RegPressureDelta RPDelta;
1570254f889dSBrendon Cahoon       ArrayRef<PressureChange> CriticalPSets;
1571254f889dSBrendon Cahoon       RecRPTracker.getMaxUpwardPressureDelta(SU->getInstr(), nullptr, RPDelta,
1572254f889dSBrendon Cahoon                                              CriticalPSets,
1573254f889dSBrendon Cahoon                                              RecRegPressure.MaxSetPressure);
1574254f889dSBrendon Cahoon       if (RPDelta.Excess.isValid()) {
1575d34e60caSNicola Zaghen         LLVM_DEBUG(
1576d34e60caSNicola Zaghen             dbgs() << "Excess register pressure: SU(" << SU->NodeNum << ") "
1577254f889dSBrendon Cahoon                    << TRI->getRegPressureSetName(RPDelta.Excess.getPSet())
1578254f889dSBrendon Cahoon                    << ":" << RPDelta.Excess.getUnitInc());
1579254f889dSBrendon Cahoon         NS.setExceedPressure(SU);
1580254f889dSBrendon Cahoon         break;
1581254f889dSBrendon Cahoon       }
1582254f889dSBrendon Cahoon       RecRPTracker.recede();
1583254f889dSBrendon Cahoon     }
1584254f889dSBrendon Cahoon   }
1585254f889dSBrendon Cahoon }
1586254f889dSBrendon Cahoon 
1587254f889dSBrendon Cahoon /// A heuristic to colocate node sets that have the same set of
1588254f889dSBrendon Cahoon /// successors.
1589254f889dSBrendon Cahoon void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1590254f889dSBrendon Cahoon   unsigned Colocate = 0;
1591254f889dSBrendon Cahoon   for (int i = 0, e = NodeSets.size(); i < e; ++i) {
1592254f889dSBrendon Cahoon     NodeSet &N1 = NodeSets[i];
1593254f889dSBrendon Cahoon     SmallSetVector<SUnit *, 8> S1;
1594254f889dSBrendon Cahoon     if (N1.empty() || !succ_L(N1, S1))
1595254f889dSBrendon Cahoon       continue;
1596254f889dSBrendon Cahoon     for (int j = i + 1; j < e; ++j) {
1597254f889dSBrendon Cahoon       NodeSet &N2 = NodeSets[j];
1598254f889dSBrendon Cahoon       if (N1.compareRecMII(N2) != 0)
1599254f889dSBrendon Cahoon         continue;
1600254f889dSBrendon Cahoon       SmallSetVector<SUnit *, 8> S2;
1601254f889dSBrendon Cahoon       if (N2.empty() || !succ_L(N2, S2))
1602254f889dSBrendon Cahoon         continue;
1603254f889dSBrendon Cahoon       if (isSubset(S1, S2) && S1.size() == S2.size()) {
1604254f889dSBrendon Cahoon         N1.setColocate(++Colocate);
1605254f889dSBrendon Cahoon         N2.setColocate(Colocate);
1606254f889dSBrendon Cahoon         break;
1607254f889dSBrendon Cahoon       }
1608254f889dSBrendon Cahoon     }
1609254f889dSBrendon Cahoon   }
1610254f889dSBrendon Cahoon }
1611254f889dSBrendon Cahoon 
1612254f889dSBrendon Cahoon /// Check if the existing node-sets are profitable. If not, then ignore the
1613254f889dSBrendon Cahoon /// recurrent node-sets, and attempt to schedule all nodes together. This is
16143ca23341SKrzysztof Parzyszek /// a heuristic. If the MII is large and all the recurrent node-sets are small,
16153ca23341SKrzysztof Parzyszek /// then it's best to try to schedule all instructions together instead of
16163ca23341SKrzysztof Parzyszek /// starting with the recurrent node-sets.
1617254f889dSBrendon Cahoon void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1618254f889dSBrendon Cahoon   // Look for loops with a large MII.
16193ca23341SKrzysztof Parzyszek   if (MII < 17)
1620254f889dSBrendon Cahoon     return;
1621254f889dSBrendon Cahoon   // Check if the node-set contains only a simple add recurrence.
16223ca23341SKrzysztof Parzyszek   for (auto &NS : NodeSets) {
16233ca23341SKrzysztof Parzyszek     if (NS.getRecMII() > 2)
1624254f889dSBrendon Cahoon       return;
16253ca23341SKrzysztof Parzyszek     if (NS.getMaxDepth() > MII)
16263ca23341SKrzysztof Parzyszek       return;
16273ca23341SKrzysztof Parzyszek   }
1628254f889dSBrendon Cahoon   NodeSets.clear();
1629d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
1630254f889dSBrendon Cahoon   return;
1631254f889dSBrendon Cahoon }
1632254f889dSBrendon Cahoon 
1633254f889dSBrendon Cahoon /// Add the nodes that do not belong to a recurrence set into groups
1634254f889dSBrendon Cahoon /// based upon connected componenets.
1635254f889dSBrendon Cahoon void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1636254f889dSBrendon Cahoon   SetVector<SUnit *> NodesAdded;
1637254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 8> Visited;
1638254f889dSBrendon Cahoon   // Add the nodes that are on a path between the previous node sets and
1639254f889dSBrendon Cahoon   // the current node set.
1640254f889dSBrendon Cahoon   for (NodeSet &I : NodeSets) {
1641254f889dSBrendon Cahoon     SmallSetVector<SUnit *, 8> N;
1642254f889dSBrendon Cahoon     // Add the nodes from the current node set to the previous node set.
1643254f889dSBrendon Cahoon     if (succ_L(I, N)) {
1644254f889dSBrendon Cahoon       SetVector<SUnit *> Path;
1645254f889dSBrendon Cahoon       for (SUnit *NI : N) {
1646254f889dSBrendon Cahoon         Visited.clear();
1647254f889dSBrendon Cahoon         computePath(NI, Path, NodesAdded, I, Visited);
1648254f889dSBrendon Cahoon       }
164932a40564SEugene Zelenko       if (!Path.empty())
1650254f889dSBrendon Cahoon         I.insert(Path.begin(), Path.end());
1651254f889dSBrendon Cahoon     }
1652254f889dSBrendon Cahoon     // Add the nodes from the previous node set to the current node set.
1653254f889dSBrendon Cahoon     N.clear();
1654254f889dSBrendon Cahoon     if (succ_L(NodesAdded, N)) {
1655254f889dSBrendon Cahoon       SetVector<SUnit *> Path;
1656254f889dSBrendon Cahoon       for (SUnit *NI : N) {
1657254f889dSBrendon Cahoon         Visited.clear();
1658254f889dSBrendon Cahoon         computePath(NI, Path, I, NodesAdded, Visited);
1659254f889dSBrendon Cahoon       }
166032a40564SEugene Zelenko       if (!Path.empty())
1661254f889dSBrendon Cahoon         I.insert(Path.begin(), Path.end());
1662254f889dSBrendon Cahoon     }
1663254f889dSBrendon Cahoon     NodesAdded.insert(I.begin(), I.end());
1664254f889dSBrendon Cahoon   }
1665254f889dSBrendon Cahoon 
1666254f889dSBrendon Cahoon   // Create a new node set with the connected nodes of any successor of a node
1667254f889dSBrendon Cahoon   // in a recurrent set.
1668254f889dSBrendon Cahoon   NodeSet NewSet;
1669254f889dSBrendon Cahoon   SmallSetVector<SUnit *, 8> N;
1670254f889dSBrendon Cahoon   if (succ_L(NodesAdded, N))
1671254f889dSBrendon Cahoon     for (SUnit *I : N)
1672254f889dSBrendon Cahoon       addConnectedNodes(I, NewSet, NodesAdded);
167332a40564SEugene Zelenko   if (!NewSet.empty())
1674254f889dSBrendon Cahoon     NodeSets.push_back(NewSet);
1675254f889dSBrendon Cahoon 
1676254f889dSBrendon Cahoon   // Create a new node set with the connected nodes of any predecessor of a node
1677254f889dSBrendon Cahoon   // in a recurrent set.
1678254f889dSBrendon Cahoon   NewSet.clear();
1679254f889dSBrendon Cahoon   if (pred_L(NodesAdded, N))
1680254f889dSBrendon Cahoon     for (SUnit *I : N)
1681254f889dSBrendon Cahoon       addConnectedNodes(I, NewSet, NodesAdded);
168232a40564SEugene Zelenko   if (!NewSet.empty())
1683254f889dSBrendon Cahoon     NodeSets.push_back(NewSet);
1684254f889dSBrendon Cahoon 
1685372ffa15SHiroshi Inoue   // Create new nodes sets with the connected nodes any remaining node that
1686254f889dSBrendon Cahoon   // has no predecessor.
1687254f889dSBrendon Cahoon   for (unsigned i = 0; i < SUnits.size(); ++i) {
1688254f889dSBrendon Cahoon     SUnit *SU = &SUnits[i];
1689254f889dSBrendon Cahoon     if (NodesAdded.count(SU) == 0) {
1690254f889dSBrendon Cahoon       NewSet.clear();
1691254f889dSBrendon Cahoon       addConnectedNodes(SU, NewSet, NodesAdded);
169232a40564SEugene Zelenko       if (!NewSet.empty())
1693254f889dSBrendon Cahoon         NodeSets.push_back(NewSet);
1694254f889dSBrendon Cahoon     }
1695254f889dSBrendon Cahoon   }
1696254f889dSBrendon Cahoon }
1697254f889dSBrendon Cahoon 
169831f47b81SAlexey Lapshin /// Add the node to the set, and add all of its connected nodes to the set.
1699254f889dSBrendon Cahoon void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
1700254f889dSBrendon Cahoon                                           SetVector<SUnit *> &NodesAdded) {
1701254f889dSBrendon Cahoon   NewSet.insert(SU);
1702254f889dSBrendon Cahoon   NodesAdded.insert(SU);
1703254f889dSBrendon Cahoon   for (auto &SI : SU->Succs) {
1704254f889dSBrendon Cahoon     SUnit *Successor = SI.getSUnit();
1705254f889dSBrendon Cahoon     if (!SI.isArtificial() && NodesAdded.count(Successor) == 0)
1706254f889dSBrendon Cahoon       addConnectedNodes(Successor, NewSet, NodesAdded);
1707254f889dSBrendon Cahoon   }
1708254f889dSBrendon Cahoon   for (auto &PI : SU->Preds) {
1709254f889dSBrendon Cahoon     SUnit *Predecessor = PI.getSUnit();
1710254f889dSBrendon Cahoon     if (!PI.isArtificial() && NodesAdded.count(Predecessor) == 0)
1711254f889dSBrendon Cahoon       addConnectedNodes(Predecessor, NewSet, NodesAdded);
1712254f889dSBrendon Cahoon   }
1713254f889dSBrendon Cahoon }
1714254f889dSBrendon Cahoon 
1715254f889dSBrendon Cahoon /// Return true if Set1 contains elements in Set2. The elements in common
1716254f889dSBrendon Cahoon /// are returned in a different container.
1717254f889dSBrendon Cahoon static bool isIntersect(SmallSetVector<SUnit *, 8> &Set1, const NodeSet &Set2,
1718254f889dSBrendon Cahoon                         SmallSetVector<SUnit *, 8> &Result) {
1719254f889dSBrendon Cahoon   Result.clear();
1720254f889dSBrendon Cahoon   for (unsigned i = 0, e = Set1.size(); i != e; ++i) {
1721254f889dSBrendon Cahoon     SUnit *SU = Set1[i];
1722254f889dSBrendon Cahoon     if (Set2.count(SU) != 0)
1723254f889dSBrendon Cahoon       Result.insert(SU);
1724254f889dSBrendon Cahoon   }
1725254f889dSBrendon Cahoon   return !Result.empty();
1726254f889dSBrendon Cahoon }
1727254f889dSBrendon Cahoon 
1728254f889dSBrendon Cahoon /// Merge the recurrence node sets that have the same initial node.
1729254f889dSBrendon Cahoon void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
1730254f889dSBrendon Cahoon   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1731254f889dSBrendon Cahoon        ++I) {
1732254f889dSBrendon Cahoon     NodeSet &NI = *I;
1733254f889dSBrendon Cahoon     for (NodeSetType::iterator J = I + 1; J != E;) {
1734254f889dSBrendon Cahoon       NodeSet &NJ = *J;
1735254f889dSBrendon Cahoon       if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
1736254f889dSBrendon Cahoon         if (NJ.compareRecMII(NI) > 0)
1737254f889dSBrendon Cahoon           NI.setRecMII(NJ.getRecMII());
1738254f889dSBrendon Cahoon         for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
1739254f889dSBrendon Cahoon              ++NII)
1740254f889dSBrendon Cahoon           I->insert(*NII);
1741254f889dSBrendon Cahoon         NodeSets.erase(J);
1742254f889dSBrendon Cahoon         E = NodeSets.end();
1743254f889dSBrendon Cahoon       } else {
1744254f889dSBrendon Cahoon         ++J;
1745254f889dSBrendon Cahoon       }
1746254f889dSBrendon Cahoon     }
1747254f889dSBrendon Cahoon   }
1748254f889dSBrendon Cahoon }
1749254f889dSBrendon Cahoon 
1750254f889dSBrendon Cahoon /// Remove nodes that have been scheduled in previous NodeSets.
1751254f889dSBrendon Cahoon void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
1752254f889dSBrendon Cahoon   for (NodeSetType::iterator I = NodeSets.begin(), E = NodeSets.end(); I != E;
1753254f889dSBrendon Cahoon        ++I)
1754254f889dSBrendon Cahoon     for (NodeSetType::iterator J = I + 1; J != E;) {
1755254f889dSBrendon Cahoon       J->remove_if([&](SUnit *SUJ) { return I->count(SUJ); });
1756254f889dSBrendon Cahoon 
175732a40564SEugene Zelenko       if (J->empty()) {
1758254f889dSBrendon Cahoon         NodeSets.erase(J);
1759254f889dSBrendon Cahoon         E = NodeSets.end();
1760254f889dSBrendon Cahoon       } else {
1761254f889dSBrendon Cahoon         ++J;
1762254f889dSBrendon Cahoon       }
1763254f889dSBrendon Cahoon     }
1764254f889dSBrendon Cahoon }
1765254f889dSBrendon Cahoon 
1766254f889dSBrendon Cahoon /// Compute an ordered list of the dependence graph nodes, which
1767254f889dSBrendon Cahoon /// indicates the order that the nodes will be scheduled.  This is a
1768254f889dSBrendon Cahoon /// two-level algorithm. First, a partial order is created, which
1769254f889dSBrendon Cahoon /// consists of a list of sets ordered from highest to lowest priority.
1770254f889dSBrendon Cahoon void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
1771254f889dSBrendon Cahoon   SmallSetVector<SUnit *, 8> R;
1772254f889dSBrendon Cahoon   NodeOrder.clear();
1773254f889dSBrendon Cahoon 
1774254f889dSBrendon Cahoon   for (auto &Nodes : NodeSets) {
1775d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes.size() << "\n");
1776254f889dSBrendon Cahoon     OrderKind Order;
1777254f889dSBrendon Cahoon     SmallSetVector<SUnit *, 8> N;
1778254f889dSBrendon Cahoon     if (pred_L(NodeOrder, N) && isSubset(N, Nodes)) {
1779254f889dSBrendon Cahoon       R.insert(N.begin(), N.end());
1780254f889dSBrendon Cahoon       Order = BottomUp;
1781d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  Bottom up (preds) ");
1782254f889dSBrendon Cahoon     } else if (succ_L(NodeOrder, N) && isSubset(N, Nodes)) {
1783254f889dSBrendon Cahoon       R.insert(N.begin(), N.end());
1784254f889dSBrendon Cahoon       Order = TopDown;
1785d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  Top down (succs) ");
1786254f889dSBrendon Cahoon     } else if (isIntersect(N, Nodes, R)) {
1787254f889dSBrendon Cahoon       // If some of the successors are in the existing node-set, then use the
1788254f889dSBrendon Cahoon       // top-down ordering.
1789254f889dSBrendon Cahoon       Order = TopDown;
1790d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  Top down (intersect) ");
1791254f889dSBrendon Cahoon     } else if (NodeSets.size() == 1) {
1792254f889dSBrendon Cahoon       for (auto &N : Nodes)
1793254f889dSBrendon Cahoon         if (N->Succs.size() == 0)
1794254f889dSBrendon Cahoon           R.insert(N);
1795254f889dSBrendon Cahoon       Order = BottomUp;
1796d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  Bottom up (all) ");
1797254f889dSBrendon Cahoon     } else {
1798254f889dSBrendon Cahoon       // Find the node with the highest ASAP.
1799254f889dSBrendon Cahoon       SUnit *maxASAP = nullptr;
1800254f889dSBrendon Cahoon       for (SUnit *SU : Nodes) {
1801a2122044SKrzysztof Parzyszek         if (maxASAP == nullptr || getASAP(SU) > getASAP(maxASAP) ||
1802a2122044SKrzysztof Parzyszek             (getASAP(SU) == getASAP(maxASAP) && SU->NodeNum > maxASAP->NodeNum))
1803254f889dSBrendon Cahoon           maxASAP = SU;
1804254f889dSBrendon Cahoon       }
1805254f889dSBrendon Cahoon       R.insert(maxASAP);
1806254f889dSBrendon Cahoon       Order = BottomUp;
1807d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "  Bottom up (default) ");
1808254f889dSBrendon Cahoon     }
1809254f889dSBrendon Cahoon 
1810254f889dSBrendon Cahoon     while (!R.empty()) {
1811254f889dSBrendon Cahoon       if (Order == TopDown) {
1812254f889dSBrendon Cahoon         // Choose the node with the maximum height.  If more than one, choose
1813a2122044SKrzysztof Parzyszek         // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
18144b8bcf00SRoorda, Jan-Willem         // choose the node with the lowest MOV.
1815254f889dSBrendon Cahoon         while (!R.empty()) {
1816254f889dSBrendon Cahoon           SUnit *maxHeight = nullptr;
1817254f889dSBrendon Cahoon           for (SUnit *I : R) {
1818cdc71612SEugene Zelenko             if (maxHeight == nullptr || getHeight(I) > getHeight(maxHeight))
1819254f889dSBrendon Cahoon               maxHeight = I;
1820254f889dSBrendon Cahoon             else if (getHeight(I) == getHeight(maxHeight) &&
18214b8bcf00SRoorda, Jan-Willem                      getZeroLatencyHeight(I) > getZeroLatencyHeight(maxHeight))
1822254f889dSBrendon Cahoon               maxHeight = I;
18234b8bcf00SRoorda, Jan-Willem             else if (getHeight(I) == getHeight(maxHeight) &&
18244b8bcf00SRoorda, Jan-Willem                      getZeroLatencyHeight(I) ==
18254b8bcf00SRoorda, Jan-Willem                          getZeroLatencyHeight(maxHeight) &&
18264b8bcf00SRoorda, Jan-Willem                      getMOV(I) < getMOV(maxHeight))
1827254f889dSBrendon Cahoon               maxHeight = I;
1828254f889dSBrendon Cahoon           }
1829254f889dSBrendon Cahoon           NodeOrder.insert(maxHeight);
1830d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << maxHeight->NodeNum << " ");
1831254f889dSBrendon Cahoon           R.remove(maxHeight);
1832254f889dSBrendon Cahoon           for (const auto &I : maxHeight->Succs) {
1833254f889dSBrendon Cahoon             if (Nodes.count(I.getSUnit()) == 0)
1834254f889dSBrendon Cahoon               continue;
1835254f889dSBrendon Cahoon             if (NodeOrder.count(I.getSUnit()) != 0)
1836254f889dSBrendon Cahoon               continue;
1837254f889dSBrendon Cahoon             if (ignoreDependence(I, false))
1838254f889dSBrendon Cahoon               continue;
1839254f889dSBrendon Cahoon             R.insert(I.getSUnit());
1840254f889dSBrendon Cahoon           }
1841254f889dSBrendon Cahoon           // Back-edges are predecessors with an anti-dependence.
1842254f889dSBrendon Cahoon           for (const auto &I : maxHeight->Preds) {
1843254f889dSBrendon Cahoon             if (I.getKind() != SDep::Anti)
1844254f889dSBrendon Cahoon               continue;
1845254f889dSBrendon Cahoon             if (Nodes.count(I.getSUnit()) == 0)
1846254f889dSBrendon Cahoon               continue;
1847254f889dSBrendon Cahoon             if (NodeOrder.count(I.getSUnit()) != 0)
1848254f889dSBrendon Cahoon               continue;
1849254f889dSBrendon Cahoon             R.insert(I.getSUnit());
1850254f889dSBrendon Cahoon           }
1851254f889dSBrendon Cahoon         }
1852254f889dSBrendon Cahoon         Order = BottomUp;
1853d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "\n   Switching order to bottom up ");
1854254f889dSBrendon Cahoon         SmallSetVector<SUnit *, 8> N;
1855254f889dSBrendon Cahoon         if (pred_L(NodeOrder, N, &Nodes))
1856254f889dSBrendon Cahoon           R.insert(N.begin(), N.end());
1857254f889dSBrendon Cahoon       } else {
1858254f889dSBrendon Cahoon         // Choose the node with the maximum depth.  If more than one, choose
18594b8bcf00SRoorda, Jan-Willem         // the node with the maximum ZeroLatencyDepth. If still more than one,
18604b8bcf00SRoorda, Jan-Willem         // choose the node with the lowest MOV.
1861254f889dSBrendon Cahoon         while (!R.empty()) {
1862254f889dSBrendon Cahoon           SUnit *maxDepth = nullptr;
1863254f889dSBrendon Cahoon           for (SUnit *I : R) {
1864cdc71612SEugene Zelenko             if (maxDepth == nullptr || getDepth(I) > getDepth(maxDepth))
1865254f889dSBrendon Cahoon               maxDepth = I;
1866254f889dSBrendon Cahoon             else if (getDepth(I) == getDepth(maxDepth) &&
18674b8bcf00SRoorda, Jan-Willem                      getZeroLatencyDepth(I) > getZeroLatencyDepth(maxDepth))
1868254f889dSBrendon Cahoon               maxDepth = I;
18694b8bcf00SRoorda, Jan-Willem             else if (getDepth(I) == getDepth(maxDepth) &&
18704b8bcf00SRoorda, Jan-Willem                      getZeroLatencyDepth(I) == getZeroLatencyDepth(maxDepth) &&
18714b8bcf00SRoorda, Jan-Willem                      getMOV(I) < getMOV(maxDepth))
1872254f889dSBrendon Cahoon               maxDepth = I;
1873254f889dSBrendon Cahoon           }
1874254f889dSBrendon Cahoon           NodeOrder.insert(maxDepth);
1875d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << maxDepth->NodeNum << " ");
1876254f889dSBrendon Cahoon           R.remove(maxDepth);
1877254f889dSBrendon Cahoon           if (Nodes.isExceedSU(maxDepth)) {
1878254f889dSBrendon Cahoon             Order = TopDown;
1879254f889dSBrendon Cahoon             R.clear();
1880254f889dSBrendon Cahoon             R.insert(Nodes.getNode(0));
1881254f889dSBrendon Cahoon             break;
1882254f889dSBrendon Cahoon           }
1883254f889dSBrendon Cahoon           for (const auto &I : maxDepth->Preds) {
1884254f889dSBrendon Cahoon             if (Nodes.count(I.getSUnit()) == 0)
1885254f889dSBrendon Cahoon               continue;
1886254f889dSBrendon Cahoon             if (NodeOrder.count(I.getSUnit()) != 0)
1887254f889dSBrendon Cahoon               continue;
1888254f889dSBrendon Cahoon             R.insert(I.getSUnit());
1889254f889dSBrendon Cahoon           }
1890254f889dSBrendon Cahoon           // Back-edges are predecessors with an anti-dependence.
1891254f889dSBrendon Cahoon           for (const auto &I : maxDepth->Succs) {
1892254f889dSBrendon Cahoon             if (I.getKind() != SDep::Anti)
1893254f889dSBrendon Cahoon               continue;
1894254f889dSBrendon Cahoon             if (Nodes.count(I.getSUnit()) == 0)
1895254f889dSBrendon Cahoon               continue;
1896254f889dSBrendon Cahoon             if (NodeOrder.count(I.getSUnit()) != 0)
1897254f889dSBrendon Cahoon               continue;
1898254f889dSBrendon Cahoon             R.insert(I.getSUnit());
1899254f889dSBrendon Cahoon           }
1900254f889dSBrendon Cahoon         }
1901254f889dSBrendon Cahoon         Order = TopDown;
1902d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "\n   Switching order to top down ");
1903254f889dSBrendon Cahoon         SmallSetVector<SUnit *, 8> N;
1904254f889dSBrendon Cahoon         if (succ_L(NodeOrder, N, &Nodes))
1905254f889dSBrendon Cahoon           R.insert(N.begin(), N.end());
1906254f889dSBrendon Cahoon       }
1907254f889dSBrendon Cahoon     }
1908d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
1909254f889dSBrendon Cahoon   }
1910254f889dSBrendon Cahoon 
1911d34e60caSNicola Zaghen   LLVM_DEBUG({
1912254f889dSBrendon Cahoon     dbgs() << "Node order: ";
1913254f889dSBrendon Cahoon     for (SUnit *I : NodeOrder)
1914254f889dSBrendon Cahoon       dbgs() << " " << I->NodeNum << " ";
1915254f889dSBrendon Cahoon     dbgs() << "\n";
1916254f889dSBrendon Cahoon   });
1917254f889dSBrendon Cahoon }
1918254f889dSBrendon Cahoon 
1919254f889dSBrendon Cahoon /// Process the nodes in the computed order and create the pipelined schedule
1920254f889dSBrendon Cahoon /// of the instructions, if possible. Return true if a schedule is found.
1921254f889dSBrendon Cahoon bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
192218e7bf5cSJinsong Ji 
192318e7bf5cSJinsong Ji   if (NodeOrder.empty()){
192418e7bf5cSJinsong Ji     LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
1925254f889dSBrendon Cahoon     return false;
192618e7bf5cSJinsong Ji   }
1927254f889dSBrendon Cahoon 
1928254f889dSBrendon Cahoon   bool scheduleFound = false;
192959d99731SBrendon Cahoon   unsigned II = 0;
1930254f889dSBrendon Cahoon   // Keep increasing II until a valid schedule is found.
193159d99731SBrendon Cahoon   for (II = MII; II <= MAX_II && !scheduleFound; ++II) {
1932254f889dSBrendon Cahoon     Schedule.reset();
1933254f889dSBrendon Cahoon     Schedule.setInitiationInterval(II);
1934d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Try to schedule with " << II << "\n");
1935254f889dSBrendon Cahoon 
1936254f889dSBrendon Cahoon     SetVector<SUnit *>::iterator NI = NodeOrder.begin();
1937254f889dSBrendon Cahoon     SetVector<SUnit *>::iterator NE = NodeOrder.end();
1938254f889dSBrendon Cahoon     do {
1939254f889dSBrendon Cahoon       SUnit *SU = *NI;
1940254f889dSBrendon Cahoon 
1941254f889dSBrendon Cahoon       // Compute the schedule time for the instruction, which is based
1942254f889dSBrendon Cahoon       // upon the scheduled time for any predecessors/successors.
1943254f889dSBrendon Cahoon       int EarlyStart = INT_MIN;
1944254f889dSBrendon Cahoon       int LateStart = INT_MAX;
1945254f889dSBrendon Cahoon       // These values are set when the size of the schedule window is limited
1946254f889dSBrendon Cahoon       // due to chain dependences.
1947254f889dSBrendon Cahoon       int SchedEnd = INT_MAX;
1948254f889dSBrendon Cahoon       int SchedStart = INT_MIN;
1949254f889dSBrendon Cahoon       Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
1950254f889dSBrendon Cahoon                             II, this);
1951d34e60caSNicola Zaghen       LLVM_DEBUG({
195218e7bf5cSJinsong Ji         dbgs() << "\n";
1953254f889dSBrendon Cahoon         dbgs() << "Inst (" << SU->NodeNum << ") ";
1954254f889dSBrendon Cahoon         SU->getInstr()->dump();
1955254f889dSBrendon Cahoon         dbgs() << "\n";
1956254f889dSBrendon Cahoon       });
1957d34e60caSNicola Zaghen       LLVM_DEBUG({
195818e7bf5cSJinsong Ji         dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart,
195918e7bf5cSJinsong Ji                          LateStart, SchedEnd, SchedStart);
1960254f889dSBrendon Cahoon       });
1961254f889dSBrendon Cahoon 
1962254f889dSBrendon Cahoon       if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
1963254f889dSBrendon Cahoon           SchedStart > LateStart)
1964254f889dSBrendon Cahoon         scheduleFound = false;
1965254f889dSBrendon Cahoon       else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
1966254f889dSBrendon Cahoon         SchedEnd = std::min(SchedEnd, EarlyStart + (int)II - 1);
1967254f889dSBrendon Cahoon         scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
1968254f889dSBrendon Cahoon       } else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
1969254f889dSBrendon Cahoon         SchedStart = std::max(SchedStart, LateStart - (int)II + 1);
1970254f889dSBrendon Cahoon         scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
1971254f889dSBrendon Cahoon       } else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
1972254f889dSBrendon Cahoon         SchedEnd =
1973254f889dSBrendon Cahoon             std::min(SchedEnd, std::min(LateStart, EarlyStart + (int)II - 1));
1974254f889dSBrendon Cahoon         // When scheduling a Phi it is better to start at the late cycle and go
1975254f889dSBrendon Cahoon         // backwards. The default order may insert the Phi too far away from
1976254f889dSBrendon Cahoon         // its first dependence.
1977254f889dSBrendon Cahoon         if (SU->getInstr()->isPHI())
1978254f889dSBrendon Cahoon           scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
1979254f889dSBrendon Cahoon         else
1980254f889dSBrendon Cahoon           scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
1981254f889dSBrendon Cahoon       } else {
1982254f889dSBrendon Cahoon         int FirstCycle = Schedule.getFirstCycle();
1983254f889dSBrendon Cahoon         scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
1984254f889dSBrendon Cahoon                                         FirstCycle + getASAP(SU) + II - 1, II);
1985254f889dSBrendon Cahoon       }
1986254f889dSBrendon Cahoon       // Even if we find a schedule, make sure the schedule doesn't exceed the
1987254f889dSBrendon Cahoon       // allowable number of stages. We keep trying if this happens.
1988254f889dSBrendon Cahoon       if (scheduleFound)
1989254f889dSBrendon Cahoon         if (SwpMaxStages > -1 &&
1990254f889dSBrendon Cahoon             Schedule.getMaxStageCount() > (unsigned)SwpMaxStages)
1991254f889dSBrendon Cahoon           scheduleFound = false;
1992254f889dSBrendon Cahoon 
1993d34e60caSNicola Zaghen       LLVM_DEBUG({
1994254f889dSBrendon Cahoon         if (!scheduleFound)
1995254f889dSBrendon Cahoon           dbgs() << "\tCan't schedule\n";
1996254f889dSBrendon Cahoon       });
1997254f889dSBrendon Cahoon     } while (++NI != NE && scheduleFound);
1998254f889dSBrendon Cahoon 
1999254f889dSBrendon Cahoon     // If a schedule is found, check if it is a valid schedule too.
2000254f889dSBrendon Cahoon     if (scheduleFound)
2001254f889dSBrendon Cahoon       scheduleFound = Schedule.isValidSchedule(this);
2002254f889dSBrendon Cahoon   }
2003254f889dSBrendon Cahoon 
200459d99731SBrendon Cahoon   LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound << " (II=" << II
200559d99731SBrendon Cahoon                     << ")\n");
2006254f889dSBrendon Cahoon 
2007254f889dSBrendon Cahoon   if (scheduleFound)
2008254f889dSBrendon Cahoon     Schedule.finalizeSchedule(this);
2009254f889dSBrendon Cahoon   else
2010254f889dSBrendon Cahoon     Schedule.reset();
2011254f889dSBrendon Cahoon 
2012254f889dSBrendon Cahoon   return scheduleFound && Schedule.getMaxStageCount() > 0;
2013254f889dSBrendon Cahoon }
2014254f889dSBrendon Cahoon 
2015254f889dSBrendon Cahoon /// Given a schedule for the loop, generate a new version of the loop,
2016254f889dSBrendon Cahoon /// and replace the old version.  This function generates a prolog
2017254f889dSBrendon Cahoon /// that contains the initial iterations in the pipeline, and kernel
2018254f889dSBrendon Cahoon /// loop, and the epilogue that contains the code for the final
2019254f889dSBrendon Cahoon /// iterations.
2020254f889dSBrendon Cahoon void SwingSchedulerDAG::generatePipelinedLoop(SMSchedule &Schedule) {
2021254f889dSBrendon Cahoon   // Create a new basic block for the kernel and add it to the CFG.
2022254f889dSBrendon Cahoon   MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2023254f889dSBrendon Cahoon 
2024254f889dSBrendon Cahoon   unsigned MaxStageCount = Schedule.getMaxStageCount();
2025254f889dSBrendon Cahoon 
2026254f889dSBrendon Cahoon   // Remember the registers that are used in different stages. The index is
2027254f889dSBrendon Cahoon   // the iteration, or stage, that the instruction is scheduled in.  This is
2028c73b6d6bSHiroshi Inoue   // a map between register names in the original block and the names created
2029254f889dSBrendon Cahoon   // in each stage of the pipelined loop.
2030254f889dSBrendon Cahoon   ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
2031254f889dSBrendon Cahoon   InstrMapTy InstrMap;
2032254f889dSBrendon Cahoon 
2033254f889dSBrendon Cahoon   SmallVector<MachineBasicBlock *, 4> PrologBBs;
2034ef2d6d99SJinsong Ji 
2035ef2d6d99SJinsong Ji   MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
2036ef2d6d99SJinsong Ji   assert(PreheaderBB != nullptr &&
2037ef2d6d99SJinsong Ji          "Need to add code to handle loops w/o preheader");
2038254f889dSBrendon Cahoon   // Generate the prolog instructions that set up the pipeline.
2039254f889dSBrendon Cahoon   generateProlog(Schedule, MaxStageCount, KernelBB, VRMap, PrologBBs);
2040254f889dSBrendon Cahoon   MF.insert(BB->getIterator(), KernelBB);
2041254f889dSBrendon Cahoon 
2042254f889dSBrendon Cahoon   // Rearrange the instructions to generate the new, pipelined loop,
2043254f889dSBrendon Cahoon   // and update register names as needed.
2044254f889dSBrendon Cahoon   for (int Cycle = Schedule.getFirstCycle(),
2045254f889dSBrendon Cahoon            LastCycle = Schedule.getFinalCycle();
2046254f889dSBrendon Cahoon        Cycle <= LastCycle; ++Cycle) {
2047254f889dSBrendon Cahoon     std::deque<SUnit *> &CycleInstrs = Schedule.getInstructions(Cycle);
2048254f889dSBrendon Cahoon     // This inner loop schedules each instruction in the cycle.
2049254f889dSBrendon Cahoon     for (SUnit *CI : CycleInstrs) {
2050254f889dSBrendon Cahoon       if (CI->getInstr()->isPHI())
2051254f889dSBrendon Cahoon         continue;
2052254f889dSBrendon Cahoon       unsigned StageNum = Schedule.stageScheduled(getSUnit(CI->getInstr()));
2053254f889dSBrendon Cahoon       MachineInstr *NewMI = cloneInstr(CI->getInstr(), MaxStageCount, StageNum);
2054254f889dSBrendon Cahoon       updateInstruction(NewMI, false, MaxStageCount, StageNum, Schedule, VRMap);
2055254f889dSBrendon Cahoon       KernelBB->push_back(NewMI);
2056254f889dSBrendon Cahoon       InstrMap[NewMI] = CI->getInstr();
2057254f889dSBrendon Cahoon     }
2058254f889dSBrendon Cahoon   }
2059254f889dSBrendon Cahoon 
2060254f889dSBrendon Cahoon   // Copy any terminator instructions to the new kernel, and update
2061254f889dSBrendon Cahoon   // names as needed.
2062254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator I = BB->getFirstTerminator(),
2063254f889dSBrendon Cahoon                                    E = BB->instr_end();
2064254f889dSBrendon Cahoon        I != E; ++I) {
2065254f889dSBrendon Cahoon     MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
2066254f889dSBrendon Cahoon     updateInstruction(NewMI, false, MaxStageCount, 0, Schedule, VRMap);
2067254f889dSBrendon Cahoon     KernelBB->push_back(NewMI);
2068254f889dSBrendon Cahoon     InstrMap[NewMI] = &*I;
2069254f889dSBrendon Cahoon   }
2070254f889dSBrendon Cahoon 
2071254f889dSBrendon Cahoon   KernelBB->transferSuccessors(BB);
2072254f889dSBrendon Cahoon   KernelBB->replaceSuccessor(BB, KernelBB);
2073254f889dSBrendon Cahoon 
2074254f889dSBrendon Cahoon   generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule,
2075254f889dSBrendon Cahoon                        VRMap, InstrMap, MaxStageCount, MaxStageCount, false);
2076254f889dSBrendon Cahoon   generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, Schedule, VRMap,
2077254f889dSBrendon Cahoon                InstrMap, MaxStageCount, MaxStageCount, false);
2078254f889dSBrendon Cahoon 
2079d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
2080254f889dSBrendon Cahoon 
2081254f889dSBrendon Cahoon   SmallVector<MachineBasicBlock *, 4> EpilogBBs;
2082254f889dSBrendon Cahoon   // Generate the epilog instructions to complete the pipeline.
2083254f889dSBrendon Cahoon   generateEpilog(Schedule, MaxStageCount, KernelBB, VRMap, EpilogBBs,
2084254f889dSBrendon Cahoon                  PrologBBs);
2085254f889dSBrendon Cahoon 
2086254f889dSBrendon Cahoon   // We need this step because the register allocation doesn't handle some
2087254f889dSBrendon Cahoon   // situations well, so we insert copies to help out.
2088254f889dSBrendon Cahoon   splitLifetimes(KernelBB, EpilogBBs, Schedule);
2089254f889dSBrendon Cahoon 
2090254f889dSBrendon Cahoon   // Remove dead instructions due to loop induction variables.
2091254f889dSBrendon Cahoon   removeDeadInstructions(KernelBB, EpilogBBs);
2092254f889dSBrendon Cahoon 
2093254f889dSBrendon Cahoon   // Add branches between prolog and epilog blocks.
2094ef2d6d99SJinsong Ji   addBranches(*PreheaderBB, PrologBBs, KernelBB, EpilogBBs, Schedule, VRMap);
2095254f889dSBrendon Cahoon 
2096254f889dSBrendon Cahoon   // Remove the original loop since it's no longer referenced.
2097c715a5d2SKrzysztof Parzyszek   for (auto &I : *BB)
2098c715a5d2SKrzysztof Parzyszek     LIS.RemoveMachineInstrFromMaps(I);
2099254f889dSBrendon Cahoon   BB->clear();
2100254f889dSBrendon Cahoon   BB->eraseFromParent();
2101254f889dSBrendon Cahoon 
2102254f889dSBrendon Cahoon   delete[] VRMap;
2103254f889dSBrendon Cahoon }
2104254f889dSBrendon Cahoon 
2105254f889dSBrendon Cahoon /// Generate the pipeline prolog code.
2106254f889dSBrendon Cahoon void SwingSchedulerDAG::generateProlog(SMSchedule &Schedule, unsigned LastStage,
2107254f889dSBrendon Cahoon                                        MachineBasicBlock *KernelBB,
2108254f889dSBrendon Cahoon                                        ValueMapTy *VRMap,
2109254f889dSBrendon Cahoon                                        MBBVectorTy &PrologBBs) {
2110254f889dSBrendon Cahoon   MachineBasicBlock *PreheaderBB = MLI->getLoopFor(BB)->getLoopPreheader();
211132a40564SEugene Zelenko   assert(PreheaderBB != nullptr &&
2112254f889dSBrendon Cahoon          "Need to add code to handle loops w/o preheader");
2113254f889dSBrendon Cahoon   MachineBasicBlock *PredBB = PreheaderBB;
2114254f889dSBrendon Cahoon   InstrMapTy InstrMap;
2115254f889dSBrendon Cahoon 
2116254f889dSBrendon Cahoon   // Generate a basic block for each stage, not including the last stage,
2117254f889dSBrendon Cahoon   // which will be generated in the kernel. Each basic block may contain
2118254f889dSBrendon Cahoon   // instructions from multiple stages/iterations.
2119254f889dSBrendon Cahoon   for (unsigned i = 0; i < LastStage; ++i) {
2120254f889dSBrendon Cahoon     // Create and insert the prolog basic block prior to the original loop
2121254f889dSBrendon Cahoon     // basic block.  The original loop is removed later.
2122254f889dSBrendon Cahoon     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
2123254f889dSBrendon Cahoon     PrologBBs.push_back(NewBB);
2124254f889dSBrendon Cahoon     MF.insert(BB->getIterator(), NewBB);
2125254f889dSBrendon Cahoon     NewBB->transferSuccessors(PredBB);
2126254f889dSBrendon Cahoon     PredBB->addSuccessor(NewBB);
2127254f889dSBrendon Cahoon     PredBB = NewBB;
2128254f889dSBrendon Cahoon 
2129254f889dSBrendon Cahoon     // Generate instructions for each appropriate stage. Process instructions
2130254f889dSBrendon Cahoon     // in original program order.
2131254f889dSBrendon Cahoon     for (int StageNum = i; StageNum >= 0; --StageNum) {
2132254f889dSBrendon Cahoon       for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2133254f889dSBrendon Cahoon                                        BBE = BB->getFirstTerminator();
2134254f889dSBrendon Cahoon            BBI != BBE; ++BBI) {
2135254f889dSBrendon Cahoon         if (Schedule.isScheduledAtStage(getSUnit(&*BBI), (unsigned)StageNum)) {
2136254f889dSBrendon Cahoon           if (BBI->isPHI())
2137254f889dSBrendon Cahoon             continue;
2138254f889dSBrendon Cahoon           MachineInstr *NewMI =
2139254f889dSBrendon Cahoon               cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum, Schedule);
2140254f889dSBrendon Cahoon           updateInstruction(NewMI, false, i, (unsigned)StageNum, Schedule,
2141254f889dSBrendon Cahoon                             VRMap);
2142254f889dSBrendon Cahoon           NewBB->push_back(NewMI);
2143254f889dSBrendon Cahoon           InstrMap[NewMI] = &*BBI;
2144254f889dSBrendon Cahoon         }
2145254f889dSBrendon Cahoon       }
2146254f889dSBrendon Cahoon     }
2147254f889dSBrendon Cahoon     rewritePhiValues(NewBB, i, Schedule, VRMap, InstrMap);
2148d34e60caSNicola Zaghen     LLVM_DEBUG({
2149254f889dSBrendon Cahoon       dbgs() << "prolog:\n";
2150254f889dSBrendon Cahoon       NewBB->dump();
2151254f889dSBrendon Cahoon     });
2152254f889dSBrendon Cahoon   }
2153254f889dSBrendon Cahoon 
2154254f889dSBrendon Cahoon   PredBB->replaceSuccessor(BB, KernelBB);
2155254f889dSBrendon Cahoon 
2156254f889dSBrendon Cahoon   // Check if we need to remove the branch from the preheader to the original
2157254f889dSBrendon Cahoon   // loop, and replace it with a branch to the new loop.
21581b9fc8edSMatt Arsenault   unsigned numBranches = TII->removeBranch(*PreheaderBB);
2159254f889dSBrendon Cahoon   if (numBranches) {
2160254f889dSBrendon Cahoon     SmallVector<MachineOperand, 0> Cond;
2161e8e0f5caSMatt Arsenault     TII->insertBranch(*PreheaderBB, PrologBBs[0], nullptr, Cond, DebugLoc());
2162254f889dSBrendon Cahoon   }
2163254f889dSBrendon Cahoon }
2164254f889dSBrendon Cahoon 
2165254f889dSBrendon Cahoon /// Generate the pipeline epilog code. The epilog code finishes the iterations
2166254f889dSBrendon Cahoon /// that were started in either the prolog or the kernel.  We create a basic
2167254f889dSBrendon Cahoon /// block for each stage that needs to complete.
2168254f889dSBrendon Cahoon void SwingSchedulerDAG::generateEpilog(SMSchedule &Schedule, unsigned LastStage,
2169254f889dSBrendon Cahoon                                        MachineBasicBlock *KernelBB,
2170254f889dSBrendon Cahoon                                        ValueMapTy *VRMap,
2171254f889dSBrendon Cahoon                                        MBBVectorTy &EpilogBBs,
2172254f889dSBrendon Cahoon                                        MBBVectorTy &PrologBBs) {
2173254f889dSBrendon Cahoon   // We need to change the branch from the kernel to the first epilog block, so
2174254f889dSBrendon Cahoon   // this call to analyze branch uses the kernel rather than the original BB.
2175254f889dSBrendon Cahoon   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2176254f889dSBrendon Cahoon   SmallVector<MachineOperand, 4> Cond;
2177254f889dSBrendon Cahoon   bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
2178254f889dSBrendon Cahoon   assert(!checkBranch && "generateEpilog must be able to analyze the branch");
2179254f889dSBrendon Cahoon   if (checkBranch)
2180254f889dSBrendon Cahoon     return;
2181254f889dSBrendon Cahoon 
2182254f889dSBrendon Cahoon   MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
2183254f889dSBrendon Cahoon   if (*LoopExitI == KernelBB)
2184254f889dSBrendon Cahoon     ++LoopExitI;
2185254f889dSBrendon Cahoon   assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
2186254f889dSBrendon Cahoon   MachineBasicBlock *LoopExitBB = *LoopExitI;
2187254f889dSBrendon Cahoon 
2188254f889dSBrendon Cahoon   MachineBasicBlock *PredBB = KernelBB;
2189254f889dSBrendon Cahoon   MachineBasicBlock *EpilogStart = LoopExitBB;
2190254f889dSBrendon Cahoon   InstrMapTy InstrMap;
2191254f889dSBrendon Cahoon 
2192254f889dSBrendon Cahoon   // Generate a basic block for each stage, not including the last stage,
2193254f889dSBrendon Cahoon   // which was generated for the kernel.  Each basic block may contain
2194254f889dSBrendon Cahoon   // instructions from multiple stages/iterations.
2195254f889dSBrendon Cahoon   int EpilogStage = LastStage + 1;
2196254f889dSBrendon Cahoon   for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
2197254f889dSBrendon Cahoon     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
2198254f889dSBrendon Cahoon     EpilogBBs.push_back(NewBB);
2199254f889dSBrendon Cahoon     MF.insert(BB->getIterator(), NewBB);
2200254f889dSBrendon Cahoon 
2201254f889dSBrendon Cahoon     PredBB->replaceSuccessor(LoopExitBB, NewBB);
2202254f889dSBrendon Cahoon     NewBB->addSuccessor(LoopExitBB);
2203254f889dSBrendon Cahoon 
2204254f889dSBrendon Cahoon     if (EpilogStart == LoopExitBB)
2205254f889dSBrendon Cahoon       EpilogStart = NewBB;
2206254f889dSBrendon Cahoon 
2207254f889dSBrendon Cahoon     // Add instructions to the epilog depending on the current block.
2208254f889dSBrendon Cahoon     // Process instructions in original program order.
2209254f889dSBrendon Cahoon     for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
2210254f889dSBrendon Cahoon       for (auto &BBI : *BB) {
2211254f889dSBrendon Cahoon         if (BBI.isPHI())
2212254f889dSBrendon Cahoon           continue;
2213254f889dSBrendon Cahoon         MachineInstr *In = &BBI;
2214254f889dSBrendon Cahoon         if (Schedule.isScheduledAtStage(getSUnit(In), StageNum)) {
2215785b6cecSKrzysztof Parzyszek           // Instructions with memoperands in the epilog are updated with
2216785b6cecSKrzysztof Parzyszek           // conservative values.
2217785b6cecSKrzysztof Parzyszek           MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
2218254f889dSBrendon Cahoon           updateInstruction(NewMI, i == 1, EpilogStage, 0, Schedule, VRMap);
2219254f889dSBrendon Cahoon           NewBB->push_back(NewMI);
2220254f889dSBrendon Cahoon           InstrMap[NewMI] = In;
2221254f889dSBrendon Cahoon         }
2222254f889dSBrendon Cahoon       }
2223254f889dSBrendon Cahoon     }
2224254f889dSBrendon Cahoon     generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule,
2225254f889dSBrendon Cahoon                          VRMap, InstrMap, LastStage, EpilogStage, i == 1);
2226254f889dSBrendon Cahoon     generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, VRMap,
2227254f889dSBrendon Cahoon                  InstrMap, LastStage, EpilogStage, i == 1);
2228254f889dSBrendon Cahoon     PredBB = NewBB;
2229254f889dSBrendon Cahoon 
2230d34e60caSNicola Zaghen     LLVM_DEBUG({
2231254f889dSBrendon Cahoon       dbgs() << "epilog:\n";
2232254f889dSBrendon Cahoon       NewBB->dump();
2233254f889dSBrendon Cahoon     });
2234254f889dSBrendon Cahoon   }
2235254f889dSBrendon Cahoon 
2236254f889dSBrendon Cahoon   // Fix any Phi nodes in the loop exit block.
2237254f889dSBrendon Cahoon   for (MachineInstr &MI : *LoopExitBB) {
2238254f889dSBrendon Cahoon     if (!MI.isPHI())
2239254f889dSBrendon Cahoon       break;
2240254f889dSBrendon Cahoon     for (unsigned i = 2, e = MI.getNumOperands() + 1; i != e; i += 2) {
2241254f889dSBrendon Cahoon       MachineOperand &MO = MI.getOperand(i);
2242254f889dSBrendon Cahoon       if (MO.getMBB() == BB)
2243254f889dSBrendon Cahoon         MO.setMBB(PredBB);
2244254f889dSBrendon Cahoon     }
2245254f889dSBrendon Cahoon   }
2246254f889dSBrendon Cahoon 
2247254f889dSBrendon Cahoon   // Create a branch to the new epilog from the kernel.
2248254f889dSBrendon Cahoon   // Remove the original branch and add a new branch to the epilog.
22491b9fc8edSMatt Arsenault   TII->removeBranch(*KernelBB);
2250e8e0f5caSMatt Arsenault   TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
2251254f889dSBrendon Cahoon   // Add a branch to the loop exit.
2252254f889dSBrendon Cahoon   if (EpilogBBs.size() > 0) {
2253254f889dSBrendon Cahoon     MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
2254254f889dSBrendon Cahoon     SmallVector<MachineOperand, 4> Cond1;
2255e8e0f5caSMatt Arsenault     TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
2256254f889dSBrendon Cahoon   }
2257254f889dSBrendon Cahoon }
2258254f889dSBrendon Cahoon 
2259254f889dSBrendon Cahoon /// Replace all uses of FromReg that appear outside the specified
2260254f889dSBrendon Cahoon /// basic block with ToReg.
2261254f889dSBrendon Cahoon static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
2262254f889dSBrendon Cahoon                                     MachineBasicBlock *MBB,
2263254f889dSBrendon Cahoon                                     MachineRegisterInfo &MRI,
2264254f889dSBrendon Cahoon                                     LiveIntervals &LIS) {
2265254f889dSBrendon Cahoon   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(FromReg),
2266254f889dSBrendon Cahoon                                          E = MRI.use_end();
2267254f889dSBrendon Cahoon        I != E;) {
2268254f889dSBrendon Cahoon     MachineOperand &O = *I;
2269254f889dSBrendon Cahoon     ++I;
2270254f889dSBrendon Cahoon     if (O.getParent()->getParent() != MBB)
2271254f889dSBrendon Cahoon       O.setReg(ToReg);
2272254f889dSBrendon Cahoon   }
2273254f889dSBrendon Cahoon   if (!LIS.hasInterval(ToReg))
2274254f889dSBrendon Cahoon     LIS.createEmptyInterval(ToReg);
2275254f889dSBrendon Cahoon }
2276254f889dSBrendon Cahoon 
2277254f889dSBrendon Cahoon /// Return true if the register has a use that occurs outside the
2278254f889dSBrendon Cahoon /// specified loop.
2279254f889dSBrendon Cahoon static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
2280254f889dSBrendon Cahoon                             MachineRegisterInfo &MRI) {
2281254f889dSBrendon Cahoon   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(Reg),
2282254f889dSBrendon Cahoon                                          E = MRI.use_end();
2283254f889dSBrendon Cahoon        I != E; ++I)
2284254f889dSBrendon Cahoon     if (I->getParent()->getParent() != BB)
2285254f889dSBrendon Cahoon       return true;
2286254f889dSBrendon Cahoon   return false;
2287254f889dSBrendon Cahoon }
2288254f889dSBrendon Cahoon 
2289254f889dSBrendon Cahoon /// Generate Phis for the specific block in the generated pipelined code.
2290254f889dSBrendon Cahoon /// This function looks at the Phis from the original code to guide the
2291254f889dSBrendon Cahoon /// creation of new Phis.
2292254f889dSBrendon Cahoon void SwingSchedulerDAG::generateExistingPhis(
2293254f889dSBrendon Cahoon     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2294254f889dSBrendon Cahoon     MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2295254f889dSBrendon Cahoon     InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2296254f889dSBrendon Cahoon     bool IsLast) {
22976bdc7555SSimon Pilgrim   // Compute the stage number for the initial value of the Phi, which
2298254f889dSBrendon Cahoon   // comes from the prolog. The prolog to use depends on to which kernel/
2299254f889dSBrendon Cahoon   // epilog that we're adding the Phi.
2300254f889dSBrendon Cahoon   unsigned PrologStage = 0;
2301254f889dSBrendon Cahoon   unsigned PrevStage = 0;
2302254f889dSBrendon Cahoon   bool InKernel = (LastStageNum == CurStageNum);
2303254f889dSBrendon Cahoon   if (InKernel) {
2304254f889dSBrendon Cahoon     PrologStage = LastStageNum - 1;
2305254f889dSBrendon Cahoon     PrevStage = CurStageNum;
2306254f889dSBrendon Cahoon   } else {
2307254f889dSBrendon Cahoon     PrologStage = LastStageNum - (CurStageNum - LastStageNum);
2308254f889dSBrendon Cahoon     PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
2309254f889dSBrendon Cahoon   }
2310254f889dSBrendon Cahoon 
2311254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
2312254f889dSBrendon Cahoon                                    BBE = BB->getFirstNonPHI();
2313254f889dSBrendon Cahoon        BBI != BBE; ++BBI) {
2314254f889dSBrendon Cahoon     unsigned Def = BBI->getOperand(0).getReg();
2315254f889dSBrendon Cahoon 
2316254f889dSBrendon Cahoon     unsigned InitVal = 0;
2317254f889dSBrendon Cahoon     unsigned LoopVal = 0;
2318254f889dSBrendon Cahoon     getPhiRegs(*BBI, BB, InitVal, LoopVal);
2319254f889dSBrendon Cahoon 
2320254f889dSBrendon Cahoon     unsigned PhiOp1 = 0;
2321254f889dSBrendon Cahoon     // The Phi value from the loop body typically is defined in the loop, but
2322254f889dSBrendon Cahoon     // not always. So, we need to check if the value is defined in the loop.
2323254f889dSBrendon Cahoon     unsigned PhiOp2 = LoopVal;
2324254f889dSBrendon Cahoon     if (VRMap[LastStageNum].count(LoopVal))
2325254f889dSBrendon Cahoon       PhiOp2 = VRMap[LastStageNum][LoopVal];
2326254f889dSBrendon Cahoon 
2327254f889dSBrendon Cahoon     int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2328254f889dSBrendon Cahoon     int LoopValStage =
2329254f889dSBrendon Cahoon         Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
2330254f889dSBrendon Cahoon     unsigned NumStages = Schedule.getStagesForReg(Def, CurStageNum);
2331254f889dSBrendon Cahoon     if (NumStages == 0) {
2332254f889dSBrendon Cahoon       // We don't need to generate a Phi anymore, but we need to rename any uses
2333254f889dSBrendon Cahoon       // of the Phi value.
2334254f889dSBrendon Cahoon       unsigned NewReg = VRMap[PrevStage][LoopVal];
2335254f889dSBrendon Cahoon       rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, 0, &*BBI,
233616e66f59SKrzysztof Parzyszek                             Def, InitVal, NewReg);
2337254f889dSBrendon Cahoon       if (VRMap[CurStageNum].count(LoopVal))
2338254f889dSBrendon Cahoon         VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
2339254f889dSBrendon Cahoon     }
2340254f889dSBrendon Cahoon     // Adjust the number of Phis needed depending on the number of prologs left,
23413f72a6b7SKrzysztof Parzyszek     // and the distance from where the Phi is first scheduled. The number of
23423f72a6b7SKrzysztof Parzyszek     // Phis cannot exceed the number of prolog stages. Each stage can
23433f72a6b7SKrzysztof Parzyszek     // potentially define two values.
23443f72a6b7SKrzysztof Parzyszek     unsigned MaxPhis = PrologStage + 2;
23453f72a6b7SKrzysztof Parzyszek     if (!InKernel && (int)PrologStage <= LoopValStage)
23463f72a6b7SKrzysztof Parzyszek       MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1);
23473f72a6b7SKrzysztof Parzyszek     unsigned NumPhis = std::min(NumStages, MaxPhis);
2348254f889dSBrendon Cahoon 
2349254f889dSBrendon Cahoon     unsigned NewReg = 0;
2350254f889dSBrendon Cahoon     unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
2351254f889dSBrendon Cahoon     // In the epilog, we may need to look back one stage to get the correct
2352254f889dSBrendon Cahoon     // Phi name because the epilog and prolog blocks execute the same stage.
2353254f889dSBrendon Cahoon     // The correct name is from the previous block only when the Phi has
2354254f889dSBrendon Cahoon     // been completely scheduled prior to the epilog, and Phi value is not
2355254f889dSBrendon Cahoon     // needed in multiple stages.
2356254f889dSBrendon Cahoon     int StageDiff = 0;
2357254f889dSBrendon Cahoon     if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
2358254f889dSBrendon Cahoon         NumPhis == 1)
2359254f889dSBrendon Cahoon       StageDiff = 1;
2360254f889dSBrendon Cahoon     // Adjust the computations below when the phi and the loop definition
2361254f889dSBrendon Cahoon     // are scheduled in different stages.
2362254f889dSBrendon Cahoon     if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
2363254f889dSBrendon Cahoon       StageDiff = StageScheduled - LoopValStage;
2364254f889dSBrendon Cahoon     for (unsigned np = 0; np < NumPhis; ++np) {
2365254f889dSBrendon Cahoon       // If the Phi hasn't been scheduled, then use the initial Phi operand
2366254f889dSBrendon Cahoon       // value. Otherwise, use the scheduled version of the instruction. This
2367254f889dSBrendon Cahoon       // is a little complicated when a Phi references another Phi.
2368254f889dSBrendon Cahoon       if (np > PrologStage || StageScheduled >= (int)LastStageNum)
2369254f889dSBrendon Cahoon         PhiOp1 = InitVal;
2370254f889dSBrendon Cahoon       // Check if the Phi has already been scheduled in a prolog stage.
2371254f889dSBrendon Cahoon       else if (PrologStage >= AccessStage + StageDiff + np &&
2372254f889dSBrendon Cahoon                VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
2373254f889dSBrendon Cahoon         PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
2374dad8c6a1SHiroshi Inoue       // Check if the Phi has already been scheduled, but the loop instruction
2375254f889dSBrendon Cahoon       // is either another Phi, or doesn't occur in the loop.
2376254f889dSBrendon Cahoon       else if (PrologStage >= AccessStage + StageDiff + np) {
2377254f889dSBrendon Cahoon         // If the Phi references another Phi, we need to examine the other
2378254f889dSBrendon Cahoon         // Phi to get the correct value.
2379254f889dSBrendon Cahoon         PhiOp1 = LoopVal;
2380254f889dSBrendon Cahoon         MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
2381254f889dSBrendon Cahoon         int Indirects = 1;
2382254f889dSBrendon Cahoon         while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
2383254f889dSBrendon Cahoon           int PhiStage = Schedule.stageScheduled(getSUnit(InstOp1));
2384254f889dSBrendon Cahoon           if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
2385254f889dSBrendon Cahoon             PhiOp1 = getInitPhiReg(*InstOp1, BB);
2386254f889dSBrendon Cahoon           else
2387254f889dSBrendon Cahoon             PhiOp1 = getLoopPhiReg(*InstOp1, BB);
2388254f889dSBrendon Cahoon           InstOp1 = MRI.getVRegDef(PhiOp1);
2389254f889dSBrendon Cahoon           int PhiOpStage = Schedule.stageScheduled(getSUnit(InstOp1));
2390254f889dSBrendon Cahoon           int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
2391254f889dSBrendon Cahoon           if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
2392254f889dSBrendon Cahoon               VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
2393254f889dSBrendon Cahoon             PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
2394254f889dSBrendon Cahoon             break;
2395254f889dSBrendon Cahoon           }
2396254f889dSBrendon Cahoon           ++Indirects;
2397254f889dSBrendon Cahoon         }
2398254f889dSBrendon Cahoon       } else
2399254f889dSBrendon Cahoon         PhiOp1 = InitVal;
2400254f889dSBrendon Cahoon       // If this references a generated Phi in the kernel, get the Phi operand
2401254f889dSBrendon Cahoon       // from the incoming block.
2402254f889dSBrendon Cahoon       if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
2403254f889dSBrendon Cahoon         if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2404254f889dSBrendon Cahoon           PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2405254f889dSBrendon Cahoon 
2406254f889dSBrendon Cahoon       MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
2407254f889dSBrendon Cahoon       bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
2408254f889dSBrendon Cahoon       // In the epilog, a map lookup is needed to get the value from the kernel,
2409254f889dSBrendon Cahoon       // or previous epilog block. How is does this depends on if the
2410254f889dSBrendon Cahoon       // instruction is scheduled in the previous block.
2411254f889dSBrendon Cahoon       if (!InKernel) {
2412254f889dSBrendon Cahoon         int StageDiffAdj = 0;
2413254f889dSBrendon Cahoon         if (LoopValStage != -1 && StageScheduled > LoopValStage)
2414254f889dSBrendon Cahoon           StageDiffAdj = StageScheduled - LoopValStage;
2415254f889dSBrendon Cahoon         // Use the loop value defined in the kernel, unless the kernel
2416254f889dSBrendon Cahoon         // contains the last definition of the Phi.
2417254f889dSBrendon Cahoon         if (np == 0 && PrevStage == LastStageNum &&
2418254f889dSBrendon Cahoon             (StageScheduled != 0 || LoopValStage != 0) &&
2419254f889dSBrendon Cahoon             VRMap[PrevStage - StageDiffAdj].count(LoopVal))
2420254f889dSBrendon Cahoon           PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
2421254f889dSBrendon Cahoon         // Use the value defined by the Phi. We add one because we switch
2422254f889dSBrendon Cahoon         // from looking at the loop value to the Phi definition.
2423254f889dSBrendon Cahoon         else if (np > 0 && PrevStage == LastStageNum &&
2424254f889dSBrendon Cahoon                  VRMap[PrevStage - np + 1].count(Def))
2425254f889dSBrendon Cahoon           PhiOp2 = VRMap[PrevStage - np + 1][Def];
2426254f889dSBrendon Cahoon         // Use the loop value defined in the kernel.
2427e3841eeaSBrendon Cahoon         else if (static_cast<unsigned>(LoopValStage) > PrologStage + 1 &&
2428254f889dSBrendon Cahoon                  VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
2429254f889dSBrendon Cahoon           PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
2430254f889dSBrendon Cahoon         // Use the value defined by the Phi, unless we're generating the first
2431254f889dSBrendon Cahoon         // epilog and the Phi refers to a Phi in a different stage.
2432254f889dSBrendon Cahoon         else if (VRMap[PrevStage - np].count(Def) &&
2433254f889dSBrendon Cahoon                  (!LoopDefIsPhi || PrevStage != LastStageNum))
2434254f889dSBrendon Cahoon           PhiOp2 = VRMap[PrevStage - np][Def];
2435254f889dSBrendon Cahoon       }
2436254f889dSBrendon Cahoon 
2437254f889dSBrendon Cahoon       // Check if we can reuse an existing Phi. This occurs when a Phi
2438254f889dSBrendon Cahoon       // references another Phi, and the other Phi is scheduled in an
2439254f889dSBrendon Cahoon       // earlier stage. We can try to reuse an existing Phi up until the last
2440254f889dSBrendon Cahoon       // stage of the current Phi.
2441e3841eeaSBrendon Cahoon       if (LoopDefIsPhi) {
2442e3841eeaSBrendon Cahoon         if (static_cast<int>(PrologStage - np) >= StageScheduled) {
2443254f889dSBrendon Cahoon           int LVNumStages = Schedule.getStagesForPhi(LoopVal);
2444254f889dSBrendon Cahoon           int StageDiff = (StageScheduled - LoopValStage);
2445254f889dSBrendon Cahoon           LVNumStages -= StageDiff;
24463a0a15afSKrzysztof Parzyszek           // Make sure the loop value Phi has been processed already.
24473a0a15afSKrzysztof Parzyszek           if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
2448254f889dSBrendon Cahoon             NewReg = PhiOp2;
2449254f889dSBrendon Cahoon             unsigned ReuseStage = CurStageNum;
2450254f889dSBrendon Cahoon             if (Schedule.isLoopCarried(this, *PhiInst))
2451254f889dSBrendon Cahoon               ReuseStage -= LVNumStages;
2452254f889dSBrendon Cahoon             // Check if the Phi to reuse has been generated yet. If not, then
2453254f889dSBrendon Cahoon             // there is nothing to reuse.
245455cb4986SKrzysztof Parzyszek             if (VRMap[ReuseStage - np].count(LoopVal)) {
245555cb4986SKrzysztof Parzyszek               NewReg = VRMap[ReuseStage - np][LoopVal];
2456254f889dSBrendon Cahoon 
2457254f889dSBrendon Cahoon               rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2458254f889dSBrendon Cahoon                                     &*BBI, Def, NewReg);
2459254f889dSBrendon Cahoon               // Update the map with the new Phi name.
2460254f889dSBrendon Cahoon               VRMap[CurStageNum - np][Def] = NewReg;
2461254f889dSBrendon Cahoon               PhiOp2 = NewReg;
2462254f889dSBrendon Cahoon               if (VRMap[LastStageNum - np - 1].count(LoopVal))
2463254f889dSBrendon Cahoon                 PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
2464254f889dSBrendon Cahoon 
2465254f889dSBrendon Cahoon               if (IsLast && np == NumPhis - 1)
2466254f889dSBrendon Cahoon                 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2467254f889dSBrendon Cahoon               continue;
2468254f889dSBrendon Cahoon             }
2469e3841eeaSBrendon Cahoon           }
2470e3841eeaSBrendon Cahoon         }
2471e3841eeaSBrendon Cahoon         if (InKernel && StageDiff > 0 &&
2472254f889dSBrendon Cahoon             VRMap[CurStageNum - StageDiff - np].count(LoopVal))
2473254f889dSBrendon Cahoon           PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
2474254f889dSBrendon Cahoon       }
2475254f889dSBrendon Cahoon 
2476254f889dSBrendon Cahoon       const TargetRegisterClass *RC = MRI.getRegClass(Def);
2477254f889dSBrendon Cahoon       NewReg = MRI.createVirtualRegister(RC);
2478254f889dSBrendon Cahoon 
2479254f889dSBrendon Cahoon       MachineInstrBuilder NewPhi =
2480254f889dSBrendon Cahoon           BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2481254f889dSBrendon Cahoon                   TII->get(TargetOpcode::PHI), NewReg);
2482254f889dSBrendon Cahoon       NewPhi.addReg(PhiOp1).addMBB(BB1);
2483254f889dSBrendon Cahoon       NewPhi.addReg(PhiOp2).addMBB(BB2);
2484254f889dSBrendon Cahoon       if (np == 0)
2485254f889dSBrendon Cahoon         InstrMap[NewPhi] = &*BBI;
2486254f889dSBrendon Cahoon 
2487254f889dSBrendon Cahoon       // We define the Phis after creating the new pipelined code, so
2488254f889dSBrendon Cahoon       // we need to rename the Phi values in scheduled instructions.
2489254f889dSBrendon Cahoon 
2490254f889dSBrendon Cahoon       unsigned PrevReg = 0;
2491254f889dSBrendon Cahoon       if (InKernel && VRMap[PrevStage - np].count(LoopVal))
2492254f889dSBrendon Cahoon         PrevReg = VRMap[PrevStage - np][LoopVal];
2493254f889dSBrendon Cahoon       rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2494254f889dSBrendon Cahoon                             Def, NewReg, PrevReg);
2495254f889dSBrendon Cahoon       // If the Phi has been scheduled, use the new name for rewriting.
2496254f889dSBrendon Cahoon       if (VRMap[CurStageNum - np].count(Def)) {
2497254f889dSBrendon Cahoon         unsigned R = VRMap[CurStageNum - np][Def];
2498254f889dSBrendon Cahoon         rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2499254f889dSBrendon Cahoon                               R, NewReg);
2500254f889dSBrendon Cahoon       }
2501254f889dSBrendon Cahoon 
2502254f889dSBrendon Cahoon       // Check if we need to rename any uses that occurs after the loop. The
2503254f889dSBrendon Cahoon       // register to replace depends on whether the Phi is scheduled in the
2504254f889dSBrendon Cahoon       // epilog.
2505254f889dSBrendon Cahoon       if (IsLast && np == NumPhis - 1)
2506254f889dSBrendon Cahoon         replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2507254f889dSBrendon Cahoon 
2508254f889dSBrendon Cahoon       // In the kernel, a dependent Phi uses the value from this Phi.
2509254f889dSBrendon Cahoon       if (InKernel)
2510254f889dSBrendon Cahoon         PhiOp2 = NewReg;
2511254f889dSBrendon Cahoon 
2512254f889dSBrendon Cahoon       // Update the map with the new Phi name.
2513254f889dSBrendon Cahoon       VRMap[CurStageNum - np][Def] = NewReg;
2514254f889dSBrendon Cahoon     }
2515254f889dSBrendon Cahoon 
2516254f889dSBrendon Cahoon     while (NumPhis++ < NumStages) {
2517254f889dSBrendon Cahoon       rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, NumPhis,
2518254f889dSBrendon Cahoon                             &*BBI, Def, NewReg, 0);
2519254f889dSBrendon Cahoon     }
2520254f889dSBrendon Cahoon 
2521254f889dSBrendon Cahoon     // Check if we need to rename a Phi that has been eliminated due to
2522254f889dSBrendon Cahoon     // scheduling.
2523254f889dSBrendon Cahoon     if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
2524254f889dSBrendon Cahoon       replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
2525254f889dSBrendon Cahoon   }
2526254f889dSBrendon Cahoon }
2527254f889dSBrendon Cahoon 
2528254f889dSBrendon Cahoon /// Generate Phis for the specified block in the generated pipelined code.
2529254f889dSBrendon Cahoon /// These are new Phis needed because the definition is scheduled after the
2530c73b6d6bSHiroshi Inoue /// use in the pipelined sequence.
2531254f889dSBrendon Cahoon void SwingSchedulerDAG::generatePhis(
2532254f889dSBrendon Cahoon     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
2533254f889dSBrendon Cahoon     MachineBasicBlock *KernelBB, SMSchedule &Schedule, ValueMapTy *VRMap,
2534254f889dSBrendon Cahoon     InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
2535254f889dSBrendon Cahoon     bool IsLast) {
2536254f889dSBrendon Cahoon   // Compute the stage number that contains the initial Phi value, and
2537254f889dSBrendon Cahoon   // the Phi from the previous stage.
2538254f889dSBrendon Cahoon   unsigned PrologStage = 0;
2539254f889dSBrendon Cahoon   unsigned PrevStage = 0;
2540254f889dSBrendon Cahoon   unsigned StageDiff = CurStageNum - LastStageNum;
2541254f889dSBrendon Cahoon   bool InKernel = (StageDiff == 0);
2542254f889dSBrendon Cahoon   if (InKernel) {
2543254f889dSBrendon Cahoon     PrologStage = LastStageNum - 1;
2544254f889dSBrendon Cahoon     PrevStage = CurStageNum;
2545254f889dSBrendon Cahoon   } else {
2546254f889dSBrendon Cahoon     PrologStage = LastStageNum - StageDiff;
2547254f889dSBrendon Cahoon     PrevStage = LastStageNum + StageDiff - 1;
2548254f889dSBrendon Cahoon   }
2549254f889dSBrendon Cahoon 
2550254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
2551254f889dSBrendon Cahoon                                    BBE = BB->instr_end();
2552254f889dSBrendon Cahoon        BBI != BBE; ++BBI) {
2553254f889dSBrendon Cahoon     for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
2554254f889dSBrendon Cahoon       MachineOperand &MO = BBI->getOperand(i);
2555254f889dSBrendon Cahoon       if (!MO.isReg() || !MO.isDef() ||
2556254f889dSBrendon Cahoon           !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2557254f889dSBrendon Cahoon         continue;
2558254f889dSBrendon Cahoon 
2559254f889dSBrendon Cahoon       int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2560254f889dSBrendon Cahoon       assert(StageScheduled != -1 && "Expecting scheduled instruction.");
2561254f889dSBrendon Cahoon       unsigned Def = MO.getReg();
2562254f889dSBrendon Cahoon       unsigned NumPhis = Schedule.getStagesForReg(Def, CurStageNum);
2563254f889dSBrendon Cahoon       // An instruction scheduled in stage 0 and is used after the loop
2564254f889dSBrendon Cahoon       // requires a phi in the epilog for the last definition from either
2565254f889dSBrendon Cahoon       // the kernel or prolog.
2566254f889dSBrendon Cahoon       if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
2567254f889dSBrendon Cahoon           hasUseAfterLoop(Def, BB, MRI))
2568254f889dSBrendon Cahoon         NumPhis = 1;
2569254f889dSBrendon Cahoon       if (!InKernel && (unsigned)StageScheduled > PrologStage)
2570254f889dSBrendon Cahoon         continue;
2571254f889dSBrendon Cahoon 
2572254f889dSBrendon Cahoon       unsigned PhiOp2 = VRMap[PrevStage][Def];
2573254f889dSBrendon Cahoon       if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
2574254f889dSBrendon Cahoon         if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
2575254f889dSBrendon Cahoon           PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
2576254f889dSBrendon Cahoon       // The number of Phis can't exceed the number of prolog stages. The
2577254f889dSBrendon Cahoon       // prolog stage number is zero based.
2578254f889dSBrendon Cahoon       if (NumPhis > PrologStage + 1 - StageScheduled)
2579254f889dSBrendon Cahoon         NumPhis = PrologStage + 1 - StageScheduled;
2580254f889dSBrendon Cahoon       for (unsigned np = 0; np < NumPhis; ++np) {
2581254f889dSBrendon Cahoon         unsigned PhiOp1 = VRMap[PrologStage][Def];
2582254f889dSBrendon Cahoon         if (np <= PrologStage)
2583254f889dSBrendon Cahoon           PhiOp1 = VRMap[PrologStage - np][Def];
2584254f889dSBrendon Cahoon         if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) {
2585254f889dSBrendon Cahoon           if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2586254f889dSBrendon Cahoon             PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
2587254f889dSBrendon Cahoon           if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
2588254f889dSBrendon Cahoon             PhiOp1 = getInitPhiReg(*InstOp1, NewBB);
2589254f889dSBrendon Cahoon         }
2590254f889dSBrendon Cahoon         if (!InKernel)
2591254f889dSBrendon Cahoon           PhiOp2 = VRMap[PrevStage - np][Def];
2592254f889dSBrendon Cahoon 
2593254f889dSBrendon Cahoon         const TargetRegisterClass *RC = MRI.getRegClass(Def);
2594254f889dSBrendon Cahoon         unsigned NewReg = MRI.createVirtualRegister(RC);
2595254f889dSBrendon Cahoon 
2596254f889dSBrendon Cahoon         MachineInstrBuilder NewPhi =
2597254f889dSBrendon Cahoon             BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
2598254f889dSBrendon Cahoon                     TII->get(TargetOpcode::PHI), NewReg);
2599254f889dSBrendon Cahoon         NewPhi.addReg(PhiOp1).addMBB(BB1);
2600254f889dSBrendon Cahoon         NewPhi.addReg(PhiOp2).addMBB(BB2);
2601254f889dSBrendon Cahoon         if (np == 0)
2602254f889dSBrendon Cahoon           InstrMap[NewPhi] = &*BBI;
2603254f889dSBrendon Cahoon 
2604254f889dSBrendon Cahoon         // Rewrite uses and update the map. The actions depend upon whether
2605254f889dSBrendon Cahoon         // we generating code for the kernel or epilog blocks.
2606254f889dSBrendon Cahoon         if (InKernel) {
2607254f889dSBrendon Cahoon           rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2608254f889dSBrendon Cahoon                                 &*BBI, PhiOp1, NewReg);
2609254f889dSBrendon Cahoon           rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2610254f889dSBrendon Cahoon                                 &*BBI, PhiOp2, NewReg);
2611254f889dSBrendon Cahoon 
2612254f889dSBrendon Cahoon           PhiOp2 = NewReg;
2613254f889dSBrendon Cahoon           VRMap[PrevStage - np - 1][Def] = NewReg;
2614254f889dSBrendon Cahoon         } else {
2615254f889dSBrendon Cahoon           VRMap[CurStageNum - np][Def] = NewReg;
2616254f889dSBrendon Cahoon           if (np == NumPhis - 1)
2617254f889dSBrendon Cahoon             rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2618254f889dSBrendon Cahoon                                   &*BBI, Def, NewReg);
2619254f889dSBrendon Cahoon         }
2620254f889dSBrendon Cahoon         if (IsLast && np == NumPhis - 1)
2621254f889dSBrendon Cahoon           replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
2622254f889dSBrendon Cahoon       }
2623254f889dSBrendon Cahoon     }
2624254f889dSBrendon Cahoon   }
2625254f889dSBrendon Cahoon }
2626254f889dSBrendon Cahoon 
2627254f889dSBrendon Cahoon /// Remove instructions that generate values with no uses.
2628254f889dSBrendon Cahoon /// Typically, these are induction variable operations that generate values
2629254f889dSBrendon Cahoon /// used in the loop itself.  A dead instruction has a definition with
2630254f889dSBrendon Cahoon /// no uses, or uses that occur in the original loop only.
2631254f889dSBrendon Cahoon void SwingSchedulerDAG::removeDeadInstructions(MachineBasicBlock *KernelBB,
2632254f889dSBrendon Cahoon                                                MBBVectorTy &EpilogBBs) {
2633254f889dSBrendon Cahoon   // For each epilog block, check that the value defined by each instruction
2634254f889dSBrendon Cahoon   // is used.  If not, delete it.
2635254f889dSBrendon Cahoon   for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(),
2636254f889dSBrendon Cahoon                                      MBE = EpilogBBs.rend();
2637254f889dSBrendon Cahoon        MBB != MBE; ++MBB)
2638254f889dSBrendon Cahoon     for (MachineBasicBlock::reverse_instr_iterator MI = (*MBB)->instr_rbegin(),
2639254f889dSBrendon Cahoon                                                    ME = (*MBB)->instr_rend();
2640254f889dSBrendon Cahoon          MI != ME;) {
2641254f889dSBrendon Cahoon       // From DeadMachineInstructionElem. Don't delete inline assembly.
2642254f889dSBrendon Cahoon       if (MI->isInlineAsm()) {
2643254f889dSBrendon Cahoon         ++MI;
2644254f889dSBrendon Cahoon         continue;
2645254f889dSBrendon Cahoon       }
2646254f889dSBrendon Cahoon       bool SawStore = false;
2647254f889dSBrendon Cahoon       // Check if it's safe to remove the instruction due to side effects.
2648254f889dSBrendon Cahoon       // We can, and want to, remove Phis here.
2649254f889dSBrendon Cahoon       if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
2650254f889dSBrendon Cahoon         ++MI;
2651254f889dSBrendon Cahoon         continue;
2652254f889dSBrendon Cahoon       }
2653254f889dSBrendon Cahoon       bool used = true;
2654254f889dSBrendon Cahoon       for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
2655254f889dSBrendon Cahoon                                       MOE = MI->operands_end();
2656254f889dSBrendon Cahoon            MOI != MOE; ++MOI) {
2657254f889dSBrendon Cahoon         if (!MOI->isReg() || !MOI->isDef())
2658254f889dSBrendon Cahoon           continue;
2659254f889dSBrendon Cahoon         unsigned reg = MOI->getReg();
2660b9b75b8cSKrzysztof Parzyszek         // Assume physical registers are used, unless they are marked dead.
2661b9b75b8cSKrzysztof Parzyszek         if (TargetRegisterInfo::isPhysicalRegister(reg)) {
2662b9b75b8cSKrzysztof Parzyszek           used = !MOI->isDead();
2663b9b75b8cSKrzysztof Parzyszek           if (used)
2664b9b75b8cSKrzysztof Parzyszek             break;
2665b9b75b8cSKrzysztof Parzyszek           continue;
2666b9b75b8cSKrzysztof Parzyszek         }
2667254f889dSBrendon Cahoon         unsigned realUses = 0;
2668254f889dSBrendon Cahoon         for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(reg),
2669254f889dSBrendon Cahoon                                                EI = MRI.use_end();
2670254f889dSBrendon Cahoon              UI != EI; ++UI) {
2671254f889dSBrendon Cahoon           // Check if there are any uses that occur only in the original
2672254f889dSBrendon Cahoon           // loop.  If so, that's not a real use.
2673254f889dSBrendon Cahoon           if (UI->getParent()->getParent() != BB) {
2674254f889dSBrendon Cahoon             realUses++;
2675254f889dSBrendon Cahoon             used = true;
2676254f889dSBrendon Cahoon             break;
2677254f889dSBrendon Cahoon           }
2678254f889dSBrendon Cahoon         }
2679254f889dSBrendon Cahoon         if (realUses > 0)
2680254f889dSBrendon Cahoon           break;
2681254f889dSBrendon Cahoon         used = false;
2682254f889dSBrendon Cahoon       }
2683254f889dSBrendon Cahoon       if (!used) {
2684c715a5d2SKrzysztof Parzyszek         LIS.RemoveMachineInstrFromMaps(*MI);
26855c001c36SDuncan P. N. Exon Smith         MI++->eraseFromParent();
2686254f889dSBrendon Cahoon         continue;
2687254f889dSBrendon Cahoon       }
2688254f889dSBrendon Cahoon       ++MI;
2689254f889dSBrendon Cahoon     }
2690254f889dSBrendon Cahoon   // In the kernel block, check if we can remove a Phi that generates a value
2691254f889dSBrendon Cahoon   // used in an instruction removed in the epilog block.
2692254f889dSBrendon Cahoon   for (MachineBasicBlock::iterator BBI = KernelBB->instr_begin(),
2693254f889dSBrendon Cahoon                                    BBE = KernelBB->getFirstNonPHI();
2694254f889dSBrendon Cahoon        BBI != BBE;) {
2695254f889dSBrendon Cahoon     MachineInstr *MI = &*BBI;
2696254f889dSBrendon Cahoon     ++BBI;
2697254f889dSBrendon Cahoon     unsigned reg = MI->getOperand(0).getReg();
2698254f889dSBrendon Cahoon     if (MRI.use_begin(reg) == MRI.use_end()) {
2699c715a5d2SKrzysztof Parzyszek       LIS.RemoveMachineInstrFromMaps(*MI);
2700254f889dSBrendon Cahoon       MI->eraseFromParent();
2701254f889dSBrendon Cahoon     }
2702254f889dSBrendon Cahoon   }
2703254f889dSBrendon Cahoon }
2704254f889dSBrendon Cahoon 
2705254f889dSBrendon Cahoon /// For loop carried definitions, we split the lifetime of a virtual register
2706254f889dSBrendon Cahoon /// that has uses past the definition in the next iteration. A copy with a new
2707254f889dSBrendon Cahoon /// virtual register is inserted before the definition, which helps with
2708254f889dSBrendon Cahoon /// generating a better register assignment.
2709254f889dSBrendon Cahoon ///
2710254f889dSBrendon Cahoon ///   v1 = phi(a, v2)     v1 = phi(a, v2)
2711254f889dSBrendon Cahoon ///   v2 = phi(b, v3)     v2 = phi(b, v3)
2712254f889dSBrendon Cahoon ///   v3 = ..             v4 = copy v1
2713254f889dSBrendon Cahoon ///   .. = V1             v3 = ..
2714254f889dSBrendon Cahoon ///                       .. = v4
2715254f889dSBrendon Cahoon void SwingSchedulerDAG::splitLifetimes(MachineBasicBlock *KernelBB,
2716254f889dSBrendon Cahoon                                        MBBVectorTy &EpilogBBs,
2717254f889dSBrendon Cahoon                                        SMSchedule &Schedule) {
2718254f889dSBrendon Cahoon   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
271990ecac01SBob Wilson   for (auto &PHI : KernelBB->phis()) {
272090ecac01SBob Wilson     unsigned Def = PHI.getOperand(0).getReg();
2721254f889dSBrendon Cahoon     // Check for any Phi definition that used as an operand of another Phi
2722254f889dSBrendon Cahoon     // in the same block.
2723254f889dSBrendon Cahoon     for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
2724254f889dSBrendon Cahoon                                                  E = MRI.use_instr_end();
2725254f889dSBrendon Cahoon          I != E; ++I) {
2726254f889dSBrendon Cahoon       if (I->isPHI() && I->getParent() == KernelBB) {
2727254f889dSBrendon Cahoon         // Get the loop carried definition.
272890ecac01SBob Wilson         unsigned LCDef = getLoopPhiReg(PHI, KernelBB);
2729254f889dSBrendon Cahoon         if (!LCDef)
2730254f889dSBrendon Cahoon           continue;
2731254f889dSBrendon Cahoon         MachineInstr *MI = MRI.getVRegDef(LCDef);
2732254f889dSBrendon Cahoon         if (!MI || MI->getParent() != KernelBB || MI->isPHI())
2733254f889dSBrendon Cahoon           continue;
2734254f889dSBrendon Cahoon         // Search through the rest of the block looking for uses of the Phi
2735254f889dSBrendon Cahoon         // definition. If one occurs, then split the lifetime.
2736254f889dSBrendon Cahoon         unsigned SplitReg = 0;
2737254f889dSBrendon Cahoon         for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
2738254f889dSBrendon Cahoon                                     KernelBB->instr_end()))
2739254f889dSBrendon Cahoon           if (BBJ.readsRegister(Def)) {
2740254f889dSBrendon Cahoon             // We split the lifetime when we find the first use.
2741254f889dSBrendon Cahoon             if (SplitReg == 0) {
2742254f889dSBrendon Cahoon               SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
2743254f889dSBrendon Cahoon               BuildMI(*KernelBB, MI, MI->getDebugLoc(),
2744254f889dSBrendon Cahoon                       TII->get(TargetOpcode::COPY), SplitReg)
2745254f889dSBrendon Cahoon                   .addReg(Def);
2746254f889dSBrendon Cahoon             }
2747254f889dSBrendon Cahoon             BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
2748254f889dSBrendon Cahoon           }
2749254f889dSBrendon Cahoon         if (!SplitReg)
2750254f889dSBrendon Cahoon           continue;
2751254f889dSBrendon Cahoon         // Search through each of the epilog blocks for any uses to be renamed.
2752254f889dSBrendon Cahoon         for (auto &Epilog : EpilogBBs)
2753254f889dSBrendon Cahoon           for (auto &I : *Epilog)
2754254f889dSBrendon Cahoon             if (I.readsRegister(Def))
2755254f889dSBrendon Cahoon               I.substituteRegister(Def, SplitReg, 0, *TRI);
2756254f889dSBrendon Cahoon         break;
2757254f889dSBrendon Cahoon       }
2758254f889dSBrendon Cahoon     }
2759254f889dSBrendon Cahoon   }
2760254f889dSBrendon Cahoon }
2761254f889dSBrendon Cahoon 
2762254f889dSBrendon Cahoon /// Remove the incoming block from the Phis in a basic block.
2763254f889dSBrendon Cahoon static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
2764254f889dSBrendon Cahoon   for (MachineInstr &MI : *BB) {
2765254f889dSBrendon Cahoon     if (!MI.isPHI())
2766254f889dSBrendon Cahoon       break;
2767254f889dSBrendon Cahoon     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
2768254f889dSBrendon Cahoon       if (MI.getOperand(i + 1).getMBB() == Incoming) {
2769254f889dSBrendon Cahoon         MI.RemoveOperand(i + 1);
2770254f889dSBrendon Cahoon         MI.RemoveOperand(i);
2771254f889dSBrendon Cahoon         break;
2772254f889dSBrendon Cahoon       }
2773254f889dSBrendon Cahoon   }
2774254f889dSBrendon Cahoon }
2775254f889dSBrendon Cahoon 
2776254f889dSBrendon Cahoon /// Create branches from each prolog basic block to the appropriate epilog
2777254f889dSBrendon Cahoon /// block.  These edges are needed if the loop ends before reaching the
2778254f889dSBrendon Cahoon /// kernel.
2779ef2d6d99SJinsong Ji void SwingSchedulerDAG::addBranches(MachineBasicBlock &PreheaderBB,
2780ef2d6d99SJinsong Ji                                     MBBVectorTy &PrologBBs,
2781254f889dSBrendon Cahoon                                     MachineBasicBlock *KernelBB,
2782254f889dSBrendon Cahoon                                     MBBVectorTy &EpilogBBs,
2783254f889dSBrendon Cahoon                                     SMSchedule &Schedule, ValueMapTy *VRMap) {
2784254f889dSBrendon Cahoon   assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
2785254f889dSBrendon Cahoon   MachineInstr *IndVar = Pass.LI.LoopInductionVar;
2786254f889dSBrendon Cahoon   MachineInstr *Cmp = Pass.LI.LoopCompare;
2787254f889dSBrendon Cahoon   MachineBasicBlock *LastPro = KernelBB;
2788254f889dSBrendon Cahoon   MachineBasicBlock *LastEpi = KernelBB;
2789254f889dSBrendon Cahoon 
2790254f889dSBrendon Cahoon   // Start from the blocks connected to the kernel and work "out"
2791254f889dSBrendon Cahoon   // to the first prolog and the last epilog blocks.
2792254f889dSBrendon Cahoon   SmallVector<MachineInstr *, 4> PrevInsts;
2793254f889dSBrendon Cahoon   unsigned MaxIter = PrologBBs.size() - 1;
2794254f889dSBrendon Cahoon   unsigned LC = UINT_MAX;
2795254f889dSBrendon Cahoon   unsigned LCMin = UINT_MAX;
2796254f889dSBrendon Cahoon   for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
2797254f889dSBrendon Cahoon     // Add branches to the prolog that go to the corresponding
2798254f889dSBrendon Cahoon     // epilog, and the fall-thru prolog/kernel block.
2799254f889dSBrendon Cahoon     MachineBasicBlock *Prolog = PrologBBs[j];
2800254f889dSBrendon Cahoon     MachineBasicBlock *Epilog = EpilogBBs[i];
2801254f889dSBrendon Cahoon     // We've executed one iteration, so decrement the loop count and check for
2802254f889dSBrendon Cahoon     // the loop end.
2803254f889dSBrendon Cahoon     SmallVector<MachineOperand, 4> Cond;
2804254f889dSBrendon Cahoon     // Check if the LOOP0 has already been removed. If so, then there is no need
2805254f889dSBrendon Cahoon     // to reduce the trip count.
2806254f889dSBrendon Cahoon     if (LC != 0)
2807ef2d6d99SJinsong Ji       LC = TII->reduceLoopCount(*Prolog, PreheaderBB, IndVar, *Cmp, Cond,
2808ef2d6d99SJinsong Ji                                 PrevInsts, j, MaxIter);
2809254f889dSBrendon Cahoon 
2810254f889dSBrendon Cahoon     // Record the value of the first trip count, which is used to determine if
2811254f889dSBrendon Cahoon     // branches and blocks can be removed for constant trip counts.
2812254f889dSBrendon Cahoon     if (LCMin == UINT_MAX)
2813254f889dSBrendon Cahoon       LCMin = LC;
2814254f889dSBrendon Cahoon 
2815254f889dSBrendon Cahoon     unsigned numAdded = 0;
2816254f889dSBrendon Cahoon     if (TargetRegisterInfo::isVirtualRegister(LC)) {
2817254f889dSBrendon Cahoon       Prolog->addSuccessor(Epilog);
2818e8e0f5caSMatt Arsenault       numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
2819254f889dSBrendon Cahoon     } else if (j >= LCMin) {
2820254f889dSBrendon Cahoon       Prolog->addSuccessor(Epilog);
2821254f889dSBrendon Cahoon       Prolog->removeSuccessor(LastPro);
2822254f889dSBrendon Cahoon       LastEpi->removeSuccessor(Epilog);
2823e8e0f5caSMatt Arsenault       numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
2824254f889dSBrendon Cahoon       removePhis(Epilog, LastEpi);
2825254f889dSBrendon Cahoon       // Remove the blocks that are no longer referenced.
2826254f889dSBrendon Cahoon       if (LastPro != LastEpi) {
2827254f889dSBrendon Cahoon         LastEpi->clear();
2828254f889dSBrendon Cahoon         LastEpi->eraseFromParent();
2829254f889dSBrendon Cahoon       }
2830254f889dSBrendon Cahoon       LastPro->clear();
2831254f889dSBrendon Cahoon       LastPro->eraseFromParent();
2832254f889dSBrendon Cahoon     } else {
2833e8e0f5caSMatt Arsenault       numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
2834254f889dSBrendon Cahoon       removePhis(Epilog, Prolog);
2835254f889dSBrendon Cahoon     }
2836254f889dSBrendon Cahoon     LastPro = Prolog;
2837254f889dSBrendon Cahoon     LastEpi = Epilog;
2838254f889dSBrendon Cahoon     for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
2839254f889dSBrendon Cahoon                                                    E = Prolog->instr_rend();
2840254f889dSBrendon Cahoon          I != E && numAdded > 0; ++I, --numAdded)
2841254f889dSBrendon Cahoon       updateInstruction(&*I, false, j, 0, Schedule, VRMap);
2842254f889dSBrendon Cahoon   }
2843254f889dSBrendon Cahoon }
2844254f889dSBrendon Cahoon 
2845254f889dSBrendon Cahoon /// Return true if we can compute the amount the instruction changes
2846254f889dSBrendon Cahoon /// during each iteration. Set Delta to the amount of the change.
2847254f889dSBrendon Cahoon bool SwingSchedulerDAG::computeDelta(MachineInstr &MI, unsigned &Delta) {
2848254f889dSBrendon Cahoon   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2849238c9d63SBjorn Pettersson   const MachineOperand *BaseOp;
2850254f889dSBrendon Cahoon   int64_t Offset;
2851d7eebd6dSFrancis Visoiu Mistrih   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI))
2852254f889dSBrendon Cahoon     return false;
2853254f889dSBrendon Cahoon 
2854d7eebd6dSFrancis Visoiu Mistrih   if (!BaseOp->isReg())
2855d7eebd6dSFrancis Visoiu Mistrih     return false;
2856d7eebd6dSFrancis Visoiu Mistrih 
2857d7eebd6dSFrancis Visoiu Mistrih   unsigned BaseReg = BaseOp->getReg();
2858d7eebd6dSFrancis Visoiu Mistrih 
2859254f889dSBrendon Cahoon   MachineRegisterInfo &MRI = MF.getRegInfo();
2860254f889dSBrendon Cahoon   // Check if there is a Phi. If so, get the definition in the loop.
2861254f889dSBrendon Cahoon   MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
2862254f889dSBrendon Cahoon   if (BaseDef && BaseDef->isPHI()) {
2863254f889dSBrendon Cahoon     BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
2864254f889dSBrendon Cahoon     BaseDef = MRI.getVRegDef(BaseReg);
2865254f889dSBrendon Cahoon   }
2866254f889dSBrendon Cahoon   if (!BaseDef)
2867254f889dSBrendon Cahoon     return false;
2868254f889dSBrendon Cahoon 
2869254f889dSBrendon Cahoon   int D = 0;
28708fb181caSKrzysztof Parzyszek   if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
2871254f889dSBrendon Cahoon     return false;
2872254f889dSBrendon Cahoon 
2873254f889dSBrendon Cahoon   Delta = D;
2874254f889dSBrendon Cahoon   return true;
2875254f889dSBrendon Cahoon }
2876254f889dSBrendon Cahoon 
2877254f889dSBrendon Cahoon /// Update the memory operand with a new offset when the pipeliner
2878cf56e92cSJustin Lebar /// generates a new copy of the instruction that refers to a
2879254f889dSBrendon Cahoon /// different memory location.
2880254f889dSBrendon Cahoon void SwingSchedulerDAG::updateMemOperands(MachineInstr &NewMI,
2881254f889dSBrendon Cahoon                                           MachineInstr &OldMI, unsigned Num) {
2882254f889dSBrendon Cahoon   if (Num == 0)
2883254f889dSBrendon Cahoon     return;
2884254f889dSBrendon Cahoon   // If the instruction has memory operands, then adjust the offset
2885254f889dSBrendon Cahoon   // when the instruction appears in different stages.
2886c73c0307SChandler Carruth   if (NewMI.memoperands_empty())
2887254f889dSBrendon Cahoon     return;
2888c73c0307SChandler Carruth   SmallVector<MachineMemOperand *, 2> NewMMOs;
28890a33a7aeSJustin Lebar   for (MachineMemOperand *MMO : NewMI.memoperands()) {
289000056ed0SPhilip Reames     // TODO: Figure out whether isAtomic is really necessary (see D57601).
289100056ed0SPhilip Reames     if (MMO->isVolatile() || MMO->isAtomic() ||
289200056ed0SPhilip Reames         (MMO->isInvariant() && MMO->isDereferenceable()) ||
2893adbf09e8SJustin Lebar         (!MMO->getValue())) {
2894c73c0307SChandler Carruth       NewMMOs.push_back(MMO);
2895254f889dSBrendon Cahoon       continue;
2896254f889dSBrendon Cahoon     }
2897254f889dSBrendon Cahoon     unsigned Delta;
2898785b6cecSKrzysztof Parzyszek     if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
2899254f889dSBrendon Cahoon       int64_t AdjOffset = Delta * Num;
2900c73c0307SChandler Carruth       NewMMOs.push_back(
2901c73c0307SChandler Carruth           MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize()));
29022d79017dSKrzysztof Parzyszek     } else {
2903cc3f6302SKrzysztof Parzyszek       NewMMOs.push_back(
2904cc3f6302SKrzysztof Parzyszek           MF.getMachineMemOperand(MMO, 0, MemoryLocation::UnknownSize));
29052d79017dSKrzysztof Parzyszek     }
2906254f889dSBrendon Cahoon   }
2907c73c0307SChandler Carruth   NewMI.setMemRefs(MF, NewMMOs);
2908254f889dSBrendon Cahoon }
2909254f889dSBrendon Cahoon 
2910254f889dSBrendon Cahoon /// Clone the instruction for the new pipelined loop and update the
2911254f889dSBrendon Cahoon /// memory operands, if needed.
2912254f889dSBrendon Cahoon MachineInstr *SwingSchedulerDAG::cloneInstr(MachineInstr *OldMI,
2913254f889dSBrendon Cahoon                                             unsigned CurStageNum,
2914254f889dSBrendon Cahoon                                             unsigned InstStageNum) {
2915254f889dSBrendon Cahoon   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
2916254f889dSBrendon Cahoon   // Check for tied operands in inline asm instructions. This should be handled
2917254f889dSBrendon Cahoon   // elsewhere, but I'm not sure of the best solution.
2918254f889dSBrendon Cahoon   if (OldMI->isInlineAsm())
2919254f889dSBrendon Cahoon     for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
2920254f889dSBrendon Cahoon       const auto &MO = OldMI->getOperand(i);
2921254f889dSBrendon Cahoon       if (MO.isReg() && MO.isUse())
2922254f889dSBrendon Cahoon         break;
2923254f889dSBrendon Cahoon       unsigned UseIdx;
2924254f889dSBrendon Cahoon       if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
2925254f889dSBrendon Cahoon         NewMI->tieOperands(i, UseIdx);
2926254f889dSBrendon Cahoon     }
2927254f889dSBrendon Cahoon   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
2928254f889dSBrendon Cahoon   return NewMI;
2929254f889dSBrendon Cahoon }
2930254f889dSBrendon Cahoon 
2931254f889dSBrendon Cahoon /// Clone the instruction for the new pipelined loop. If needed, this
2932254f889dSBrendon Cahoon /// function updates the instruction using the values saved in the
2933254f889dSBrendon Cahoon /// InstrChanges structure.
2934254f889dSBrendon Cahoon MachineInstr *SwingSchedulerDAG::cloneAndChangeInstr(MachineInstr *OldMI,
2935254f889dSBrendon Cahoon                                                      unsigned CurStageNum,
2936254f889dSBrendon Cahoon                                                      unsigned InstStageNum,
2937254f889dSBrendon Cahoon                                                      SMSchedule &Schedule) {
2938254f889dSBrendon Cahoon   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
2939254f889dSBrendon Cahoon   DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
2940254f889dSBrendon Cahoon       InstrChanges.find(getSUnit(OldMI));
2941254f889dSBrendon Cahoon   if (It != InstrChanges.end()) {
2942254f889dSBrendon Cahoon     std::pair<unsigned, int64_t> RegAndOffset = It->second;
2943254f889dSBrendon Cahoon     unsigned BasePos, OffsetPos;
29448fb181caSKrzysztof Parzyszek     if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
2945254f889dSBrendon Cahoon       return nullptr;
2946254f889dSBrendon Cahoon     int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
2947254f889dSBrendon Cahoon     MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
2948254f889dSBrendon Cahoon     if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum)
2949254f889dSBrendon Cahoon       NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
2950254f889dSBrendon Cahoon     NewMI->getOperand(OffsetPos).setImm(NewOffset);
2951254f889dSBrendon Cahoon   }
2952254f889dSBrendon Cahoon   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
2953254f889dSBrendon Cahoon   return NewMI;
2954254f889dSBrendon Cahoon }
2955254f889dSBrendon Cahoon 
2956254f889dSBrendon Cahoon /// Update the machine instruction with new virtual registers.  This
2957254f889dSBrendon Cahoon /// function may change the defintions and/or uses.
2958254f889dSBrendon Cahoon void SwingSchedulerDAG::updateInstruction(MachineInstr *NewMI, bool LastDef,
2959254f889dSBrendon Cahoon                                           unsigned CurStageNum,
2960254f889dSBrendon Cahoon                                           unsigned InstrStageNum,
2961254f889dSBrendon Cahoon                                           SMSchedule &Schedule,
2962254f889dSBrendon Cahoon                                           ValueMapTy *VRMap) {
2963254f889dSBrendon Cahoon   for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
2964254f889dSBrendon Cahoon     MachineOperand &MO = NewMI->getOperand(i);
2965254f889dSBrendon Cahoon     if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2966254f889dSBrendon Cahoon       continue;
2967254f889dSBrendon Cahoon     unsigned reg = MO.getReg();
2968254f889dSBrendon Cahoon     if (MO.isDef()) {
2969254f889dSBrendon Cahoon       // Create a new virtual register for the definition.
2970254f889dSBrendon Cahoon       const TargetRegisterClass *RC = MRI.getRegClass(reg);
2971254f889dSBrendon Cahoon       unsigned NewReg = MRI.createVirtualRegister(RC);
2972254f889dSBrendon Cahoon       MO.setReg(NewReg);
2973254f889dSBrendon Cahoon       VRMap[CurStageNum][reg] = NewReg;
2974254f889dSBrendon Cahoon       if (LastDef)
2975254f889dSBrendon Cahoon         replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
2976254f889dSBrendon Cahoon     } else if (MO.isUse()) {
2977254f889dSBrendon Cahoon       MachineInstr *Def = MRI.getVRegDef(reg);
2978254f889dSBrendon Cahoon       // Compute the stage that contains the last definition for instruction.
2979254f889dSBrendon Cahoon       int DefStageNum = Schedule.stageScheduled(getSUnit(Def));
2980254f889dSBrendon Cahoon       unsigned StageNum = CurStageNum;
2981254f889dSBrendon Cahoon       if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
2982254f889dSBrendon Cahoon         // Compute the difference in stages between the defintion and the use.
2983254f889dSBrendon Cahoon         unsigned StageDiff = (InstrStageNum - DefStageNum);
2984254f889dSBrendon Cahoon         // Make an adjustment to get the last definition.
2985254f889dSBrendon Cahoon         StageNum -= StageDiff;
2986254f889dSBrendon Cahoon       }
2987254f889dSBrendon Cahoon       if (VRMap[StageNum].count(reg))
2988254f889dSBrendon Cahoon         MO.setReg(VRMap[StageNum][reg]);
2989254f889dSBrendon Cahoon     }
2990254f889dSBrendon Cahoon   }
2991254f889dSBrendon Cahoon }
2992254f889dSBrendon Cahoon 
2993254f889dSBrendon Cahoon /// Return the instruction in the loop that defines the register.
2994254f889dSBrendon Cahoon /// If the definition is a Phi, then follow the Phi operand to
2995254f889dSBrendon Cahoon /// the instruction in the loop.
2996254f889dSBrendon Cahoon MachineInstr *SwingSchedulerDAG::findDefInLoop(unsigned Reg) {
2997254f889dSBrendon Cahoon   SmallPtrSet<MachineInstr *, 8> Visited;
2998254f889dSBrendon Cahoon   MachineInstr *Def = MRI.getVRegDef(Reg);
2999254f889dSBrendon Cahoon   while (Def->isPHI()) {
3000254f889dSBrendon Cahoon     if (!Visited.insert(Def).second)
3001254f889dSBrendon Cahoon       break;
3002254f889dSBrendon Cahoon     for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
3003254f889dSBrendon Cahoon       if (Def->getOperand(i + 1).getMBB() == BB) {
3004254f889dSBrendon Cahoon         Def = MRI.getVRegDef(Def->getOperand(i).getReg());
3005254f889dSBrendon Cahoon         break;
3006254f889dSBrendon Cahoon       }
3007254f889dSBrendon Cahoon   }
3008254f889dSBrendon Cahoon   return Def;
3009254f889dSBrendon Cahoon }
3010254f889dSBrendon Cahoon 
3011254f889dSBrendon Cahoon /// Return the new name for the value from the previous stage.
3012254f889dSBrendon Cahoon unsigned SwingSchedulerDAG::getPrevMapVal(unsigned StageNum, unsigned PhiStage,
3013254f889dSBrendon Cahoon                                           unsigned LoopVal, unsigned LoopStage,
3014254f889dSBrendon Cahoon                                           ValueMapTy *VRMap,
3015254f889dSBrendon Cahoon                                           MachineBasicBlock *BB) {
3016254f889dSBrendon Cahoon   unsigned PrevVal = 0;
3017254f889dSBrendon Cahoon   if (StageNum > PhiStage) {
3018254f889dSBrendon Cahoon     MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
3019254f889dSBrendon Cahoon     if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
3020254f889dSBrendon Cahoon       // The name is defined in the previous stage.
3021254f889dSBrendon Cahoon       PrevVal = VRMap[StageNum - 1][LoopVal];
3022254f889dSBrendon Cahoon     else if (VRMap[StageNum].count(LoopVal))
3023254f889dSBrendon Cahoon       // The previous name is defined in the current stage when the instruction
3024254f889dSBrendon Cahoon       // order is swapped.
3025254f889dSBrendon Cahoon       PrevVal = VRMap[StageNum][LoopVal];
3026df24da22SKrzysztof Parzyszek     else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
3027254f889dSBrendon Cahoon       // The loop value hasn't yet been scheduled.
3028254f889dSBrendon Cahoon       PrevVal = LoopVal;
3029254f889dSBrendon Cahoon     else if (StageNum == PhiStage + 1)
3030254f889dSBrendon Cahoon       // The loop value is another phi, which has not been scheduled.
3031254f889dSBrendon Cahoon       PrevVal = getInitPhiReg(*LoopInst, BB);
3032254f889dSBrendon Cahoon     else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
3033254f889dSBrendon Cahoon       // The loop value is another phi, which has been scheduled.
3034254f889dSBrendon Cahoon       PrevVal =
3035254f889dSBrendon Cahoon           getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
3036254f889dSBrendon Cahoon                         LoopStage, VRMap, BB);
3037254f889dSBrendon Cahoon   }
3038254f889dSBrendon Cahoon   return PrevVal;
3039254f889dSBrendon Cahoon }
3040254f889dSBrendon Cahoon 
3041254f889dSBrendon Cahoon /// Rewrite the Phi values in the specified block to use the mappings
3042254f889dSBrendon Cahoon /// from the initial operand. Once the Phi is scheduled, we switch
3043254f889dSBrendon Cahoon /// to using the loop value instead of the Phi value, so those names
3044254f889dSBrendon Cahoon /// do not need to be rewritten.
3045254f889dSBrendon Cahoon void SwingSchedulerDAG::rewritePhiValues(MachineBasicBlock *NewBB,
3046254f889dSBrendon Cahoon                                          unsigned StageNum,
3047254f889dSBrendon Cahoon                                          SMSchedule &Schedule,
3048254f889dSBrendon Cahoon                                          ValueMapTy *VRMap,
3049254f889dSBrendon Cahoon                                          InstrMapTy &InstrMap) {
305090ecac01SBob Wilson   for (auto &PHI : BB->phis()) {
3051254f889dSBrendon Cahoon     unsigned InitVal = 0;
3052254f889dSBrendon Cahoon     unsigned LoopVal = 0;
305390ecac01SBob Wilson     getPhiRegs(PHI, BB, InitVal, LoopVal);
305490ecac01SBob Wilson     unsigned PhiDef = PHI.getOperand(0).getReg();
3055254f889dSBrendon Cahoon 
3056254f889dSBrendon Cahoon     unsigned PhiStage =
3057254f889dSBrendon Cahoon         (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(PhiDef)));
3058254f889dSBrendon Cahoon     unsigned LoopStage =
3059254f889dSBrendon Cahoon         (unsigned)Schedule.stageScheduled(getSUnit(MRI.getVRegDef(LoopVal)));
3060254f889dSBrendon Cahoon     unsigned NumPhis = Schedule.getStagesForPhi(PhiDef);
3061254f889dSBrendon Cahoon     if (NumPhis > StageNum)
3062254f889dSBrendon Cahoon       NumPhis = StageNum;
3063254f889dSBrendon Cahoon     for (unsigned np = 0; np <= NumPhis; ++np) {
3064254f889dSBrendon Cahoon       unsigned NewVal =
3065254f889dSBrendon Cahoon           getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
3066254f889dSBrendon Cahoon       if (!NewVal)
3067254f889dSBrendon Cahoon         NewVal = InitVal;
306890ecac01SBob Wilson       rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &PHI,
3069254f889dSBrendon Cahoon                             PhiDef, NewVal);
3070254f889dSBrendon Cahoon     }
3071254f889dSBrendon Cahoon   }
3072254f889dSBrendon Cahoon }
3073254f889dSBrendon Cahoon 
3074254f889dSBrendon Cahoon /// Rewrite a previously scheduled instruction to use the register value
3075254f889dSBrendon Cahoon /// from the new instruction. Make sure the instruction occurs in the
3076254f889dSBrendon Cahoon /// basic block, and we don't change the uses in the new instruction.
3077254f889dSBrendon Cahoon void SwingSchedulerDAG::rewriteScheduledInstr(
3078254f889dSBrendon Cahoon     MachineBasicBlock *BB, SMSchedule &Schedule, InstrMapTy &InstrMap,
3079254f889dSBrendon Cahoon     unsigned CurStageNum, unsigned PhiNum, MachineInstr *Phi, unsigned OldReg,
3080254f889dSBrendon Cahoon     unsigned NewReg, unsigned PrevReg) {
3081254f889dSBrendon Cahoon   bool InProlog = (CurStageNum < Schedule.getMaxStageCount());
3082254f889dSBrendon Cahoon   int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum;
3083254f889dSBrendon Cahoon   // Rewrite uses that have been scheduled already to use the new
3084254f889dSBrendon Cahoon   // Phi register.
3085254f889dSBrendon Cahoon   for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(OldReg),
3086254f889dSBrendon Cahoon                                          EI = MRI.use_end();
3087254f889dSBrendon Cahoon        UI != EI;) {
3088254f889dSBrendon Cahoon     MachineOperand &UseOp = *UI;
3089254f889dSBrendon Cahoon     MachineInstr *UseMI = UseOp.getParent();
3090254f889dSBrendon Cahoon     ++UI;
3091254f889dSBrendon Cahoon     if (UseMI->getParent() != BB)
3092254f889dSBrendon Cahoon       continue;
3093254f889dSBrendon Cahoon     if (UseMI->isPHI()) {
3094254f889dSBrendon Cahoon       if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
3095254f889dSBrendon Cahoon         continue;
3096254f889dSBrendon Cahoon       if (getLoopPhiReg(*UseMI, BB) != OldReg)
3097254f889dSBrendon Cahoon         continue;
3098254f889dSBrendon Cahoon     }
3099254f889dSBrendon Cahoon     InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
3100254f889dSBrendon Cahoon     assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
3101254f889dSBrendon Cahoon     SUnit *OrigMISU = getSUnit(OrigInstr->second);
3102254f889dSBrendon Cahoon     int StageSched = Schedule.stageScheduled(OrigMISU);
3103254f889dSBrendon Cahoon     int CycleSched = Schedule.cycleScheduled(OrigMISU);
3104254f889dSBrendon Cahoon     unsigned ReplaceReg = 0;
3105254f889dSBrendon Cahoon     // This is the stage for the scheduled instruction.
3106254f889dSBrendon Cahoon     if (StagePhi == StageSched && Phi->isPHI()) {
3107254f889dSBrendon Cahoon       int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi));
3108254f889dSBrendon Cahoon       if (PrevReg && InProlog)
3109254f889dSBrendon Cahoon         ReplaceReg = PrevReg;
3110254f889dSBrendon Cahoon       else if (PrevReg && !Schedule.isLoopCarried(this, *Phi) &&
3111254f889dSBrendon Cahoon                (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI()))
3112254f889dSBrendon Cahoon         ReplaceReg = PrevReg;
3113254f889dSBrendon Cahoon       else
3114254f889dSBrendon Cahoon         ReplaceReg = NewReg;
3115254f889dSBrendon Cahoon     }
3116254f889dSBrendon Cahoon     // The scheduled instruction occurs before the scheduled Phi, and the
3117254f889dSBrendon Cahoon     // Phi is not loop carried.
3118254f889dSBrendon Cahoon     if (!InProlog && StagePhi + 1 == StageSched &&
3119254f889dSBrendon Cahoon         !Schedule.isLoopCarried(this, *Phi))
3120254f889dSBrendon Cahoon       ReplaceReg = NewReg;
3121254f889dSBrendon Cahoon     if (StagePhi > StageSched && Phi->isPHI())
3122254f889dSBrendon Cahoon       ReplaceReg = NewReg;
3123254f889dSBrendon Cahoon     if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
3124254f889dSBrendon Cahoon       ReplaceReg = NewReg;
3125254f889dSBrendon Cahoon     if (ReplaceReg) {
3126254f889dSBrendon Cahoon       MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
3127254f889dSBrendon Cahoon       UseOp.setReg(ReplaceReg);
3128254f889dSBrendon Cahoon     }
3129254f889dSBrendon Cahoon   }
3130254f889dSBrendon Cahoon }
3131254f889dSBrendon Cahoon 
3132254f889dSBrendon Cahoon /// Check if we can change the instruction to use an offset value from the
3133254f889dSBrendon Cahoon /// previous iteration. If so, return true and set the base and offset values
3134254f889dSBrendon Cahoon /// so that we can rewrite the load, if necessary.
3135254f889dSBrendon Cahoon ///   v1 = Phi(v0, v3)
3136254f889dSBrendon Cahoon ///   v2 = load v1, 0
3137254f889dSBrendon Cahoon ///   v3 = post_store v1, 4, x
3138254f889dSBrendon Cahoon /// This function enables the load to be rewritten as v2 = load v3, 4.
3139254f889dSBrendon Cahoon bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *MI,
3140254f889dSBrendon Cahoon                                               unsigned &BasePos,
3141254f889dSBrendon Cahoon                                               unsigned &OffsetPos,
3142254f889dSBrendon Cahoon                                               unsigned &NewBase,
3143254f889dSBrendon Cahoon                                               int64_t &Offset) {
3144254f889dSBrendon Cahoon   // Get the load instruction.
31458fb181caSKrzysztof Parzyszek   if (TII->isPostIncrement(*MI))
3146254f889dSBrendon Cahoon     return false;
3147254f889dSBrendon Cahoon   unsigned BasePosLd, OffsetPosLd;
31488fb181caSKrzysztof Parzyszek   if (!TII->getBaseAndOffsetPosition(*MI, BasePosLd, OffsetPosLd))
3149254f889dSBrendon Cahoon     return false;
3150254f889dSBrendon Cahoon   unsigned BaseReg = MI->getOperand(BasePosLd).getReg();
3151254f889dSBrendon Cahoon 
3152254f889dSBrendon Cahoon   // Look for the Phi instruction.
3153fdf9bf4fSJustin Bogner   MachineRegisterInfo &MRI = MI->getMF()->getRegInfo();
3154254f889dSBrendon Cahoon   MachineInstr *Phi = MRI.getVRegDef(BaseReg);
3155254f889dSBrendon Cahoon   if (!Phi || !Phi->isPHI())
3156254f889dSBrendon Cahoon     return false;
3157254f889dSBrendon Cahoon   // Get the register defined in the loop block.
3158254f889dSBrendon Cahoon   unsigned PrevReg = getLoopPhiReg(*Phi, MI->getParent());
3159254f889dSBrendon Cahoon   if (!PrevReg)
3160254f889dSBrendon Cahoon     return false;
3161254f889dSBrendon Cahoon 
3162254f889dSBrendon Cahoon   // Check for the post-increment load/store instruction.
3163254f889dSBrendon Cahoon   MachineInstr *PrevDef = MRI.getVRegDef(PrevReg);
3164254f889dSBrendon Cahoon   if (!PrevDef || PrevDef == MI)
3165254f889dSBrendon Cahoon     return false;
3166254f889dSBrendon Cahoon 
31678fb181caSKrzysztof Parzyszek   if (!TII->isPostIncrement(*PrevDef))
3168254f889dSBrendon Cahoon     return false;
3169254f889dSBrendon Cahoon 
3170254f889dSBrendon Cahoon   unsigned BasePos1 = 0, OffsetPos1 = 0;
31718fb181caSKrzysztof Parzyszek   if (!TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
3172254f889dSBrendon Cahoon     return false;
3173254f889dSBrendon Cahoon 
317440df8a2bSKrzysztof Parzyszek   // Make sure that the instructions do not access the same memory location in
317540df8a2bSKrzysztof Parzyszek   // the next iteration.
3176254f889dSBrendon Cahoon   int64_t LoadOffset = MI->getOperand(OffsetPosLd).getImm();
3177254f889dSBrendon Cahoon   int64_t StoreOffset = PrevDef->getOperand(OffsetPos1).getImm();
317840df8a2bSKrzysztof Parzyszek   MachineInstr *NewMI = MF.CloneMachineInstr(MI);
317940df8a2bSKrzysztof Parzyszek   NewMI->getOperand(OffsetPosLd).setImm(LoadOffset + StoreOffset);
318040df8a2bSKrzysztof Parzyszek   bool Disjoint = TII->areMemAccessesTriviallyDisjoint(*NewMI, *PrevDef);
318140df8a2bSKrzysztof Parzyszek   MF.DeleteMachineInstr(NewMI);
318240df8a2bSKrzysztof Parzyszek   if (!Disjoint)
3183254f889dSBrendon Cahoon     return false;
3184254f889dSBrendon Cahoon 
3185254f889dSBrendon Cahoon   // Set the return value once we determine that we return true.
3186254f889dSBrendon Cahoon   BasePos = BasePosLd;
3187254f889dSBrendon Cahoon   OffsetPos = OffsetPosLd;
3188254f889dSBrendon Cahoon   NewBase = PrevReg;
3189254f889dSBrendon Cahoon   Offset = StoreOffset;
3190254f889dSBrendon Cahoon   return true;
3191254f889dSBrendon Cahoon }
3192254f889dSBrendon Cahoon 
3193254f889dSBrendon Cahoon /// Apply changes to the instruction if needed. The changes are need
3194254f889dSBrendon Cahoon /// to improve the scheduling and depend up on the final schedule.
31958f174ddeSKrzysztof Parzyszek void SwingSchedulerDAG::applyInstrChange(MachineInstr *MI,
31968f174ddeSKrzysztof Parzyszek                                          SMSchedule &Schedule) {
3197254f889dSBrendon Cahoon   SUnit *SU = getSUnit(MI);
3198254f889dSBrendon Cahoon   DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
3199254f889dSBrendon Cahoon       InstrChanges.find(SU);
3200254f889dSBrendon Cahoon   if (It != InstrChanges.end()) {
3201254f889dSBrendon Cahoon     std::pair<unsigned, int64_t> RegAndOffset = It->second;
3202254f889dSBrendon Cahoon     unsigned BasePos, OffsetPos;
32038fb181caSKrzysztof Parzyszek     if (!TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
32048f174ddeSKrzysztof Parzyszek       return;
3205254f889dSBrendon Cahoon     unsigned BaseReg = MI->getOperand(BasePos).getReg();
3206254f889dSBrendon Cahoon     MachineInstr *LoopDef = findDefInLoop(BaseReg);
3207254f889dSBrendon Cahoon     int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
3208254f889dSBrendon Cahoon     int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
3209254f889dSBrendon Cahoon     int BaseStageNum = Schedule.stageScheduled(SU);
3210254f889dSBrendon Cahoon     int BaseCycleNum = Schedule.cycleScheduled(SU);
3211254f889dSBrendon Cahoon     if (BaseStageNum < DefStageNum) {
3212254f889dSBrendon Cahoon       MachineInstr *NewMI = MF.CloneMachineInstr(MI);
3213254f889dSBrendon Cahoon       int OffsetDiff = DefStageNum - BaseStageNum;
3214254f889dSBrendon Cahoon       if (DefCycleNum < BaseCycleNum) {
3215254f889dSBrendon Cahoon         NewMI->getOperand(BasePos).setReg(RegAndOffset.first);
3216254f889dSBrendon Cahoon         if (OffsetDiff > 0)
3217254f889dSBrendon Cahoon           --OffsetDiff;
3218254f889dSBrendon Cahoon       }
3219254f889dSBrendon Cahoon       int64_t NewOffset =
3220254f889dSBrendon Cahoon           MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
3221254f889dSBrendon Cahoon       NewMI->getOperand(OffsetPos).setImm(NewOffset);
3222254f889dSBrendon Cahoon       SU->setInstr(NewMI);
3223254f889dSBrendon Cahoon       MISUnitMap[NewMI] = SU;
3224254f889dSBrendon Cahoon       NewMIs.insert(NewMI);
3225254f889dSBrendon Cahoon     }
3226254f889dSBrendon Cahoon   }
3227254f889dSBrendon Cahoon }
3228254f889dSBrendon Cahoon 
32298e1363dfSKrzysztof Parzyszek /// Return true for an order or output dependence that is loop carried
32308e1363dfSKrzysztof Parzyszek /// potentially. A dependence is loop carried if the destination defines a valu
32318e1363dfSKrzysztof Parzyszek /// that may be used or defined by the source in a subsequent iteration.
32328e1363dfSKrzysztof Parzyszek bool SwingSchedulerDAG::isLoopCarriedDep(SUnit *Source, const SDep &Dep,
3233254f889dSBrendon Cahoon                                          bool isSucc) {
32348e1363dfSKrzysztof Parzyszek   if ((Dep.getKind() != SDep::Order && Dep.getKind() != SDep::Output) ||
32358e1363dfSKrzysztof Parzyszek       Dep.isArtificial())
3236254f889dSBrendon Cahoon     return false;
3237254f889dSBrendon Cahoon 
3238254f889dSBrendon Cahoon   if (!SwpPruneLoopCarried)
3239254f889dSBrendon Cahoon     return true;
3240254f889dSBrendon Cahoon 
32418e1363dfSKrzysztof Parzyszek   if (Dep.getKind() == SDep::Output)
32428e1363dfSKrzysztof Parzyszek     return true;
32438e1363dfSKrzysztof Parzyszek 
3244254f889dSBrendon Cahoon   MachineInstr *SI = Source->getInstr();
3245254f889dSBrendon Cahoon   MachineInstr *DI = Dep.getSUnit()->getInstr();
3246254f889dSBrendon Cahoon   if (!isSucc)
3247254f889dSBrendon Cahoon     std::swap(SI, DI);
3248254f889dSBrendon Cahoon   assert(SI != nullptr && DI != nullptr && "Expecting SUnit with an MI.");
3249254f889dSBrendon Cahoon 
3250254f889dSBrendon Cahoon   // Assume ordered loads and stores may have a loop carried dependence.
3251254f889dSBrendon Cahoon   if (SI->hasUnmodeledSideEffects() || DI->hasUnmodeledSideEffects() ||
32526c5d5ce5SUlrich Weigand       SI->mayRaiseFPException() || DI->mayRaiseFPException() ||
3253254f889dSBrendon Cahoon       SI->hasOrderedMemoryRef() || DI->hasOrderedMemoryRef())
3254254f889dSBrendon Cahoon     return true;
3255254f889dSBrendon Cahoon 
3256254f889dSBrendon Cahoon   // Only chain dependences between a load and store can be loop carried.
3257254f889dSBrendon Cahoon   if (!DI->mayStore() || !SI->mayLoad())
3258254f889dSBrendon Cahoon     return false;
3259254f889dSBrendon Cahoon 
3260254f889dSBrendon Cahoon   unsigned DeltaS, DeltaD;
3261254f889dSBrendon Cahoon   if (!computeDelta(*SI, DeltaS) || !computeDelta(*DI, DeltaD))
3262254f889dSBrendon Cahoon     return true;
3263254f889dSBrendon Cahoon 
3264238c9d63SBjorn Pettersson   const MachineOperand *BaseOpS, *BaseOpD;
3265254f889dSBrendon Cahoon   int64_t OffsetS, OffsetD;
3266254f889dSBrendon Cahoon   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
3267d7eebd6dSFrancis Visoiu Mistrih   if (!TII->getMemOperandWithOffset(*SI, BaseOpS, OffsetS, TRI) ||
3268d7eebd6dSFrancis Visoiu Mistrih       !TII->getMemOperandWithOffset(*DI, BaseOpD, OffsetD, TRI))
3269254f889dSBrendon Cahoon     return true;
3270254f889dSBrendon Cahoon 
3271d7eebd6dSFrancis Visoiu Mistrih   if (!BaseOpS->isIdenticalTo(*BaseOpD))
3272254f889dSBrendon Cahoon     return true;
3273254f889dSBrendon Cahoon 
32748c07d0c4SKrzysztof Parzyszek   // Check that the base register is incremented by a constant value for each
32758c07d0c4SKrzysztof Parzyszek   // iteration.
3276d7eebd6dSFrancis Visoiu Mistrih   MachineInstr *Def = MRI.getVRegDef(BaseOpS->getReg());
32778c07d0c4SKrzysztof Parzyszek   if (!Def || !Def->isPHI())
32788c07d0c4SKrzysztof Parzyszek     return true;
32798c07d0c4SKrzysztof Parzyszek   unsigned InitVal = 0;
32808c07d0c4SKrzysztof Parzyszek   unsigned LoopVal = 0;
32818c07d0c4SKrzysztof Parzyszek   getPhiRegs(*Def, BB, InitVal, LoopVal);
32828c07d0c4SKrzysztof Parzyszek   MachineInstr *LoopDef = MRI.getVRegDef(LoopVal);
32838c07d0c4SKrzysztof Parzyszek   int D = 0;
32848c07d0c4SKrzysztof Parzyszek   if (!LoopDef || !TII->getIncrementValue(*LoopDef, D))
32858c07d0c4SKrzysztof Parzyszek     return true;
32868c07d0c4SKrzysztof Parzyszek 
3287254f889dSBrendon Cahoon   uint64_t AccessSizeS = (*SI->memoperands_begin())->getSize();
3288254f889dSBrendon Cahoon   uint64_t AccessSizeD = (*DI->memoperands_begin())->getSize();
3289254f889dSBrendon Cahoon 
3290254f889dSBrendon Cahoon   // This is the main test, which checks the offset values and the loop
3291254f889dSBrendon Cahoon   // increment value to determine if the accesses may be loop carried.
329257c3d4beSBrendon Cahoon   if (AccessSizeS == MemoryLocation::UnknownSize ||
329357c3d4beSBrendon Cahoon       AccessSizeD == MemoryLocation::UnknownSize)
3294254f889dSBrendon Cahoon     return true;
329557c3d4beSBrendon Cahoon 
329657c3d4beSBrendon Cahoon   if (DeltaS != DeltaD || DeltaS < AccessSizeS || DeltaD < AccessSizeD)
329757c3d4beSBrendon Cahoon     return true;
329857c3d4beSBrendon Cahoon 
329957c3d4beSBrendon Cahoon   return (OffsetS + (int64_t)AccessSizeS < OffsetD + (int64_t)AccessSizeD);
3300254f889dSBrendon Cahoon }
3301254f889dSBrendon Cahoon 
330288391248SKrzysztof Parzyszek void SwingSchedulerDAG::postprocessDAG() {
330388391248SKrzysztof Parzyszek   for (auto &M : Mutations)
330488391248SKrzysztof Parzyszek     M->apply(this);
330588391248SKrzysztof Parzyszek }
330688391248SKrzysztof Parzyszek 
3307254f889dSBrendon Cahoon /// Try to schedule the node at the specified StartCycle and continue
3308254f889dSBrendon Cahoon /// until the node is schedule or the EndCycle is reached.  This function
3309254f889dSBrendon Cahoon /// returns true if the node is scheduled.  This routine may search either
3310254f889dSBrendon Cahoon /// forward or backward for a place to insert the instruction based upon
3311254f889dSBrendon Cahoon /// the relative values of StartCycle and EndCycle.
3312254f889dSBrendon Cahoon bool SMSchedule::insert(SUnit *SU, int StartCycle, int EndCycle, int II) {
3313254f889dSBrendon Cahoon   bool forward = true;
331418e7bf5cSJinsong Ji   LLVM_DEBUG({
331518e7bf5cSJinsong Ji     dbgs() << "Trying to insert node between " << StartCycle << " and "
331618e7bf5cSJinsong Ji            << EndCycle << " II: " << II << "\n";
331718e7bf5cSJinsong Ji   });
3318254f889dSBrendon Cahoon   if (StartCycle > EndCycle)
3319254f889dSBrendon Cahoon     forward = false;
3320254f889dSBrendon Cahoon 
3321254f889dSBrendon Cahoon   // The terminating condition depends on the direction.
3322254f889dSBrendon Cahoon   int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
3323254f889dSBrendon Cahoon   for (int curCycle = StartCycle; curCycle != termCycle;
3324254f889dSBrendon Cahoon        forward ? ++curCycle : --curCycle) {
3325254f889dSBrendon Cahoon 
3326f6cb3bcbSJinsong Ji     // Add the already scheduled instructions at the specified cycle to the
3327f6cb3bcbSJinsong Ji     // DFA.
3328f6cb3bcbSJinsong Ji     ProcItinResources.clearResources();
3329254f889dSBrendon Cahoon     for (int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
3330254f889dSBrendon Cahoon          checkCycle <= LastCycle; checkCycle += II) {
3331254f889dSBrendon Cahoon       std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
3332254f889dSBrendon Cahoon 
3333254f889dSBrendon Cahoon       for (std::deque<SUnit *>::iterator I = cycleInstrs.begin(),
3334254f889dSBrendon Cahoon                                          E = cycleInstrs.end();
3335254f889dSBrendon Cahoon            I != E; ++I) {
3336254f889dSBrendon Cahoon         if (ST.getInstrInfo()->isZeroCost((*I)->getInstr()->getOpcode()))
3337254f889dSBrendon Cahoon           continue;
3338f6cb3bcbSJinsong Ji         assert(ProcItinResources.canReserveResources(*(*I)->getInstr()) &&
3339254f889dSBrendon Cahoon                "These instructions have already been scheduled.");
3340f6cb3bcbSJinsong Ji         ProcItinResources.reserveResources(*(*I)->getInstr());
3341254f889dSBrendon Cahoon       }
3342254f889dSBrendon Cahoon     }
3343254f889dSBrendon Cahoon     if (ST.getInstrInfo()->isZeroCost(SU->getInstr()->getOpcode()) ||
3344f6cb3bcbSJinsong Ji         ProcItinResources.canReserveResources(*SU->getInstr())) {
3345d34e60caSNicola Zaghen       LLVM_DEBUG({
3346254f889dSBrendon Cahoon         dbgs() << "\tinsert at cycle " << curCycle << " ";
3347254f889dSBrendon Cahoon         SU->getInstr()->dump();
3348254f889dSBrendon Cahoon       });
3349254f889dSBrendon Cahoon 
3350254f889dSBrendon Cahoon       ScheduledInstrs[curCycle].push_back(SU);
3351254f889dSBrendon Cahoon       InstrToCycle.insert(std::make_pair(SU, curCycle));
3352254f889dSBrendon Cahoon       if (curCycle > LastCycle)
3353254f889dSBrendon Cahoon         LastCycle = curCycle;
3354254f889dSBrendon Cahoon       if (curCycle < FirstCycle)
3355254f889dSBrendon Cahoon         FirstCycle = curCycle;
3356254f889dSBrendon Cahoon       return true;
3357254f889dSBrendon Cahoon     }
3358d34e60caSNicola Zaghen     LLVM_DEBUG({
3359254f889dSBrendon Cahoon       dbgs() << "\tfailed to insert at cycle " << curCycle << " ";
3360254f889dSBrendon Cahoon       SU->getInstr()->dump();
3361254f889dSBrendon Cahoon     });
3362254f889dSBrendon Cahoon   }
3363254f889dSBrendon Cahoon   return false;
3364254f889dSBrendon Cahoon }
3365254f889dSBrendon Cahoon 
3366254f889dSBrendon Cahoon // Return the cycle of the earliest scheduled instruction in the chain.
3367254f889dSBrendon Cahoon int SMSchedule::earliestCycleInChain(const SDep &Dep) {
3368254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 8> Visited;
3369254f889dSBrendon Cahoon   SmallVector<SDep, 8> Worklist;
3370254f889dSBrendon Cahoon   Worklist.push_back(Dep);
3371254f889dSBrendon Cahoon   int EarlyCycle = INT_MAX;
3372254f889dSBrendon Cahoon   while (!Worklist.empty()) {
3373254f889dSBrendon Cahoon     const SDep &Cur = Worklist.pop_back_val();
3374254f889dSBrendon Cahoon     SUnit *PrevSU = Cur.getSUnit();
3375254f889dSBrendon Cahoon     if (Visited.count(PrevSU))
3376254f889dSBrendon Cahoon       continue;
3377254f889dSBrendon Cahoon     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
3378254f889dSBrendon Cahoon     if (it == InstrToCycle.end())
3379254f889dSBrendon Cahoon       continue;
3380254f889dSBrendon Cahoon     EarlyCycle = std::min(EarlyCycle, it->second);
3381254f889dSBrendon Cahoon     for (const auto &PI : PrevSU->Preds)
33828e1363dfSKrzysztof Parzyszek       if (PI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
3383254f889dSBrendon Cahoon         Worklist.push_back(PI);
3384254f889dSBrendon Cahoon     Visited.insert(PrevSU);
3385254f889dSBrendon Cahoon   }
3386254f889dSBrendon Cahoon   return EarlyCycle;
3387254f889dSBrendon Cahoon }
3388254f889dSBrendon Cahoon 
3389254f889dSBrendon Cahoon // Return the cycle of the latest scheduled instruction in the chain.
3390254f889dSBrendon Cahoon int SMSchedule::latestCycleInChain(const SDep &Dep) {
3391254f889dSBrendon Cahoon   SmallPtrSet<SUnit *, 8> Visited;
3392254f889dSBrendon Cahoon   SmallVector<SDep, 8> Worklist;
3393254f889dSBrendon Cahoon   Worklist.push_back(Dep);
3394254f889dSBrendon Cahoon   int LateCycle = INT_MIN;
3395254f889dSBrendon Cahoon   while (!Worklist.empty()) {
3396254f889dSBrendon Cahoon     const SDep &Cur = Worklist.pop_back_val();
3397254f889dSBrendon Cahoon     SUnit *SuccSU = Cur.getSUnit();
3398254f889dSBrendon Cahoon     if (Visited.count(SuccSU))
3399254f889dSBrendon Cahoon       continue;
3400254f889dSBrendon Cahoon     std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
3401254f889dSBrendon Cahoon     if (it == InstrToCycle.end())
3402254f889dSBrendon Cahoon       continue;
3403254f889dSBrendon Cahoon     LateCycle = std::max(LateCycle, it->second);
3404254f889dSBrendon Cahoon     for (const auto &SI : SuccSU->Succs)
34058e1363dfSKrzysztof Parzyszek       if (SI.getKind() == SDep::Order || Dep.getKind() == SDep::Output)
3406254f889dSBrendon Cahoon         Worklist.push_back(SI);
3407254f889dSBrendon Cahoon     Visited.insert(SuccSU);
3408254f889dSBrendon Cahoon   }
3409254f889dSBrendon Cahoon   return LateCycle;
3410254f889dSBrendon Cahoon }
3411254f889dSBrendon Cahoon 
3412254f889dSBrendon Cahoon /// If an instruction has a use that spans multiple iterations, then
3413254f889dSBrendon Cahoon /// return true. These instructions are characterized by having a back-ege
3414254f889dSBrendon Cahoon /// to a Phi, which contains a reference to another Phi.
3415254f889dSBrendon Cahoon static SUnit *multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG) {
3416254f889dSBrendon Cahoon   for (auto &P : SU->Preds)
3417254f889dSBrendon Cahoon     if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
3418254f889dSBrendon Cahoon       for (auto &S : P.getSUnit()->Succs)
3419b9b75b8cSKrzysztof Parzyszek         if (S.getKind() == SDep::Data && S.getSUnit()->getInstr()->isPHI())
3420254f889dSBrendon Cahoon           return P.getSUnit();
3421254f889dSBrendon Cahoon   return nullptr;
3422254f889dSBrendon Cahoon }
3423254f889dSBrendon Cahoon 
3424254f889dSBrendon Cahoon /// Compute the scheduling start slot for the instruction.  The start slot
3425254f889dSBrendon Cahoon /// depends on any predecessor or successor nodes scheduled already.
3426254f889dSBrendon Cahoon void SMSchedule::computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart,
3427254f889dSBrendon Cahoon                               int *MinEnd, int *MaxStart, int II,
3428254f889dSBrendon Cahoon                               SwingSchedulerDAG *DAG) {
3429254f889dSBrendon Cahoon   // Iterate over each instruction that has been scheduled already.  The start
3430c73b6d6bSHiroshi Inoue   // slot computation depends on whether the previously scheduled instruction
3431254f889dSBrendon Cahoon   // is a predecessor or successor of the specified instruction.
3432254f889dSBrendon Cahoon   for (int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
3433254f889dSBrendon Cahoon 
3434254f889dSBrendon Cahoon     // Iterate over each instruction in the current cycle.
3435254f889dSBrendon Cahoon     for (SUnit *I : getInstructions(cycle)) {
3436254f889dSBrendon Cahoon       // Because we're processing a DAG for the dependences, we recognize
3437254f889dSBrendon Cahoon       // the back-edge in recurrences by anti dependences.
3438254f889dSBrendon Cahoon       for (unsigned i = 0, e = (unsigned)SU->Preds.size(); i != e; ++i) {
3439254f889dSBrendon Cahoon         const SDep &Dep = SU->Preds[i];
3440254f889dSBrendon Cahoon         if (Dep.getSUnit() == I) {
3441254f889dSBrendon Cahoon           if (!DAG->isBackedge(SU, Dep)) {
3442c715a5d2SKrzysztof Parzyszek             int EarlyStart = cycle + Dep.getLatency() -
3443254f889dSBrendon Cahoon                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3444254f889dSBrendon Cahoon             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
34458e1363dfSKrzysztof Parzyszek             if (DAG->isLoopCarriedDep(SU, Dep, false)) {
3446254f889dSBrendon Cahoon               int End = earliestCycleInChain(Dep) + (II - 1);
3447254f889dSBrendon Cahoon               *MinEnd = std::min(*MinEnd, End);
3448254f889dSBrendon Cahoon             }
3449254f889dSBrendon Cahoon           } else {
3450c715a5d2SKrzysztof Parzyszek             int LateStart = cycle - Dep.getLatency() +
3451254f889dSBrendon Cahoon                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3452254f889dSBrendon Cahoon             *MinLateStart = std::min(*MinLateStart, LateStart);
3453254f889dSBrendon Cahoon           }
3454254f889dSBrendon Cahoon         }
3455254f889dSBrendon Cahoon         // For instruction that requires multiple iterations, make sure that
3456254f889dSBrendon Cahoon         // the dependent instruction is not scheduled past the definition.
3457254f889dSBrendon Cahoon         SUnit *BE = multipleIterations(I, DAG);
3458254f889dSBrendon Cahoon         if (BE && Dep.getSUnit() == BE && !SU->getInstr()->isPHI() &&
3459254f889dSBrendon Cahoon             !SU->isPred(I))
3460254f889dSBrendon Cahoon           *MinLateStart = std::min(*MinLateStart, cycle);
3461254f889dSBrendon Cahoon       }
3462a2122044SKrzysztof Parzyszek       for (unsigned i = 0, e = (unsigned)SU->Succs.size(); i != e; ++i) {
3463254f889dSBrendon Cahoon         if (SU->Succs[i].getSUnit() == I) {
3464254f889dSBrendon Cahoon           const SDep &Dep = SU->Succs[i];
3465254f889dSBrendon Cahoon           if (!DAG->isBackedge(SU, Dep)) {
3466c715a5d2SKrzysztof Parzyszek             int LateStart = cycle - Dep.getLatency() +
3467254f889dSBrendon Cahoon                             DAG->getDistance(SU, Dep.getSUnit(), Dep) * II;
3468254f889dSBrendon Cahoon             *MinLateStart = std::min(*MinLateStart, LateStart);
34698e1363dfSKrzysztof Parzyszek             if (DAG->isLoopCarriedDep(SU, Dep)) {
3470254f889dSBrendon Cahoon               int Start = latestCycleInChain(Dep) + 1 - II;
3471254f889dSBrendon Cahoon               *MaxStart = std::max(*MaxStart, Start);
3472254f889dSBrendon Cahoon             }
3473254f889dSBrendon Cahoon           } else {
3474c715a5d2SKrzysztof Parzyszek             int EarlyStart = cycle + Dep.getLatency() -
3475254f889dSBrendon Cahoon                              DAG->getDistance(Dep.getSUnit(), SU, Dep) * II;
3476254f889dSBrendon Cahoon             *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
3477254f889dSBrendon Cahoon           }
3478254f889dSBrendon Cahoon         }
3479254f889dSBrendon Cahoon       }
3480254f889dSBrendon Cahoon     }
3481254f889dSBrendon Cahoon   }
3482a2122044SKrzysztof Parzyszek }
3483254f889dSBrendon Cahoon 
3484254f889dSBrendon Cahoon /// Order the instructions within a cycle so that the definitions occur
3485254f889dSBrendon Cahoon /// before the uses. Returns true if the instruction is added to the start
3486254f889dSBrendon Cahoon /// of the list, or false if added to the end.
3487f13bbf1dSKrzysztof Parzyszek void SMSchedule::orderDependence(SwingSchedulerDAG *SSD, SUnit *SU,
3488254f889dSBrendon Cahoon                                  std::deque<SUnit *> &Insts) {
3489254f889dSBrendon Cahoon   MachineInstr *MI = SU->getInstr();
3490254f889dSBrendon Cahoon   bool OrderBeforeUse = false;
3491254f889dSBrendon Cahoon   bool OrderAfterDef = false;
3492254f889dSBrendon Cahoon   bool OrderBeforeDef = false;
3493254f889dSBrendon Cahoon   unsigned MoveDef = 0;
3494254f889dSBrendon Cahoon   unsigned MoveUse = 0;
3495254f889dSBrendon Cahoon   int StageInst1 = stageScheduled(SU);
3496254f889dSBrendon Cahoon 
3497254f889dSBrendon Cahoon   unsigned Pos = 0;
3498254f889dSBrendon Cahoon   for (std::deque<SUnit *>::iterator I = Insts.begin(), E = Insts.end(); I != E;
3499254f889dSBrendon Cahoon        ++I, ++Pos) {
3500254f889dSBrendon Cahoon     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3501254f889dSBrendon Cahoon       MachineOperand &MO = MI->getOperand(i);
3502254f889dSBrendon Cahoon       if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
3503254f889dSBrendon Cahoon         continue;
3504f13bbf1dSKrzysztof Parzyszek 
3505254f889dSBrendon Cahoon       unsigned Reg = MO.getReg();
3506254f889dSBrendon Cahoon       unsigned BasePos, OffsetPos;
35078fb181caSKrzysztof Parzyszek       if (ST.getInstrInfo()->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos))
3508254f889dSBrendon Cahoon         if (MI->getOperand(BasePos).getReg() == Reg)
3509254f889dSBrendon Cahoon           if (unsigned NewReg = SSD->getInstrBaseReg(SU))
3510254f889dSBrendon Cahoon             Reg = NewReg;
3511254f889dSBrendon Cahoon       bool Reads, Writes;
3512254f889dSBrendon Cahoon       std::tie(Reads, Writes) =
3513254f889dSBrendon Cahoon           (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3514254f889dSBrendon Cahoon       if (MO.isDef() && Reads && stageScheduled(*I) <= StageInst1) {
3515254f889dSBrendon Cahoon         OrderBeforeUse = true;
3516f13bbf1dSKrzysztof Parzyszek         if (MoveUse == 0)
3517254f889dSBrendon Cahoon           MoveUse = Pos;
3518254f889dSBrendon Cahoon       } else if (MO.isDef() && Reads && stageScheduled(*I) > StageInst1) {
3519254f889dSBrendon Cahoon         // Add the instruction after the scheduled instruction.
3520254f889dSBrendon Cahoon         OrderAfterDef = true;
3521254f889dSBrendon Cahoon         MoveDef = Pos;
3522254f889dSBrendon Cahoon       } else if (MO.isUse() && Writes && stageScheduled(*I) == StageInst1) {
3523254f889dSBrendon Cahoon         if (cycleScheduled(*I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
3524254f889dSBrendon Cahoon           OrderBeforeUse = true;
3525f13bbf1dSKrzysztof Parzyszek           if (MoveUse == 0)
3526254f889dSBrendon Cahoon             MoveUse = Pos;
3527254f889dSBrendon Cahoon         } else {
3528254f889dSBrendon Cahoon           OrderAfterDef = true;
3529254f889dSBrendon Cahoon           MoveDef = Pos;
3530254f889dSBrendon Cahoon         }
3531254f889dSBrendon Cahoon       } else if (MO.isUse() && Writes && stageScheduled(*I) > StageInst1) {
3532254f889dSBrendon Cahoon         OrderBeforeUse = true;
3533f13bbf1dSKrzysztof Parzyszek         if (MoveUse == 0)
3534254f889dSBrendon Cahoon           MoveUse = Pos;
3535254f889dSBrendon Cahoon         if (MoveUse != 0) {
3536254f889dSBrendon Cahoon           OrderAfterDef = true;
3537254f889dSBrendon Cahoon           MoveDef = Pos - 1;
3538254f889dSBrendon Cahoon         }
3539254f889dSBrendon Cahoon       } else if (MO.isUse() && Writes && stageScheduled(*I) < StageInst1) {
3540254f889dSBrendon Cahoon         // Add the instruction before the scheduled instruction.
3541254f889dSBrendon Cahoon         OrderBeforeUse = true;
3542f13bbf1dSKrzysztof Parzyszek         if (MoveUse == 0)
3543254f889dSBrendon Cahoon           MoveUse = Pos;
3544254f889dSBrendon Cahoon       } else if (MO.isUse() && stageScheduled(*I) == StageInst1 &&
3545254f889dSBrendon Cahoon                  isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
3546f13bbf1dSKrzysztof Parzyszek         if (MoveUse == 0) {
3547254f889dSBrendon Cahoon           OrderBeforeDef = true;
3548254f889dSBrendon Cahoon           MoveUse = Pos;
3549254f889dSBrendon Cahoon         }
3550254f889dSBrendon Cahoon       }
3551f13bbf1dSKrzysztof Parzyszek     }
3552254f889dSBrendon Cahoon     // Check for order dependences between instructions. Make sure the source
3553254f889dSBrendon Cahoon     // is ordered before the destination.
35548e1363dfSKrzysztof Parzyszek     for (auto &S : SU->Succs) {
35558e1363dfSKrzysztof Parzyszek       if (S.getSUnit() != *I)
35568e1363dfSKrzysztof Parzyszek         continue;
35578e1363dfSKrzysztof Parzyszek       if (S.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3558254f889dSBrendon Cahoon         OrderBeforeUse = true;
35598e1363dfSKrzysztof Parzyszek         if (Pos < MoveUse)
3560254f889dSBrendon Cahoon           MoveUse = Pos;
3561254f889dSBrendon Cahoon       }
3562254f889dSBrendon Cahoon     }
35638e1363dfSKrzysztof Parzyszek     for (auto &P : SU->Preds) {
35648e1363dfSKrzysztof Parzyszek       if (P.getSUnit() != *I)
35658e1363dfSKrzysztof Parzyszek         continue;
35668e1363dfSKrzysztof Parzyszek       if (P.getKind() == SDep::Order && stageScheduled(*I) == StageInst1) {
3567254f889dSBrendon Cahoon         OrderAfterDef = true;
3568254f889dSBrendon Cahoon         MoveDef = Pos;
3569254f889dSBrendon Cahoon       }
3570254f889dSBrendon Cahoon     }
3571254f889dSBrendon Cahoon   }
3572254f889dSBrendon Cahoon 
3573254f889dSBrendon Cahoon   // A circular dependence.
3574254f889dSBrendon Cahoon   if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3575254f889dSBrendon Cahoon     OrderBeforeUse = false;
3576254f889dSBrendon Cahoon 
3577254f889dSBrendon Cahoon   // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
3578254f889dSBrendon Cahoon   // to a loop-carried dependence.
3579254f889dSBrendon Cahoon   if (OrderBeforeDef)
3580254f889dSBrendon Cahoon     OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3581254f889dSBrendon Cahoon 
3582254f889dSBrendon Cahoon   // The uncommon case when the instruction order needs to be updated because
3583254f889dSBrendon Cahoon   // there is both a use and def.
3584254f889dSBrendon Cahoon   if (OrderBeforeUse && OrderAfterDef) {
3585254f889dSBrendon Cahoon     SUnit *UseSU = Insts.at(MoveUse);
3586254f889dSBrendon Cahoon     SUnit *DefSU = Insts.at(MoveDef);
3587254f889dSBrendon Cahoon     if (MoveUse > MoveDef) {
3588254f889dSBrendon Cahoon       Insts.erase(Insts.begin() + MoveUse);
3589254f889dSBrendon Cahoon       Insts.erase(Insts.begin() + MoveDef);
3590254f889dSBrendon Cahoon     } else {
3591254f889dSBrendon Cahoon       Insts.erase(Insts.begin() + MoveDef);
3592254f889dSBrendon Cahoon       Insts.erase(Insts.begin() + MoveUse);
3593254f889dSBrendon Cahoon     }
3594f13bbf1dSKrzysztof Parzyszek     orderDependence(SSD, UseSU, Insts);
3595f13bbf1dSKrzysztof Parzyszek     orderDependence(SSD, SU, Insts);
3596254f889dSBrendon Cahoon     orderDependence(SSD, DefSU, Insts);
3597f13bbf1dSKrzysztof Parzyszek     return;
3598254f889dSBrendon Cahoon   }
3599254f889dSBrendon Cahoon   // Put the new instruction first if there is a use in the list. Otherwise,
3600254f889dSBrendon Cahoon   // put it at the end of the list.
3601254f889dSBrendon Cahoon   if (OrderBeforeUse)
3602254f889dSBrendon Cahoon     Insts.push_front(SU);
3603254f889dSBrendon Cahoon   else
3604254f889dSBrendon Cahoon     Insts.push_back(SU);
3605254f889dSBrendon Cahoon }
3606254f889dSBrendon Cahoon 
3607254f889dSBrendon Cahoon /// Return true if the scheduled Phi has a loop carried operand.
3608254f889dSBrendon Cahoon bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD, MachineInstr &Phi) {
3609254f889dSBrendon Cahoon   if (!Phi.isPHI())
3610254f889dSBrendon Cahoon     return false;
3611c73b6d6bSHiroshi Inoue   assert(Phi.isPHI() && "Expecting a Phi.");
3612254f889dSBrendon Cahoon   SUnit *DefSU = SSD->getSUnit(&Phi);
3613254f889dSBrendon Cahoon   unsigned DefCycle = cycleScheduled(DefSU);
3614254f889dSBrendon Cahoon   int DefStage = stageScheduled(DefSU);
3615254f889dSBrendon Cahoon 
3616254f889dSBrendon Cahoon   unsigned InitVal = 0;
3617254f889dSBrendon Cahoon   unsigned LoopVal = 0;
3618254f889dSBrendon Cahoon   getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
3619254f889dSBrendon Cahoon   SUnit *UseSU = SSD->getSUnit(MRI.getVRegDef(LoopVal));
3620254f889dSBrendon Cahoon   if (!UseSU)
3621254f889dSBrendon Cahoon     return true;
3622254f889dSBrendon Cahoon   if (UseSU->getInstr()->isPHI())
3623254f889dSBrendon Cahoon     return true;
3624254f889dSBrendon Cahoon   unsigned LoopCycle = cycleScheduled(UseSU);
3625254f889dSBrendon Cahoon   int LoopStage = stageScheduled(UseSU);
36263d8482a8SSimon Pilgrim   return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
3627254f889dSBrendon Cahoon }
3628254f889dSBrendon Cahoon 
3629254f889dSBrendon Cahoon /// Return true if the instruction is a definition that is loop carried
3630254f889dSBrendon Cahoon /// and defines the use on the next iteration.
3631254f889dSBrendon Cahoon ///        v1 = phi(v2, v3)
3632254f889dSBrendon Cahoon ///  (Def) v3 = op v1
3633254f889dSBrendon Cahoon ///  (MO)   = v1
3634254f889dSBrendon Cahoon /// If MO appears before Def, then then v1 and v3 may get assigned to the same
3635254f889dSBrendon Cahoon /// register.
3636254f889dSBrendon Cahoon bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
3637254f889dSBrendon Cahoon                                        MachineInstr *Def, MachineOperand &MO) {
3638254f889dSBrendon Cahoon   if (!MO.isReg())
3639254f889dSBrendon Cahoon     return false;
3640254f889dSBrendon Cahoon   if (Def->isPHI())
3641254f889dSBrendon Cahoon     return false;
3642254f889dSBrendon Cahoon   MachineInstr *Phi = MRI.getVRegDef(MO.getReg());
3643254f889dSBrendon Cahoon   if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
3644254f889dSBrendon Cahoon     return false;
3645254f889dSBrendon Cahoon   if (!isLoopCarried(SSD, *Phi))
3646254f889dSBrendon Cahoon     return false;
3647254f889dSBrendon Cahoon   unsigned LoopReg = getLoopPhiReg(*Phi, Phi->getParent());
3648254f889dSBrendon Cahoon   for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
3649254f889dSBrendon Cahoon     MachineOperand &DMO = Def->getOperand(i);
3650254f889dSBrendon Cahoon     if (!DMO.isReg() || !DMO.isDef())
3651254f889dSBrendon Cahoon       continue;
3652254f889dSBrendon Cahoon     if (DMO.getReg() == LoopReg)
3653254f889dSBrendon Cahoon       return true;
3654254f889dSBrendon Cahoon   }
3655254f889dSBrendon Cahoon   return false;
3656254f889dSBrendon Cahoon }
3657254f889dSBrendon Cahoon 
3658254f889dSBrendon Cahoon // Check if the generated schedule is valid. This function checks if
3659254f889dSBrendon Cahoon // an instruction that uses a physical register is scheduled in a
3660254f889dSBrendon Cahoon // different stage than the definition. The pipeliner does not handle
3661254f889dSBrendon Cahoon // physical register values that may cross a basic block boundary.
3662254f889dSBrendon Cahoon bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
3663254f889dSBrendon Cahoon   for (int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
3664254f889dSBrendon Cahoon     SUnit &SU = SSD->SUnits[i];
3665254f889dSBrendon Cahoon     if (!SU.hasPhysRegDefs)
3666254f889dSBrendon Cahoon       continue;
3667254f889dSBrendon Cahoon     int StageDef = stageScheduled(&SU);
3668254f889dSBrendon Cahoon     assert(StageDef != -1 && "Instruction should have been scheduled.");
3669254f889dSBrendon Cahoon     for (auto &SI : SU.Succs)
3670254f889dSBrendon Cahoon       if (SI.isAssignedRegDep())
3671b39236b6SSimon Pilgrim         if (ST.getRegisterInfo()->isPhysicalRegister(SI.getReg()))
3672254f889dSBrendon Cahoon           if (stageScheduled(SI.getSUnit()) != StageDef)
3673254f889dSBrendon Cahoon             return false;
3674254f889dSBrendon Cahoon   }
3675254f889dSBrendon Cahoon   return true;
3676254f889dSBrendon Cahoon }
3677254f889dSBrendon Cahoon 
36784b8bcf00SRoorda, Jan-Willem /// A property of the node order in swing-modulo-scheduling is
36794b8bcf00SRoorda, Jan-Willem /// that for nodes outside circuits the following holds:
36804b8bcf00SRoorda, Jan-Willem /// none of them is scheduled after both a successor and a
36814b8bcf00SRoorda, Jan-Willem /// predecessor.
36824b8bcf00SRoorda, Jan-Willem /// The method below checks whether the property is met.
36834b8bcf00SRoorda, Jan-Willem /// If not, debug information is printed and statistics information updated.
36844b8bcf00SRoorda, Jan-Willem /// Note that we do not use an assert statement.
36854b8bcf00SRoorda, Jan-Willem /// The reason is that although an invalid node oder may prevent
36864b8bcf00SRoorda, Jan-Willem /// the pipeliner from finding a pipelined schedule for arbitrary II,
36874b8bcf00SRoorda, Jan-Willem /// it does not lead to the generation of incorrect code.
36884b8bcf00SRoorda, Jan-Willem void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType &Circuits) const {
36894b8bcf00SRoorda, Jan-Willem 
36904b8bcf00SRoorda, Jan-Willem   // a sorted vector that maps each SUnit to its index in the NodeOrder
36914b8bcf00SRoorda, Jan-Willem   typedef std::pair<SUnit *, unsigned> UnitIndex;
36924b8bcf00SRoorda, Jan-Willem   std::vector<UnitIndex> Indices(NodeOrder.size(), std::make_pair(nullptr, 0));
36934b8bcf00SRoorda, Jan-Willem 
36944b8bcf00SRoorda, Jan-Willem   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i)
36954b8bcf00SRoorda, Jan-Willem     Indices.push_back(std::make_pair(NodeOrder[i], i));
36964b8bcf00SRoorda, Jan-Willem 
36974b8bcf00SRoorda, Jan-Willem   auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
36984b8bcf00SRoorda, Jan-Willem     return std::get<0>(i1) < std::get<0>(i2);
36994b8bcf00SRoorda, Jan-Willem   };
37004b8bcf00SRoorda, Jan-Willem 
37014b8bcf00SRoorda, Jan-Willem   // sort, so that we can perform a binary search
37020cac726aSFangrui Song   llvm::sort(Indices, CompareKey);
37034b8bcf00SRoorda, Jan-Willem 
37044b8bcf00SRoorda, Jan-Willem   bool Valid = true;
3705febf70a9SDavid L Kreitzer   (void)Valid;
37064b8bcf00SRoorda, Jan-Willem   // for each SUnit in the NodeOrder, check whether
37074b8bcf00SRoorda, Jan-Willem   // it appears after both a successor and a predecessor
37084b8bcf00SRoorda, Jan-Willem   // of the SUnit. If this is the case, and the SUnit
37094b8bcf00SRoorda, Jan-Willem   // is not part of circuit, then the NodeOrder is not
37104b8bcf00SRoorda, Jan-Willem   // valid.
37114b8bcf00SRoorda, Jan-Willem   for (unsigned i = 0, s = NodeOrder.size(); i < s; ++i) {
37124b8bcf00SRoorda, Jan-Willem     SUnit *SU = NodeOrder[i];
37134b8bcf00SRoorda, Jan-Willem     unsigned Index = i;
37144b8bcf00SRoorda, Jan-Willem 
37154b8bcf00SRoorda, Jan-Willem     bool PredBefore = false;
37164b8bcf00SRoorda, Jan-Willem     bool SuccBefore = false;
37174b8bcf00SRoorda, Jan-Willem 
37184b8bcf00SRoorda, Jan-Willem     SUnit *Succ;
37194b8bcf00SRoorda, Jan-Willem     SUnit *Pred;
3720febf70a9SDavid L Kreitzer     (void)Succ;
3721febf70a9SDavid L Kreitzer     (void)Pred;
37224b8bcf00SRoorda, Jan-Willem 
37234b8bcf00SRoorda, Jan-Willem     for (SDep &PredEdge : SU->Preds) {
37244b8bcf00SRoorda, Jan-Willem       SUnit *PredSU = PredEdge.getSUnit();
3725dc8de603SFangrui Song       unsigned PredIndex = std::get<1>(
3726dc8de603SFangrui Song           *llvm::lower_bound(Indices, std::make_pair(PredSU, 0), CompareKey));
37274b8bcf00SRoorda, Jan-Willem       if (!PredSU->getInstr()->isPHI() && PredIndex < Index) {
37284b8bcf00SRoorda, Jan-Willem         PredBefore = true;
37294b8bcf00SRoorda, Jan-Willem         Pred = PredSU;
37304b8bcf00SRoorda, Jan-Willem         break;
37314b8bcf00SRoorda, Jan-Willem       }
37324b8bcf00SRoorda, Jan-Willem     }
37334b8bcf00SRoorda, Jan-Willem 
37344b8bcf00SRoorda, Jan-Willem     for (SDep &SuccEdge : SU->Succs) {
37354b8bcf00SRoorda, Jan-Willem       SUnit *SuccSU = SuccEdge.getSUnit();
37361c884458SJinsong Ji       // Do not process a boundary node, it was not included in NodeOrder,
37371c884458SJinsong Ji       // hence not in Indices either, call to std::lower_bound() below will
37381c884458SJinsong Ji       // return Indices.end().
37391c884458SJinsong Ji       if (SuccSU->isBoundaryNode())
37401c884458SJinsong Ji         continue;
3741dc8de603SFangrui Song       unsigned SuccIndex = std::get<1>(
3742dc8de603SFangrui Song           *llvm::lower_bound(Indices, std::make_pair(SuccSU, 0), CompareKey));
37434b8bcf00SRoorda, Jan-Willem       if (!SuccSU->getInstr()->isPHI() && SuccIndex < Index) {
37444b8bcf00SRoorda, Jan-Willem         SuccBefore = true;
37454b8bcf00SRoorda, Jan-Willem         Succ = SuccSU;
37464b8bcf00SRoorda, Jan-Willem         break;
37474b8bcf00SRoorda, Jan-Willem       }
37484b8bcf00SRoorda, Jan-Willem     }
37494b8bcf00SRoorda, Jan-Willem 
37504b8bcf00SRoorda, Jan-Willem     if (PredBefore && SuccBefore && !SU->getInstr()->isPHI()) {
37514b8bcf00SRoorda, Jan-Willem       // instructions in circuits are allowed to be scheduled
37524b8bcf00SRoorda, Jan-Willem       // after both a successor and predecessor.
3753dc8de603SFangrui Song       bool InCircuit = llvm::any_of(
3754dc8de603SFangrui Song           Circuits, [SU](const NodeSet &Circuit) { return Circuit.count(SU); });
37554b8bcf00SRoorda, Jan-Willem       if (InCircuit)
3756d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
37574b8bcf00SRoorda, Jan-Willem       else {
37584b8bcf00SRoorda, Jan-Willem         Valid = false;
37594b8bcf00SRoorda, Jan-Willem         NumNodeOrderIssues++;
3760d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Predecessor ";);
37614b8bcf00SRoorda, Jan-Willem       }
3762d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << Pred->NodeNum << " and successor " << Succ->NodeNum
3763d34e60caSNicola Zaghen                         << " are scheduled before node " << SU->NodeNum
3764d34e60caSNicola Zaghen                         << "\n";);
37654b8bcf00SRoorda, Jan-Willem     }
37664b8bcf00SRoorda, Jan-Willem   }
37674b8bcf00SRoorda, Jan-Willem 
3768d34e60caSNicola Zaghen   LLVM_DEBUG({
37694b8bcf00SRoorda, Jan-Willem     if (!Valid)
37704b8bcf00SRoorda, Jan-Willem       dbgs() << "Invalid node order found!\n";
37714b8bcf00SRoorda, Jan-Willem   });
37724b8bcf00SRoorda, Jan-Willem }
37734b8bcf00SRoorda, Jan-Willem 
37748f174ddeSKrzysztof Parzyszek /// Attempt to fix the degenerate cases when the instruction serialization
37758f174ddeSKrzysztof Parzyszek /// causes the register lifetimes to overlap. For example,
37768f174ddeSKrzysztof Parzyszek ///   p' = store_pi(p, b)
37778f174ddeSKrzysztof Parzyszek ///      = load p, offset
37788f174ddeSKrzysztof Parzyszek /// In this case p and p' overlap, which means that two registers are needed.
37798f174ddeSKrzysztof Parzyszek /// Instead, this function changes the load to use p' and updates the offset.
37808f174ddeSKrzysztof Parzyszek void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
37818f174ddeSKrzysztof Parzyszek   unsigned OverlapReg = 0;
37828f174ddeSKrzysztof Parzyszek   unsigned NewBaseReg = 0;
37838f174ddeSKrzysztof Parzyszek   for (SUnit *SU : Instrs) {
37848f174ddeSKrzysztof Parzyszek     MachineInstr *MI = SU->getInstr();
37858f174ddeSKrzysztof Parzyszek     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
37868f174ddeSKrzysztof Parzyszek       const MachineOperand &MO = MI->getOperand(i);
37878f174ddeSKrzysztof Parzyszek       // Look for an instruction that uses p. The instruction occurs in the
37888f174ddeSKrzysztof Parzyszek       // same cycle but occurs later in the serialized order.
37898f174ddeSKrzysztof Parzyszek       if (MO.isReg() && MO.isUse() && MO.getReg() == OverlapReg) {
37908f174ddeSKrzysztof Parzyszek         // Check that the instruction appears in the InstrChanges structure,
37918f174ddeSKrzysztof Parzyszek         // which contains instructions that can have the offset updated.
37928f174ddeSKrzysztof Parzyszek         DenseMap<SUnit *, std::pair<unsigned, int64_t>>::iterator It =
37938f174ddeSKrzysztof Parzyszek           InstrChanges.find(SU);
37948f174ddeSKrzysztof Parzyszek         if (It != InstrChanges.end()) {
37958f174ddeSKrzysztof Parzyszek           unsigned BasePos, OffsetPos;
37968f174ddeSKrzysztof Parzyszek           // Update the base register and adjust the offset.
37978f174ddeSKrzysztof Parzyszek           if (TII->getBaseAndOffsetPosition(*MI, BasePos, OffsetPos)) {
379812bdcab5SKrzysztof Parzyszek             MachineInstr *NewMI = MF.CloneMachineInstr(MI);
379912bdcab5SKrzysztof Parzyszek             NewMI->getOperand(BasePos).setReg(NewBaseReg);
380012bdcab5SKrzysztof Parzyszek             int64_t NewOffset =
380112bdcab5SKrzysztof Parzyszek                 MI->getOperand(OffsetPos).getImm() - It->second.second;
380212bdcab5SKrzysztof Parzyszek             NewMI->getOperand(OffsetPos).setImm(NewOffset);
380312bdcab5SKrzysztof Parzyszek             SU->setInstr(NewMI);
380412bdcab5SKrzysztof Parzyszek             MISUnitMap[NewMI] = SU;
380512bdcab5SKrzysztof Parzyszek             NewMIs.insert(NewMI);
38068f174ddeSKrzysztof Parzyszek           }
38078f174ddeSKrzysztof Parzyszek         }
38088f174ddeSKrzysztof Parzyszek         OverlapReg = 0;
38098f174ddeSKrzysztof Parzyszek         NewBaseReg = 0;
38108f174ddeSKrzysztof Parzyszek         break;
38118f174ddeSKrzysztof Parzyszek       }
38128f174ddeSKrzysztof Parzyszek       // Look for an instruction of the form p' = op(p), which uses and defines
38138f174ddeSKrzysztof Parzyszek       // two virtual registers that get allocated to the same physical register.
38148f174ddeSKrzysztof Parzyszek       unsigned TiedUseIdx = 0;
38158f174ddeSKrzysztof Parzyszek       if (MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
38168f174ddeSKrzysztof Parzyszek         // OverlapReg is p in the example above.
38178f174ddeSKrzysztof Parzyszek         OverlapReg = MI->getOperand(TiedUseIdx).getReg();
38188f174ddeSKrzysztof Parzyszek         // NewBaseReg is p' in the example above.
38198f174ddeSKrzysztof Parzyszek         NewBaseReg = MI->getOperand(i).getReg();
38208f174ddeSKrzysztof Parzyszek         break;
38218f174ddeSKrzysztof Parzyszek       }
38228f174ddeSKrzysztof Parzyszek     }
38238f174ddeSKrzysztof Parzyszek   }
38248f174ddeSKrzysztof Parzyszek }
38258f174ddeSKrzysztof Parzyszek 
3826254f889dSBrendon Cahoon /// After the schedule has been formed, call this function to combine
3827254f889dSBrendon Cahoon /// the instructions from the different stages/cycles.  That is, this
3828254f889dSBrendon Cahoon /// function creates a schedule that represents a single iteration.
3829254f889dSBrendon Cahoon void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
3830254f889dSBrendon Cahoon   // Move all instructions to the first stage from later stages.
3831254f889dSBrendon Cahoon   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3832254f889dSBrendon Cahoon     for (int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
3833254f889dSBrendon Cahoon          ++stage) {
3834254f889dSBrendon Cahoon       std::deque<SUnit *> &cycleInstrs =
3835254f889dSBrendon Cahoon           ScheduledInstrs[cycle + (stage * InitiationInterval)];
3836254f889dSBrendon Cahoon       for (std::deque<SUnit *>::reverse_iterator I = cycleInstrs.rbegin(),
3837254f889dSBrendon Cahoon                                                  E = cycleInstrs.rend();
3838254f889dSBrendon Cahoon            I != E; ++I)
3839254f889dSBrendon Cahoon         ScheduledInstrs[cycle].push_front(*I);
3840254f889dSBrendon Cahoon     }
3841254f889dSBrendon Cahoon   }
3842254f889dSBrendon Cahoon   // Iterate over the definitions in each instruction, and compute the
3843254f889dSBrendon Cahoon   // stage difference for each use.  Keep the maximum value.
3844254f889dSBrendon Cahoon   for (auto &I : InstrToCycle) {
3845254f889dSBrendon Cahoon     int DefStage = stageScheduled(I.first);
3846254f889dSBrendon Cahoon     MachineInstr *MI = I.first->getInstr();
3847254f889dSBrendon Cahoon     for (unsigned i = 0, e = MI->getNumOperands(); i < e; ++i) {
3848254f889dSBrendon Cahoon       MachineOperand &Op = MI->getOperand(i);
3849254f889dSBrendon Cahoon       if (!Op.isReg() || !Op.isDef())
3850254f889dSBrendon Cahoon         continue;
3851254f889dSBrendon Cahoon 
3852254f889dSBrendon Cahoon       unsigned Reg = Op.getReg();
3853254f889dSBrendon Cahoon       unsigned MaxDiff = 0;
3854254f889dSBrendon Cahoon       bool PhiIsSwapped = false;
3855254f889dSBrendon Cahoon       for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(Reg),
3856254f889dSBrendon Cahoon                                              EI = MRI.use_end();
3857254f889dSBrendon Cahoon            UI != EI; ++UI) {
3858254f889dSBrendon Cahoon         MachineOperand &UseOp = *UI;
3859254f889dSBrendon Cahoon         MachineInstr *UseMI = UseOp.getParent();
3860254f889dSBrendon Cahoon         SUnit *SUnitUse = SSD->getSUnit(UseMI);
3861254f889dSBrendon Cahoon         int UseStage = stageScheduled(SUnitUse);
3862254f889dSBrendon Cahoon         unsigned Diff = 0;
3863254f889dSBrendon Cahoon         if (UseStage != -1 && UseStage >= DefStage)
3864254f889dSBrendon Cahoon           Diff = UseStage - DefStage;
3865254f889dSBrendon Cahoon         if (MI->isPHI()) {
3866254f889dSBrendon Cahoon           if (isLoopCarried(SSD, *MI))
3867254f889dSBrendon Cahoon             ++Diff;
3868254f889dSBrendon Cahoon           else
3869254f889dSBrendon Cahoon             PhiIsSwapped = true;
3870254f889dSBrendon Cahoon         }
3871254f889dSBrendon Cahoon         MaxDiff = std::max(Diff, MaxDiff);
3872254f889dSBrendon Cahoon       }
3873254f889dSBrendon Cahoon       RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
3874254f889dSBrendon Cahoon     }
3875254f889dSBrendon Cahoon   }
3876254f889dSBrendon Cahoon 
3877254f889dSBrendon Cahoon   // Erase all the elements in the later stages. Only one iteration should
3878254f889dSBrendon Cahoon   // remain in the scheduled list, and it contains all the instructions.
3879254f889dSBrendon Cahoon   for (int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
3880254f889dSBrendon Cahoon     ScheduledInstrs.erase(cycle);
3881254f889dSBrendon Cahoon 
3882254f889dSBrendon Cahoon   // Change the registers in instruction as specified in the InstrChanges
3883254f889dSBrendon Cahoon   // map. We need to use the new registers to create the correct order.
3884254f889dSBrendon Cahoon   for (int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
3885254f889dSBrendon Cahoon     SUnit *SU = &SSD->SUnits[i];
38868f174ddeSKrzysztof Parzyszek     SSD->applyInstrChange(SU->getInstr(), *this);
3887254f889dSBrendon Cahoon   }
3888254f889dSBrendon Cahoon 
3889254f889dSBrendon Cahoon   // Reorder the instructions in each cycle to fix and improve the
3890254f889dSBrendon Cahoon   // generated code.
3891254f889dSBrendon Cahoon   for (int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <= E; ++Cycle) {
3892254f889dSBrendon Cahoon     std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
3893f13bbf1dSKrzysztof Parzyszek     std::deque<SUnit *> newOrderPhi;
3894254f889dSBrendon Cahoon     for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
3895254f889dSBrendon Cahoon       SUnit *SU = cycleInstrs[i];
3896f13bbf1dSKrzysztof Parzyszek       if (SU->getInstr()->isPHI())
3897f13bbf1dSKrzysztof Parzyszek         newOrderPhi.push_back(SU);
3898254f889dSBrendon Cahoon     }
3899254f889dSBrendon Cahoon     std::deque<SUnit *> newOrderI;
3900254f889dSBrendon Cahoon     for (unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
3901254f889dSBrendon Cahoon       SUnit *SU = cycleInstrs[i];
3902f13bbf1dSKrzysztof Parzyszek       if (!SU->getInstr()->isPHI())
3903254f889dSBrendon Cahoon         orderDependence(SSD, SU, newOrderI);
3904254f889dSBrendon Cahoon     }
3905254f889dSBrendon Cahoon     // Replace the old order with the new order.
3906f13bbf1dSKrzysztof Parzyszek     cycleInstrs.swap(newOrderPhi);
3907254f889dSBrendon Cahoon     cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
39088f174ddeSKrzysztof Parzyszek     SSD->fixupRegisterOverlaps(cycleInstrs);
3909254f889dSBrendon Cahoon   }
3910254f889dSBrendon Cahoon 
3911d34e60caSNicola Zaghen   LLVM_DEBUG(dump(););
3912254f889dSBrendon Cahoon }
3913254f889dSBrendon Cahoon 
3914fa2e3583SAdrian Prantl void NodeSet::print(raw_ostream &os) const {
3915fa2e3583SAdrian Prantl   os << "Num nodes " << size() << " rec " << RecMII << " mov " << MaxMOV
3916fa2e3583SAdrian Prantl      << " depth " << MaxDepth << " col " << Colocate << "\n";
3917fa2e3583SAdrian Prantl   for (const auto &I : Nodes)
3918fa2e3583SAdrian Prantl     os << "   SU(" << I->NodeNum << ") " << *(I->getInstr());
3919fa2e3583SAdrian Prantl   os << "\n";
3920fa2e3583SAdrian Prantl }
3921fa2e3583SAdrian Prantl 
3922615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3923254f889dSBrendon Cahoon /// Print the schedule information to the given output.
3924254f889dSBrendon Cahoon void SMSchedule::print(raw_ostream &os) const {
3925254f889dSBrendon Cahoon   // Iterate over each cycle.
3926254f889dSBrendon Cahoon   for (int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
3927254f889dSBrendon Cahoon     // Iterate over each instruction in the cycle.
3928254f889dSBrendon Cahoon     const_sched_iterator cycleInstrs = ScheduledInstrs.find(cycle);
3929254f889dSBrendon Cahoon     for (SUnit *CI : cycleInstrs->second) {
3930254f889dSBrendon Cahoon       os << "cycle " << cycle << " (" << stageScheduled(CI) << ") ";
3931254f889dSBrendon Cahoon       os << "(" << CI->NodeNum << ") ";
3932254f889dSBrendon Cahoon       CI->getInstr()->print(os);
3933254f889dSBrendon Cahoon       os << "\n";
3934254f889dSBrendon Cahoon     }
3935254f889dSBrendon Cahoon   }
3936254f889dSBrendon Cahoon }
3937254f889dSBrendon Cahoon 
3938254f889dSBrendon Cahoon /// Utility function used for debugging to print the schedule.
39398c209aa8SMatthias Braun LLVM_DUMP_METHOD void SMSchedule::dump() const { print(dbgs()); }
3940fa2e3583SAdrian Prantl LLVM_DUMP_METHOD void NodeSet::dump() const { print(dbgs()); }
3941fa2e3583SAdrian Prantl 
39428c209aa8SMatthias Braun #endif
3943fa2e3583SAdrian Prantl 
3944f6cb3bcbSJinsong Ji void ResourceManager::initProcResourceVectors(
3945f6cb3bcbSJinsong Ji     const MCSchedModel &SM, SmallVectorImpl<uint64_t> &Masks) {
3946f6cb3bcbSJinsong Ji   unsigned ProcResourceID = 0;
3947fa2e3583SAdrian Prantl 
3948f6cb3bcbSJinsong Ji   // We currently limit the resource kinds to 64 and below so that we can use
3949f6cb3bcbSJinsong Ji   // uint64_t for Masks
3950f6cb3bcbSJinsong Ji   assert(SM.getNumProcResourceKinds() < 64 &&
3951f6cb3bcbSJinsong Ji          "Too many kinds of resources, unsupported");
3952f6cb3bcbSJinsong Ji   // Create a unique bitmask for every processor resource unit.
3953f6cb3bcbSJinsong Ji   // Skip resource at index 0, since it always references 'InvalidUnit'.
3954f6cb3bcbSJinsong Ji   Masks.resize(SM.getNumProcResourceKinds());
3955f6cb3bcbSJinsong Ji   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3956f6cb3bcbSJinsong Ji     const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3957f6cb3bcbSJinsong Ji     if (Desc.SubUnitsIdxBegin)
3958f6cb3bcbSJinsong Ji       continue;
3959f6cb3bcbSJinsong Ji     Masks[I] = 1ULL << ProcResourceID;
3960f6cb3bcbSJinsong Ji     ProcResourceID++;
3961f6cb3bcbSJinsong Ji   }
3962f6cb3bcbSJinsong Ji   // Create a unique bitmask for every processor resource group.
3963f6cb3bcbSJinsong Ji   for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3964f6cb3bcbSJinsong Ji     const MCProcResourceDesc &Desc = *SM.getProcResource(I);
3965f6cb3bcbSJinsong Ji     if (!Desc.SubUnitsIdxBegin)
3966f6cb3bcbSJinsong Ji       continue;
3967f6cb3bcbSJinsong Ji     Masks[I] = 1ULL << ProcResourceID;
3968f6cb3bcbSJinsong Ji     for (unsigned U = 0; U < Desc.NumUnits; ++U)
3969f6cb3bcbSJinsong Ji       Masks[I] |= Masks[Desc.SubUnitsIdxBegin[U]];
3970f6cb3bcbSJinsong Ji     ProcResourceID++;
3971f6cb3bcbSJinsong Ji   }
3972f6cb3bcbSJinsong Ji   LLVM_DEBUG({
3973ba43840bSJinsong Ji     if (SwpShowResMask) {
3974f6cb3bcbSJinsong Ji       dbgs() << "ProcResourceDesc:\n";
3975f6cb3bcbSJinsong Ji       for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
3976f6cb3bcbSJinsong Ji         const MCProcResourceDesc *ProcResource = SM.getProcResource(I);
3977f6cb3bcbSJinsong Ji         dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
3978ba43840bSJinsong Ji                          ProcResource->Name, I, Masks[I],
3979ba43840bSJinsong Ji                          ProcResource->NumUnits);
3980f6cb3bcbSJinsong Ji       }
3981f6cb3bcbSJinsong Ji       dbgs() << " -----------------\n";
3982ba43840bSJinsong Ji     }
3983f6cb3bcbSJinsong Ji   });
3984f6cb3bcbSJinsong Ji }
3985f6cb3bcbSJinsong Ji 
3986f6cb3bcbSJinsong Ji bool ResourceManager::canReserveResources(const MCInstrDesc *MID) const {
3987f6cb3bcbSJinsong Ji 
3988ba43840bSJinsong Ji   LLVM_DEBUG({
3989ba43840bSJinsong Ji     if (SwpDebugResource)
3990ba43840bSJinsong Ji       dbgs() << "canReserveResources:\n";
3991ba43840bSJinsong Ji   });
3992f6cb3bcbSJinsong Ji   if (UseDFA)
3993f6cb3bcbSJinsong Ji     return DFAResources->canReserveResources(MID);
3994f6cb3bcbSJinsong Ji 
3995f6cb3bcbSJinsong Ji   unsigned InsnClass = MID->getSchedClass();
3996f6cb3bcbSJinsong Ji   const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
3997f6cb3bcbSJinsong Ji   if (!SCDesc->isValid()) {
3998f6cb3bcbSJinsong Ji     LLVM_DEBUG({
3999f6cb3bcbSJinsong Ji       dbgs() << "No valid Schedule Class Desc for schedClass!\n";
4000f6cb3bcbSJinsong Ji       dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
4001f6cb3bcbSJinsong Ji     });
4002f6cb3bcbSJinsong Ji     return true;
4003f6cb3bcbSJinsong Ji   }
4004f6cb3bcbSJinsong Ji 
4005f6cb3bcbSJinsong Ji   const MCWriteProcResEntry *I = STI->getWriteProcResBegin(SCDesc);
4006f6cb3bcbSJinsong Ji   const MCWriteProcResEntry *E = STI->getWriteProcResEnd(SCDesc);
4007f6cb3bcbSJinsong Ji   for (; I != E; ++I) {
4008f6cb3bcbSJinsong Ji     if (!I->Cycles)
4009f6cb3bcbSJinsong Ji       continue;
4010f6cb3bcbSJinsong Ji     const MCProcResourceDesc *ProcResource =
4011f6cb3bcbSJinsong Ji         SM.getProcResource(I->ProcResourceIdx);
4012f6cb3bcbSJinsong Ji     unsigned NumUnits = ProcResource->NumUnits;
4013f6cb3bcbSJinsong Ji     LLVM_DEBUG({
4014ba43840bSJinsong Ji       if (SwpDebugResource)
4015f6cb3bcbSJinsong Ji         dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
4016f6cb3bcbSJinsong Ji                          ProcResource->Name, I->ProcResourceIdx,
4017f6cb3bcbSJinsong Ji                          ProcResourceCount[I->ProcResourceIdx], NumUnits,
4018f6cb3bcbSJinsong Ji                          I->Cycles);
4019f6cb3bcbSJinsong Ji     });
4020f6cb3bcbSJinsong Ji     if (ProcResourceCount[I->ProcResourceIdx] >= NumUnits)
4021f6cb3bcbSJinsong Ji       return false;
4022f6cb3bcbSJinsong Ji   }
4023ba43840bSJinsong Ji   LLVM_DEBUG(if (SwpDebugResource) dbgs() << "return true\n\n";);
4024f6cb3bcbSJinsong Ji   return true;
4025f6cb3bcbSJinsong Ji }
4026f6cb3bcbSJinsong Ji 
4027f6cb3bcbSJinsong Ji void ResourceManager::reserveResources(const MCInstrDesc *MID) {
4028ba43840bSJinsong Ji   LLVM_DEBUG({
4029ba43840bSJinsong Ji     if (SwpDebugResource)
4030ba43840bSJinsong Ji       dbgs() << "reserveResources:\n";
4031ba43840bSJinsong Ji   });
4032f6cb3bcbSJinsong Ji   if (UseDFA)
4033f6cb3bcbSJinsong Ji     return DFAResources->reserveResources(MID);
4034f6cb3bcbSJinsong Ji 
4035f6cb3bcbSJinsong Ji   unsigned InsnClass = MID->getSchedClass();
4036f6cb3bcbSJinsong Ji   const MCSchedClassDesc *SCDesc = SM.getSchedClassDesc(InsnClass);
4037f6cb3bcbSJinsong Ji   if (!SCDesc->isValid()) {
4038f6cb3bcbSJinsong Ji     LLVM_DEBUG({
4039f6cb3bcbSJinsong Ji       dbgs() << "No valid Schedule Class Desc for schedClass!\n";
4040f6cb3bcbSJinsong Ji       dbgs() << "isPseduo:" << MID->isPseudo() << "\n";
4041f6cb3bcbSJinsong Ji     });
4042f6cb3bcbSJinsong Ji     return;
4043f6cb3bcbSJinsong Ji   }
4044f6cb3bcbSJinsong Ji   for (const MCWriteProcResEntry &PRE :
4045f6cb3bcbSJinsong Ji        make_range(STI->getWriteProcResBegin(SCDesc),
4046f6cb3bcbSJinsong Ji                   STI->getWriteProcResEnd(SCDesc))) {
4047f6cb3bcbSJinsong Ji     if (!PRE.Cycles)
4048f6cb3bcbSJinsong Ji       continue;
4049f6cb3bcbSJinsong Ji     ++ProcResourceCount[PRE.ProcResourceIdx];
4050f6cb3bcbSJinsong Ji     LLVM_DEBUG({
4051ba43840bSJinsong Ji       if (SwpDebugResource) {
4052c77aff7eSRichard Trieu         const MCProcResourceDesc *ProcResource =
4053c77aff7eSRichard Trieu             SM.getProcResource(PRE.ProcResourceIdx);
4054f6cb3bcbSJinsong Ji         dbgs() << format(" %16s(%2d): Count: %2d, NumUnits:%2d, Cycles:%2d\n",
4055f6cb3bcbSJinsong Ji                          ProcResource->Name, PRE.ProcResourceIdx,
4056e8698eadSRichard Trieu                          ProcResourceCount[PRE.ProcResourceIdx],
4057e8698eadSRichard Trieu                          ProcResource->NumUnits, PRE.Cycles);
4058ba43840bSJinsong Ji       }
4059f6cb3bcbSJinsong Ji     });
4060f6cb3bcbSJinsong Ji   }
4061ba43840bSJinsong Ji   LLVM_DEBUG({
4062ba43840bSJinsong Ji     if (SwpDebugResource)
4063ba43840bSJinsong Ji       dbgs() << "reserveResources: done!\n\n";
4064ba43840bSJinsong Ji   });
4065f6cb3bcbSJinsong Ji }
4066f6cb3bcbSJinsong Ji 
4067f6cb3bcbSJinsong Ji bool ResourceManager::canReserveResources(const MachineInstr &MI) const {
4068f6cb3bcbSJinsong Ji   return canReserveResources(&MI.getDesc());
4069f6cb3bcbSJinsong Ji }
4070f6cb3bcbSJinsong Ji 
4071f6cb3bcbSJinsong Ji void ResourceManager::reserveResources(const MachineInstr &MI) {
4072f6cb3bcbSJinsong Ji   return reserveResources(&MI.getDesc());
4073f6cb3bcbSJinsong Ji }
4074f6cb3bcbSJinsong Ji 
4075f6cb3bcbSJinsong Ji void ResourceManager::clearResources() {
4076f6cb3bcbSJinsong Ji   if (UseDFA)
4077f6cb3bcbSJinsong Ji     return DFAResources->clearResources();
4078f6cb3bcbSJinsong Ji   std::fill(ProcResourceCount.begin(), ProcResourceCount.end(), 0);
4079f6cb3bcbSJinsong Ji }
4080fa2e3583SAdrian Prantl 
4081