xref: /src/contrib/llvm-project/llvm/lib/Target/PowerPC/PPCLoopInstrFormPrep.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1706b4fc4SDimitry Andric //===------ PPCLoopInstrFormPrep.cpp - Loop Instr Form Prep Pass ----------===//
2706b4fc4SDimitry Andric //
3706b4fc4SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4706b4fc4SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5706b4fc4SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6706b4fc4SDimitry Andric //
7706b4fc4SDimitry Andric //===----------------------------------------------------------------------===//
8706b4fc4SDimitry Andric //
9706b4fc4SDimitry Andric // This file implements a pass to prepare loops for ppc preferred addressing
10706b4fc4SDimitry Andric // modes, leveraging different instruction form. (eg: DS/DQ form, D/DS form with
11706b4fc4SDimitry Andric // update)
12706b4fc4SDimitry Andric // Additional PHIs are created for loop induction variables used by load/store
13706b4fc4SDimitry Andric // instructions so that preferred addressing modes can be used.
14706b4fc4SDimitry Andric //
15706b4fc4SDimitry Andric // 1: DS/DQ form preparation, prepare the load/store instructions so that they
16706b4fc4SDimitry Andric //    can satisfy the DS/DQ form displacement requirements.
17706b4fc4SDimitry Andric //    Generically, this means transforming loops like this:
18706b4fc4SDimitry Andric //    for (int i = 0; i < n; ++i) {
19706b4fc4SDimitry Andric //      unsigned long x1 = *(unsigned long *)(p + i + 5);
20706b4fc4SDimitry Andric //      unsigned long x2 = *(unsigned long *)(p + i + 9);
21706b4fc4SDimitry Andric //    }
22706b4fc4SDimitry Andric //
23706b4fc4SDimitry Andric //    to look like this:
24706b4fc4SDimitry Andric //
25706b4fc4SDimitry Andric //    unsigned NewP = p + 5;
26706b4fc4SDimitry Andric //    for (int i = 0; i < n; ++i) {
27706b4fc4SDimitry Andric //      unsigned long x1 = *(unsigned long *)(i + NewP);
28706b4fc4SDimitry Andric //      unsigned long x2 = *(unsigned long *)(i + NewP + 4);
29706b4fc4SDimitry Andric //    }
30706b4fc4SDimitry Andric //
31706b4fc4SDimitry Andric // 2: D/DS form with update preparation, prepare the load/store instructions so
32706b4fc4SDimitry Andric //    that we can use update form to do pre-increment.
33706b4fc4SDimitry Andric //    Generically, this means transforming loops like this:
34706b4fc4SDimitry Andric //    for (int i = 0; i < n; ++i)
35706b4fc4SDimitry Andric //      array[i] = c;
36706b4fc4SDimitry Andric //
37706b4fc4SDimitry Andric //    to look like this:
38706b4fc4SDimitry Andric //
39706b4fc4SDimitry Andric //    T *p = array[-1];
40706b4fc4SDimitry Andric //    for (int i = 0; i < n; ++i)
41706b4fc4SDimitry Andric //      *++p = c;
42c0981da4SDimitry Andric //
43c0981da4SDimitry Andric // 3: common multiple chains for the load/stores with same offsets in the loop,
44c0981da4SDimitry Andric //    so that we can reuse the offsets and reduce the register pressure in the
45c0981da4SDimitry Andric //    loop. This transformation can also increase the loop ILP as now each chain
46c0981da4SDimitry Andric //    uses its own loop induction add/addi. But this will increase the number of
47c0981da4SDimitry Andric //    add/addi in the loop.
48c0981da4SDimitry Andric //
49c0981da4SDimitry Andric //    Generically, this means transforming loops like this:
50c0981da4SDimitry Andric //
51c0981da4SDimitry Andric //    char *p;
52c0981da4SDimitry Andric //    A1 = p + base1
53c0981da4SDimitry Andric //    A2 = p + base1 + offset
54c0981da4SDimitry Andric //    B1 = p + base2
55c0981da4SDimitry Andric //    B2 = p + base2 + offset
56c0981da4SDimitry Andric //
57c0981da4SDimitry Andric //    for (int i = 0; i < n; i++)
58c0981da4SDimitry Andric //      unsigned long x1 = *(unsigned long *)(A1 + i);
59c0981da4SDimitry Andric //      unsigned long x2 = *(unsigned long *)(A2 + i)
60c0981da4SDimitry Andric //      unsigned long x3 = *(unsigned long *)(B1 + i);
61c0981da4SDimitry Andric //      unsigned long x4 = *(unsigned long *)(B2 + i);
62c0981da4SDimitry Andric //    }
63c0981da4SDimitry Andric //
64c0981da4SDimitry Andric //    to look like this:
65c0981da4SDimitry Andric //
66c0981da4SDimitry Andric //    A1_new = p + base1 // chain 1
67c0981da4SDimitry Andric //    B1_new = p + base2 // chain 2, now inside the loop, common offset is
68c0981da4SDimitry Andric //                       // reused.
69c0981da4SDimitry Andric //
70c0981da4SDimitry Andric //    for (long long i = 0; i < n; i+=count) {
71c0981da4SDimitry Andric //      unsigned long x1 = *(unsigned long *)(A1_new + i);
72c0981da4SDimitry Andric //      unsigned long x2 = *(unsigned long *)((A1_new + i) + offset);
73c0981da4SDimitry Andric //      unsigned long x3 = *(unsigned long *)(B1_new + i);
74c0981da4SDimitry Andric //      unsigned long x4 = *(unsigned long *)((B1_new + i) + offset);
75c0981da4SDimitry Andric //    }
76706b4fc4SDimitry Andric //===----------------------------------------------------------------------===//
77706b4fc4SDimitry Andric 
78706b4fc4SDimitry Andric #include "PPC.h"
79706b4fc4SDimitry Andric #include "PPCSubtarget.h"
80706b4fc4SDimitry Andric #include "PPCTargetMachine.h"
81706b4fc4SDimitry Andric #include "llvm/ADT/DepthFirstIterator.h"
82706b4fc4SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
83706b4fc4SDimitry Andric #include "llvm/ADT/SmallSet.h"
84706b4fc4SDimitry Andric #include "llvm/ADT/SmallVector.h"
85706b4fc4SDimitry Andric #include "llvm/ADT/Statistic.h"
86706b4fc4SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
87706b4fc4SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
88706b4fc4SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
89706b4fc4SDimitry Andric #include "llvm/IR/BasicBlock.h"
90706b4fc4SDimitry Andric #include "llvm/IR/CFG.h"
91706b4fc4SDimitry Andric #include "llvm/IR/Dominators.h"
92706b4fc4SDimitry Andric #include "llvm/IR/Instruction.h"
93706b4fc4SDimitry Andric #include "llvm/IR/Instructions.h"
94706b4fc4SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
95b60736ecSDimitry Andric #include "llvm/IR/IntrinsicsPowerPC.h"
96706b4fc4SDimitry Andric #include "llvm/IR/Module.h"
97706b4fc4SDimitry Andric #include "llvm/IR/Type.h"
98706b4fc4SDimitry Andric #include "llvm/IR/Value.h"
99706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
100706b4fc4SDimitry Andric #include "llvm/Pass.h"
101706b4fc4SDimitry Andric #include "llvm/Support/Casting.h"
102706b4fc4SDimitry Andric #include "llvm/Support/CommandLine.h"
103706b4fc4SDimitry Andric #include "llvm/Support/Debug.h"
104706b4fc4SDimitry Andric #include "llvm/Transforms/Scalar.h"
105706b4fc4SDimitry Andric #include "llvm/Transforms/Utils.h"
106706b4fc4SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
107706b4fc4SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
108706b4fc4SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
109cfca06d7SDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
110706b4fc4SDimitry Andric #include <cassert>
111e3b55780SDimitry Andric #include <cmath>
112706b4fc4SDimitry Andric #include <iterator>
113706b4fc4SDimitry Andric #include <utility>
114706b4fc4SDimitry Andric 
115344a3780SDimitry Andric #define DEBUG_TYPE "ppc-loop-instr-form-prep"
116344a3780SDimitry Andric 
117706b4fc4SDimitry Andric using namespace llvm;
118706b4fc4SDimitry Andric 
119c0981da4SDimitry Andric static cl::opt<unsigned>
120c0981da4SDimitry Andric     MaxVarsPrep("ppc-formprep-max-vars", cl::Hidden, cl::init(24),
121c0981da4SDimitry Andric                 cl::desc("Potential common base number threshold per function "
122c0981da4SDimitry Andric                          "for PPC loop prep"));
123706b4fc4SDimitry Andric 
124706b4fc4SDimitry Andric static cl::opt<bool> PreferUpdateForm("ppc-formprep-prefer-update",
125706b4fc4SDimitry Andric                                  cl::init(true), cl::Hidden,
126706b4fc4SDimitry Andric   cl::desc("prefer update form when ds form is also a update form"));
127706b4fc4SDimitry Andric 
128c0981da4SDimitry Andric static cl::opt<bool> EnableUpdateFormForNonConstInc(
129c0981da4SDimitry Andric     "ppc-formprep-update-nonconst-inc", cl::init(false), cl::Hidden,
130c0981da4SDimitry Andric     cl::desc("prepare update form when the load/store increment is a loop "
131c0981da4SDimitry Andric              "invariant non-const value."));
132c0981da4SDimitry Andric 
133c0981da4SDimitry Andric static cl::opt<bool> EnableChainCommoning(
134c0981da4SDimitry Andric     "ppc-formprep-chain-commoning", cl::init(false), cl::Hidden,
135c0981da4SDimitry Andric     cl::desc("Enable chain commoning in PPC loop prepare pass."));
136c0981da4SDimitry Andric 
137706b4fc4SDimitry Andric // Sum of following 3 per loop thresholds for all loops can not be larger
138706b4fc4SDimitry Andric // than MaxVarsPrep.
139b60736ecSDimitry Andric // now the thresholds for each kind prep are exterimental values on Power9.
140706b4fc4SDimitry Andric static cl::opt<unsigned> MaxVarsUpdateForm("ppc-preinc-prep-max-vars",
141706b4fc4SDimitry Andric                                  cl::Hidden, cl::init(3),
142706b4fc4SDimitry Andric   cl::desc("Potential PHI threshold per loop for PPC loop prep of update "
143706b4fc4SDimitry Andric            "form"));
144706b4fc4SDimitry Andric 
145706b4fc4SDimitry Andric static cl::opt<unsigned> MaxVarsDSForm("ppc-dsprep-max-vars",
146706b4fc4SDimitry Andric                                  cl::Hidden, cl::init(3),
147706b4fc4SDimitry Andric   cl::desc("Potential PHI threshold per loop for PPC loop prep of DS form"));
148706b4fc4SDimitry Andric 
149706b4fc4SDimitry Andric static cl::opt<unsigned> MaxVarsDQForm("ppc-dqprep-max-vars",
150b60736ecSDimitry Andric                                  cl::Hidden, cl::init(8),
151706b4fc4SDimitry Andric   cl::desc("Potential PHI threshold per loop for PPC loop prep of DQ form"));
152706b4fc4SDimitry Andric 
153c0981da4SDimitry Andric // Commoning chain will reduce the register pressure, so we don't consider about
154c0981da4SDimitry Andric // the PHI nodes number.
155c0981da4SDimitry Andric // But commoning chain will increase the addi/add number in the loop and also
156c0981da4SDimitry Andric // increase loop ILP. Maximum chain number should be same with hardware
157c0981da4SDimitry Andric // IssueWidth, because we won't benefit from ILP if the parallel chains number
158c0981da4SDimitry Andric // is bigger than IssueWidth. We assume there are 2 chains in one bucket, so
159c0981da4SDimitry Andric // there would be 4 buckets at most on P9(IssueWidth is 8).
160c0981da4SDimitry Andric static cl::opt<unsigned> MaxVarsChainCommon(
161c0981da4SDimitry Andric     "ppc-chaincommon-max-vars", cl::Hidden, cl::init(4),
162c0981da4SDimitry Andric     cl::desc("Bucket number per loop for PPC loop chain common"));
163706b4fc4SDimitry Andric 
164706b4fc4SDimitry Andric // If would not be profitable if the common base has only one load/store, ISEL
165706b4fc4SDimitry Andric // should already be able to choose best load/store form based on offset for
166706b4fc4SDimitry Andric // single load/store. Set minimal profitable value default to 2 and make it as
167706b4fc4SDimitry Andric // an option.
168706b4fc4SDimitry Andric static cl::opt<unsigned> DispFormPrepMinThreshold("ppc-dispprep-min-threshold",
169706b4fc4SDimitry Andric                                     cl::Hidden, cl::init(2),
170706b4fc4SDimitry Andric   cl::desc("Minimal common base load/store instructions triggering DS/DQ form "
171706b4fc4SDimitry Andric            "preparation"));
172706b4fc4SDimitry Andric 
173c0981da4SDimitry Andric static cl::opt<unsigned> ChainCommonPrepMinThreshold(
174c0981da4SDimitry Andric     "ppc-chaincommon-min-threshold", cl::Hidden, cl::init(4),
175c0981da4SDimitry Andric     cl::desc("Minimal common base load/store instructions triggering chain "
176c0981da4SDimitry Andric              "commoning preparation. Must be not smaller than 4"));
177c0981da4SDimitry Andric 
178706b4fc4SDimitry Andric STATISTIC(PHINodeAlreadyExistsUpdate, "PHI node already in pre-increment form");
179706b4fc4SDimitry Andric STATISTIC(PHINodeAlreadyExistsDS, "PHI node already in DS form");
180706b4fc4SDimitry Andric STATISTIC(PHINodeAlreadyExistsDQ, "PHI node already in DQ form");
181706b4fc4SDimitry Andric STATISTIC(DSFormChainRewritten, "Num of DS form chain rewritten");
182706b4fc4SDimitry Andric STATISTIC(DQFormChainRewritten, "Num of DQ form chain rewritten");
183706b4fc4SDimitry Andric STATISTIC(UpdFormChainRewritten, "Num of update form chain rewritten");
184c0981da4SDimitry Andric STATISTIC(ChainCommoningRewritten, "Num of commoning chains");
185706b4fc4SDimitry Andric 
186706b4fc4SDimitry Andric namespace {
187706b4fc4SDimitry Andric   struct BucketElement {
BucketElement__anonfc27e9820111::BucketElement188c0981da4SDimitry Andric     BucketElement(const SCEV *O, Instruction *I) : Offset(O), Instr(I) {}
BucketElement__anonfc27e9820111::BucketElement189706b4fc4SDimitry Andric     BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {}
190706b4fc4SDimitry Andric 
191c0981da4SDimitry Andric     const SCEV *Offset;
192706b4fc4SDimitry Andric     Instruction *Instr;
193706b4fc4SDimitry Andric   };
194706b4fc4SDimitry Andric 
195706b4fc4SDimitry Andric   struct Bucket {
Bucket__anonfc27e9820111::Bucket196c0981da4SDimitry Andric     Bucket(const SCEV *B, Instruction *I)
197c0981da4SDimitry Andric         : BaseSCEV(B), Elements(1, BucketElement(I)) {
198c0981da4SDimitry Andric       ChainSize = 0;
199c0981da4SDimitry Andric     }
200706b4fc4SDimitry Andric 
201c0981da4SDimitry Andric     // The base of the whole bucket.
202706b4fc4SDimitry Andric     const SCEV *BaseSCEV;
203c0981da4SDimitry Andric 
204c0981da4SDimitry Andric     // All elements in the bucket. In the bucket, the element with the BaseSCEV
205c0981da4SDimitry Andric     // has no offset and all other elements are stored as offsets to the
206c0981da4SDimitry Andric     // BaseSCEV.
207706b4fc4SDimitry Andric     SmallVector<BucketElement, 16> Elements;
208c0981da4SDimitry Andric 
209c0981da4SDimitry Andric     // The potential chains size. This is used for chain commoning only.
210c0981da4SDimitry Andric     unsigned ChainSize;
211c0981da4SDimitry Andric 
212c0981da4SDimitry Andric     // The base for each potential chain. This is used for chain commoning only.
213c0981da4SDimitry Andric     SmallVector<BucketElement, 16> ChainBases;
214706b4fc4SDimitry Andric   };
215706b4fc4SDimitry Andric 
216706b4fc4SDimitry Andric   // "UpdateForm" is not a real PPC instruction form, it stands for dform
217706b4fc4SDimitry Andric   // load/store with update like ldu/stdu, or Prefetch intrinsic.
218706b4fc4SDimitry Andric   // For DS form instructions, their displacements must be multiple of 4.
219706b4fc4SDimitry Andric   // For DQ form instructions, their displacements must be multiple of 16.
220c0981da4SDimitry Andric   enum PrepForm { UpdateForm = 1, DSForm = 4, DQForm = 16, ChainCommoning };
221706b4fc4SDimitry Andric 
222706b4fc4SDimitry Andric   class PPCLoopInstrFormPrep : public FunctionPass {
223706b4fc4SDimitry Andric   public:
224706b4fc4SDimitry Andric     static char ID; // Pass ID, replacement for typeid
225706b4fc4SDimitry Andric 
PPCLoopInstrFormPrep()226706b4fc4SDimitry Andric     PPCLoopInstrFormPrep() : FunctionPass(ID) {
227706b4fc4SDimitry Andric       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
228706b4fc4SDimitry Andric     }
229706b4fc4SDimitry Andric 
PPCLoopInstrFormPrep(PPCTargetMachine & TM)230706b4fc4SDimitry Andric     PPCLoopInstrFormPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
231706b4fc4SDimitry Andric       initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
232706b4fc4SDimitry Andric     }
233706b4fc4SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const234706b4fc4SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
235706b4fc4SDimitry Andric       AU.addPreserved<DominatorTreeWrapperPass>();
236706b4fc4SDimitry Andric       AU.addRequired<LoopInfoWrapperPass>();
237706b4fc4SDimitry Andric       AU.addPreserved<LoopInfoWrapperPass>();
238706b4fc4SDimitry Andric       AU.addRequired<ScalarEvolutionWrapperPass>();
239706b4fc4SDimitry Andric     }
240706b4fc4SDimitry Andric 
241706b4fc4SDimitry Andric     bool runOnFunction(Function &F) override;
242706b4fc4SDimitry Andric 
243706b4fc4SDimitry Andric   private:
244706b4fc4SDimitry Andric     PPCTargetMachine *TM = nullptr;
245706b4fc4SDimitry Andric     const PPCSubtarget *ST;
246706b4fc4SDimitry Andric     DominatorTree *DT;
247706b4fc4SDimitry Andric     LoopInfo *LI;
248706b4fc4SDimitry Andric     ScalarEvolution *SE;
249706b4fc4SDimitry Andric     bool PreserveLCSSA;
250c0981da4SDimitry Andric     bool HasCandidateForPrepare;
251706b4fc4SDimitry Andric 
252706b4fc4SDimitry Andric     /// Successful preparation number for Update/DS/DQ form in all inner most
253706b4fc4SDimitry Andric     /// loops. One successful preparation will put one common base out of loop,
254706b4fc4SDimitry Andric     /// this may leads to register presure like LICM does.
255706b4fc4SDimitry Andric     /// Make sure total preparation number can be controlled by option.
256706b4fc4SDimitry Andric     unsigned SuccPrepCount;
257706b4fc4SDimitry Andric 
258706b4fc4SDimitry Andric     bool runOnLoop(Loop *L);
259706b4fc4SDimitry Andric 
260706b4fc4SDimitry Andric     /// Check if required PHI node is already exist in Loop \p L.
261706b4fc4SDimitry Andric     bool alreadyPrepared(Loop *L, Instruction *MemI,
262706b4fc4SDimitry Andric                          const SCEV *BasePtrStartSCEV,
263c0981da4SDimitry Andric                          const SCEV *BasePtrIncSCEV, PrepForm Form);
264c0981da4SDimitry Andric 
265c0981da4SDimitry Andric     /// Get the value which defines the increment SCEV \p BasePtrIncSCEV.
266c0981da4SDimitry Andric     Value *getNodeForInc(Loop *L, Instruction *MemI,
267c0981da4SDimitry Andric                          const SCEV *BasePtrIncSCEV);
268c0981da4SDimitry Andric 
269c0981da4SDimitry Andric     /// Common chains to reuse offsets for a loop to reduce register pressure.
270c0981da4SDimitry Andric     bool chainCommoning(Loop *L, SmallVector<Bucket, 16> &Buckets);
271c0981da4SDimitry Andric 
272c0981da4SDimitry Andric     /// Find out the potential commoning chains and their bases.
273c0981da4SDimitry Andric     bool prepareBasesForCommoningChains(Bucket &BucketChain);
274c0981da4SDimitry Andric 
275c0981da4SDimitry Andric     /// Rewrite load/store according to the common chains.
276c0981da4SDimitry Andric     bool
277c0981da4SDimitry Andric     rewriteLoadStoresForCommoningChains(Loop *L, Bucket &Bucket,
278c0981da4SDimitry Andric                                         SmallSet<BasicBlock *, 16> &BBChanged);
279706b4fc4SDimitry Andric 
280706b4fc4SDimitry Andric     /// Collect condition matched(\p isValidCandidate() returns true)
281706b4fc4SDimitry Andric     /// candidates in Loop \p L.
282344a3780SDimitry Andric     SmallVector<Bucket, 16> collectCandidates(
283344a3780SDimitry Andric         Loop *L,
284c0981da4SDimitry Andric         std::function<bool(const Instruction *, Value *, const Type *)>
285706b4fc4SDimitry Andric             isValidCandidate,
286c0981da4SDimitry Andric         std::function<bool(const SCEV *)> isValidDiff,
287706b4fc4SDimitry Andric         unsigned MaxCandidateNum);
288706b4fc4SDimitry Andric 
289c0981da4SDimitry Andric     /// Add a candidate to candidates \p Buckets if diff between candidate and
290c0981da4SDimitry Andric     /// one base in \p Buckets matches \p isValidDiff.
291706b4fc4SDimitry Andric     void addOneCandidate(Instruction *MemI, const SCEV *LSCEV,
292706b4fc4SDimitry Andric                          SmallVector<Bucket, 16> &Buckets,
293c0981da4SDimitry Andric                          std::function<bool(const SCEV *)> isValidDiff,
294706b4fc4SDimitry Andric                          unsigned MaxCandidateNum);
295706b4fc4SDimitry Andric 
296706b4fc4SDimitry Andric     /// Prepare all candidates in \p Buckets for update form.
297706b4fc4SDimitry Andric     bool updateFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets);
298706b4fc4SDimitry Andric 
299706b4fc4SDimitry Andric     /// Prepare all candidates in \p Buckets for displacement form, now for
300706b4fc4SDimitry Andric     /// ds/dq.
301c0981da4SDimitry Andric     bool dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets, PrepForm Form);
302706b4fc4SDimitry Andric 
303706b4fc4SDimitry Andric     /// Prepare for one chain \p BucketChain, find the best base element and
304706b4fc4SDimitry Andric     /// update all other elements in \p BucketChain accordingly.
305706b4fc4SDimitry Andric     /// \p Form is used to find the best base element.
306706b4fc4SDimitry Andric     /// If success, best base element must be stored as the first element of
307706b4fc4SDimitry Andric     /// \p BucketChain.
308706b4fc4SDimitry Andric     /// Return false if no base element found, otherwise return true.
309c0981da4SDimitry Andric     bool prepareBaseForDispFormChain(Bucket &BucketChain, PrepForm Form);
310706b4fc4SDimitry Andric 
311706b4fc4SDimitry Andric     /// Prepare for one chain \p BucketChain, find the best base element and
312706b4fc4SDimitry Andric     /// update all other elements in \p BucketChain accordingly.
313706b4fc4SDimitry Andric     /// If success, best base element must be stored as the first element of
314706b4fc4SDimitry Andric     /// \p BucketChain.
315706b4fc4SDimitry Andric     /// Return false if no base element found, otherwise return true.
316706b4fc4SDimitry Andric     bool prepareBaseForUpdateFormChain(Bucket &BucketChain);
317706b4fc4SDimitry Andric 
318706b4fc4SDimitry Andric     /// Rewrite load/store instructions in \p BucketChain according to
319706b4fc4SDimitry Andric     /// preparation.
320706b4fc4SDimitry Andric     bool rewriteLoadStores(Loop *L, Bucket &BucketChain,
321706b4fc4SDimitry Andric                            SmallSet<BasicBlock *, 16> &BBChanged,
322c0981da4SDimitry Andric                            PrepForm Form);
323c0981da4SDimitry Andric 
324c0981da4SDimitry Andric     /// Rewrite for the base load/store of a chain.
325c0981da4SDimitry Andric     std::pair<Instruction *, Instruction *>
326c0981da4SDimitry Andric     rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
327c0981da4SDimitry Andric                    Instruction *BaseMemI, bool CanPreInc, PrepForm Form,
328c0981da4SDimitry Andric                    SCEVExpander &SCEVE, SmallPtrSet<Value *, 16> &DeletedPtrs);
329c0981da4SDimitry Andric 
330c0981da4SDimitry Andric     /// Rewrite for the other load/stores of a chain according to the new \p
331c0981da4SDimitry Andric     /// Base.
332c0981da4SDimitry Andric     Instruction *
333c0981da4SDimitry Andric     rewriteForBucketElement(std::pair<Instruction *, Instruction *> Base,
334c0981da4SDimitry Andric                             const BucketElement &Element, Value *OffToBase,
335c0981da4SDimitry Andric                             SmallPtrSet<Value *, 16> &DeletedPtrs);
336706b4fc4SDimitry Andric   };
337706b4fc4SDimitry Andric 
338706b4fc4SDimitry Andric } // end anonymous namespace
339706b4fc4SDimitry Andric 
340706b4fc4SDimitry Andric char PPCLoopInstrFormPrep::ID = 0;
341706b4fc4SDimitry Andric static const char *name = "Prepare loop for ppc preferred instruction forms";
342706b4fc4SDimitry Andric INITIALIZE_PASS_BEGIN(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
343706b4fc4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
344706b4fc4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
345706b4fc4SDimitry Andric INITIALIZE_PASS_END(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
346706b4fc4SDimitry Andric 
347cfca06d7SDimitry Andric static constexpr StringRef PHINodeNameSuffix    = ".phi";
348cfca06d7SDimitry Andric static constexpr StringRef CastNodeNameSuffix   = ".cast";
349cfca06d7SDimitry Andric static constexpr StringRef GEPNodeIncNameSuffix = ".inc";
350cfca06d7SDimitry Andric static constexpr StringRef GEPNodeOffNameSuffix = ".off";
351706b4fc4SDimitry Andric 
createPPCLoopInstrFormPrepPass(PPCTargetMachine & TM)352706b4fc4SDimitry Andric FunctionPass *llvm::createPPCLoopInstrFormPrepPass(PPCTargetMachine &TM) {
353706b4fc4SDimitry Andric   return new PPCLoopInstrFormPrep(TM);
354706b4fc4SDimitry Andric }
355706b4fc4SDimitry Andric 
IsPtrInBounds(Value * BasePtr)356706b4fc4SDimitry Andric static bool IsPtrInBounds(Value *BasePtr) {
357706b4fc4SDimitry Andric   Value *StrippedBasePtr = BasePtr;
358706b4fc4SDimitry Andric   while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
359706b4fc4SDimitry Andric     StrippedBasePtr = BC->getOperand(0);
360706b4fc4SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
361706b4fc4SDimitry Andric     return GEP->isInBounds();
362706b4fc4SDimitry Andric 
363706b4fc4SDimitry Andric   return false;
364706b4fc4SDimitry Andric }
365706b4fc4SDimitry Andric 
getInstrName(const Value * I,StringRef Suffix)366cfca06d7SDimitry Andric static std::string getInstrName(const Value *I, StringRef Suffix) {
367706b4fc4SDimitry Andric   assert(I && "Invalid paramater!");
368706b4fc4SDimitry Andric   if (I->hasName())
369706b4fc4SDimitry Andric     return (I->getName() + Suffix).str();
370706b4fc4SDimitry Andric   else
371706b4fc4SDimitry Andric     return "";
372706b4fc4SDimitry Andric }
373706b4fc4SDimitry Andric 
getPointerOperandAndType(Value * MemI,Type ** PtrElementType=nullptr)374c0981da4SDimitry Andric static Value *getPointerOperandAndType(Value *MemI,
375c0981da4SDimitry Andric                                        Type **PtrElementType = nullptr) {
376706b4fc4SDimitry Andric 
377c0981da4SDimitry Andric   Value *PtrValue = nullptr;
378c0981da4SDimitry Andric   Type *PointerElementType = nullptr;
379c0981da4SDimitry Andric 
380c0981da4SDimitry Andric   if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
381c0981da4SDimitry Andric     PtrValue = LMemI->getPointerOperand();
382c0981da4SDimitry Andric     PointerElementType = LMemI->getType();
383c0981da4SDimitry Andric   } else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
384c0981da4SDimitry Andric     PtrValue = SMemI->getPointerOperand();
385c0981da4SDimitry Andric     PointerElementType = SMemI->getValueOperand()->getType();
386c0981da4SDimitry Andric   } else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
387c0981da4SDimitry Andric     PointerElementType = Type::getInt8Ty(MemI->getContext());
388c0981da4SDimitry Andric     if (IMemI->getIntrinsicID() == Intrinsic::prefetch ||
389c0981da4SDimitry Andric         IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) {
390c0981da4SDimitry Andric       PtrValue = IMemI->getArgOperand(0);
391c0981da4SDimitry Andric     } else if (IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp) {
392c0981da4SDimitry Andric       PtrValue = IMemI->getArgOperand(1);
393c0981da4SDimitry Andric     }
394c0981da4SDimitry Andric   }
395c0981da4SDimitry Andric   /*Get ElementType if PtrElementType is not null.*/
396c0981da4SDimitry Andric   if (PtrElementType)
397c0981da4SDimitry Andric     *PtrElementType = PointerElementType;
398c0981da4SDimitry Andric 
399c0981da4SDimitry Andric   return PtrValue;
400706b4fc4SDimitry Andric }
401706b4fc4SDimitry Andric 
runOnFunction(Function & F)402706b4fc4SDimitry Andric bool PPCLoopInstrFormPrep::runOnFunction(Function &F) {
403706b4fc4SDimitry Andric   if (skipFunction(F))
404706b4fc4SDimitry Andric     return false;
405706b4fc4SDimitry Andric 
406706b4fc4SDimitry Andric   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
407706b4fc4SDimitry Andric   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
408706b4fc4SDimitry Andric   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
409706b4fc4SDimitry Andric   DT = DTWP ? &DTWP->getDomTree() : nullptr;
410706b4fc4SDimitry Andric   PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
411706b4fc4SDimitry Andric   ST = TM ? TM->getSubtargetImpl(F) : nullptr;
412706b4fc4SDimitry Andric   SuccPrepCount = 0;
413706b4fc4SDimitry Andric 
414706b4fc4SDimitry Andric   bool MadeChange = false;
415706b4fc4SDimitry Andric 
41677fc4c14SDimitry Andric   for (Loop *I : *LI)
41777fc4c14SDimitry Andric     for (Loop *L : depth_first(I))
41877fc4c14SDimitry Andric       MadeChange |= runOnLoop(L);
419706b4fc4SDimitry Andric 
420706b4fc4SDimitry Andric   return MadeChange;
421706b4fc4SDimitry Andric }
422706b4fc4SDimitry Andric 
423c0981da4SDimitry Andric // Finding the minimal(chain_number + reusable_offset_number) is a complicated
424c0981da4SDimitry Andric // algorithmic problem.
425c0981da4SDimitry Andric // For now, the algorithm used here is simply adjusted to handle the case for
426c0981da4SDimitry Andric // manually unrolling cases.
427c0981da4SDimitry Andric // FIXME: use a more powerful algorithm to find minimal sum of chain_number and
428c0981da4SDimitry Andric // reusable_offset_number for one base with multiple offsets.
prepareBasesForCommoningChains(Bucket & CBucket)429c0981da4SDimitry Andric bool PPCLoopInstrFormPrep::prepareBasesForCommoningChains(Bucket &CBucket) {
430c0981da4SDimitry Andric   // The minimal size for profitable chain commoning:
431c0981da4SDimitry Andric   // A1 = base + offset1
432c0981da4SDimitry Andric   // A2 = base + offset2 (offset2 - offset1 = X)
433c0981da4SDimitry Andric   // A3 = base + offset3
434c0981da4SDimitry Andric   // A4 = base + offset4 (offset4 - offset3 = X)
435c0981da4SDimitry Andric   // ======>
436c0981da4SDimitry Andric   // base1 = base + offset1
437c0981da4SDimitry Andric   // base2 = base + offset3
438c0981da4SDimitry Andric   // A1 = base1
439c0981da4SDimitry Andric   // A2 = base1 + X
440c0981da4SDimitry Andric   // A3 = base2
441c0981da4SDimitry Andric   // A4 = base2 + X
442c0981da4SDimitry Andric   //
443c0981da4SDimitry Andric   // There is benefit because of reuse of offest 'X'.
444c0981da4SDimitry Andric 
445c0981da4SDimitry Andric   assert(ChainCommonPrepMinThreshold >= 4 &&
446c0981da4SDimitry Andric          "Thredhold can not be smaller than 4!\n");
447c0981da4SDimitry Andric   if (CBucket.Elements.size() < ChainCommonPrepMinThreshold)
448c0981da4SDimitry Andric     return false;
449c0981da4SDimitry Andric 
450c0981da4SDimitry Andric   // We simply select the FirstOffset as the first reusable offset between each
451c0981da4SDimitry Andric   // chain element 1 and element 0.
452c0981da4SDimitry Andric   const SCEV *FirstOffset = CBucket.Elements[1].Offset;
453c0981da4SDimitry Andric 
454c0981da4SDimitry Andric   // Figure out how many times above FirstOffset is used in the chain.
455c0981da4SDimitry Andric   // For a success commoning chain candidate, offset difference between each
456c0981da4SDimitry Andric   // chain element 1 and element 0 must be also FirstOffset.
457c0981da4SDimitry Andric   unsigned FirstOffsetReusedCount = 1;
458c0981da4SDimitry Andric 
459c0981da4SDimitry Andric   // Figure out how many times above FirstOffset is used in the first chain.
460c0981da4SDimitry Andric   // Chain number is FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain
461c0981da4SDimitry Andric   unsigned FirstOffsetReusedCountInFirstChain = 1;
462c0981da4SDimitry Andric 
463c0981da4SDimitry Andric   unsigned EleNum = CBucket.Elements.size();
464c0981da4SDimitry Andric   bool SawChainSeparater = false;
465c0981da4SDimitry Andric   for (unsigned j = 2; j != EleNum; ++j) {
466c0981da4SDimitry Andric     if (SE->getMinusSCEV(CBucket.Elements[j].Offset,
467c0981da4SDimitry Andric                          CBucket.Elements[j - 1].Offset) == FirstOffset) {
468c0981da4SDimitry Andric       if (!SawChainSeparater)
469c0981da4SDimitry Andric         FirstOffsetReusedCountInFirstChain++;
470c0981da4SDimitry Andric       FirstOffsetReusedCount++;
471c0981da4SDimitry Andric     } else
472c0981da4SDimitry Andric       // For now, if we meet any offset which is not FirstOffset, we assume we
473c0981da4SDimitry Andric       // find a new Chain.
474c0981da4SDimitry Andric       // This makes us miss some opportunities.
475c0981da4SDimitry Andric       // For example, we can common:
476c0981da4SDimitry Andric       //
477c0981da4SDimitry Andric       // {OffsetA, Offset A, OffsetB, OffsetA, OffsetA, OffsetB}
478c0981da4SDimitry Andric       //
479c0981da4SDimitry Andric       // as two chains:
480c0981da4SDimitry Andric       // {{OffsetA, Offset A, OffsetB}, {OffsetA, OffsetA, OffsetB}}
481c0981da4SDimitry Andric       // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 2
482c0981da4SDimitry Andric       //
483c0981da4SDimitry Andric       // But we fail to common:
484c0981da4SDimitry Andric       //
485c0981da4SDimitry Andric       // {OffsetA, OffsetB, OffsetA, OffsetA, OffsetB, OffsetA}
486c0981da4SDimitry Andric       // FirstOffsetReusedCount = 4; FirstOffsetReusedCountInFirstChain = 1
487c0981da4SDimitry Andric 
488c0981da4SDimitry Andric       SawChainSeparater = true;
489c0981da4SDimitry Andric   }
490c0981da4SDimitry Andric 
491c0981da4SDimitry Andric   // FirstOffset is not reused, skip this bucket.
492c0981da4SDimitry Andric   if (FirstOffsetReusedCount == 1)
493c0981da4SDimitry Andric     return false;
494c0981da4SDimitry Andric 
495c0981da4SDimitry Andric   unsigned ChainNum =
496c0981da4SDimitry Andric       FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain;
497c0981da4SDimitry Andric 
498c0981da4SDimitry Andric   // All elements are increased by FirstOffset.
499c0981da4SDimitry Andric   // The number of chains should be sqrt(EleNum).
500c0981da4SDimitry Andric   if (!SawChainSeparater)
501c0981da4SDimitry Andric     ChainNum = (unsigned)sqrt((double)EleNum);
502c0981da4SDimitry Andric 
503c0981da4SDimitry Andric   CBucket.ChainSize = (unsigned)(EleNum / ChainNum);
504c0981da4SDimitry Andric 
505c0981da4SDimitry Andric   // If this is not a perfect chain(eg: not all elements can be put inside
506c0981da4SDimitry Andric   // commoning chains.), skip now.
507c0981da4SDimitry Andric   if (CBucket.ChainSize * ChainNum != EleNum)
508c0981da4SDimitry Andric     return false;
509c0981da4SDimitry Andric 
510c0981da4SDimitry Andric   if (SawChainSeparater) {
511c0981da4SDimitry Andric     // Check that the offset seqs are the same for all chains.
512c0981da4SDimitry Andric     for (unsigned i = 1; i < CBucket.ChainSize; i++)
513c0981da4SDimitry Andric       for (unsigned j = 1; j < ChainNum; j++)
514c0981da4SDimitry Andric         if (CBucket.Elements[i].Offset !=
515c0981da4SDimitry Andric             SE->getMinusSCEV(CBucket.Elements[i + j * CBucket.ChainSize].Offset,
516c0981da4SDimitry Andric                              CBucket.Elements[j * CBucket.ChainSize].Offset))
517c0981da4SDimitry Andric           return false;
518c0981da4SDimitry Andric   }
519c0981da4SDimitry Andric 
520c0981da4SDimitry Andric   for (unsigned i = 0; i < ChainNum; i++)
521c0981da4SDimitry Andric     CBucket.ChainBases.push_back(CBucket.Elements[i * CBucket.ChainSize]);
522c0981da4SDimitry Andric 
523c0981da4SDimitry Andric   LLVM_DEBUG(dbgs() << "Bucket has " << ChainNum << " chains.\n");
524c0981da4SDimitry Andric 
525c0981da4SDimitry Andric   return true;
526c0981da4SDimitry Andric }
527c0981da4SDimitry Andric 
chainCommoning(Loop * L,SmallVector<Bucket,16> & Buckets)528c0981da4SDimitry Andric bool PPCLoopInstrFormPrep::chainCommoning(Loop *L,
529c0981da4SDimitry Andric                                           SmallVector<Bucket, 16> &Buckets) {
530c0981da4SDimitry Andric   bool MadeChange = false;
531c0981da4SDimitry Andric 
532c0981da4SDimitry Andric   if (Buckets.empty())
533c0981da4SDimitry Andric     return MadeChange;
534c0981da4SDimitry Andric 
535c0981da4SDimitry Andric   SmallSet<BasicBlock *, 16> BBChanged;
536c0981da4SDimitry Andric 
537c0981da4SDimitry Andric   for (auto &Bucket : Buckets) {
538c0981da4SDimitry Andric     if (prepareBasesForCommoningChains(Bucket))
539c0981da4SDimitry Andric       MadeChange |= rewriteLoadStoresForCommoningChains(L, Bucket, BBChanged);
540c0981da4SDimitry Andric   }
541c0981da4SDimitry Andric 
542c0981da4SDimitry Andric   if (MadeChange)
543c0981da4SDimitry Andric     for (auto *BB : BBChanged)
544c0981da4SDimitry Andric       DeleteDeadPHIs(BB);
545c0981da4SDimitry Andric   return MadeChange;
546c0981da4SDimitry Andric }
547c0981da4SDimitry Andric 
rewriteLoadStoresForCommoningChains(Loop * L,Bucket & Bucket,SmallSet<BasicBlock *,16> & BBChanged)548c0981da4SDimitry Andric bool PPCLoopInstrFormPrep::rewriteLoadStoresForCommoningChains(
549c0981da4SDimitry Andric     Loop *L, Bucket &Bucket, SmallSet<BasicBlock *, 16> &BBChanged) {
550c0981da4SDimitry Andric   bool MadeChange = false;
551c0981da4SDimitry Andric 
552c0981da4SDimitry Andric   assert(Bucket.Elements.size() ==
553c0981da4SDimitry Andric              Bucket.ChainBases.size() * Bucket.ChainSize &&
554c0981da4SDimitry Andric          "invalid bucket for chain commoning!\n");
555c0981da4SDimitry Andric   SmallPtrSet<Value *, 16> DeletedPtrs;
556c0981da4SDimitry Andric 
557c0981da4SDimitry Andric   BasicBlock *Header = L->getHeader();
558c0981da4SDimitry Andric   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
559c0981da4SDimitry Andric 
560ac9a064cSDimitry Andric   SCEVExpander SCEVE(*SE, Header->getDataLayout(),
561c0981da4SDimitry Andric                      "loopprepare-chaincommon");
562c0981da4SDimitry Andric 
563c0981da4SDimitry Andric   for (unsigned ChainIdx = 0; ChainIdx < Bucket.ChainBases.size(); ++ChainIdx) {
564c0981da4SDimitry Andric     unsigned BaseElemIdx = Bucket.ChainSize * ChainIdx;
565c0981da4SDimitry Andric     const SCEV *BaseSCEV =
566c0981da4SDimitry Andric         ChainIdx ? SE->getAddExpr(Bucket.BaseSCEV,
567c0981da4SDimitry Andric                                   Bucket.Elements[BaseElemIdx].Offset)
568c0981da4SDimitry Andric                  : Bucket.BaseSCEV;
569c0981da4SDimitry Andric     const SCEVAddRecExpr *BasePtrSCEV = cast<SCEVAddRecExpr>(BaseSCEV);
570c0981da4SDimitry Andric 
571c0981da4SDimitry Andric     // Make sure the base is able to expand.
5724b4fe385SDimitry Andric     if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart()))
573c0981da4SDimitry Andric       return MadeChange;
574c0981da4SDimitry Andric 
575c0981da4SDimitry Andric     assert(BasePtrSCEV->isAffine() &&
576c0981da4SDimitry Andric            "Invalid SCEV type for the base ptr for a candidate chain!\n");
577c0981da4SDimitry Andric 
578c0981da4SDimitry Andric     std::pair<Instruction *, Instruction *> Base = rewriteForBase(
579c0981da4SDimitry Andric         L, BasePtrSCEV, Bucket.Elements[BaseElemIdx].Instr,
580c0981da4SDimitry Andric         false /* CanPreInc */, ChainCommoning, SCEVE, DeletedPtrs);
581c0981da4SDimitry Andric 
582c0981da4SDimitry Andric     if (!Base.first || !Base.second)
583c0981da4SDimitry Andric       return MadeChange;
584c0981da4SDimitry Andric 
585c0981da4SDimitry Andric     // Keep track of the replacement pointer values we've inserted so that we
586c0981da4SDimitry Andric     // don't generate more pointer values than necessary.
587c0981da4SDimitry Andric     SmallPtrSet<Value *, 16> NewPtrs;
588c0981da4SDimitry Andric     NewPtrs.insert(Base.first);
589c0981da4SDimitry Andric 
590c0981da4SDimitry Andric     for (unsigned Idx = BaseElemIdx + 1; Idx < BaseElemIdx + Bucket.ChainSize;
591c0981da4SDimitry Andric          ++Idx) {
592c0981da4SDimitry Andric       BucketElement &I = Bucket.Elements[Idx];
593c0981da4SDimitry Andric       Value *Ptr = getPointerOperandAndType(I.Instr);
594c0981da4SDimitry Andric       assert(Ptr && "No pointer operand");
595c0981da4SDimitry Andric       if (NewPtrs.count(Ptr))
596c0981da4SDimitry Andric         continue;
597c0981da4SDimitry Andric 
598c0981da4SDimitry Andric       const SCEV *OffsetSCEV =
599c0981da4SDimitry Andric           BaseElemIdx ? SE->getMinusSCEV(Bucket.Elements[Idx].Offset,
600c0981da4SDimitry Andric                                          Bucket.Elements[BaseElemIdx].Offset)
601c0981da4SDimitry Andric                       : Bucket.Elements[Idx].Offset;
602c0981da4SDimitry Andric 
603c0981da4SDimitry Andric       // Make sure offset is able to expand. Only need to check one time as the
604c0981da4SDimitry Andric       // offsets are reused between different chains.
605c0981da4SDimitry Andric       if (!BaseElemIdx)
6064b4fe385SDimitry Andric         if (!SCEVE.isSafeToExpand(OffsetSCEV))
607c0981da4SDimitry Andric           return false;
608c0981da4SDimitry Andric 
609c0981da4SDimitry Andric       Value *OffsetValue = SCEVE.expandCodeFor(
610c0981da4SDimitry Andric           OffsetSCEV, OffsetSCEV->getType(), LoopPredecessor->getTerminator());
611c0981da4SDimitry Andric 
612c0981da4SDimitry Andric       Instruction *NewPtr = rewriteForBucketElement(Base, Bucket.Elements[Idx],
613c0981da4SDimitry Andric                                                     OffsetValue, DeletedPtrs);
614c0981da4SDimitry Andric 
615c0981da4SDimitry Andric       assert(NewPtr && "Wrong rewrite!\n");
616c0981da4SDimitry Andric       NewPtrs.insert(NewPtr);
617c0981da4SDimitry Andric     }
618c0981da4SDimitry Andric 
619c0981da4SDimitry Andric     ++ChainCommoningRewritten;
620c0981da4SDimitry Andric   }
621c0981da4SDimitry Andric 
622c0981da4SDimitry Andric   // Clear the rewriter cache, because values that are in the rewriter's cache
623c0981da4SDimitry Andric   // can be deleted below, causing the AssertingVH in the cache to trigger.
624c0981da4SDimitry Andric   SCEVE.clear();
625c0981da4SDimitry Andric 
626c0981da4SDimitry Andric   for (auto *Ptr : DeletedPtrs) {
627c0981da4SDimitry Andric     if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
628c0981da4SDimitry Andric       BBChanged.insert(IDel->getParent());
629c0981da4SDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(Ptr);
630c0981da4SDimitry Andric   }
631c0981da4SDimitry Andric 
632c0981da4SDimitry Andric   MadeChange = true;
633c0981da4SDimitry Andric   return MadeChange;
634c0981da4SDimitry Andric }
635c0981da4SDimitry Andric 
636c0981da4SDimitry Andric // Rewrite the new base according to BasePtrSCEV.
637c0981da4SDimitry Andric // bb.loop.preheader:
638c0981da4SDimitry Andric //   %newstart = ...
639c0981da4SDimitry Andric // bb.loop.body:
640c0981da4SDimitry Andric //   %phinode = phi [ %newstart, %bb.loop.preheader ], [ %add, %bb.loop.body ]
641c0981da4SDimitry Andric //   ...
642c0981da4SDimitry Andric //   %add = getelementptr %phinode, %inc
643c0981da4SDimitry Andric //
644c0981da4SDimitry Andric // First returned instruciton is %phinode (or a type cast to %phinode), caller
645c0981da4SDimitry Andric // needs this value to rewrite other load/stores in the same chain.
646c0981da4SDimitry Andric // Second returned instruction is %add, caller needs this value to rewrite other
647c0981da4SDimitry Andric // load/stores in the same chain.
648c0981da4SDimitry Andric std::pair<Instruction *, Instruction *>
rewriteForBase(Loop * L,const SCEVAddRecExpr * BasePtrSCEV,Instruction * BaseMemI,bool CanPreInc,PrepForm Form,SCEVExpander & SCEVE,SmallPtrSet<Value *,16> & DeletedPtrs)649c0981da4SDimitry Andric PPCLoopInstrFormPrep::rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
650c0981da4SDimitry Andric                                      Instruction *BaseMemI, bool CanPreInc,
651c0981da4SDimitry Andric                                      PrepForm Form, SCEVExpander &SCEVE,
652c0981da4SDimitry Andric                                      SmallPtrSet<Value *, 16> &DeletedPtrs) {
653c0981da4SDimitry Andric 
654c0981da4SDimitry Andric   LLVM_DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
655c0981da4SDimitry Andric 
656c0981da4SDimitry Andric   assert(BasePtrSCEV->getLoop() == L && "AddRec for the wrong loop?");
657c0981da4SDimitry Andric 
658c0981da4SDimitry Andric   Value *BasePtr = getPointerOperandAndType(BaseMemI);
659c0981da4SDimitry Andric   assert(BasePtr && "No pointer operand");
660c0981da4SDimitry Andric 
661c0981da4SDimitry Andric   Type *I8Ty = Type::getInt8Ty(BaseMemI->getParent()->getContext());
662c0981da4SDimitry Andric   Type *I8PtrTy =
663b1c73532SDimitry Andric       PointerType::get(BaseMemI->getParent()->getContext(),
664c0981da4SDimitry Andric                        BasePtr->getType()->getPointerAddressSpace());
665c0981da4SDimitry Andric 
666c0981da4SDimitry Andric   bool IsConstantInc = false;
667c0981da4SDimitry Andric   const SCEV *BasePtrIncSCEV = BasePtrSCEV->getStepRecurrence(*SE);
668c0981da4SDimitry Andric   Value *IncNode = getNodeForInc(L, BaseMemI, BasePtrIncSCEV);
669c0981da4SDimitry Andric 
670c0981da4SDimitry Andric   const SCEVConstant *BasePtrIncConstantSCEV =
671c0981da4SDimitry Andric       dyn_cast<SCEVConstant>(BasePtrIncSCEV);
672c0981da4SDimitry Andric   if (BasePtrIncConstantSCEV)
673c0981da4SDimitry Andric     IsConstantInc = true;
674c0981da4SDimitry Andric 
675c0981da4SDimitry Andric   // No valid representation for the increment.
676c0981da4SDimitry Andric   if (!IncNode) {
677c0981da4SDimitry Andric     LLVM_DEBUG(dbgs() << "Loop Increasement can not be represented!\n");
678c0981da4SDimitry Andric     return std::make_pair(nullptr, nullptr);
679c0981da4SDimitry Andric   }
680c0981da4SDimitry Andric 
681c0981da4SDimitry Andric   if (Form == UpdateForm && !IsConstantInc && !EnableUpdateFormForNonConstInc) {
682c0981da4SDimitry Andric     LLVM_DEBUG(
683c0981da4SDimitry Andric         dbgs()
684c0981da4SDimitry Andric         << "Update form prepare for non-const increment is not enabled!\n");
685c0981da4SDimitry Andric     return std::make_pair(nullptr, nullptr);
686c0981da4SDimitry Andric   }
687c0981da4SDimitry Andric 
688c0981da4SDimitry Andric   const SCEV *BasePtrStartSCEV = nullptr;
689c0981da4SDimitry Andric   if (CanPreInc) {
690c0981da4SDimitry Andric     assert(SE->isLoopInvariant(BasePtrIncSCEV, L) &&
691c0981da4SDimitry Andric            "Increment is not loop invariant!\n");
692c0981da4SDimitry Andric     BasePtrStartSCEV = SE->getMinusSCEV(BasePtrSCEV->getStart(),
693c0981da4SDimitry Andric                                         IsConstantInc ? BasePtrIncConstantSCEV
694c0981da4SDimitry Andric                                                       : BasePtrIncSCEV);
695c0981da4SDimitry Andric   } else
696c0981da4SDimitry Andric     BasePtrStartSCEV = BasePtrSCEV->getStart();
697c0981da4SDimitry Andric 
698c0981da4SDimitry Andric   if (alreadyPrepared(L, BaseMemI, BasePtrStartSCEV, BasePtrIncSCEV, Form)) {
699c0981da4SDimitry Andric     LLVM_DEBUG(dbgs() << "Instruction form is already prepared!\n");
700c0981da4SDimitry Andric     return std::make_pair(nullptr, nullptr);
701c0981da4SDimitry Andric   }
702c0981da4SDimitry Andric 
703c0981da4SDimitry Andric   LLVM_DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
704c0981da4SDimitry Andric 
705c0981da4SDimitry Andric   BasicBlock *Header = L->getHeader();
706c0981da4SDimitry Andric   unsigned HeaderLoopPredCount = pred_size(Header);
707c0981da4SDimitry Andric   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
708c0981da4SDimitry Andric 
709c0981da4SDimitry Andric   PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
710b1c73532SDimitry Andric                                     getInstrName(BaseMemI, PHINodeNameSuffix));
711b1c73532SDimitry Andric   NewPHI->insertBefore(Header->getFirstNonPHIIt());
712c0981da4SDimitry Andric 
713c0981da4SDimitry Andric   Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
714c0981da4SDimitry Andric                                             LoopPredecessor->getTerminator());
715c0981da4SDimitry Andric 
716c0981da4SDimitry Andric   // Note that LoopPredecessor might occur in the predecessor list multiple
717c0981da4SDimitry Andric   // times, and we need to add it the right number of times.
718e3b55780SDimitry Andric   for (auto *PI : predecessors(Header)) {
719c0981da4SDimitry Andric     if (PI != LoopPredecessor)
720c0981da4SDimitry Andric       continue;
721c0981da4SDimitry Andric 
722c0981da4SDimitry Andric     NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
723c0981da4SDimitry Andric   }
724c0981da4SDimitry Andric 
725c0981da4SDimitry Andric   Instruction *PtrInc = nullptr;
726c0981da4SDimitry Andric   Instruction *NewBasePtr = nullptr;
727c0981da4SDimitry Andric   if (CanPreInc) {
728ac9a064cSDimitry Andric     BasicBlock::iterator InsPoint = Header->getFirstInsertionPt();
729c0981da4SDimitry Andric     PtrInc = GetElementPtrInst::Create(
730c0981da4SDimitry Andric         I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
731c0981da4SDimitry Andric         InsPoint);
732c0981da4SDimitry Andric     cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
733e3b55780SDimitry Andric     for (auto *PI : predecessors(Header)) {
734c0981da4SDimitry Andric       if (PI == LoopPredecessor)
735c0981da4SDimitry Andric         continue;
736c0981da4SDimitry Andric 
737c0981da4SDimitry Andric       NewPHI->addIncoming(PtrInc, PI);
738c0981da4SDimitry Andric     }
739c0981da4SDimitry Andric     if (PtrInc->getType() != BasePtr->getType())
740c0981da4SDimitry Andric       NewBasePtr =
741c0981da4SDimitry Andric           new BitCastInst(PtrInc, BasePtr->getType(),
742c0981da4SDimitry Andric                           getInstrName(PtrInc, CastNodeNameSuffix), InsPoint);
743c0981da4SDimitry Andric     else
744c0981da4SDimitry Andric       NewBasePtr = PtrInc;
745c0981da4SDimitry Andric   } else {
746c0981da4SDimitry Andric     // Note that LoopPredecessor might occur in the predecessor list multiple
747c0981da4SDimitry Andric     // times, and we need to make sure no more incoming value for them in PHI.
748e3b55780SDimitry Andric     for (auto *PI : predecessors(Header)) {
749c0981da4SDimitry Andric       if (PI == LoopPredecessor)
750c0981da4SDimitry Andric         continue;
751c0981da4SDimitry Andric 
752c0981da4SDimitry Andric       // For the latch predecessor, we need to insert a GEP just before the
753c0981da4SDimitry Andric       // terminator to increase the address.
754c0981da4SDimitry Andric       BasicBlock *BB = PI;
755ac9a064cSDimitry Andric       BasicBlock::iterator InsPoint = BB->getTerminator()->getIterator();
756c0981da4SDimitry Andric       PtrInc = GetElementPtrInst::Create(
757c0981da4SDimitry Andric           I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
758c0981da4SDimitry Andric           InsPoint);
759c0981da4SDimitry Andric       cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
760c0981da4SDimitry Andric 
761c0981da4SDimitry Andric       NewPHI->addIncoming(PtrInc, PI);
762c0981da4SDimitry Andric     }
763c0981da4SDimitry Andric     PtrInc = NewPHI;
764c0981da4SDimitry Andric     if (NewPHI->getType() != BasePtr->getType())
765c0981da4SDimitry Andric       NewBasePtr = new BitCastInst(NewPHI, BasePtr->getType(),
766c0981da4SDimitry Andric                                    getInstrName(NewPHI, CastNodeNameSuffix),
767ac9a064cSDimitry Andric                                    Header->getFirstInsertionPt());
768c0981da4SDimitry Andric     else
769c0981da4SDimitry Andric       NewBasePtr = NewPHI;
770c0981da4SDimitry Andric   }
771c0981da4SDimitry Andric 
772c0981da4SDimitry Andric   BasePtr->replaceAllUsesWith(NewBasePtr);
773c0981da4SDimitry Andric 
774c0981da4SDimitry Andric   DeletedPtrs.insert(BasePtr);
775c0981da4SDimitry Andric 
776c0981da4SDimitry Andric   return std::make_pair(NewBasePtr, PtrInc);
777c0981da4SDimitry Andric }
778c0981da4SDimitry Andric 
rewriteForBucketElement(std::pair<Instruction *,Instruction * > Base,const BucketElement & Element,Value * OffToBase,SmallPtrSet<Value *,16> & DeletedPtrs)779c0981da4SDimitry Andric Instruction *PPCLoopInstrFormPrep::rewriteForBucketElement(
780c0981da4SDimitry Andric     std::pair<Instruction *, Instruction *> Base, const BucketElement &Element,
781c0981da4SDimitry Andric     Value *OffToBase, SmallPtrSet<Value *, 16> &DeletedPtrs) {
782c0981da4SDimitry Andric   Instruction *NewBasePtr = Base.first;
783c0981da4SDimitry Andric   Instruction *PtrInc = Base.second;
784c0981da4SDimitry Andric   assert((NewBasePtr && PtrInc) && "base does not exist!\n");
785c0981da4SDimitry Andric 
786c0981da4SDimitry Andric   Type *I8Ty = Type::getInt8Ty(PtrInc->getParent()->getContext());
787c0981da4SDimitry Andric 
788c0981da4SDimitry Andric   Value *Ptr = getPointerOperandAndType(Element.Instr);
789c0981da4SDimitry Andric   assert(Ptr && "No pointer operand");
790c0981da4SDimitry Andric 
791c0981da4SDimitry Andric   Instruction *RealNewPtr;
792c0981da4SDimitry Andric   if (!Element.Offset ||
793c0981da4SDimitry Andric       (isa<SCEVConstant>(Element.Offset) &&
794c0981da4SDimitry Andric        cast<SCEVConstant>(Element.Offset)->getValue()->isZero())) {
795c0981da4SDimitry Andric     RealNewPtr = NewBasePtr;
796c0981da4SDimitry Andric   } else {
797ac9a064cSDimitry Andric     std::optional<BasicBlock::iterator> PtrIP = std::nullopt;
798ac9a064cSDimitry Andric     if (Instruction *I = dyn_cast<Instruction>(Ptr))
799ac9a064cSDimitry Andric       PtrIP = I->getIterator();
800ac9a064cSDimitry Andric 
801c0981da4SDimitry Andric     if (PtrIP && isa<Instruction>(NewBasePtr) &&
802ac9a064cSDimitry Andric         cast<Instruction>(NewBasePtr)->getParent() == (*PtrIP)->getParent())
803ac9a064cSDimitry Andric       PtrIP = std::nullopt;
804ac9a064cSDimitry Andric     else if (PtrIP && isa<PHINode>(*PtrIP))
805ac9a064cSDimitry Andric       PtrIP = (*PtrIP)->getParent()->getFirstInsertionPt();
806c0981da4SDimitry Andric     else if (!PtrIP)
807ac9a064cSDimitry Andric       PtrIP = Element.Instr->getIterator();
808c0981da4SDimitry Andric 
809c0981da4SDimitry Andric     assert(OffToBase && "There should be an offset for non base element!\n");
810c0981da4SDimitry Andric     GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
811c0981da4SDimitry Andric         I8Ty, PtrInc, OffToBase,
812ac9a064cSDimitry Andric         getInstrName(Element.Instr, GEPNodeOffNameSuffix));
813ac9a064cSDimitry Andric     if (PtrIP)
814ac9a064cSDimitry Andric       NewPtr->insertBefore(*(*PtrIP)->getParent(), *PtrIP);
815ac9a064cSDimitry Andric     else
816c0981da4SDimitry Andric       NewPtr->insertAfter(cast<Instruction>(PtrInc));
817c0981da4SDimitry Andric     NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
818c0981da4SDimitry Andric     RealNewPtr = NewPtr;
819c0981da4SDimitry Andric   }
820c0981da4SDimitry Andric 
821c0981da4SDimitry Andric   Instruction *ReplNewPtr;
822c0981da4SDimitry Andric   if (Ptr->getType() != RealNewPtr->getType()) {
823c0981da4SDimitry Andric     ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
824c0981da4SDimitry Andric                                  getInstrName(Ptr, CastNodeNameSuffix));
825c0981da4SDimitry Andric     ReplNewPtr->insertAfter(RealNewPtr);
826c0981da4SDimitry Andric   } else
827c0981da4SDimitry Andric     ReplNewPtr = RealNewPtr;
828c0981da4SDimitry Andric 
829c0981da4SDimitry Andric   Ptr->replaceAllUsesWith(ReplNewPtr);
830c0981da4SDimitry Andric   DeletedPtrs.insert(Ptr);
831c0981da4SDimitry Andric 
832c0981da4SDimitry Andric   return ReplNewPtr;
833c0981da4SDimitry Andric }
834c0981da4SDimitry Andric 
addOneCandidate(Instruction * MemI,const SCEV * LSCEV,SmallVector<Bucket,16> & Buckets,std::function<bool (const SCEV *)> isValidDiff,unsigned MaxCandidateNum)835c0981da4SDimitry Andric void PPCLoopInstrFormPrep::addOneCandidate(
836c0981da4SDimitry Andric     Instruction *MemI, const SCEV *LSCEV, SmallVector<Bucket, 16> &Buckets,
837c0981da4SDimitry Andric     std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
838c0981da4SDimitry Andric   assert((MemI && getPointerOperandAndType(MemI)) &&
839706b4fc4SDimitry Andric          "Candidate should be a memory instruction.");
840706b4fc4SDimitry Andric   assert(LSCEV && "Invalid SCEV for Ptr value.");
841c0981da4SDimitry Andric 
842706b4fc4SDimitry Andric   bool FoundBucket = false;
843706b4fc4SDimitry Andric   for (auto &B : Buckets) {
844c0981da4SDimitry Andric     if (cast<SCEVAddRecExpr>(B.BaseSCEV)->getStepRecurrence(*SE) !=
845c0981da4SDimitry Andric         cast<SCEVAddRecExpr>(LSCEV)->getStepRecurrence(*SE))
846c0981da4SDimitry Andric       continue;
847706b4fc4SDimitry Andric     const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
848c0981da4SDimitry Andric     if (isValidDiff(Diff)) {
849c0981da4SDimitry Andric       B.Elements.push_back(BucketElement(Diff, MemI));
850706b4fc4SDimitry Andric       FoundBucket = true;
851706b4fc4SDimitry Andric       break;
852706b4fc4SDimitry Andric     }
853706b4fc4SDimitry Andric   }
854706b4fc4SDimitry Andric 
855706b4fc4SDimitry Andric   if (!FoundBucket) {
856c0981da4SDimitry Andric     if (Buckets.size() == MaxCandidateNum) {
857c0981da4SDimitry Andric       LLVM_DEBUG(dbgs() << "Can not prepare more chains, reach maximum limit "
858c0981da4SDimitry Andric                         << MaxCandidateNum << "\n");
859706b4fc4SDimitry Andric       return;
860c0981da4SDimitry Andric     }
861706b4fc4SDimitry Andric     Buckets.push_back(Bucket(LSCEV, MemI));
862706b4fc4SDimitry Andric   }
863706b4fc4SDimitry Andric }
864706b4fc4SDimitry Andric 
collectCandidates(Loop * L,std::function<bool (const Instruction *,Value *,const Type *)> isValidCandidate,std::function<bool (const SCEV *)> isValidDiff,unsigned MaxCandidateNum)865706b4fc4SDimitry Andric SmallVector<Bucket, 16> PPCLoopInstrFormPrep::collectCandidates(
866706b4fc4SDimitry Andric     Loop *L,
867c0981da4SDimitry Andric     std::function<bool(const Instruction *, Value *, const Type *)>
868344a3780SDimitry Andric         isValidCandidate,
869c0981da4SDimitry Andric     std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
870706b4fc4SDimitry Andric   SmallVector<Bucket, 16> Buckets;
871c0981da4SDimitry Andric 
872706b4fc4SDimitry Andric   for (const auto &BB : L->blocks())
873706b4fc4SDimitry Andric     for (auto &J : *BB) {
874c0981da4SDimitry Andric       Value *PtrValue = nullptr;
875c0981da4SDimitry Andric       Type *PointerElementType = nullptr;
876c0981da4SDimitry Andric       PtrValue = getPointerOperandAndType(&J, &PointerElementType);
877706b4fc4SDimitry Andric 
878c0981da4SDimitry Andric       if (!PtrValue)
879c0981da4SDimitry Andric         continue;
880706b4fc4SDimitry Andric 
881c0981da4SDimitry Andric       if (PtrValue->getType()->getPointerAddressSpace())
882706b4fc4SDimitry Andric         continue;
883706b4fc4SDimitry Andric 
884706b4fc4SDimitry Andric       if (L->isLoopInvariant(PtrValue))
885706b4fc4SDimitry Andric         continue;
886706b4fc4SDimitry Andric 
887706b4fc4SDimitry Andric       const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
888706b4fc4SDimitry Andric       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
889706b4fc4SDimitry Andric       if (!LARSCEV || LARSCEV->getLoop() != L)
890706b4fc4SDimitry Andric         continue;
891706b4fc4SDimitry Andric 
892c0981da4SDimitry Andric       // Mark that we have candidates for preparing.
893c0981da4SDimitry Andric       HasCandidateForPrepare = true;
894c0981da4SDimitry Andric 
895344a3780SDimitry Andric       if (isValidCandidate(&J, PtrValue, PointerElementType))
896c0981da4SDimitry Andric         addOneCandidate(&J, LSCEV, Buckets, isValidDiff, MaxCandidateNum);
897706b4fc4SDimitry Andric     }
898706b4fc4SDimitry Andric   return Buckets;
899706b4fc4SDimitry Andric }
900706b4fc4SDimitry Andric 
prepareBaseForDispFormChain(Bucket & BucketChain,PrepForm Form)901706b4fc4SDimitry Andric bool PPCLoopInstrFormPrep::prepareBaseForDispFormChain(Bucket &BucketChain,
902c0981da4SDimitry Andric                                                        PrepForm Form) {
903706b4fc4SDimitry Andric   // RemainderOffsetInfo details:
904706b4fc4SDimitry Andric   // key:            value of (Offset urem DispConstraint). For DSForm, it can
905706b4fc4SDimitry Andric   //                 be [0, 4).
906706b4fc4SDimitry Andric   // first of pair:  the index of first BucketElement whose remainder is equal
907706b4fc4SDimitry Andric   //                 to key. For key 0, this value must be 0.
908706b4fc4SDimitry Andric   // second of pair: number of load/stores with the same remainder.
909706b4fc4SDimitry Andric   DenseMap<unsigned, std::pair<unsigned, unsigned>> RemainderOffsetInfo;
910706b4fc4SDimitry Andric 
911706b4fc4SDimitry Andric   for (unsigned j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
912706b4fc4SDimitry Andric     if (!BucketChain.Elements[j].Offset)
913706b4fc4SDimitry Andric       RemainderOffsetInfo[0] = std::make_pair(0, 1);
914706b4fc4SDimitry Andric     else {
915c0981da4SDimitry Andric       unsigned Remainder = cast<SCEVConstant>(BucketChain.Elements[j].Offset)
916c0981da4SDimitry Andric                                ->getAPInt()
917c0981da4SDimitry Andric                                .urem(Form);
9187fa27ce4SDimitry Andric       if (!RemainderOffsetInfo.contains(Remainder))
919706b4fc4SDimitry Andric         RemainderOffsetInfo[Remainder] = std::make_pair(j, 1);
920706b4fc4SDimitry Andric       else
921706b4fc4SDimitry Andric         RemainderOffsetInfo[Remainder].second++;
922706b4fc4SDimitry Andric     }
923706b4fc4SDimitry Andric   }
924706b4fc4SDimitry Andric   // Currently we choose the most profitable base as the one which has the max
925706b4fc4SDimitry Andric   // number of load/store with same remainder.
926706b4fc4SDimitry Andric   // FIXME: adjust the base selection strategy according to load/store offset
927706b4fc4SDimitry Andric   // distribution.
928706b4fc4SDimitry Andric   // For example, if we have one candidate chain for DS form preparation, which
929706b4fc4SDimitry Andric   // contains following load/stores with different remainders:
930706b4fc4SDimitry Andric   // 1: 10 load/store whose remainder is 1;
931706b4fc4SDimitry Andric   // 2: 9 load/store whose remainder is 2;
932706b4fc4SDimitry Andric   // 3: 1 for remainder 3 and 0 for remainder 0;
933706b4fc4SDimitry Andric   // Now we will choose the first load/store whose remainder is 1 as base and
934706b4fc4SDimitry Andric   // adjust all other load/stores according to new base, so we will get 10 DS
935706b4fc4SDimitry Andric   // form and 10 X form.
936706b4fc4SDimitry Andric   // But we should be more clever, for this case we could use two bases, one for
937c0981da4SDimitry Andric   // remainder 1 and the other for remainder 2, thus we could get 19 DS form and
938c0981da4SDimitry Andric   // 1 X form.
939706b4fc4SDimitry Andric   unsigned MaxCountRemainder = 0;
940706b4fc4SDimitry Andric   for (unsigned j = 0; j < (unsigned)Form; j++)
9417fa27ce4SDimitry Andric     if ((RemainderOffsetInfo.contains(j)) &&
942706b4fc4SDimitry Andric         RemainderOffsetInfo[j].second >
943706b4fc4SDimitry Andric             RemainderOffsetInfo[MaxCountRemainder].second)
944706b4fc4SDimitry Andric       MaxCountRemainder = j;
945706b4fc4SDimitry Andric 
946706b4fc4SDimitry Andric   // Abort when there are too few insts with common base.
947706b4fc4SDimitry Andric   if (RemainderOffsetInfo[MaxCountRemainder].second < DispFormPrepMinThreshold)
948706b4fc4SDimitry Andric     return false;
949706b4fc4SDimitry Andric 
950706b4fc4SDimitry Andric   // If the first value is most profitable, no needed to adjust BucketChain
951706b4fc4SDimitry Andric   // elements as they are substracted the first value when collecting.
952706b4fc4SDimitry Andric   if (MaxCountRemainder == 0)
953706b4fc4SDimitry Andric     return true;
954706b4fc4SDimitry Andric 
955706b4fc4SDimitry Andric   // Adjust load/store to the new chosen base.
956706b4fc4SDimitry Andric   const SCEV *Offset =
957706b4fc4SDimitry Andric       BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first].Offset;
958706b4fc4SDimitry Andric   BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
959706b4fc4SDimitry Andric   for (auto &E : BucketChain.Elements) {
960706b4fc4SDimitry Andric     if (E.Offset)
961706b4fc4SDimitry Andric       E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
962706b4fc4SDimitry Andric     else
963706b4fc4SDimitry Andric       E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
964706b4fc4SDimitry Andric   }
965706b4fc4SDimitry Andric 
966706b4fc4SDimitry Andric   std::swap(BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first],
967706b4fc4SDimitry Andric             BucketChain.Elements[0]);
968706b4fc4SDimitry Andric   return true;
969706b4fc4SDimitry Andric }
970706b4fc4SDimitry Andric 
971706b4fc4SDimitry Andric // FIXME: implement a more clever base choosing policy.
972706b4fc4SDimitry Andric // Currently we always choose an exist load/store offset. This maybe lead to
973706b4fc4SDimitry Andric // suboptimal code sequences. For example, for one DS chain with offsets
974706b4fc4SDimitry Andric // {-32769, 2003, 2007, 2011}, we choose -32769 as base offset, and left disp
975706b4fc4SDimitry Andric // for load/stores are {0, 34772, 34776, 34780}. Though each offset now is a
976706b4fc4SDimitry Andric // multipler of 4, it cannot be represented by sint16.
prepareBaseForUpdateFormChain(Bucket & BucketChain)977706b4fc4SDimitry Andric bool PPCLoopInstrFormPrep::prepareBaseForUpdateFormChain(Bucket &BucketChain) {
978706b4fc4SDimitry Andric   // We have a choice now of which instruction's memory operand we use as the
979706b4fc4SDimitry Andric   // base for the generated PHI. Always picking the first instruction in each
980706b4fc4SDimitry Andric   // bucket does not work well, specifically because that instruction might
981706b4fc4SDimitry Andric   // be a prefetch (and there are no pre-increment dcbt variants). Otherwise,
982706b4fc4SDimitry Andric   // the choice is somewhat arbitrary, because the backend will happily
983706b4fc4SDimitry Andric   // generate direct offsets from both the pre-incremented and
984706b4fc4SDimitry Andric   // post-incremented pointer values. Thus, we'll pick the first non-prefetch
985706b4fc4SDimitry Andric   // instruction in each bucket, and adjust the recurrence and other offsets
986706b4fc4SDimitry Andric   // accordingly.
987706b4fc4SDimitry Andric   for (int j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
988706b4fc4SDimitry Andric     if (auto *II = dyn_cast<IntrinsicInst>(BucketChain.Elements[j].Instr))
989706b4fc4SDimitry Andric       if (II->getIntrinsicID() == Intrinsic::prefetch)
990706b4fc4SDimitry Andric         continue;
991706b4fc4SDimitry Andric 
992706b4fc4SDimitry Andric     // If we'd otherwise pick the first element anyway, there's nothing to do.
993706b4fc4SDimitry Andric     if (j == 0)
994706b4fc4SDimitry Andric       break;
995706b4fc4SDimitry Andric 
996706b4fc4SDimitry Andric     // If our chosen element has no offset from the base pointer, there's
997706b4fc4SDimitry Andric     // nothing to do.
998706b4fc4SDimitry Andric     if (!BucketChain.Elements[j].Offset ||
999c0981da4SDimitry Andric         cast<SCEVConstant>(BucketChain.Elements[j].Offset)->isZero())
1000706b4fc4SDimitry Andric       break;
1001706b4fc4SDimitry Andric 
1002706b4fc4SDimitry Andric     const SCEV *Offset = BucketChain.Elements[j].Offset;
1003706b4fc4SDimitry Andric     BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
1004706b4fc4SDimitry Andric     for (auto &E : BucketChain.Elements) {
1005706b4fc4SDimitry Andric       if (E.Offset)
1006706b4fc4SDimitry Andric         E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
1007706b4fc4SDimitry Andric       else
1008706b4fc4SDimitry Andric         E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
1009706b4fc4SDimitry Andric     }
1010706b4fc4SDimitry Andric 
1011706b4fc4SDimitry Andric     std::swap(BucketChain.Elements[j], BucketChain.Elements[0]);
1012706b4fc4SDimitry Andric     break;
1013706b4fc4SDimitry Andric   }
1014706b4fc4SDimitry Andric   return true;
1015706b4fc4SDimitry Andric }
1016706b4fc4SDimitry Andric 
rewriteLoadStores(Loop * L,Bucket & BucketChain,SmallSet<BasicBlock *,16> & BBChanged,PrepForm Form)1017c0981da4SDimitry Andric bool PPCLoopInstrFormPrep::rewriteLoadStores(
1018c0981da4SDimitry Andric     Loop *L, Bucket &BucketChain, SmallSet<BasicBlock *, 16> &BBChanged,
1019c0981da4SDimitry Andric     PrepForm Form) {
1020706b4fc4SDimitry Andric   bool MadeChange = false;
1021c0981da4SDimitry Andric 
1022706b4fc4SDimitry Andric   const SCEVAddRecExpr *BasePtrSCEV =
1023706b4fc4SDimitry Andric       cast<SCEVAddRecExpr>(BucketChain.BaseSCEV);
1024706b4fc4SDimitry Andric   if (!BasePtrSCEV->isAffine())
1025706b4fc4SDimitry Andric     return MadeChange;
1026706b4fc4SDimitry Andric 
1027706b4fc4SDimitry Andric   BasicBlock *Header = L->getHeader();
1028ac9a064cSDimitry Andric   SCEVExpander SCEVE(*SE, Header->getDataLayout(),
1029c0981da4SDimitry Andric                      "loopprepare-formrewrite");
10304b4fe385SDimitry Andric   if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart()))
10314b4fe385SDimitry Andric     return MadeChange;
10324b4fe385SDimitry Andric 
10334b4fe385SDimitry Andric   SmallPtrSet<Value *, 16> DeletedPtrs;
1034706b4fc4SDimitry Andric 
1035c0981da4SDimitry Andric   // For some DS form load/store instructions, it can also be an update form,
1036c0981da4SDimitry Andric   // if the stride is constant and is a multipler of 4. Use update form if
1037c0981da4SDimitry Andric   // prefer it.
1038c0981da4SDimitry Andric   bool CanPreInc = (Form == UpdateForm ||
1039c0981da4SDimitry Andric                     ((Form == DSForm) &&
1040c0981da4SDimitry Andric                      isa<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE)) &&
1041c0981da4SDimitry Andric                      !cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE))
1042c0981da4SDimitry Andric                           ->getAPInt()
1043c0981da4SDimitry Andric                           .urem(4) &&
1044c0981da4SDimitry Andric                      PreferUpdateForm));
1045706b4fc4SDimitry Andric 
1046c0981da4SDimitry Andric   std::pair<Instruction *, Instruction *> Base =
1047c0981da4SDimitry Andric       rewriteForBase(L, BasePtrSCEV, BucketChain.Elements.begin()->Instr,
1048c0981da4SDimitry Andric                      CanPreInc, Form, SCEVE, DeletedPtrs);
1049706b4fc4SDimitry Andric 
1050c0981da4SDimitry Andric   if (!Base.first || !Base.second)
1051c0981da4SDimitry Andric     return MadeChange;
1052c0981da4SDimitry Andric 
1053c0981da4SDimitry Andric   // Keep track of the replacement pointer values we've inserted so that we
1054c0981da4SDimitry Andric   // don't generate more pointer values than necessary.
1055c0981da4SDimitry Andric   SmallPtrSet<Value *, 16> NewPtrs;
1056c0981da4SDimitry Andric   NewPtrs.insert(Base.first);
1057c0981da4SDimitry Andric 
1058e3b55780SDimitry Andric   for (const BucketElement &BE : llvm::drop_begin(BucketChain.Elements)) {
1059e3b55780SDimitry Andric     Value *Ptr = getPointerOperandAndType(BE.Instr);
1060c0981da4SDimitry Andric     assert(Ptr && "No pointer operand");
1061c0981da4SDimitry Andric     if (NewPtrs.count(Ptr))
1062706b4fc4SDimitry Andric       continue;
1063706b4fc4SDimitry Andric 
1064c0981da4SDimitry Andric     Instruction *NewPtr = rewriteForBucketElement(
1065e3b55780SDimitry Andric         Base, BE,
1066e3b55780SDimitry Andric         BE.Offset ? cast<SCEVConstant>(BE.Offset)->getValue() : nullptr,
1067c0981da4SDimitry Andric         DeletedPtrs);
1068c0981da4SDimitry Andric     assert(NewPtr && "wrong rewrite!\n");
1069c0981da4SDimitry Andric     NewPtrs.insert(NewPtr);
1070706b4fc4SDimitry Andric   }
1071706b4fc4SDimitry Andric 
1072b60736ecSDimitry Andric   // Clear the rewriter cache, because values that are in the rewriter's cache
1073b60736ecSDimitry Andric   // can be deleted below, causing the AssertingVH in the cache to trigger.
1074b60736ecSDimitry Andric   SCEVE.clear();
1075b60736ecSDimitry Andric 
1076c0981da4SDimitry Andric   for (auto *Ptr : DeletedPtrs) {
1077706b4fc4SDimitry Andric     if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
1078706b4fc4SDimitry Andric       BBChanged.insert(IDel->getParent());
1079706b4fc4SDimitry Andric     RecursivelyDeleteTriviallyDeadInstructions(Ptr);
1080706b4fc4SDimitry Andric   }
1081706b4fc4SDimitry Andric 
1082706b4fc4SDimitry Andric   MadeChange = true;
1083706b4fc4SDimitry Andric 
1084706b4fc4SDimitry Andric   SuccPrepCount++;
1085706b4fc4SDimitry Andric 
1086706b4fc4SDimitry Andric   if (Form == DSForm && !CanPreInc)
1087706b4fc4SDimitry Andric     DSFormChainRewritten++;
1088706b4fc4SDimitry Andric   else if (Form == DQForm)
1089706b4fc4SDimitry Andric     DQFormChainRewritten++;
1090706b4fc4SDimitry Andric   else if (Form == UpdateForm || (Form == DSForm && CanPreInc))
1091706b4fc4SDimitry Andric     UpdFormChainRewritten++;
1092706b4fc4SDimitry Andric 
1093706b4fc4SDimitry Andric   return MadeChange;
1094706b4fc4SDimitry Andric }
1095706b4fc4SDimitry Andric 
updateFormPrep(Loop * L,SmallVector<Bucket,16> & Buckets)1096706b4fc4SDimitry Andric bool PPCLoopInstrFormPrep::updateFormPrep(Loop *L,
1097706b4fc4SDimitry Andric                                        SmallVector<Bucket, 16> &Buckets) {
1098706b4fc4SDimitry Andric   bool MadeChange = false;
1099706b4fc4SDimitry Andric   if (Buckets.empty())
1100706b4fc4SDimitry Andric     return MadeChange;
1101706b4fc4SDimitry Andric   SmallSet<BasicBlock *, 16> BBChanged;
1102706b4fc4SDimitry Andric   for (auto &Bucket : Buckets)
1103706b4fc4SDimitry Andric     // The base address of each bucket is transformed into a phi and the others
1104706b4fc4SDimitry Andric     // are rewritten based on new base.
1105706b4fc4SDimitry Andric     if (prepareBaseForUpdateFormChain(Bucket))
1106706b4fc4SDimitry Andric       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, UpdateForm);
1107706b4fc4SDimitry Andric 
1108706b4fc4SDimitry Andric   if (MadeChange)
1109c0981da4SDimitry Andric     for (auto *BB : BBChanged)
1110706b4fc4SDimitry Andric       DeleteDeadPHIs(BB);
1111706b4fc4SDimitry Andric   return MadeChange;
1112706b4fc4SDimitry Andric }
1113706b4fc4SDimitry Andric 
dispFormPrep(Loop * L,SmallVector<Bucket,16> & Buckets,PrepForm Form)1114c0981da4SDimitry Andric bool PPCLoopInstrFormPrep::dispFormPrep(Loop *L,
1115c0981da4SDimitry Andric                                         SmallVector<Bucket, 16> &Buckets,
1116c0981da4SDimitry Andric                                         PrepForm Form) {
1117706b4fc4SDimitry Andric   bool MadeChange = false;
1118706b4fc4SDimitry Andric 
1119706b4fc4SDimitry Andric   if (Buckets.empty())
1120706b4fc4SDimitry Andric     return MadeChange;
1121706b4fc4SDimitry Andric 
1122706b4fc4SDimitry Andric   SmallSet<BasicBlock *, 16> BBChanged;
1123706b4fc4SDimitry Andric   for (auto &Bucket : Buckets) {
1124706b4fc4SDimitry Andric     if (Bucket.Elements.size() < DispFormPrepMinThreshold)
1125706b4fc4SDimitry Andric       continue;
1126706b4fc4SDimitry Andric     if (prepareBaseForDispFormChain(Bucket, Form))
1127706b4fc4SDimitry Andric       MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, Form);
1128706b4fc4SDimitry Andric   }
1129706b4fc4SDimitry Andric 
1130706b4fc4SDimitry Andric   if (MadeChange)
1131c0981da4SDimitry Andric     for (auto *BB : BBChanged)
1132706b4fc4SDimitry Andric       DeleteDeadPHIs(BB);
1133706b4fc4SDimitry Andric   return MadeChange;
1134706b4fc4SDimitry Andric }
1135706b4fc4SDimitry Andric 
1136c0981da4SDimitry Andric // Find the loop invariant increment node for SCEV BasePtrIncSCEV.
1137c0981da4SDimitry Andric // bb.loop.preheader:
1138c0981da4SDimitry Andric //   %start = ...
1139c0981da4SDimitry Andric // bb.loop.body:
1140c0981da4SDimitry Andric //   %phinode = phi [ %start, %bb.loop.preheader ], [ %add, %bb.loop.body ]
1141c0981da4SDimitry Andric //   ...
1142c0981da4SDimitry Andric //   %add = add %phinode, %inc  ; %inc is what we want to get.
1143c0981da4SDimitry Andric //
getNodeForInc(Loop * L,Instruction * MemI,const SCEV * BasePtrIncSCEV)1144c0981da4SDimitry Andric Value *PPCLoopInstrFormPrep::getNodeForInc(Loop *L, Instruction *MemI,
1145c0981da4SDimitry Andric                                            const SCEV *BasePtrIncSCEV) {
1146c0981da4SDimitry Andric   // If the increment is a constant, no definition is needed.
1147c0981da4SDimitry Andric   // Return the value directly.
1148c0981da4SDimitry Andric   if (isa<SCEVConstant>(BasePtrIncSCEV))
1149c0981da4SDimitry Andric     return cast<SCEVConstant>(BasePtrIncSCEV)->getValue();
1150c0981da4SDimitry Andric 
1151c0981da4SDimitry Andric   if (!SE->isLoopInvariant(BasePtrIncSCEV, L))
1152c0981da4SDimitry Andric     return nullptr;
1153c0981da4SDimitry Andric 
1154c0981da4SDimitry Andric   BasicBlock *BB = MemI->getParent();
1155c0981da4SDimitry Andric   if (!BB)
1156c0981da4SDimitry Andric     return nullptr;
1157c0981da4SDimitry Andric 
1158c0981da4SDimitry Andric   BasicBlock *LatchBB = L->getLoopLatch();
1159c0981da4SDimitry Andric 
1160c0981da4SDimitry Andric   if (!LatchBB)
1161c0981da4SDimitry Andric     return nullptr;
1162c0981da4SDimitry Andric 
1163c0981da4SDimitry Andric   // Run through the PHIs and check their operands to find valid representation
1164c0981da4SDimitry Andric   // for the increment SCEV.
1165c0981da4SDimitry Andric   iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
1166c0981da4SDimitry Andric   for (auto &CurrentPHI : PHIIter) {
1167c0981da4SDimitry Andric     PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
1168c0981da4SDimitry Andric     if (!CurrentPHINode)
1169c0981da4SDimitry Andric       continue;
1170c0981da4SDimitry Andric 
1171c0981da4SDimitry Andric     if (!SE->isSCEVable(CurrentPHINode->getType()))
1172c0981da4SDimitry Andric       continue;
1173c0981da4SDimitry Andric 
1174c0981da4SDimitry Andric     const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
1175c0981da4SDimitry Andric 
1176c0981da4SDimitry Andric     const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
1177c0981da4SDimitry Andric     if (!PHIBasePtrSCEV)
1178c0981da4SDimitry Andric       continue;
1179c0981da4SDimitry Andric 
1180c0981da4SDimitry Andric     const SCEV *PHIBasePtrIncSCEV = PHIBasePtrSCEV->getStepRecurrence(*SE);
1181c0981da4SDimitry Andric 
1182c0981da4SDimitry Andric     if (!PHIBasePtrIncSCEV || (PHIBasePtrIncSCEV != BasePtrIncSCEV))
1183c0981da4SDimitry Andric       continue;
1184c0981da4SDimitry Andric 
1185c0981da4SDimitry Andric     // Get the incoming value from the loop latch and check if the value has
1186c0981da4SDimitry Andric     // the add form with the required increment.
11877fa27ce4SDimitry Andric     if (CurrentPHINode->getBasicBlockIndex(LatchBB) < 0)
11887fa27ce4SDimitry Andric       continue;
1189c0981da4SDimitry Andric     if (Instruction *I = dyn_cast<Instruction>(
1190c0981da4SDimitry Andric             CurrentPHINode->getIncomingValueForBlock(LatchBB))) {
1191c0981da4SDimitry Andric       Value *StrippedBaseI = I;
1192c0981da4SDimitry Andric       while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBaseI))
1193c0981da4SDimitry Andric         StrippedBaseI = BC->getOperand(0);
1194c0981da4SDimitry Andric 
1195c0981da4SDimitry Andric       Instruction *StrippedI = dyn_cast<Instruction>(StrippedBaseI);
1196c0981da4SDimitry Andric       if (!StrippedI)
1197c0981da4SDimitry Andric         continue;
1198c0981da4SDimitry Andric 
1199c0981da4SDimitry Andric       // LSR pass may add a getelementptr instruction to do the loop increment,
1200c0981da4SDimitry Andric       // also search in that getelementptr instruction.
1201c0981da4SDimitry Andric       if (StrippedI->getOpcode() == Instruction::Add ||
1202c0981da4SDimitry Andric           (StrippedI->getOpcode() == Instruction::GetElementPtr &&
1203c0981da4SDimitry Andric            StrippedI->getNumOperands() == 2)) {
1204c0981da4SDimitry Andric         if (SE->getSCEVAtScope(StrippedI->getOperand(0), L) == BasePtrIncSCEV)
1205c0981da4SDimitry Andric           return StrippedI->getOperand(0);
1206c0981da4SDimitry Andric         if (SE->getSCEVAtScope(StrippedI->getOperand(1), L) == BasePtrIncSCEV)
1207c0981da4SDimitry Andric           return StrippedI->getOperand(1);
1208c0981da4SDimitry Andric       }
1209c0981da4SDimitry Andric     }
1210c0981da4SDimitry Andric   }
1211c0981da4SDimitry Andric   return nullptr;
1212c0981da4SDimitry Andric }
1213c0981da4SDimitry Andric 
1214706b4fc4SDimitry Andric // In order to prepare for the preferred instruction form, a PHI is added.
1215706b4fc4SDimitry Andric // This function will check to see if that PHI already exists and will return
1216706b4fc4SDimitry Andric // true if it found an existing PHI with the matched start and increment as the
1217706b4fc4SDimitry Andric // one we wanted to create.
alreadyPrepared(Loop * L,Instruction * MemI,const SCEV * BasePtrStartSCEV,const SCEV * BasePtrIncSCEV,PrepForm Form)1218706b4fc4SDimitry Andric bool PPCLoopInstrFormPrep::alreadyPrepared(Loop *L, Instruction *MemI,
1219706b4fc4SDimitry Andric                                            const SCEV *BasePtrStartSCEV,
1220c0981da4SDimitry Andric                                            const SCEV *BasePtrIncSCEV,
1221c0981da4SDimitry Andric                                            PrepForm Form) {
1222706b4fc4SDimitry Andric   BasicBlock *BB = MemI->getParent();
1223706b4fc4SDimitry Andric   if (!BB)
1224706b4fc4SDimitry Andric     return false;
1225706b4fc4SDimitry Andric 
1226706b4fc4SDimitry Andric   BasicBlock *PredBB = L->getLoopPredecessor();
1227706b4fc4SDimitry Andric   BasicBlock *LatchBB = L->getLoopLatch();
1228706b4fc4SDimitry Andric 
1229706b4fc4SDimitry Andric   if (!PredBB || !LatchBB)
1230706b4fc4SDimitry Andric     return false;
1231706b4fc4SDimitry Andric 
1232706b4fc4SDimitry Andric   // Run through the PHIs and see if we have some that looks like a preparation
1233706b4fc4SDimitry Andric   iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
1234706b4fc4SDimitry Andric   for (auto & CurrentPHI : PHIIter) {
1235706b4fc4SDimitry Andric     PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
1236706b4fc4SDimitry Andric     if (!CurrentPHINode)
1237706b4fc4SDimitry Andric       continue;
1238706b4fc4SDimitry Andric 
1239706b4fc4SDimitry Andric     if (!SE->isSCEVable(CurrentPHINode->getType()))
1240706b4fc4SDimitry Andric       continue;
1241706b4fc4SDimitry Andric 
1242706b4fc4SDimitry Andric     const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
1243706b4fc4SDimitry Andric 
1244706b4fc4SDimitry Andric     const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
1245706b4fc4SDimitry Andric     if (!PHIBasePtrSCEV)
1246706b4fc4SDimitry Andric       continue;
1247706b4fc4SDimitry Andric 
1248706b4fc4SDimitry Andric     const SCEVConstant *PHIBasePtrIncSCEV =
1249706b4fc4SDimitry Andric       dyn_cast<SCEVConstant>(PHIBasePtrSCEV->getStepRecurrence(*SE));
1250706b4fc4SDimitry Andric     if (!PHIBasePtrIncSCEV)
1251706b4fc4SDimitry Andric       continue;
1252706b4fc4SDimitry Andric 
1253706b4fc4SDimitry Andric     if (CurrentPHINode->getNumIncomingValues() == 2) {
1254706b4fc4SDimitry Andric       if ((CurrentPHINode->getIncomingBlock(0) == LatchBB &&
1255706b4fc4SDimitry Andric            CurrentPHINode->getIncomingBlock(1) == PredBB) ||
1256706b4fc4SDimitry Andric           (CurrentPHINode->getIncomingBlock(1) == LatchBB &&
1257706b4fc4SDimitry Andric            CurrentPHINode->getIncomingBlock(0) == PredBB)) {
1258706b4fc4SDimitry Andric         if (PHIBasePtrIncSCEV == BasePtrIncSCEV) {
1259706b4fc4SDimitry Andric           // The existing PHI (CurrentPHINode) has the same start and increment
1260706b4fc4SDimitry Andric           // as the PHI that we wanted to create.
1261c0981da4SDimitry Andric           if ((Form == UpdateForm || Form == ChainCommoning ) &&
1262706b4fc4SDimitry Andric               PHIBasePtrSCEV->getStart() == BasePtrStartSCEV) {
1263706b4fc4SDimitry Andric             ++PHINodeAlreadyExistsUpdate;
1264706b4fc4SDimitry Andric             return true;
1265706b4fc4SDimitry Andric           }
1266706b4fc4SDimitry Andric           if (Form == DSForm || Form == DQForm) {
1267706b4fc4SDimitry Andric             const SCEVConstant *Diff = dyn_cast<SCEVConstant>(
1268706b4fc4SDimitry Andric                 SE->getMinusSCEV(PHIBasePtrSCEV->getStart(), BasePtrStartSCEV));
1269706b4fc4SDimitry Andric             if (Diff && !Diff->getAPInt().urem(Form)) {
1270706b4fc4SDimitry Andric               if (Form == DSForm)
1271706b4fc4SDimitry Andric                 ++PHINodeAlreadyExistsDS;
1272706b4fc4SDimitry Andric               else
1273706b4fc4SDimitry Andric                 ++PHINodeAlreadyExistsDQ;
1274706b4fc4SDimitry Andric               return true;
1275706b4fc4SDimitry Andric             }
1276706b4fc4SDimitry Andric           }
1277706b4fc4SDimitry Andric         }
1278706b4fc4SDimitry Andric       }
1279706b4fc4SDimitry Andric     }
1280706b4fc4SDimitry Andric   }
1281706b4fc4SDimitry Andric   return false;
1282706b4fc4SDimitry Andric }
1283706b4fc4SDimitry Andric 
runOnLoop(Loop * L)1284706b4fc4SDimitry Andric bool PPCLoopInstrFormPrep::runOnLoop(Loop *L) {
1285706b4fc4SDimitry Andric   bool MadeChange = false;
1286706b4fc4SDimitry Andric 
1287706b4fc4SDimitry Andric   // Only prep. the inner-most loop
1288b60736ecSDimitry Andric   if (!L->isInnermost())
1289706b4fc4SDimitry Andric     return MadeChange;
1290706b4fc4SDimitry Andric 
1291706b4fc4SDimitry Andric   // Return if already done enough preparation.
1292706b4fc4SDimitry Andric   if (SuccPrepCount >= MaxVarsPrep)
1293706b4fc4SDimitry Andric     return MadeChange;
1294706b4fc4SDimitry Andric 
1295706b4fc4SDimitry Andric   LLVM_DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
1296706b4fc4SDimitry Andric 
1297706b4fc4SDimitry Andric   BasicBlock *LoopPredecessor = L->getLoopPredecessor();
1298706b4fc4SDimitry Andric   // If there is no loop predecessor, or the loop predecessor's terminator
1299706b4fc4SDimitry Andric   // returns a value (which might contribute to determining the loop's
1300706b4fc4SDimitry Andric   // iteration space), insert a new preheader for the loop.
1301706b4fc4SDimitry Andric   if (!LoopPredecessor ||
1302706b4fc4SDimitry Andric       !LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
1303706b4fc4SDimitry Andric     LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
1304706b4fc4SDimitry Andric     if (LoopPredecessor)
1305706b4fc4SDimitry Andric       MadeChange = true;
1306706b4fc4SDimitry Andric   }
1307706b4fc4SDimitry Andric   if (!LoopPredecessor) {
1308706b4fc4SDimitry Andric     LLVM_DEBUG(dbgs() << "PIP fails since no predecessor for current loop.\n");
1309706b4fc4SDimitry Andric     return MadeChange;
1310706b4fc4SDimitry Andric   }
1311706b4fc4SDimitry Andric   // Check if a load/store has update form. This lambda is used by function
1312706b4fc4SDimitry Andric   // collectCandidates which can collect candidates for types defined by lambda.
1313c0981da4SDimitry Andric   auto isUpdateFormCandidate = [&](const Instruction *I, Value *PtrValue,
1314344a3780SDimitry Andric                                    const Type *PointerElementType) {
1315706b4fc4SDimitry Andric     assert((PtrValue && I) && "Invalid parameter!");
1316706b4fc4SDimitry Andric     // There are no update forms for Altivec vector load/stores.
1317344a3780SDimitry Andric     if (ST && ST->hasAltivec() && PointerElementType->isVectorTy())
1318706b4fc4SDimitry Andric       return false;
1319b60736ecSDimitry Andric     // There are no update forms for P10 lxvp/stxvp intrinsic.
1320b60736ecSDimitry Andric     auto *II = dyn_cast<IntrinsicInst>(I);
1321b60736ecSDimitry Andric     if (II && ((II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) ||
1322b60736ecSDimitry Andric                II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp))
1323b60736ecSDimitry Andric       return false;
1324706b4fc4SDimitry Andric     // See getPreIndexedAddressParts, the displacement for LDU/STDU has to
1325706b4fc4SDimitry Andric     // be 4's multiple (DS-form). For i64 loads/stores when the displacement
1326706b4fc4SDimitry Andric     // fits in a 16-bit signed field but isn't a multiple of 4, it will be
1327706b4fc4SDimitry Andric     // useless and possible to break some original well-form addressing mode
1328706b4fc4SDimitry Andric     // to make this pre-inc prep for it.
1329344a3780SDimitry Andric     if (PointerElementType->isIntegerTy(64)) {
1330706b4fc4SDimitry Andric       const SCEV *LSCEV = SE->getSCEVAtScope(const_cast<Value *>(PtrValue), L);
1331706b4fc4SDimitry Andric       const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
1332706b4fc4SDimitry Andric       if (!LARSCEV || LARSCEV->getLoop() != L)
1333706b4fc4SDimitry Andric         return false;
1334706b4fc4SDimitry Andric       if (const SCEVConstant *StepConst =
1335706b4fc4SDimitry Andric               dyn_cast<SCEVConstant>(LARSCEV->getStepRecurrence(*SE))) {
1336706b4fc4SDimitry Andric         const APInt &ConstInt = StepConst->getValue()->getValue();
1337706b4fc4SDimitry Andric         if (ConstInt.isSignedIntN(16) && ConstInt.srem(4) != 0)
1338706b4fc4SDimitry Andric           return false;
1339706b4fc4SDimitry Andric       }
1340706b4fc4SDimitry Andric     }
1341706b4fc4SDimitry Andric     return true;
1342706b4fc4SDimitry Andric   };
1343706b4fc4SDimitry Andric 
1344706b4fc4SDimitry Andric   // Check if a load/store has DS form.
1345c0981da4SDimitry Andric   auto isDSFormCandidate = [](const Instruction *I, Value *PtrValue,
1346344a3780SDimitry Andric                               const Type *PointerElementType) {
1347706b4fc4SDimitry Andric     assert((PtrValue && I) && "Invalid parameter!");
1348706b4fc4SDimitry Andric     if (isa<IntrinsicInst>(I))
1349706b4fc4SDimitry Andric       return false;
1350706b4fc4SDimitry Andric     return (PointerElementType->isIntegerTy(64)) ||
1351706b4fc4SDimitry Andric            (PointerElementType->isFloatTy()) ||
1352706b4fc4SDimitry Andric            (PointerElementType->isDoubleTy()) ||
1353706b4fc4SDimitry Andric            (PointerElementType->isIntegerTy(32) &&
1354706b4fc4SDimitry Andric             llvm::any_of(I->users(),
1355706b4fc4SDimitry Andric                          [](const User *U) { return isa<SExtInst>(U); }));
1356706b4fc4SDimitry Andric   };
1357706b4fc4SDimitry Andric 
1358706b4fc4SDimitry Andric   // Check if a load/store has DQ form.
1359c0981da4SDimitry Andric   auto isDQFormCandidate = [&](const Instruction *I, Value *PtrValue,
1360344a3780SDimitry Andric                                const Type *PointerElementType) {
1361706b4fc4SDimitry Andric     assert((PtrValue && I) && "Invalid parameter!");
1362b60736ecSDimitry Andric     // Check if it is a P10 lxvp/stxvp intrinsic.
1363b60736ecSDimitry Andric     auto *II = dyn_cast<IntrinsicInst>(I);
1364b60736ecSDimitry Andric     if (II)
1365b60736ecSDimitry Andric       return II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp ||
1366b60736ecSDimitry Andric              II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp;
1367b60736ecSDimitry Andric     // Check if it is a P9 vector load/store.
1368344a3780SDimitry Andric     return ST && ST->hasP9Vector() && (PointerElementType->isVectorTy());
1369706b4fc4SDimitry Andric   };
1370706b4fc4SDimitry Andric 
1371c0981da4SDimitry Andric   // Check if a load/store is candidate for chain commoning.
1372c0981da4SDimitry Andric   // If the SCEV is only with one ptr operand in its start, we can use that
1373c0981da4SDimitry Andric   // start as a chain separator. Mark this load/store as a candidate.
1374c0981da4SDimitry Andric   auto isChainCommoningCandidate = [&](const Instruction *I, Value *PtrValue,
1375c0981da4SDimitry Andric                                        const Type *PointerElementType) {
1376c0981da4SDimitry Andric     const SCEVAddRecExpr *ARSCEV =
1377c0981da4SDimitry Andric         cast<SCEVAddRecExpr>(SE->getSCEVAtScope(PtrValue, L));
1378c0981da4SDimitry Andric     if (!ARSCEV)
1379c0981da4SDimitry Andric       return false;
1380c0981da4SDimitry Andric 
1381c0981da4SDimitry Andric     if (!ARSCEV->isAffine())
1382c0981da4SDimitry Andric       return false;
1383c0981da4SDimitry Andric 
1384c0981da4SDimitry Andric     const SCEV *Start = ARSCEV->getStart();
1385c0981da4SDimitry Andric 
1386c0981da4SDimitry Andric     // A single pointer. We can treat it as offset 0.
1387c0981da4SDimitry Andric     if (isa<SCEVUnknown>(Start) && Start->getType()->isPointerTy())
1388c0981da4SDimitry Andric       return true;
1389c0981da4SDimitry Andric 
1390c0981da4SDimitry Andric     const SCEVAddExpr *ASCEV = dyn_cast<SCEVAddExpr>(Start);
1391c0981da4SDimitry Andric 
1392c0981da4SDimitry Andric     // We need a SCEVAddExpr to include both base and offset.
1393c0981da4SDimitry Andric     if (!ASCEV)
1394c0981da4SDimitry Andric       return false;
1395c0981da4SDimitry Andric 
1396c0981da4SDimitry Andric     // Make sure there is only one pointer operand(base) and all other operands
1397c0981da4SDimitry Andric     // are integer type.
1398c0981da4SDimitry Andric     bool SawPointer = false;
1399c0981da4SDimitry Andric     for (const SCEV *Op : ASCEV->operands()) {
1400c0981da4SDimitry Andric       if (Op->getType()->isPointerTy()) {
1401c0981da4SDimitry Andric         if (SawPointer)
1402c0981da4SDimitry Andric           return false;
1403c0981da4SDimitry Andric         SawPointer = true;
1404c0981da4SDimitry Andric       } else if (!Op->getType()->isIntegerTy())
1405c0981da4SDimitry Andric         return false;
1406c0981da4SDimitry Andric     }
1407c0981da4SDimitry Andric 
1408c0981da4SDimitry Andric     return SawPointer;
1409c0981da4SDimitry Andric   };
1410c0981da4SDimitry Andric 
1411c0981da4SDimitry Andric   // Check if the diff is a constant type. This is used for update/DS/DQ form
1412c0981da4SDimitry Andric   // preparation.
1413c0981da4SDimitry Andric   auto isValidConstantDiff = [](const SCEV *Diff) {
1414c0981da4SDimitry Andric     return dyn_cast<SCEVConstant>(Diff) != nullptr;
1415c0981da4SDimitry Andric   };
1416c0981da4SDimitry Andric 
1417c0981da4SDimitry Andric   // Make sure the diff between the base and new candidate is required type.
1418c0981da4SDimitry Andric   // This is used for chain commoning preparation.
1419c0981da4SDimitry Andric   auto isValidChainCommoningDiff = [](const SCEV *Diff) {
1420c0981da4SDimitry Andric     assert(Diff && "Invalid Diff!\n");
1421c0981da4SDimitry Andric 
1422c0981da4SDimitry Andric     // Don't mess up previous dform prepare.
1423c0981da4SDimitry Andric     if (isa<SCEVConstant>(Diff))
1424c0981da4SDimitry Andric       return false;
1425c0981da4SDimitry Andric 
1426c0981da4SDimitry Andric     // A single integer type offset.
1427c0981da4SDimitry Andric     if (isa<SCEVUnknown>(Diff) && Diff->getType()->isIntegerTy())
1428c0981da4SDimitry Andric       return true;
1429c0981da4SDimitry Andric 
1430c0981da4SDimitry Andric     const SCEVNAryExpr *ADiff = dyn_cast<SCEVNAryExpr>(Diff);
1431c0981da4SDimitry Andric     if (!ADiff)
1432c0981da4SDimitry Andric       return false;
1433c0981da4SDimitry Andric 
1434c0981da4SDimitry Andric     for (const SCEV *Op : ADiff->operands())
1435c0981da4SDimitry Andric       if (!Op->getType()->isIntegerTy())
1436c0981da4SDimitry Andric         return false;
1437c0981da4SDimitry Andric 
1438c0981da4SDimitry Andric     return true;
1439c0981da4SDimitry Andric   };
1440c0981da4SDimitry Andric 
1441c0981da4SDimitry Andric   HasCandidateForPrepare = false;
1442c0981da4SDimitry Andric 
1443c0981da4SDimitry Andric   LLVM_DEBUG(dbgs() << "Start to prepare for update form.\n");
1444c0981da4SDimitry Andric   // Collect buckets of comparable addresses used by loads and stores for update
1445c0981da4SDimitry Andric   // form.
1446c0981da4SDimitry Andric   SmallVector<Bucket, 16> UpdateFormBuckets = collectCandidates(
1447c0981da4SDimitry Andric       L, isUpdateFormCandidate, isValidConstantDiff, MaxVarsUpdateForm);
1448706b4fc4SDimitry Andric 
1449706b4fc4SDimitry Andric   // Prepare for update form.
1450706b4fc4SDimitry Andric   if (!UpdateFormBuckets.empty())
1451706b4fc4SDimitry Andric     MadeChange |= updateFormPrep(L, UpdateFormBuckets);
1452c0981da4SDimitry Andric   else if (!HasCandidateForPrepare) {
1453c0981da4SDimitry Andric     LLVM_DEBUG(
1454c0981da4SDimitry Andric         dbgs()
1455c0981da4SDimitry Andric         << "No prepare candidates found, stop praparation for current loop!\n");
1456c0981da4SDimitry Andric     // If no candidate for preparing, return early.
1457c0981da4SDimitry Andric     return MadeChange;
1458c0981da4SDimitry Andric   }
1459706b4fc4SDimitry Andric 
1460c0981da4SDimitry Andric   LLVM_DEBUG(dbgs() << "Start to prepare for DS form.\n");
1461706b4fc4SDimitry Andric   // Collect buckets of comparable addresses used by loads and stores for DS
1462706b4fc4SDimitry Andric   // form.
1463c0981da4SDimitry Andric   SmallVector<Bucket, 16> DSFormBuckets = collectCandidates(
1464c0981da4SDimitry Andric       L, isDSFormCandidate, isValidConstantDiff, MaxVarsDSForm);
1465706b4fc4SDimitry Andric 
1466706b4fc4SDimitry Andric   // Prepare for DS form.
1467706b4fc4SDimitry Andric   if (!DSFormBuckets.empty())
1468706b4fc4SDimitry Andric     MadeChange |= dispFormPrep(L, DSFormBuckets, DSForm);
1469706b4fc4SDimitry Andric 
1470c0981da4SDimitry Andric   LLVM_DEBUG(dbgs() << "Start to prepare for DQ form.\n");
1471706b4fc4SDimitry Andric   // Collect buckets of comparable addresses used by loads and stores for DQ
1472706b4fc4SDimitry Andric   // form.
1473c0981da4SDimitry Andric   SmallVector<Bucket, 16> DQFormBuckets = collectCandidates(
1474c0981da4SDimitry Andric       L, isDQFormCandidate, isValidConstantDiff, MaxVarsDQForm);
1475706b4fc4SDimitry Andric 
1476706b4fc4SDimitry Andric   // Prepare for DQ form.
1477706b4fc4SDimitry Andric   if (!DQFormBuckets.empty())
1478706b4fc4SDimitry Andric     MadeChange |= dispFormPrep(L, DQFormBuckets, DQForm);
1479706b4fc4SDimitry Andric 
1480c0981da4SDimitry Andric   // Collect buckets of comparable addresses used by loads and stores for chain
1481c0981da4SDimitry Andric   // commoning. With chain commoning, we reuse offsets between the chains, so
1482c0981da4SDimitry Andric   // the register pressure will be reduced.
1483c0981da4SDimitry Andric   if (!EnableChainCommoning) {
1484c0981da4SDimitry Andric     LLVM_DEBUG(dbgs() << "Chain commoning is not enabled.\n");
1485c0981da4SDimitry Andric     return MadeChange;
1486c0981da4SDimitry Andric   }
1487c0981da4SDimitry Andric 
1488c0981da4SDimitry Andric   LLVM_DEBUG(dbgs() << "Start to prepare for chain commoning.\n");
1489c0981da4SDimitry Andric   SmallVector<Bucket, 16> Buckets =
1490c0981da4SDimitry Andric       collectCandidates(L, isChainCommoningCandidate, isValidChainCommoningDiff,
1491c0981da4SDimitry Andric                         MaxVarsChainCommon);
1492c0981da4SDimitry Andric 
1493c0981da4SDimitry Andric   // Prepare for chain commoning.
1494c0981da4SDimitry Andric   if (!Buckets.empty())
1495c0981da4SDimitry Andric     MadeChange |= chainCommoning(L, Buckets);
1496c0981da4SDimitry Andric 
1497706b4fc4SDimitry Andric   return MadeChange;
1498706b4fc4SDimitry Andric }
1499